@oracle-agent/oracle 0.35.5 → 0.35.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  3. package/dist/bin/desk-server.mjs +25 -23
  4. package/dist/bin/oracle-data-mcp.mjs +13 -11
  5. package/dist/bin/oracle-mev-arb-shadow.mjs +7 -5
  6. package/dist/bin/oracle-mev-shadow.mjs +7 -5
  7. package/dist/bin/oracle-public-server.mjs +6 -4
  8. package/dist/bin/oracle-route.mjs +22 -20
  9. package/dist/bin/oracle-scan.mjs +14 -12
  10. package/dist/bin/oracle.mjs +2 -1
  11. package/dist/cli/commands/chat.mjs +166 -164
  12. package/dist/cli/commands/doctor.mjs +3 -3
  13. package/dist/cli/commands/eval.mjs +113 -113
  14. package/dist/cli/commands/farm.mjs +14 -14
  15. package/dist/cli/commands/follow.mjs +16 -14
  16. package/dist/cli/commands/model.mjs +170 -168
  17. package/dist/cli/commands/project.mjs +17 -0
  18. package/dist/cli/commands/resolve.mjs +8 -6
  19. package/dist/cli/commands/shadow.mjs +10 -8
  20. package/dist/cli/commands/signer.mjs +10 -10
  21. package/dist/cli/commands/snipe.mjs +10 -8
  22. package/dist/cli/commands/strategy.mjs +5 -5
  23. package/dist/cli/commands/swap.mjs +27 -25
  24. package/dist/cli/commands/venues.mjs +2 -2
  25. package/dist/data/desk-data.mjs +23 -21
  26. package/dist/data/names.mjs +4 -2
  27. package/dist/data/providers/farming.mjs +2 -2
  28. package/dist/index.mjs +37 -35
  29. package/dist/local-signer/index.mjs +3 -3
  30. package/dist/local-signer/runtime.mjs +9 -9
  31. package/dist/nft/universal-mint-router.mjs +5 -3
  32. package/dist/router/index.mjs +4 -2
  33. package/dist/router/prepare-bridge.mjs +2 -2
  34. package/dist/scanner/index.mjs +5 -3
  35. package/dist/strategy/index.mjs +3 -3
  36. package/package.json +1 -1
  37. package/public/oracle-splash/index.html +2 -2
@@ -1,2 +1,2 @@
1
- var bt=Object.defineProperty;var R=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var ve=(e,t)=>{for(var r in t)bt(e,r,{get:t[r],enumerable:!0})};import z from"node:net";import yt from"node:dns";function W(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=p=>{if(!p)return[];let c=p.split(":"),l=c.at(-1);if(l?.includes(".")){let u=l.split(".").map(Number);if(u.length!==4||u.some(w=>!Number.isInteger(w)||w<0||w>255))return null;c.splice(c.length-1,1,(u[0]<<8|u[1]).toString(16),(u[2]<<8|u[3]).toString(16))}return c.some(u=>!/^[0-9a-f]{1,4}$/.test(u))?null:c.map(u=>Number.parseInt(u,16))},[n,i]=t.split("::"),o=r(n),s=r(i);if(!o||!s)return null;let a=t.includes("::"),f=8-o.length-s.length;if(!a&&f!==0||a&&f<1)return null;let d=[...o,...Array(Math.max(0,f)).fill(0),...s];return d.length!==8?null:Uint8Array.from(d.flatMap(p=>[p>>8,p&255]))}function ae(e,t,r){let n=Math.floor(r/8),i=r%8;for(let s=0;s<n;s+=1)if(e[s]!==t[s])return!1;if(!i)return!0;let o=255<<8-i;return(e[n]&o)===(t[n]&o)}function ce(e){if(z.isIPv4(e)){let t=e.split(".").map(Number);return!(t[0]===0||t[0]===10||t[0]===127||t[0]>=224||t[0]===100&&t[1]>=64&&t[1]<=127||t[0]===169&&t[1]===254||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&(t[1]===0||t[1]===2||t[1]===168)||t[0]===192&&t[1]===88&&t[2]===99||t[0]===198&&(t[1]===18||t[1]===19||t[1]===51)||t[0]===203&&t[1]===0&&t[2]===113)}if(z.isIPv6(e)){let t=W(e);if(!t)return!1;let r=W("::ffff:0:0");return ae(t,r,96)?ce([...t.slice(12)].join(".")):ae(t,W("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([i,o])=>ae(t,W(i),o)):!1}return!1}function At(e){let t;try{t=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,error:`refused protocol ${t.protocol} (only http/https)`};let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Et.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=z.isIP(r);return n!==0&&!ce(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function ue(e,{lookupFn:t=yt.promises.lookup}={}){let r=At(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:z.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(i=>!ce(i.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function le({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let c=await t();r=c.Agent,n=c.fetch}catch(c){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${c?.message||c}`);return null}if(typeof r!="function"||typeof n!="function"){if(e)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let i=c=>String(c).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,s=c=>(Array.isArray(c)?c:[c]).map(l=>typeof l=="string"?{address:l}:l).filter(l=>l&&l.address).map(l=>({address:l.address,family:l.family||(z.isIPv6(l.address)?6:4)})),a=(c,l,u)=>{o.set(i(c),s(typeof l=="string"?[{address:l,family:u}]:l))},f=c=>{let l=i(c);if(z.isIP(l))return[{address:l,family:z.isIPv6(l)?6:4}];let u=o.get(l);if(!u||!u.length)throw new Error(`refused: unpinned host ${c} during pinned fetch`);return u},d=new r({connect:{lookup(c,l,u){let w;try{w=f(c)}catch(y){return u(y)}return l?.all?u(null,w):u(null,w[0].address,w[0].family)}}}),p=xt((c,l={})=>n(c,{...l,dispatcher:d}),a);return{dispatcher:d,fetch:p,pin:a,resolve:f,async close(){try{await d.destroy()}catch{}}}}function xt(e,t){if(typeof e!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof t!="function")throw new Error("markPinCapableFetch: pin must be a function");return e[de]=Object.freeze({pin:t}),e}function pe(e){return typeof e=="function"&&typeof e[de]?.pin=="function"}function Be(e,t,r){if(!pe(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[de].pin(t,r)}var Et,de,Re=R(()=>{Et=new Set(["localhost","metadata.google.internal","metadata.goog"]);de=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as St}from"node:crypto";function Ot(e){let t=String(e||"").toLowerCase();return De.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function Nt(e){let t={};for(let[r,n]of Object.entries(e||{}))Ot(r)||(t[r]=n);return t}function Tt(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 _t(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Bt(e,t,r,n={}){let i={};for(let[p,c]of Object.entries(r||{}))i[p.toLowerCase()]=c;let o=Object.keys(i).filter(p=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(p)),a=[...new Set([...De,...o])].sort().map(p=>`${p}=${i[p]??""}`).join(`
2
- `),f=St("sha256").update(a).digest("hex").slice(0,32),d=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`;return`${e} ${t} ${d} ${f}`}function Rt(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,$e):Math.min(250*2**e,$e)+Math.floor(Math.random()*100)}function G(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function me(e,t,r){return G(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function K(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function $t(e){return e?e.byteLength??e.length??0:0}async function Ue(e,t,{url:r,truncate:n=!1,onOversize:i}={}){if(t==null)return await e.text();let o=Number(e.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>t&&(K(e),!n))throw me(r,`content-length ${o}`,t);let s=e.body?.getReader?.();if(!s){let c=await e.text(),l=Buffer.byteLength(c,"utf8");if(l>t){if(!n)throw me(r,`body ${l} bytes`,t);return Buffer.from(c,"utf8").subarray(0,t).toString("utf8")}return c}let a=[],f=0,d=!1;try{for(;;){let{value:c,done:l}=await s.read();if(l)break;if(c&&(a.push(Buffer.from(c)),f+=$t(c),f>t)){d=!0;break}}}finally{if(d)try{await s.cancel()}catch{}try{s.releaseLock?.()}catch{}}if(d&&(typeof i=="function"&&i(),!n))throw me(r,`streamed ${f} bytes`,t);let p=Buffer.concat(a);return(d?p.subarray(0,t):p).toString("utf8")}function Fe(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function Lt(e,{fetchImpl:t,method:r,headers:n,body:i,timeoutMs:o,lookupFn:s,realFetch:a,untrustedUrl:f=!1,maxResponseBytes:d=null,importUndici:p,validateResponse:c,signal:l}){let u=new AbortController,w=setTimeout(()=>u.abort(),o),y=l?typeof AbortSignal.any=="function"?AbortSignal.any([l,u.signal]):l:u.signal,m=null,E=t,v=s?{lookupFn:s}:{};if(f&&!a&&!pe(E))throw G(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let N=async(b,{status:S=null}={})=>{let x=await ue(b,v);if(!x.ok)throw G(S==null?`HTTP refused ${b}: ${x.error}`:`HTTP redirect to ${b} ${x.error}`,S==null?{}:{status:S});let g=new URL(b).hostname;if(a){if(m&&(await m.close(),m=null),!m)try{m=await le({requireUndici:!0,...p?{importUndici:p}:{}})}catch(h){throw G(S==null?`HTTP refused ${b}: ${h?.message||h}`:`HTTP redirect to ${b} refused: ${h?.message||h}`,S==null?{}:{status:S})}m.pin(g,x.addresses),E=m.fetch}else Be(E,g,x.addresses);return x};try{let b=String(e),S={...n||{}};f&&await N(b);for(let x=0;x<=Le;x+=1){let g=await E(b,{method:r,headers:S,body:i,signal:y,redirect:"manual"});if(kt.has(g.status)){if(r!=="GET"&&r!=="HEAD"){let C=await Ue(g,d??vt,{url:b,truncate:!0}),T=new Error(`HTTP ${g.status} ${r} ${b} redirected non-idempotent request`);throw T.status=g.status,T.body=Fe(C)??C.slice(0,300),T}if(x===Le)throw K(g),new Error(`HTTP redirect loop for ${e}`);let I=g.headers?.get?.("location"),O;try{O=Tt(I,b)}catch(C){throw K(g),C}let B=!_t(O,b);if(K(g),B&&(S=Nt(S)),f)await N(O,{status:g.status});else if(B){let C=await ue(O,v);if(!C.ok){let T=new Error(`HTTP redirect from ${b} ${C.error}`);throw T.status=g.status,T.retryable=!1,T}a&&C.addresses?.length&&(m||(m=await le(p?{importUndici:p}:{})),m&&(m.pin(new URL(O).hostname,C.addresses),E=m.fetch))}b=O;continue}if(typeof c=="function")try{await c(g,{url:b})}catch(I){throw K(g),G(I?.message||String(I))}let h=await Ue(g,d,{url:b,onOversize:()=>u.abort()}),A=Fe(h);if(!g.ok){let I=new Error(`HTTP ${g.status} ${r} ${b}`);throw I.status=g.status,I.retryAfter=g.headers?.get?.("retry-after")??null,I.body=A??h.slice(0,300),I}return A??h}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(w),m&&await m.close()}}async function k(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,i=(t.method||"GET").toUpperCase(),o={Accept:"application/json",...t.headers||{}},s=t.body;s!=null&&typeof s!="string"&&(o["Content-Type"]=o["Content-Type"]||"application/json",s=JSON.stringify(s));let a=Number.isInteger(t.retries)?Math.max(t.retries,0):Ct,f=t.lookupFn,d=!t.fetchImpl,p=t.untrustedUrl===!0,c=t.importUndici,l=t.validateResponse,u=t.signal,w=Number(t.maxResponseBytes),y=Number.isFinite(w)&&w>0?Math.floor(w):null,m=async()=>{let S;for(let x=0;x<=a;x++){u?.throwIfAborted?.();try{return await Lt(e,{fetchImpl:r,method:i,headers:o,body:s,timeoutMs:n,lookupFn:f,realFetch:d,untrustedUrl:p,maxResponseBytes:y,importUndici:c,validateResponse:l,signal:u})}catch(g){S=g;let h=g?.status,A=g?.name==="AbortError"||g?.name==="TimeoutError"||u?.aborted,I=new Set([408,425,429]),O=g?.retryable===!1?!1:h!=null?I.has(h)||It.has(h)&&Pe.has(i):!A&&Pe.has(i);if(x===a||!O)throw g;let B=Rt(x,g?.retryAfter);u?await new Promise((C,T)=>{let X=setTimeout(C,B);u.addEventListener("abort",()=>{clearTimeout(X),T(u.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await Pt(B)}}throw S};if(!(t.dedupe!==!1&&!u&&i==="GET"&&s==null))return m();let v=Bt(i,e,o,{untrustedUrl:p,maxResponseBytes:y}),N=fe.get(v);if(N)return N;let b=m().finally(()=>fe.delete(v));return fe.set(v,b),b}var It,Pe,Ct,$e,De,kt,Le,vt,fe,Pt,$=R(()=>{Re();It=new Set([408,425,429,500,502,503,504]),Pe=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Ct=2,$e=4e3,De=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],kt=new Set([301,302,303,307,308]),Le=3,vt=64*1024;fe=new Map;Pt=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as Ut}from"node:fs";import{homedir as Ft}from"node:os";import{join as Q}from"node:path";function Dt(){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=Ft();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Q(t,".config","oracle")).trim();return[e,Q(r,"exec.env")].filter(Boolean)}return[e,Q(t,".config","oracle","exec.env"),Q(t,".config","mad-desk","exec.env")].filter(Boolean)}function Me(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let i of Dt())try{let o=Ut(i,"utf8"),s=o.match(new RegExp(`^${t}=(.*)$`,"m"))||o.match(new RegExp(`^${r}=(.*)$`,"m"));if(s&&(n=s[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}var qe=R(()=>{});var He=R(()=>{});import{createHash as Mt,createHmac as ze,timingSafeEqual as qt}from"node:crypto";function Z(e){return Array.isArray(e)?`[${e.map(Z).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Z(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Ve(e,{required:t=!1}={}){try{return Me(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function we(e){let{signature:t,...r}=e;return r}function Ge(e,{secret:t}={}){let r=Ve(t);return r?{...e,signature:ze("sha256",r).update(Z(we(e))).digest("hex")}:e}function Ht(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 Mt("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function D(e,{chainId:t,venue:r,data:n,secret:i}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");if(Number(e.chainId)!==Number(t))throw new Error("auto-slippage guard chain mismatch");if(String(e.venue).toLowerCase()!==String(r||"").toLowerCase())throw new Error("auto-slippage guard venue mismatch");let o=Ve(i);if(o){let u=ze("sha256",o).update(Z(we(e))).digest("hex");if(!jt(e.signature,u))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let s=Number(e.selectedBps),a=Number(e.capBps);if(!Number.isInteger(s)||s<0||s>J||!Number.isInteger(a)||a<0||a>J||s>a)throw new Error("auto-slippage guard bounds are invalid");let f=BigInt(e.quoteAmountOut??0),d=BigInt(e.minAmountOut??0);if(f<=0n||d<=0n)throw new Error("auto-slippage guard amounts must be positive");let p=f*BigInt(1e4-s),c=p/10000n;if(p%10000n!==0n&&(c+=1n),d<c)throw new Error("auto-slippage guard is under-protected relative to its quote");let l=Gt(n);if(l!=null&&l!==d)throw new Error(`auto-slippage: calldata encodes floor ${l}, not the guard floor ${d} \u2014 refusing to bind`);return Ge({...we(e),calldataHash:Ht(n)},{secret:i})}function jt(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:qt(r,n)}function he(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function zt(e){let t=e==null?J: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,J)}function M({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:i}={}){let o=he(e,0),s=o>0?o>=25e4?5:o>=1e5?10:o>=5e4?20:o>=1e4?40:70:n?30:10,a=Math.min(60,Math.abs(he(t,0))*2),f=Math.min(40,Math.floor(Math.max(0,he(r,0))/5e3)*5),d=Math.max(25,Math.ceil(20+s+a+f)),p=zt(i);return{mode:"auto",requiredBps:d,selectedBps:Math.min(d,p),capBps:p,executable:d<=p}}function Vt({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:i=0,quoteAgeMs:o=0,crossChain:s=!1,requestedCapBps:a,quotedAtMs:f=Date.now(),ttlMs:d=je,secret:p}={}){let c=BigInt(r??0);if(c<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let l=M({liquidityUsd:n,priceChange5m:i,quoteAgeMs:o,crossChain:s,requestedCapBps:a});if(!l.executable)throw new Error(`auto-slippage requires ${l.requiredBps} bps above hard/requested cap ${l.capBps}; route blocked`);let u=Number(f);if(!Number.isFinite(u))throw new Error("auto-slippage: quotedAtMs must be a finite number");let w=Math.min(3e4,Math.max(1e3,Number(d)||je)),y=c*BigInt(1e4-l.selectedBps),m=y/10000n;if(y%10000n!==0n&&(m+=1n),m>c&&(m=c),c>0n&&m<=0n)throw new Error(`auto-slippage: quote ${c} is too small to express a ${l.selectedBps} bps floor without rounding to zero`);let E=Number((c-m)*10000n/(c===0n?1n:c));if(E>l.capBps)throw new Error(`auto-slippage: realised floor implies ${E} bps, above cap ${l.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Ge({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:c.toString(),minAmountOut:m.toString(),requiredBps:l.requiredBps,selectedBps:l.selectedBps,capBps:l.capBps,quotedAtMs:u,expiresAtMs:u+w},{secret:p})}function Gt(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let o=10;o+64<=t.length;o+=64)n.push(t.slice(o,o+64));let i=o=>n[o]==null?null:BigInt("0x"+n[o]);switch(r){case"0x414bf389":return i(6);case"0x04e45aaf":return i(5);case"0xc04b8d59":{let o=i(0);if(o==null)return null;let s=Number(o)/32;return!Number.isInteger(s)||s<0?null:i(s+4)}case"0xb858183f":{let o=i(0);if(o==null)return null;let s=Number(o)/32;return!Number.isInteger(s)||s<0?null:i(s+3)}case"0xa026383e":return i(6);case"0x38ed1739":case"0x5c11d795":return i(1);case"0x7ff36ab5":case"0xb6f9de95":return i(0);case"0x18cbafe5":case"0x791ac947":return i(1);default:return null}}function P(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:i,priceChange5m:o,crossChain:s,requestedCapBps:a,quotedAtMs:f=Date.now(),ttlMs:d}={}){let p=Vt({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:i,priceChange5m:o,crossChain:s,requestedCapBps:a,quotedAtMs:f,ttlMs:d});return{...e,autoSlippage:p,amountOutMinimum:p.minAmountOut}}var J,je,U=R(()=>{qe();He();J=100,je=2e4});var V,ee=R(()=>{V="0x000000000000000000000000000000000000dEaD"});import{createHash as Kt,createHmac as Xt,timingSafeEqual as kn}from"node:crypto";function ge(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ge).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${ge(e[r])}`).join(",")}}`}function Ke(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Xe(e=process.env){return Ke(process.env)||Ke(e)}function Jt(e){let{prepareHash:t,prepareMac:r,note:n,...i}=e||{};return i}function Zt(e){let t=Jt(e);return Kt("sha256").update(ge(t)).digest("hex")}function er(e,t=Xe()){return t?Xt("sha256",t).update(String(e)).digest("hex"):""}function _(e,{provider:t,kind:r,env:n=process.env,nowMs:i=Date.now(),expiresAtMs:o}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let s=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(s&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let a={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:s?e.oraclePrepared:!0};if(!a.provider)throw new Error("stampPrepared: provider required");if(!a.kind)throw new Error("stampPrepared: kind required");let f=Number(i),d=o==null?f+Wt:Number(o),p=d-f;if(!Number.isSafeInteger(f)||!Number.isSafeInteger(d)||p<=0||p>Qt)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let l={...a,preparedAt:f,expiresAt:d,prepareVersion:Yt},u=Zt(l),w=Xe(n),y=w?er(u,w):void 0,m={...l,prepareHash:u};return y&&(m.prepareMac=y),m}var Yt,Wt,Qt,L=R(()=>{Yt=2,Wt=300*1e3,Qt=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as tr,JsonRpcProvider as rr}from"ethers";function cr(e){return ar.test(String(e||""))}async function Ye(e,{contract:t=nr,rpc:r=ir,chainId:n=or,balanceOf:i}={}){if(!cr(e))throw new Error("invalid-address");if(i)return BigInt(await i(e));let o=new rr(r,n,{staticNetwork:!0}),s=new tr(t,sr,o);return BigInt(await s.balanceOf(e))}var nr,or,ir,sr,ar,We=R(()=>{nr="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",or=999,ir="https://rpc.hyperliquid.xyz/evm",sr=["function balanceOf(address owner) view returns (uint256)"],ar=/^0x[a-fA-F0-9]{40}$/});import{existsSync as ur,readFileSync as lr,lstatSync as dr}from"node:fs";import{homedir as Qe}from"node:os";import{join as be}from"node:path";function mr(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Je,t)?Je[t]:fr}function yr(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[Ze])return String(e[Ze]);let t=e.ORACLE_CONFIG_DIR||be(Qe(),".config","oracle");return be(t,"fee-recipient")}return be(Qe(),".config","oracle","fee-recipient")}function Er(e=process.env){try{let t=yr(e);if(!ur(t)||dr(t).isSymbolicLink())return"";let r=lr(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}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),pr)}function xr({env:e=process.env,action:t="swap",admin:r=!1}={}){let n=String(e[wr]||"").trim(),i=String(e[gr]||br).trim();if(r===!0)return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"admin-oracle"};let o=mr(t),s=Ar(e[hr],{fallback:n?o:0}),a=Math.min(s,o);if(!a)return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"no-recipient"};let f=Er(e);return!f||f!==n.toLowerCase()?{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:a,recipient:n,integrator:i,action:t,applies:!0,reason:"configured"}}async function ye({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={},admin:i=!1}={}){let o=xr({env:t,action:r,admin:i});if(i===!0)return{...o,holderVerificationStatus:"admin-oracle"};let s=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(s))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await Ye(s,n))>0n?{...o,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...o,holderVerificationStatus:"non-holder"}}catch{return{...o,holderVerificationStatus:"unavailable"}}}function et(e){return e?.applies?`Oracle routing fee ${e.bps} bps (${(e.bps/100).toFixed(2)}%) to ${e.recipient}.`:e?.reason==="admin-oracle"?"No Oracle fee (admin Oracle).":e?.reason==="locals-only-holder"?"No Oracle fee (Locals Only holder).":"No Oracle fee."}function tt(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}var pr,fr,Je,hr,wr,gr,Ze,br,te=R(()=>{We();pr=100,fr=5,Je=Object.freeze({swap:5,bridge:5,perps:0,nft:0});hr="ORACLE_INTEGRATOR_FEE_BPS",wr="ORACLE_INTEGRATOR_FEE_RECIPIENT",gr="ORACLE_INTEGRATOR_ID",Ze="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",br="oracle"});var ot={};ve(ot,{LIFI_API:()=>nt,lifiChains:()=>vr,lifiHealth:()=>Cr,lifiPrepare:()=>kr,lifiQuote:()=>re});function Ae(e={}){return(e.baseUrl||process.env.LIFI_API_URL||nt).replace(/\/$/,"")}function Ir(e){let t=String(e||Ee).toLowerCase();return t===Ee.toLowerCase()||t===Sr}function rt(e,t){let r=String(e||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(r))throw new Error(`lifi: ${t} must be a 20-byte address`);return r.toLowerCase()}async function Cr(e={}){let t=await k(`${Ae(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3}),r=Array.isArray(t)?t.length:t?.chains?.length||0;return{ok:r>0,chainCount:r}}async function re(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:i=Ee,toToken:o,fromAmount:s,fromAddress:a=V}=e;if(r==null||!o||!s)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let f=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:i,toToken:o,fromAmount:String(s),fromAddress:a}),d=M({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}`);f.set("slippage",String(d.selectedBps/1e4));let p=await ye({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[m,E]of Object.entries(tt(p)))f.set(m,E);let c=await k(`${Ae(t)}/quote?${f}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),l=c?.estimate?.toAmount||c?.toAmount;if(!l)return{...c,autoSlippagePolicy:d,oracleFee:p};let u=c?.transactionRequest?.to||c?.estimate?.approvalAddress||"lifi",w=P(c,{chainId:Number(r),venue:u,amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),y=c?.estimate?.toAmountMin||c?.toAmountMin;if(y!=null&&BigInt(y)<BigInt(w.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...w,oracleFee:p}}async function kr(e={},t={}){let r=await re(e,t),n=r?.transactionRequest;if(!n?.to||!n?.data)throw new Error("lifi: quote did not return an executable transactionRequest");let i=Number(e.fromChain);if(n.chainId!=null&&Number(n.chainId)!==i)throw new Error("lifi: transaction chain mismatch");if(e.fromAddress&&n.from&&String(n.from).toLowerCase()!==String(e.fromAddress).toLowerCase())throw new Error("lifi: transaction sender mismatch");let o=null;if(!Ir(e.fromToken)){let s=r?.estimate?.approvalAddress||r?.approvalAddress;if(!s)throw new Error("lifi: ERC20 route missing approvalAddress");let a=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;o={token:rt(a,"approval token"),spender:rt(s,"approval spender"),amount:String(e.fromAmount)}}return _({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:i,quote:r,autoSlippage:r.autoSlippage,requiresApproval:o,transaction:{chainId:i,from:n.from||e.fromAddress,to:n.to,data:n.data,value:n.value??"0x0",...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:D(r.autoSlippage,{chainId:i,venue:n.to,data:n.data})}},{provider:"lifi",kind:"lifi-tx"})}async function vr(e={}){return k(`${Ae(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var nt,Ee,Sr,xe=R(()=>{$();U();ee();L();te();nt="https://li.quest/v1";Ee="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Sr="0x0000000000000000000000000000000000000000"});var ne={};ve(ne,{ACROSS_API:()=>ct,HOP_API:()=>ut,RELAY_API:()=>lt,acrossHealth:()=>Dr,acrossSuggestedFees:()=>dt,hopHealth:()=>Mr,hopQuote:()=>pt,relayHealth:()=>qr,relayPrepare:()=>Hr,relayQuote:()=>Ce});async function Dr(e={}){try{return{ok:!0,estimatedFillTimeSec:(await dt({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 dt(e={},t={}){let{token:r,destinationToken:n=r,originChainId:i,destinationChainId:o,amount:s}=e;if(!r||i==null||o==null||!s)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let a=new URLSearchParams({token:r,destinationToken:n,originChainId:String(i),destinationChainId:String(o),amount:String(s)}),f=(t.baseUrl||process.env.ACROSS_API_URL||ct).replace(/\/$/,"");return k(`${f}/suggested-fees?${a}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function Mr(e={}){try{let t=await pt({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 pt(e={},t={}){let{amount:r,token:n="ETH",fromChain:i="ethereum",toChain:o="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let s=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),a=M({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:i!==o,requestedCapBps:e.maxSlippageBps??e.slippageBps??s});if(!a.executable)throw new Error(`hop: route requires ${a.requiredBps} bps above cap ${a.capBps}`);let f=new URLSearchParams({amount:String(r),token:n,fromChain:i,toChain:o,slippage:String(a.selectedBps/100)}),d=(t.baseUrl||process.env.HOP_API_URL||ut).replace(/\/$/,""),p=await k(`${d}/quote?${f}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),c=p?.estimatedRecieved||p?.estimatedReceived;return c?P(p,{chainId:Number(e.originChainId||e.chainId||Fr[i]||0),venue:p?.tx?.to||"hop",amountOut:c,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:i!==o,requestedCapBps:e.maxSlippageBps??e.slippageBps??s}):{...p,autoSlippagePolicy:a}}async function qr(e={}){try{let t=await Ce({user:V,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=V,originChainId:n,destinationChainId:i,originCurrency:o="0x0000000000000000000000000000000000000000",destinationCurrency:s="0x0000000000000000000000000000000000000000",amount:a,tradeType:f="EXACT_INPUT"}=e;if(n==null||i==null||!a)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let d=M({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(i),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||lt).replace(/\/$/,""),c=await k(`${p}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(i),originCurrency:o,destinationCurrency:s,amount:String(a),tradeType:f,slippageTolerance:String(d.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),l=c?.details?.currencyOut?.amount;return!l||!/^\d+$/.test(String(l))?{...c,autoSlippagePolicy:d}:P(c,{chainId:Number(n),venue:c?.steps?.[0]?.items?.[0]?.data?.to||"relay",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(i),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Hr(e={},t={}){let r=await Ce(e,t),n=Number(e.originChainId),i=(r.steps||[]).flatMap(a=>(a.items||[]).filter(f=>f?.data?.to&&f?.data?.data).map(f=>({stepId:a.id,...f.data})));if(!i.length)throw new Error("relay: quote returned no executable transaction items");let o=String(r?.autoSlippage?.venue||"").toLowerCase();if(i.some(a=>String(a.to).toLowerCase()!==o))throw new Error("relay: route includes a separate approval/transaction that is not yet safely bound");let s=i.map(a=>({chainId:n,from:a.from||e.user,to:a.to,data:a.data,value:a.value??"0x0",...a.gasLimit!=null||a.gas!=null?{gasLimit:a.gasLimit??a.gas}:{},slippageGuard:D(r.autoSlippage,{chainId:n,venue:a.to,data:a.data})}));return _({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:r,autoSlippage:r.autoSlippage,transactions:s},{provider:"relay",kind:"relay-tx"})}var ct,ut,lt,Fr,oe=R(()=>{$();U();ee();L();ct="https://across.to/api",ut="https://api.hop.exchange/v1",lt="https://api.relay.link",Fr={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453}});var en=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),tn=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),rn=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var F=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"});var Oe=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function Ne(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:i=null,feeUsd:o=null,oracleFeeBps:s=0,estimatedGas:a=null,liquidityUsd:f=null,error:d=null,executionReady:p=!1,meta:c={}}=e||{};if(d||r==null)return{source:t,quality:F.FAILED,amountOut:null,error:d||"no amountOut returned"};let l=Oe(r);if(l==null||l<=0n)return{source:t,quality:F.FAILED,amountOut:null,error:"non-positive amountOut"};let u=Number(s);return{source:t,quality:i==null?F.NO_GAS:F.FULL,amountOut:l.toString(),minOut:Oe(n)?.toString()??null,gasUsd:i,feeUsd:o,oracleFeeBps:Number.isFinite(u)&&u>0?Math.floor(u):0,estimatedGas:a==null?null:String(a),liquidityUsd:f==null?null:Number(f),executionReady:p,meta:c}}function Te(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:i=50,gasPriceWei:o=null,nativePriceUsd:s=null}={}){let a=e.filter(h=>h.quality!==F.FAILED),f=e.filter(h=>h.quality===F.FAILED),d=t!=null&&t>0&&r!=null&&r>=0,p=Number(o),c=Number(s),l=Number.isFinite(p)&&p>0&&Number.isFinite(c)&&c>0,u=a.map(h=>{let A=BigInt(h.amountOut),I=0n,O=!1,B=!1,C=BigInt(h.oracleFeeBps??0),T=C>0n?A*C/10000n:0n;if(d){let Y=h.gasUsd,se=Number(h.meta?.gasUnits??h.estimatedGas);if(Y==null&&l&&Number.isFinite(se)&&se>0){let j=se*p/1e18*c;Number.isFinite(j)&&j>=0&&(Y=j,B=!0)}let ke=(Y??0)+(h.feeUsd??0);if(ke>0){let j=ke/t*10**r;Number.isFinite(j)&&j>=0&&(I=BigInt(Math.floor(j)),O=!0)}else Y===0&&(O=!0)}let X=I+T,gt=A>X?A-X:0n;return{...h,grossOut:A.toString(),netOut:gt.toString(),costInDest:I.toString(),oracleFeeInDest:T.toString(),costAccounted:O,gasEstimated:B}}),w=Number(i)>0?Number(i):0,y=u.reduce((h,A)=>BigInt(A.netOut)>h?BigInt(A.netOut):h,0n),m=h=>y>0n?Number((y-BigInt(h))*10000n/y):0,E=[],v=u.slice().sort((h,A)=>BigInt(A.netOut)>BigInt(h.netOut)?1:-1)[0]??null;u.sort((h,A)=>{let I=m(h.netOut)<=w?0:1,O=m(A.netOut)<=w?0:1;if(n&&w>0&&I!==O)return I-O;if(n&&w>0){let B=h.liquidityUsd??-1,C=A.liquidityUsd??-1;if(B!==C)return C-B}return BigInt(A.netOut)>BigInt(h.netOut)?1:-1}),n&&w>0&&v&&u[0]&&u[0].source!==v.source&&E.push(`liquidity-first: chose ${u[0].source} (liquidity $${u[0].liquidityUsd??"unknown"}) over best-price ${v.source} within ${w} bps`);let N=u.filter(h=>!h.costAccounted).map(h=>h.source);d?N.length&&E.push(`gas not reported by: ${N.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):E.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let b=u[0];if(d&&b&&b.costAccounted===!1){let h=u.find(A=>A.costAccounted&&m(A.netOut)<=w);h&&E.push(`winner ${b.source} has UNMEASURED gas; gas-measured ${h.source} is within ${w} bps and may net more once ${b.source}'s real gas is paid \u2014 prefer it if unsure.`)}let S=u.filter(h=>h.gasEstimated).map(h=>h.source);S.length&&E.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${S.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let x=null,g=null;if(u.length>=2&&u[0].costAccounted&&u[1].costAccounted){let h=BigInt(u[0].netOut),A=BigInt(u[1].netOut);A>0n&&(x=Number((h-A)*10000n/A),g=`${u[0].source} vs ${u[1].source}`)}return{best:u[0]??null,routes:u,failed:f,improvementBps:x,spreadBasis:g,rankedOn:d?"net-of-cost":"gross",warnings:E}}async function _e(e,{timeoutMs:t=12e3}={}){let r=(i,o)=>Promise.race([i,new Promise((s,a)=>setTimeout(()=>a(new Error(`${o}: timeout`)),t))]);return(await Promise.allSettled(e.map(i=>r(Promise.resolve().then(i.run),i.source)))).map((i,o)=>{let s=e[o].source;return i.status==="rejected"?Ne({source:s,error:String(i.reason?.message||i.reason)}):Ne({source:s,...i.value})})}xe();$();U();L();te();$();U();L();$();U();L();$();U();import{TypedDataEncoder as uo,getAddress as lo,isAddress as po}from"ethers";var oo=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});ee();L();var yo=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Eo=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var Ao=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"}]}),xo=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});import{Interface as st,getAddress as Ho,isAddress as jo}from"ethers";$();var it={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}},Io=new Map(Object.values(it).map(e=>[e.chainId,e]));import{Interface as Tr,getAddress as Bo}from"ethers";var Ro=new Tr(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);$();var Do=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});U();L();var Xo=new st(["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)"]),Yo=new st(["function exactInputSingle((address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)"]);import{AbiCoder as Rr,Interface as Se,getAddress as Zo,isAddress as ei,keccak256 as ti}from"ethers";U();L();var si=Rr.defaultAbiCoder();var ai=new Se(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountIn, uint256 gasEstimate)"]),ci=new Se(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),ui=new Se(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),li=Object.freeze([[13,"beforeInitialize"],[12,"afterInitialize"],[11,"beforeAddLiquidity"],[10,"afterAddLiquidity"],[9,"beforeRemoveLiquidity"],[8,"afterRemoveLiquidity"],[7,"beforeSwap"],[6,"afterSwap"],[5,"beforeDonate"],[4,"afterDonate"],[3,"beforeSwapReturnsDelta"],[2,"afterSwapReturnsDelta"],[1,"afterAddLiquidityReturnsDelta"],[0,"afterRemoveLiquidityReturnsDelta"]]),di=(1n<<14n)-1n;$();var Pr="https://coins.llama.fi",$r="https://api.llama.fi";function Lr(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Pr).replace(/\/$/,"")}function Ur(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||$r).replace(/\/$/,"")}async function Ie(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return k(`${Lr(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function at(e={}){return k(`${Ur(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var H=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function ft(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let i=H(n?.amountUSD);i!=null&&(t+=i,r=!0)}return r?t:null}var q=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),mt=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 jr(e={}){try{let t=await at({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function zr(e,t={}){let r=q(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...mt[r]||[r]),n.push(...mt[q(e)]||[e]),n}function Vr(e,t,r={}){let n=Array.isArray(e)?e:[],i=zr(t,r).map(q).filter(Boolean);for(let o of i){let s=n.find(f=>q(f?.slug)===o||q(f?.name)===o),a=H(s?.tvl);if(a!=null)return{liquidityUsd:a,protocol:s?.name??s?.slug??o}}for(let o of i){let s=n.find(f=>{let d=q(f?.category);return!d.includes("bridge")&&!d.includes("crosschain")?!1:q(f?.slug).includes(o)||q(f?.name).includes(o)}),a=H(s?.tvl);if(a!=null)return{liquidityUsd:a,protocol:s?.name??s?.slug??o}}return null}function ht({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:i,taker:o,opts:s={}}){let a=[],f=null,d=async(p,c={})=>(f||=jr(s),Vr(await f,p,c));return a.push({source:"lifi",run:async()=>{let p=await re({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:i},s),c=p?.estimate??p?.[0]?.estimate,l={tool:p?.tool??p?.toolDetails?.name,durationSeconds:H(c?.executionDuration)},u=await d("lifi",l);return{amountOut:c?.toAmount,minOut:c?.toAmountMin,gasUsd:ft(c?.gasCosts),feeUsd:ft(c?.feeCosts),oracleFeeBps:p?.oracleFee?.applies?p.oracleFee.bps:0,liquidityUsd:u?.liquidityUsd??null,meta:{...l,liquidityProtocol:u?.protocol,oracleFee:p?.oracleFee??null}}}}),a.push({source:"relay",run:async()=>{let{relayQuote:p}=await Promise.resolve().then(()=>(oe(),ne)),l=(await p({user:o,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(i)},s))?.details,u={durationSeconds:H(l?.timeEstimate),rate:l?.rate},w=await d("relay",u);return{amountOut:l?.currencyOut?.amount,minOut:l?.currencyOut?.minimumAmount,gasUsd:H(l?.totalImpact?.usd)!=null?Math.abs(H(l.totalImpact.usd)):null,liquidityUsd:w?.liquidityUsd??null,meta:{...u,liquidityProtocol:w?.protocol}}}}),a.push({source:"across",run:async()=>{let{acrossSuggestedFees:p}=await Promise.resolve().then(()=>(oe(),ne)),c=await p({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(i)},s),l=c?.totalRelayFee?.total,u=null;if(l!=null)try{let y=BigInt(String(i))-BigInt(String(l));y>0n&&(u=y.toString())}catch{}let w=await d("across");return{amountOut:u,gasUsd:null,liquidityUsd:w?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:H(c?.estimatedFillTimeSec),limits:c?.limits?{min:c.limits.minDeposit,max:c.limits.maxDeposit}:void 0,liquidityProtocol:w?.protocol}}}}),a}te();var Gr={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function Kr(e,t,r){let n=Gr[Number(e)];if(!n)return{priceUsd:null,decimals:null};let i=`${n}:${t}`;try{let s=(await Ie([i],r))?.coins?.[i],a=Number(s?.price),f=Number(s?.decimals);return{priceUsd:Number.isFinite(a)?a:null,decimals:Number.isFinite(f)?f:null}}catch{return{priceUsd:null,decimals:null}}}async function wt(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:i,tokenOut:o,amountIn:s}=e;if(r==null||n==null||!i||!o||s==null)throw new Error("bestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(r)===Number(n))throw new Error("bestBridgeRoute is for cross-chain; use bestSwapRoute for same-chain");let a=Kr(n,o,t),f=ht({...e,opts:t}),[d,p]=await Promise.all([_e(f,{timeoutMs:t.timeoutMs??15e3}),a]),c=Te(d,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50}),l=c.routes.map(u=>({source:u.source,seconds:u.meta?.durationSeconds??null})).filter(u=>u.seconds!=null);return{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:i,tokenOut:o,amountIn:String(s),...c,durations:l,sourcesTried:f.length,sourcesAnswered:d.filter(u=>u.quality!==F.FAILED).length,note:Yr(c,f.length)}}function Xr(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${et(t)}`:""}function Yr(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=Xr(e.best);if(r===1)return`only 1 of ${t} sources answered, so this is the ONLY route, not a proven best one. Treat it as unbenchmarked.`+n;if(e.improvementBps!=null){let i=e.improvementBps,o=i/100;if(i<.01)return`best of ${r} routes, ranked on ${e.rankedOn}: effectively tied with the runner-up (${e.spreadBasis}), inside quote noise. Re-quote before you size up.`+n;let s=o>=.01?`${o.toFixed(2)}%`:`${i.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${s} better than the runner-up (${e.spreadBasis})`+n}return`best of ${r} routes, ranked on ${e.rankedOn}. No spread quoted: the top routes report cost differently, so the margin is not comparable.`+n}L();var Wr=/^0x[0-9a-fA-F]{40}$/,Qr=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),Jr=100,ie={relay:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:i,taker:o},s)=>{let{relayPrepare:a}=await Promise.resolve().then(()=>(oe(),ne)),f=await a({user:o,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(i)},s);return{transactions:f.transactions||[],amountOut:f.quote?.details?.currencyOut?.amount??null,minOut:f.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:f.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:i,taker:o,isHolder:s},a)=>{let{lifiPrepare:f}=await Promise.resolve().then(()=>(xe(),ot)),d=await f({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:i,fromAddress:o,isHolder:s,feeAction:"bridge"},a);return{transactions:d.transaction?[d.transaction]:[],requiresApproval:d.requiresApproval??null,amountOut:d.quote?.estimate?.toAmount??null,minOut:d.quote?.estimate?.toAmountMin??null,durationSeconds:d.quote?.estimate?.executionDuration??null}}};function Ji(){return Object.keys(ie)}async function Zi(e,t={}){let{taker:r,fromChainId:n,toChainId:i}=e;if(!r)throw new Error("prepareBestBridgeRoute requires taker: bridge transactions are built FOR an address, and the quote-only placeholder must never end up in one");if(!Wr.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(Qr.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. Bridging to it would send funds to an address nobody controls, on a chain where you cannot undo it.`);let o=await wt(e,t);if(!o.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:o};let s=e.source||o.best.source,a=o.routes.find(m=>m.source===s);if(!a)return{ok:!1,reason:`source "${s}" returned no usable route`,comparison:o};let f=ie[s];if(!f){let m=o.routes.find(E=>ie[E.source]&&E.source!==s);return{ok:!1,reason:`${s} won the comparison but has no bridge prepare path in this build. `+(m?`Next preparable route is ${m.source}; pass source:"${m.source}".`:"No route in this comparison can be prepared."),failureKind:"no-prepare-path",...m?{alternative:m.source}:{},winner:s,comparison:o}}let d;try{d=await f(e,t)}catch(m){let E=typeof m?.body=="string"?m.body:m?.body?JSON.stringify(m.body):"",v=[String(m?.message||m),E].filter(Boolean).join(" :: "),N=/allowance/i.test(v),b=!N&&/not enough|insufficient|balance/i.test(v),S=o.routes.find(x=>ie[x.source]&&x.source!==s);return{ok:!1,reason:N?`${s} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${v}`:b?`${s} refused to build: ${v}. Quoting works for any address; preparing needs the real funded wallet on chain ${n}.`:`${s} bridge prepare failed: ${v}`,failureKind:N?"approval-required-first":b?"taker-not-funded":"provider-error",...S?{alternative:S.source}:{},comparison:o}}let p=d.transactions||[];if(!p.length)return{ok:!1,reason:`${s} returned no executable transaction for this route`,failureKind:"provider-error",comparison:o};let c=p.filter(m=>m.chainId!=null&&Number(m.chainId)!==Number(n));if(c.length)return{ok:!1,reason:`${s} returned a transaction for chain ${c[0].chainId} but the origin chain is ${n}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:o};let l=e.driftToleranceBps??Jr,u=null,w=null;if(d.amountOut!=null&&a.grossOut!=null)try{let m=BigInt(a.grossOut),E=BigInt(d.amountOut);m>0n&&(u=Number((E-m)*10000n/m),u<-l&&(w=`route moved ${(u/100).toFixed(2)}% against you since the comparison (tolerance ${(l/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let y=[...w?[w]:[],...o.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${i}. Expect ~${d.durationSeconds!=null?`${d.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];return p.length>1&&y.push(`This route needs ${p.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`),_({ok:!0,chosen:{source:s,wasWinner:s===o.best.source,netOut:a.netOut,grossOut:a.grossOut,gasUsd:a.gasUsd},artifactKind:"unsigned-transaction-sequence",fromChainId:Number(n),toChainId:Number(i),transactionCount:p.length,transactions:p,requiresApproval:d.requiresApproval??null,minOut:d.minOut??null,durationSeconds:d.durationSeconds??null,destination:p[0]?.to??null,unsigned:!0,signedBy:"user-wallet",driftBps:u,warnings:y,runnersUp:o.routes.filter(m=>m.source!==s).map(m=>({source:m.source,netOut:m.netOut,gasUsd:m.gasUsd})),comparison:{rankedOn:o.rankedOn,sourcesAnswered:o.sourcesAnswered,sourcesTried:o.sourcesTried,improvementBps:o.improvementBps},note:`UNSIGNED. ${p.length} transaction(s) on chain ${n}, crediting chain ${i}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge"})}export{Zi as prepareBestBridgeRoute,Ji as supportedBridgePreparers};
1
+ var Et=Object.defineProperty;var R=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var ve=(e,t)=>{for(var r in t)Et(e,r,{get:t[r],enumerable:!0})};import z from"node:net";import At from"node:dns";function W(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=f=>{if(!f)return[];let s=f.split(":"),u=s.at(-1);if(u?.includes(".")){let l=u.split(".").map(Number);if(l.length!==4||l.some(w=>!Number.isInteger(w)||w<0||w>255))return null;s.splice(s.length-1,1,(l[0]<<8|l[1]).toString(16),(l[2]<<8|l[3]).toString(16))}return s.some(l=>!/^[0-9a-f]{1,4}$/.test(l))?null:s.map(l=>Number.parseInt(l,16))},[n,i]=t.split("::"),o=r(n),a=r(i);if(!o||!a)return null;let c=t.includes("::"),p=8-o.length-a.length;if(!c&&p!==0||c&&p<1)return null;let d=[...o,...Array(Math.max(0,p)).fill(0),...a];return d.length!==8?null:Uint8Array.from(d.flatMap(f=>[f>>8,f&255]))}function se(e,t,r){let n=Math.floor(r/8),i=r%8;for(let a=0;a<n;a+=1)if(e[a]!==t[a])return!1;if(!i)return!0;let o=255<<8-i;return(e[n]&o)===(t[n]&o)}function ce(e){if(z.isIPv4(e)){let t=e.split(".").map(Number);return!(t[0]===0||t[0]===10||t[0]===127||t[0]>=224||t[0]===100&&t[1]>=64&&t[1]<=127||t[0]===169&&t[1]===254||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&(t[1]===0||t[1]===2||t[1]===168)||t[0]===192&&t[1]===88&&t[2]===99||t[0]===198&&(t[1]===18||t[1]===19||t[1]===51)||t[0]===203&&t[1]===0&&t[2]===113)}if(z.isIPv6(e)){let t=W(e);if(!t)return!1;let r=W("::ffff:0:0");return se(t,r,96)?ce([...t.slice(12)].join(".")):se(t,W("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([i,o])=>se(t,W(i),o)):!1}return!1}function St(e){let t;try{t=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,error:`refused protocol ${t.protocol} (only http/https)`};let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(xt.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=z.isIP(r);return n!==0&&!ce(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function ue(e,{lookupFn:t=At.promises.lookup}={}){let r=St(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:z.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(i=>!ce(i.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function le({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let s=await t();r=s.Agent,n=s.fetch}catch(s){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${s?.message||s}`);return null}if(typeof r!="function"||typeof n!="function"){if(e)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let i=s=>String(s).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,a=s=>(Array.isArray(s)?s:[s]).map(u=>typeof u=="string"?{address:u}:u).filter(u=>u&&u.address).map(u=>({address:u.address,family:u.family||(z.isIPv6(u.address)?6:4)})),c=(s,u,l)=>{o.set(i(s),a(typeof u=="string"?[{address:u,family:l}]:u))},p=s=>{let u=i(s);if(z.isIP(u))return[{address:u,family:z.isIPv6(u)?6:4}];let l=o.get(u);if(!l||!l.length)throw new Error(`refused: unpinned host ${s} during pinned fetch`);return l},d=new r({connect:{lookup(s,u,l){let w;try{w=p(s)}catch(y){return l(y)}return u?.all?l(null,w):l(null,w[0].address,w[0].family)}}}),f=It((s,u={})=>n(s,{...u,dispatcher:d}),c);return{dispatcher:d,fetch:f,pin:c,resolve:p,async close(){try{await d.destroy()}catch{}}}}function It(e,t){if(typeof e!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof t!="function")throw new Error("markPinCapableFetch: pin must be a function");return e[de]=Object.freeze({pin:t}),e}function pe(e){return typeof e=="function"&&typeof e[de]?.pin=="function"}function Be(e,t,r){if(!pe(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[de].pin(t,r)}var xt,de,Re=R(()=>{xt=new Set(["localhost","metadata.google.internal","metadata.goog"]);de=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as Pe}from"node:crypto";function Nt(e){let t=String(e||"").toLowerCase();return qe.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function _t(e){let t={};for(let[r,n]of Object.entries(e||{}))Nt(r)||(t[r]=n);return t}function Tt(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 Bt(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Ue(e){let t=String(e?.method||"");return t?!Rt.test(t):!1}function $t(e,t){if(e==="GET"&&t==null)return!0;if(e!=="POST"||t==null)return!1;let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{return!1}return Array.isArray(r)?r.length>0&&r.every(Ue):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?Ue(r):typeof r.type=="string"&&Pt.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function Lt(e,t,r,n={},i=null){let o={};for(let[u,l]of Object.entries(r||{}))o[u.toLowerCase()]=l;let a=Object.keys(o).filter(u=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(u)),p=[...new Set([...qe,...a])].sort().map(u=>`${u}=${o[u]??""}`).join(`
2
+ `),d=Pe("sha256").update(p).digest("hex").slice(0,32),f=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`,s=i==null?"-":Pe("sha256").update(String(i)).digest("hex").slice(0,32);return`${e} ${t} ${f} ${d} ${s}`}function Ft(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Le):Math.min(250*2**e,Le)+Math.floor(Math.random()*100)}function G(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function me(e,t,r){return G(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function K(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function Dt(e){return e?e.byteLength??e.length??0:0}async function De(e,t,{url:r,truncate:n=!1,onOversize:i}={}){if(t==null)return await e.text();let o=Number(e.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>t&&(K(e),!n))throw me(r,`content-length ${o}`,t);let a=e.body?.getReader?.();if(!a){let s=await e.text(),u=Buffer.byteLength(s,"utf8");if(u>t){if(!n)throw me(r,`body ${u} bytes`,t);return Buffer.from(s,"utf8").subarray(0,t).toString("utf8")}return s}let c=[],p=0,d=!1;try{for(;;){let{value:s,done:u}=await a.read();if(u)break;if(s&&(c.push(Buffer.from(s)),p+=Dt(s),p>t)){d=!0;break}}}finally{if(d)try{await a.cancel()}catch{}try{a.releaseLock?.()}catch{}}if(d&&(typeof i=="function"&&i(),!n))throw me(r,`streamed ${p} bytes`,t);let f=Buffer.concat(c);return(d?f.subarray(0,t):f).toString("utf8")}function Me(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function Mt(e,{fetchImpl:t,method:r,headers:n,body:i,timeoutMs:o,lookupFn:a,realFetch:c,untrustedUrl:p=!1,maxResponseBytes:d=null,importUndici:f,validateResponse:s,signal:u}){let l=new AbortController,w=setTimeout(()=>l.abort(),o),y=u?typeof AbortSignal.any=="function"?AbortSignal.any([u,l.signal]):u:l.signal,m=null,E=t,v=a?{lookupFn:a}:{};if(p&&!c&&!pe(E))throw G(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let N=async(b,{status:S=null}={})=>{let x=await ue(b,v);if(!x.ok)throw G(S==null?`HTTP refused ${b}: ${x.error}`:`HTTP redirect to ${b} ${x.error}`,S==null?{}:{status:S});let g=new URL(b).hostname;if(c){if(m&&(await m.close(),m=null),!m)try{m=await le({requireUndici:!0,...f?{importUndici:f}:{}})}catch(h){throw G(S==null?`HTTP refused ${b}: ${h?.message||h}`:`HTTP redirect to ${b} refused: ${h?.message||h}`,S==null?{}:{status:S})}m.pin(g,x.addresses),E=m.fetch}else Be(E,g,x.addresses);return x};try{let b=String(e),S={...n||{}};p&&await N(b);for(let x=0;x<=Fe;x+=1){let g=await E(b,{method:r,headers:S,body:i,signal:y,redirect:"manual"});if(vt.has(g.status)){if(r!=="GET"&&r!=="HEAD"){let C=await De(g,d??Ot,{url:b,truncate:!0}),_=new Error(`HTTP ${g.status} ${r} ${b} redirected non-idempotent request`);throw _.status=g.status,_.body=Me(C)??C.slice(0,300),_}if(x===Fe)throw K(g),new Error(`HTTP redirect loop for ${e}`);let I=g.headers?.get?.("location"),O;try{O=Tt(I,b)}catch(C){throw K(g),C}let B=!Bt(O,b);if(K(g),B&&(S=_t(S)),p)await N(O,{status:g.status});else if(B){let C=await ue(O,v);if(!C.ok){let _=new Error(`HTTP redirect from ${b} ${C.error}`);throw _.status=g.status,_.retryable=!1,_}c&&C.addresses?.length&&(m||(m=await le(f?{importUndici:f}:{})),m&&(m.pin(new URL(O).hostname,C.addresses),E=m.fetch))}b=O;continue}if(typeof s=="function")try{await s(g,{url:b})}catch(I){throw K(g),G(I?.message||String(I))}let h=await De(g,d,{url:b,onOversize:()=>l.abort()}),A=Me(h);if(!g.ok){let I=new Error(`HTTP ${g.status} ${r} ${b}`);throw I.status=g.status,I.retryAfter=g.headers?.get?.("retry-after")??null,I.body=A??h.slice(0,300),I}return A??h}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(w),m&&await m.close()}}async function k(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,i=(t.method||"GET").toUpperCase(),o={Accept:"application/json",...t.headers||{}},a=t.body;a!=null&&typeof a!="string"&&(o["Content-Type"]=o["Content-Type"]||"application/json",a=JSON.stringify(a));let c=Number.isInteger(t.retries)?Math.max(t.retries,0):kt,p=t.lookupFn,d=!t.fetchImpl,f=t.untrustedUrl===!0,s=t.importUndici,u=t.validateResponse,l=t.signal,w=Number(t.maxResponseBytes),y=Number.isFinite(w)&&w>0?Math.floor(w):null,m=async()=>{let S;for(let x=0;x<=c;x++){l?.throwIfAborted?.();try{return await Mt(e,{fetchImpl:r,method:i,headers:o,body:a,timeoutMs:n,lookupFn:p,realFetch:d,untrustedUrl:f,maxResponseBytes:y,importUndici:s,validateResponse:u,signal:l})}catch(g){S=g;let h=g?.status,A=g?.name==="AbortError"||g?.name==="TimeoutError"||l?.aborted,I=new Set([408,425,429]),O=g?.retryable===!1?!1:h!=null?I.has(h)||Ct.has(h)&&$e.has(i):!A&&$e.has(i);if(x===c||!O)throw g;let B=Ft(x,g?.retryAfter);l?await new Promise((C,_)=>{let X=setTimeout(C,B);l.addEventListener("abort",()=>{clearTimeout(X),_(l.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await Ut(B)}}throw S};if(!(t.dedupe!==!1&&!l&&$t(i,a)))return m();let v=Lt(i,e,o,{untrustedUrl:f,maxResponseBytes:y},a),N=fe.get(v);if(N)return N;let b=m().finally(()=>fe.delete(v));return fe.set(v,b),b}var Ct,$e,kt,Le,qe,vt,Fe,Ot,fe,Rt,Pt,Ut,$=R(()=>{Re();Ct=new Set([408,425,429,500,502,503,504]),$e=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),kt=2,Le=4e3,qe=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],vt=new Set([301,302,303,307,308]),Fe=3,Ot=64*1024;fe=new Map,Rt=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,Pt=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);Ut=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as qt}from"node:fs";import{homedir as Ht}from"node:os";import{join as Q}from"node:path";function jt(){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=Ht();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Q(t,".config","oracle")).trim();return[e,Q(r,"exec.env")].filter(Boolean)}return[e,Q(t,".config","oracle","exec.env"),Q(t,".config","mad-desk","exec.env")].filter(Boolean)}function He(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let i of jt())try{let o=qt(i,"utf8"),a=o.match(new RegExp(`^${t}=(.*)$`,"m"))||o.match(new RegExp(`^${r}=(.*)$`,"m"));if(a&&(n=a[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}var je=R(()=>{});var ze=R(()=>{});import{createHash as zt,createHmac as Ge,timingSafeEqual as Vt}from"node:crypto";function Z(e){return Array.isArray(e)?`[${e.map(Z).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Z(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Ke(e,{required:t=!1}={}){try{return He(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function we(e){let{signature:t,...r}=e;return r}function Xe(e,{secret:t}={}){let r=Ke(t);return r?{...e,signature:Ge("sha256",r).update(Z(we(e))).digest("hex")}:e}function Gt(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 zt("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function D(e,{chainId:t,venue:r,data:n,secret:i}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");if(Number(e.chainId)!==Number(t))throw new Error("auto-slippage guard chain mismatch");if(String(e.venue).toLowerCase()!==String(r||"").toLowerCase())throw new Error("auto-slippage guard venue mismatch");let o=Ke(i);if(o){let l=Ge("sha256",o).update(Z(we(e))).digest("hex");if(!Kt(e.signature,l))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let a=Number(e.selectedBps),c=Number(e.capBps);if(!Number.isInteger(a)||a<0||a>J||!Number.isInteger(c)||c<0||c>J||a>c)throw new Error("auto-slippage guard bounds are invalid");let p=BigInt(e.quoteAmountOut??0),d=BigInt(e.minAmountOut??0);if(p<=0n||d<=0n)throw new Error("auto-slippage guard amounts must be positive");let f=p*BigInt(1e4-a),s=f/10000n;if(f%10000n!==0n&&(s+=1n),d<s)throw new Error("auto-slippage guard is under-protected relative to its quote");let u=Wt(n);if(u!=null&&u!==d)throw new Error(`auto-slippage: calldata encodes floor ${u}, not the guard floor ${d} \u2014 refusing to bind`);return Xe({...we(e),calldataHash:Gt(n)},{secret:i})}function Kt(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:Vt(r,n)}function he(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function Xt(e){let t=e==null?J: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,J)}function M({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:i}={}){let o=he(e,0),a=o>0?o>=25e4?5:o>=1e5?10:o>=5e4?20:o>=1e4?40:70:n?30:10,c=Math.min(60,Math.abs(he(t,0))*2),p=Math.min(40,Math.floor(Math.max(0,he(r,0))/5e3)*5),d=Math.max(25,Math.ceil(20+a+c+p)),f=Xt(i);return{mode:"auto",requiredBps:d,selectedBps:Math.min(d,f),capBps:f,executable:d<=f}}function Yt({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:i=0,quoteAgeMs:o=0,crossChain:a=!1,requestedCapBps:c,quotedAtMs:p=Date.now(),ttlMs:d=Ve,secret:f}={}){let s=BigInt(r??0);if(s<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let u=M({liquidityUsd:n,priceChange5m:i,quoteAgeMs:o,crossChain:a,requestedCapBps:c});if(!u.executable)throw new Error(`auto-slippage requires ${u.requiredBps} bps above hard/requested cap ${u.capBps}; route blocked`);let l=Number(p);if(!Number.isFinite(l))throw new Error("auto-slippage: quotedAtMs must be a finite number");let w=Math.min(3e4,Math.max(1e3,Number(d)||Ve)),y=s*BigInt(1e4-u.selectedBps),m=y/10000n;if(y%10000n!==0n&&(m+=1n),m>s&&(m=s),s>0n&&m<=0n)throw new Error(`auto-slippage: quote ${s} is too small to express a ${u.selectedBps} bps floor without rounding to zero`);let E=Number((s-m)*10000n/(s===0n?1n:s));if(E>u.capBps)throw new Error(`auto-slippage: realised floor implies ${E} bps, above cap ${u.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Xe({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:s.toString(),minAmountOut:m.toString(),requiredBps:u.requiredBps,selectedBps:u.selectedBps,capBps:u.capBps,quotedAtMs:l,expiresAtMs:l+w},{secret:f})}function Wt(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let o=10;o+64<=t.length;o+=64)n.push(t.slice(o,o+64));let i=o=>n[o]==null?null:BigInt("0x"+n[o]);switch(r){case"0x414bf389":return i(6);case"0x04e45aaf":return i(5);case"0xc04b8d59":{let o=i(0);if(o==null)return null;let a=Number(o)/32;return!Number.isInteger(a)||a<0?null:i(a+4)}case"0xb858183f":{let o=i(0);if(o==null)return null;let a=Number(o)/32;return!Number.isInteger(a)||a<0?null:i(a+3)}case"0xa026383e":return i(6);case"0x38ed1739":case"0x5c11d795":return i(1);case"0x7ff36ab5":case"0xb6f9de95":return i(0);case"0x18cbafe5":case"0x791ac947":return i(1);default:return null}}function P(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:i,priceChange5m:o,crossChain:a,requestedCapBps:c,quotedAtMs:p=Date.now(),ttlMs:d}={}){let f=Yt({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:i,priceChange5m:o,crossChain:a,requestedCapBps:c,quotedAtMs:p,ttlMs:d});return{...e,autoSlippage:f,amountOutMinimum:f.minAmountOut}}var J,Ve,F=R(()=>{je();ze();J=100,Ve=2e4});var V,ee=R(()=>{V="0x000000000000000000000000000000000000dEaD"});import{createHash as Qt,createHmac as Jt,timingSafeEqual as _n}from"node:crypto";function ge(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ge).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${ge(e[r])}`).join(",")}}`}function Ye(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function We(e=process.env){return Ye(process.env)||Ye(e)}function rr(e){let{prepareHash:t,prepareMac:r,note:n,...i}=e||{};return i}function nr(e){let t=rr(e);return Qt("sha256").update(ge(t)).digest("hex")}function or(e,t=We()){return t?Jt("sha256",t).update(String(e)).digest("hex"):""}function T(e,{provider:t,kind:r,env:n=process.env,nowMs:i=Date.now(),expiresAtMs:o}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let a=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(a&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let c={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:a?e.oraclePrepared:!0};if(!c.provider)throw new Error("stampPrepared: provider required");if(!c.kind)throw new Error("stampPrepared: kind required");let p=Number(i),d=o==null?p+er:Number(o),f=d-p;if(!Number.isSafeInteger(p)||!Number.isSafeInteger(d)||f<=0||f>tr)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let u={...c,preparedAt:p,expiresAt:d,prepareVersion:Zt},l=nr(u),w=We(n),y=w?or(l,w):void 0,m={...u,prepareHash:l};return y&&(m.prepareMac=y),m}var Zt,er,tr,L=R(()=>{Zt=2,er=300*1e3,tr=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as ir,JsonRpcProvider as ar}from"ethers";function pr(e){return dr.test(String(e||""))}async function Qe(e,{contract:t=sr,rpc:r=ur,chainId:n=cr,balanceOf:i}={}){if(!pr(e))throw new Error("invalid-address");if(i)return BigInt(await i(e));let o=new ar(r,n,{staticNetwork:!0}),a=new ir(t,lr,o);return BigInt(await a.balanceOf(e))}var sr,cr,ur,lr,dr,Je=R(()=>{sr="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",cr=999,ur="https://rpc.hyperliquid.xyz/evm",lr=["function balanceOf(address owner) view returns (uint256)"],dr=/^0x[a-fA-F0-9]{40}$/});import{existsSync as fr,readFileSync as mr,lstatSync as hr}from"node:fs";import{homedir as Ze}from"node:os";import{join as be}from"node:path";function br(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(et,t)?et[t]:gr}function Sr(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[tt])return String(e[tt]);let t=e.ORACLE_CONFIG_DIR||be(Ze(),".config","oracle");return be(t,"fee-recipient")}return be(Ze(),".config","oracle","fee-recipient")}function Ir(e=process.env){try{let t=Sr(e);if(!fr(t)||hr(t).isSymbolicLink())return"";let r=mr(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function Cr(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),wr)}function kr({env:e=process.env,action:t="swap",admin:r=!1}={}){let n=String(e[Er]||"").trim(),i=String(e[Ar]||xr).trim();if(r===!0)return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"admin-oracle"};let o=br(t),a=Cr(e[yr],{fallback:n?o:0}),c=Math.min(a,o);if(!c)return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"no-recipient"};let p=Ir(e);return!p||p!==n.toLowerCase()?{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:c,recipient:n,integrator:i,action:t,applies:!0,reason:"configured"}}async function ye({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={},admin:i=!1}={}){let o=kr({env:t,action:r,admin:i});if(i===!0)return{...o,holderVerificationStatus:"admin-oracle"};let a=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(a))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await Qe(a,n))>0n?{...o,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...o,holderVerificationStatus:"non-holder"}}catch{return{...o,holderVerificationStatus:"unavailable"}}}function rt(e){return e?.applies?`Oracle routing fee ${e.bps} bps (${(e.bps/100).toFixed(2)}%) to ${e.recipient}.`:e?.reason==="admin-oracle"?"No Oracle fee (admin Oracle).":e?.reason==="locals-only-holder"?"No Oracle fee (Locals Only holder).":"No Oracle fee."}function nt(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}var wr,gr,et,yr,Er,Ar,tt,xr,te=R(()=>{Je();wr=100,gr=5,et=Object.freeze({swap:5,bridge:5,perps:0,nft:0});yr="ORACLE_INTEGRATOR_FEE_BPS",Er="ORACLE_INTEGRATOR_FEE_RECIPIENT",Ar="ORACLE_INTEGRATOR_ID",tt="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",xr="oracle"});var at={};ve(at,{LIFI_API:()=>it,lifiChains:()=>Tr,lifiHealth:()=>Nr,lifiPrepare:()=>_r,lifiQuote:()=>re});function Ae(e={}){return(e.baseUrl||process.env.LIFI_API_URL||it).replace(/\/$/,"")}function Or(e){let t=String(e||Ee).toLowerCase();return t===Ee.toLowerCase()||t===vr}function ot(e,t){let r=String(e||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(r))throw new Error(`lifi: ${t} must be a 20-byte address`);return r.toLowerCase()}async function Nr(e={}){let t=await k(`${Ae(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3}),r=Array.isArray(t)?t.length:t?.chains?.length||0;return{ok:r>0,chainCount:r}}async function re(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:i=Ee,toToken:o,fromAmount:a,fromAddress:c=V}=e;if(r==null||!o||!a)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let p=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:i,toToken:o,fromAmount:String(a),fromAddress:c}),d=M({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}`);p.set("slippage",String(d.selectedBps/1e4));let f=await ye({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[m,E]of Object.entries(nt(f)))p.set(m,E);let s=await k(`${Ae(t)}/quote?${p}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=s?.estimate?.toAmount||s?.toAmount;if(!u)return{...s,autoSlippagePolicy:d,oracleFee:f};let l=s?.transactionRequest?.to||s?.estimate?.approvalAddress||"lifi",w=P(s,{chainId:Number(r),venue:l,amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),y=s?.estimate?.toAmountMin||s?.toAmountMin;if(y!=null&&BigInt(y)<BigInt(w.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...w,oracleFee:f}}async function _r(e={},t={}){let r=await re(e,t),n=r?.transactionRequest;if(!n?.to||!n?.data)throw new Error("lifi: quote did not return an executable transactionRequest");let i=Number(e.fromChain);if(n.chainId!=null&&Number(n.chainId)!==i)throw new Error("lifi: transaction chain mismatch");if(e.fromAddress&&n.from&&String(n.from).toLowerCase()!==String(e.fromAddress).toLowerCase())throw new Error("lifi: transaction sender mismatch");let o=null;if(!Or(e.fromToken)){let a=r?.estimate?.approvalAddress||r?.approvalAddress;if(!a)throw new Error("lifi: ERC20 route missing approvalAddress");let c=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;o={token:ot(c,"approval token"),spender:ot(a,"approval spender"),amount:String(e.fromAmount)}}return T({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:i,quote:r,autoSlippage:r.autoSlippage,requiresApproval:o,transaction:{chainId:i,from:n.from||e.fromAddress,to:n.to,data:n.data,value:n.value??"0x0",...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:D(r.autoSlippage,{chainId:i,venue:n.to,data:n.data})}},{provider:"lifi",kind:"lifi-tx"})}async function Tr(e={}){return k(`${Ae(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var it,Ee,vr,xe=R(()=>{$();F();ee();L();te();it="https://li.quest/v1";Ee="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",vr="0x0000000000000000000000000000000000000000"});var ne={};ve(ne,{ACROSS_API:()=>lt,HOP_API:()=>dt,RELAY_API:()=>pt,acrossHealth:()=>jr,acrossSuggestedFees:()=>ft,hopHealth:()=>zr,hopQuote:()=>mt,relayHealth:()=>Vr,relayPrepare:()=>Gr,relayQuote:()=>Ce});async function jr(e={}){try{return{ok:!0,estimatedFillTimeSec:(await ft({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 ft(e={},t={}){let{token:r,destinationToken:n=r,originChainId:i,destinationChainId:o,amount:a}=e;if(!r||i==null||o==null||!a)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let c=new URLSearchParams({token:r,destinationToken:n,originChainId:String(i),destinationChainId:String(o),amount:String(a)}),p=(t.baseUrl||process.env.ACROSS_API_URL||lt).replace(/\/$/,"");return k(`${p}/suggested-fees?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function zr(e={}){try{let t=await mt({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 mt(e={},t={}){let{amount:r,token:n="ETH",fromChain:i="ethereum",toChain:o="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let a=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),c=M({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:i!==o,requestedCapBps:e.maxSlippageBps??e.slippageBps??a});if(!c.executable)throw new Error(`hop: route requires ${c.requiredBps} bps above cap ${c.capBps}`);let p=new URLSearchParams({amount:String(r),token:n,fromChain:i,toChain:o,slippage:String(c.selectedBps/100)}),d=(t.baseUrl||process.env.HOP_API_URL||dt).replace(/\/$/,""),f=await k(`${d}/quote?${p}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),s=f?.estimatedRecieved||f?.estimatedReceived;return s?P(f,{chainId:Number(e.originChainId||e.chainId||Hr[i]||0),venue:f?.tx?.to||"hop",amountOut:s,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:i!==o,requestedCapBps:e.maxSlippageBps??e.slippageBps??a}):{...f,autoSlippagePolicy:c}}async function Vr(e={}){try{let t=await Ce({user:V,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=V,originChainId:n,destinationChainId:i,originCurrency:o="0x0000000000000000000000000000000000000000",destinationCurrency:a="0x0000000000000000000000000000000000000000",amount:c,tradeType:p="EXACT_INPUT"}=e;if(n==null||i==null||!c)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let d=M({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(i),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!d.executable)throw new Error(`relay: route requires ${d.requiredBps} bps above cap ${d.capBps}`);let f=(t.baseUrl||process.env.RELAY_API_URL||pt).replace(/\/$/,""),s=await k(`${f}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(i),originCurrency:o,destinationCurrency:a,amount:String(c),tradeType:p,slippageTolerance:String(d.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=s?.details?.currencyOut?.amount;return!u||!/^\d+$/.test(String(u))?{...s,autoSlippagePolicy:d}:P(s,{chainId:Number(n),venue:s?.steps?.[0]?.items?.[0]?.data?.to||"relay",amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(i),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Gr(e={},t={}){let r=await Ce(e,t),n=Number(e.originChainId),i=(r.steps||[]).flatMap(c=>(c.items||[]).filter(p=>p?.data?.to&&p?.data?.data).map(p=>({stepId:c.id,...p.data})));if(!i.length)throw new Error("relay: quote returned no executable transaction items");let o=String(r?.autoSlippage?.venue||"").toLowerCase();if(i.some(c=>String(c.to).toLowerCase()!==o))throw new Error("relay: route includes a separate approval/transaction that is not yet safely bound");let a=i.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:D(r.autoSlippage,{chainId:n,venue:c.to,data:c.data})}));return T({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 lt,dt,pt,Hr,oe=R(()=>{$();F();ee();L();lt="https://across.to/api",dt="https://api.hop.exchange/v1",pt="https://api.relay.link",Hr={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453}});var on=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),an=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),sn=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var U=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"});var Oe=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function Ne(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:i=null,feeUsd:o=null,oracleFeeBps:a=0,estimatedGas:c=null,liquidityUsd:p=null,error:d=null,executionReady:f=!1,meta:s={}}=e||{};if(d||r==null)return{source:t,quality:U.FAILED,amountOut:null,error:d||"no amountOut returned"};let u=Oe(r);if(u==null||u<=0n)return{source:t,quality:U.FAILED,amountOut:null,error:"non-positive amountOut"};let l=Number(a);return{source:t,quality:i==null?U.NO_GAS:U.FULL,amountOut:u.toString(),minOut:Oe(n)?.toString()??null,gasUsd:i,feeUsd:o,oracleFeeBps:Number.isFinite(l)&&l>0?Math.floor(l):0,estimatedGas:c==null?null:String(c),liquidityUsd:p==null?null:Number(p),executionReady:f,meta:s}}function _e(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:i=50,gasPriceWei:o=null,nativePriceUsd:a=null}={}){let c=e.filter(h=>h.quality!==U.FAILED),p=e.filter(h=>h.quality===U.FAILED),d=t!=null&&t>0&&r!=null&&r>=0,f=Number(o),s=Number(a),u=Number.isFinite(f)&&f>0&&Number.isFinite(s)&&s>0,l=c.map(h=>{let A=BigInt(h.amountOut),I=0n,O=!1,B=!1,C=BigInt(h.oracleFeeBps??0),_=C>0n?A*C/10000n:0n;if(d){let Y=h.gasUsd,ae=Number(h.meta?.gasUnits??h.estimatedGas);if(Y==null&&u&&Number.isFinite(ae)&&ae>0){let j=ae*f/1e18*s;Number.isFinite(j)&&j>=0&&(Y=j,B=!0)}let ke=(Y??0)+(h.feeUsd??0);if(ke>0){let j=ke/t*10**r;Number.isFinite(j)&&j>=0&&(I=BigInt(Math.floor(j)),O=!0)}else Y===0&&(O=!0)}let X=I+_,yt=A>X?A-X:0n;return{...h,grossOut:A.toString(),netOut:yt.toString(),costInDest:I.toString(),oracleFeeInDest:_.toString(),costAccounted:O,gasEstimated:B}}),w=Number(i)>0?Number(i):0,y=l.reduce((h,A)=>BigInt(A.netOut)>h?BigInt(A.netOut):h,0n),m=h=>y>0n?Number((y-BigInt(h))*10000n/y):0,E=[],v=l.slice().sort((h,A)=>BigInt(A.netOut)>BigInt(h.netOut)?1:-1)[0]??null;l.sort((h,A)=>{let I=m(h.netOut)<=w?0:1,O=m(A.netOut)<=w?0:1;if(n&&w>0&&I!==O)return I-O;if(n&&w>0){let B=h.liquidityUsd??-1,C=A.liquidityUsd??-1;if(B!==C)return C-B}return BigInt(A.netOut)>BigInt(h.netOut)?1:-1}),n&&w>0&&v&&l[0]&&l[0].source!==v.source&&E.push(`liquidity-first: chose ${l[0].source} (liquidity $${l[0].liquidityUsd??"unknown"}) over best-price ${v.source} within ${w} bps`);let N=l.filter(h=>!h.costAccounted).map(h=>h.source);d?N.length&&E.push(`gas not reported by: ${N.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):E.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let b=l[0];if(d&&b&&b.costAccounted===!1){let h=l.find(A=>A.costAccounted&&m(A.netOut)<=w);h&&E.push(`winner ${b.source} has UNMEASURED gas; gas-measured ${h.source} is within ${w} bps and may net more once ${b.source}'s real gas is paid \u2014 prefer it if unsure.`)}let S=l.filter(h=>h.gasEstimated).map(h=>h.source);S.length&&E.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${S.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let x=null,g=null;if(l.length>=2&&l[0].costAccounted&&l[1].costAccounted){let h=BigInt(l[0].netOut),A=BigInt(l[1].netOut);A>0n&&(x=Number((h-A)*10000n/A),g=`${l[0].source} vs ${l[1].source}`)}return{best:l[0]??null,routes:l,failed:p,improvementBps:x,spreadBasis:g,rankedOn:d?"net-of-cost":"gross",warnings:E}}async function Te(e,{timeoutMs:t=12e3}={}){let r=(i,o)=>Promise.race([i,new Promise((a,c)=>setTimeout(()=>c(new Error(`${o}: timeout`)),t))]);return(await Promise.allSettled(e.map(i=>r(Promise.resolve().then(i.run),i.source)))).map((i,o)=>{let a=e[o].source;return i.status==="rejected"?Ne({source:a,error:String(i.reason?.message||i.reason)}):Ne({source:a,...i.value})})}xe();$();F();L();te();$();F();L();$();F();L();$();F();import{TypedDataEncoder as mo,getAddress as ho,isAddress as wo}from"ethers";var co=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});ee();L();var So=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Io=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var Co=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[]"}]});import{Interface as ct,getAddress as Go,isAddress as Ko}from"ethers";$();var st={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},Oo=new Map(Object.values(st).map(e=>[e.chainId,e]));import{Interface as Pr,getAddress as Lo}from"ethers";var Fo=new Pr(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);$();var jo=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});F();L();var Jo=new ct(["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)"]),Zo=new ct(["function exactInputSingle((address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)"]);import{AbiCoder as Fr,Interface as Se,getAddress as ni,isAddress as oi,keccak256 as ii}from"ethers";F();L();var li=Fr.defaultAbiCoder();var di=new Se(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountIn, uint256 gasEstimate)"]),pi=new Se(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),fi=new Se(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),mi=Object.freeze([[13,"beforeInitialize"],[12,"afterInitialize"],[11,"beforeAddLiquidity"],[10,"afterAddLiquidity"],[9,"beforeRemoveLiquidity"],[8,"afterRemoveLiquidity"],[7,"beforeSwap"],[6,"afterSwap"],[5,"beforeDonate"],[4,"afterDonate"],[3,"beforeSwapReturnsDelta"],[2,"afterSwapReturnsDelta"],[1,"afterAddLiquidityReturnsDelta"],[0,"afterRemoveLiquidityReturnsDelta"]]),hi=(1n<<14n)-1n;$();var Ur="https://coins.llama.fi",Dr="https://api.llama.fi";function Mr(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Ur).replace(/\/$/,"")}function qr(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||Dr).replace(/\/$/,"")}async function Ie(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return k(`${Mr(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function ut(e={}){return k(`${qr(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var H=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function ht(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let i=H(n?.amountUSD);i!=null&&(t+=i,r=!0)}return r?t:null}var q=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),wt=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 Kr(e={}){try{let t=await ut({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function Xr(e,t={}){let r=q(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...wt[r]||[r]),n.push(...wt[q(e)]||[e]),n}function Yr(e,t,r={}){let n=Array.isArray(e)?e:[],i=Xr(t,r).map(q).filter(Boolean);for(let o of i){let a=n.find(p=>q(p?.slug)===o||q(p?.name)===o),c=H(a?.tvl);if(c!=null)return{liquidityUsd:c,protocol:a?.name??a?.slug??o}}for(let o of i){let a=n.find(p=>{let d=q(p?.category);return!d.includes("bridge")&&!d.includes("crosschain")?!1:q(p?.slug).includes(o)||q(p?.name).includes(o)}),c=H(a?.tvl);if(c!=null)return{liquidityUsd:c,protocol:a?.name??a?.slug??o}}return null}function gt({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:i,taker:o,opts:a={}}){let c=[],p=null,d=async(f,s={})=>(p||=Kr(a),Yr(await p,f,s));return c.push({source:"lifi",run:async()=>{let f=await re({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:i},a),s=f?.estimate??f?.[0]?.estimate,u={tool:f?.tool??f?.toolDetails?.name,durationSeconds:H(s?.executionDuration)},l=await d("lifi",u);return{amountOut:s?.toAmount,minOut:s?.toAmountMin,gasUsd:ht(s?.gasCosts),feeUsd:ht(s?.feeCosts),oracleFeeBps:f?.oracleFee?.applies?f.oracleFee.bps:0,liquidityUsd:l?.liquidityUsd??null,meta:{...u,liquidityProtocol:l?.protocol,oracleFee:f?.oracleFee??null}}}}),c.push({source:"relay",run:async()=>{let{relayQuote:f}=await Promise.resolve().then(()=>(oe(),ne)),u=(await f({user:o,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(i)},a))?.details,l={durationSeconds:H(u?.timeEstimate),rate:u?.rate},w=await d("relay",l);return{amountOut:u?.currencyOut?.amount,minOut:u?.currencyOut?.minimumAmount,gasUsd:H(u?.totalImpact?.usd)!=null?Math.abs(H(u.totalImpact.usd)):null,liquidityUsd:w?.liquidityUsd??null,meta:{...l,liquidityProtocol:w?.protocol}}}}),c.push({source:"across",run:async()=>{let{acrossSuggestedFees:f}=await Promise.resolve().then(()=>(oe(),ne)),s=await f({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(i)},a),u=s?.totalRelayFee?.total,l=null;if(u!=null)try{let y=BigInt(String(i))-BigInt(String(u));y>0n&&(l=y.toString())}catch{}let w=await d("across");return{amountOut:l,gasUsd:null,liquidityUsd:w?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:H(s?.estimatedFillTimeSec),limits:s?.limits?{min:s.limits.minDeposit,max:s.limits.maxDeposit}:void 0,liquidityProtocol:w?.protocol}}}}),c}te();var Wr={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function Qr(e,t,r){let n=Wr[Number(e)];if(!n)return{priceUsd:null,decimals:null};let i=`${n}:${t}`;try{let a=(await Ie([i],r))?.coins?.[i],c=Number(a?.price),p=Number(a?.decimals);return{priceUsd:Number.isFinite(c)?c:null,decimals:Number.isFinite(p)?p:null}}catch{return{priceUsd:null,decimals:null}}}async function bt(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:i,tokenOut:o,amountIn:a}=e;if(r==null||n==null||!i||!o||a==null)throw new Error("bestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(r)===Number(n))throw new Error("bestBridgeRoute is for cross-chain; use bestSwapRoute for same-chain");let c=Qr(n,o,t),p=gt({...e,opts:t}),[d,f]=await Promise.all([Te(p,{timeoutMs:t.timeoutMs??15e3}),c]),s=_e(d,{destPriceUsd:f.priceUsd,destDecimals:e.decimalsOut??f.decimals,liquidityBandBps:t.liquidityBandBps??50}),u=s.routes.map(l=>({source:l.source,seconds:l.meta?.durationSeconds??null})).filter(l=>l.seconds!=null);return{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:i,tokenOut:o,amountIn:String(a),...s,durations:u,sourcesTried:p.length,sourcesAnswered:d.filter(l=>l.quality!==U.FAILED).length,note:Zr(s,p.length)}}function Jr(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${rt(t)}`:""}function Zr(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=Jr(e.best);if(r===1)return`only 1 of ${t} sources answered, so this is the ONLY route, not a proven best one. Treat it as unbenchmarked.`+n;if(e.improvementBps!=null){let i=e.improvementBps,o=i/100;if(i<.01)return`best of ${r} routes, ranked on ${e.rankedOn}: effectively tied with the runner-up (${e.spreadBasis}), inside quote noise. Re-quote before you size up.`+n;let a=o>=.01?`${o.toFixed(2)}%`:`${i.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${a} better than the runner-up (${e.spreadBasis})`+n}return`best of ${r} routes, ranked on ${e.rankedOn}. No spread quoted: the top routes report cost differently, so the margin is not comparable.`+n}L();var en=/^0x[0-9a-fA-F]{40}$/,tn=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),rn=100,ie={relay:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:i,taker:o},a)=>{let{relayPrepare:c}=await Promise.resolve().then(()=>(oe(),ne)),p=await c({user:o,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(i)},a);return{transactions:p.transactions||[],amountOut:p.quote?.details?.currencyOut?.amount??null,minOut:p.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:p.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:i,taker:o,isHolder:a},c)=>{let{lifiPrepare:p}=await Promise.resolve().then(()=>(xe(),at)),d=await p({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:i,fromAddress:o,isHolder:a,feeAction:"bridge"},c);return{transactions:d.transaction?[d.transaction]:[],requiresApproval:d.requiresApproval??null,amountOut:d.quote?.estimate?.toAmount??null,minOut:d.quote?.estimate?.toAmountMin??null,durationSeconds:d.quote?.estimate?.executionDuration??null}}};function ra(){return Object.keys(ie)}async function na(e,t={}){let{taker:r,fromChainId:n,toChainId:i}=e;if(!r)throw new Error("prepareBestBridgeRoute requires taker: bridge transactions are built FOR an address, and the quote-only placeholder must never end up in one");if(!en.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(tn.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. Bridging to it would send funds to an address nobody controls, on a chain where you cannot undo it.`);let o=await bt(e,t);if(!o.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:o};let a=e.source||o.best.source,c=o.routes.find(m=>m.source===a);if(!c)return{ok:!1,reason:`source "${a}" returned no usable route`,comparison:o};let p=ie[a];if(!p){let m=o.routes.find(E=>ie[E.source]&&E.source!==a);return{ok:!1,reason:`${a} won the comparison but has no bridge prepare path in this build. `+(m?`Next preparable route is ${m.source}; pass source:"${m.source}".`:"No route in this comparison can be prepared."),failureKind:"no-prepare-path",...m?{alternative:m.source}:{},winner:a,comparison:o}}let d;try{d=await p(e,t)}catch(m){let E=typeof m?.body=="string"?m.body:m?.body?JSON.stringify(m.body):"",v=[String(m?.message||m),E].filter(Boolean).join(" :: "),N=/allowance/i.test(v),b=!N&&/not enough|insufficient|balance/i.test(v),S=o.routes.find(x=>ie[x.source]&&x.source!==a);return{ok:!1,reason:N?`${a} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${v}`:b?`${a} refused to build: ${v}. Quoting works for any address; preparing needs the real funded wallet on chain ${n}.`:`${a} bridge prepare failed: ${v}`,failureKind:N?"approval-required-first":b?"taker-not-funded":"provider-error",...S?{alternative:S.source}:{},comparison:o}}let f=d.transactions||[];if(!f.length)return{ok:!1,reason:`${a} returned no executable transaction for this route`,failureKind:"provider-error",comparison:o};let s=f.filter(m=>m.chainId!=null&&Number(m.chainId)!==Number(n));if(s.length)return{ok:!1,reason:`${a} returned a transaction for chain ${s[0].chainId} but the origin chain is ${n}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:o};let u=e.driftToleranceBps??rn,l=null,w=null;if(d.amountOut!=null&&c.grossOut!=null)try{let m=BigInt(c.grossOut),E=BigInt(d.amountOut);m>0n&&(l=Number((E-m)*10000n/m),l<-u&&(w=`route moved ${(l/100).toFixed(2)}% against you since the comparison (tolerance ${(u/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let y=[...w?[w]:[],...o.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${i}. Expect ~${d.durationSeconds!=null?`${d.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];return f.length>1&&y.push(`This route needs ${f.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`),T({ok:!0,chosen:{source:a,wasWinner:a===o.best.source,netOut:c.netOut,grossOut:c.grossOut,gasUsd:c.gasUsd},artifactKind:"unsigned-transaction-sequence",fromChainId:Number(n),toChainId:Number(i),transactionCount:f.length,transactions:f,requiresApproval:d.requiresApproval??null,minOut:d.minOut??null,durationSeconds:d.durationSeconds??null,destination:f[0]?.to??null,unsigned:!0,signedBy:"user-wallet",driftBps:l,warnings:y,runnersUp:o.routes.filter(m=>m.source!==a).map(m=>({source:m.source,netOut:m.netOut,gasUsd:m.gasUsd})),comparison:{rankedOn:o.rankedOn,sourcesAnswered:o.sourcesAnswered,sourcesTried:o.sourcesTried,improvementBps:o.improvementBps},note:`UNSIGNED. ${f.length} transaction(s) on chain ${n}, crediting chain ${i}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge"})}export{na as prepareBestBridgeRoute,ra as supportedBridgePreparers};
@@ -1,4 +1,6 @@
1
- var O=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),y=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),m=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Re=/^0x[0-9a-fA-F]{40}$/;function Be(t={}){let e=[],r=[];if(!t||typeof t!="object")return{ok:!1,errors:["definition must be an object"],warnings:r};if((!Number.isInteger(t.chainId)||t.chainId<=0)&&e.push("chainId must be a positive integer"),(typeof t.key!="string"||!/^[a-z][a-z0-9-]*$/.test(t.key||""))&&e.push('key must be a lowercase slug (e.g. "base")'),(typeof t.name!="string"||!t.name.trim())&&e.push("name is required"),!Array.isArray(t.rpcEnv)||t.rpcEnv.length===0)e.push("rpcEnv must list at least one environment variable name");else for(let a of t.rpcEnv)(typeof a!="string"||!/^[A-Z][A-Z0-9_]*$/.test(a))&&e.push(`rpcEnv entry "${a}" should be an UPPER_SNAKE env var name`);if(t.nativeCurrency){let a=t.nativeCurrency;(typeof a.symbol!="string"||!a.symbol)&&e.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(a.decimals)||e.push("nativeCurrency.decimals must be an integer")}for(let[a,n]of(t.venues||[]).entries()){let s=`venues[${a}]`;if(!n||typeof n!="object"){e.push(`${s} must be an object`);continue}Re.test(n.address||"")||e.push(`${s}.address is not a valid 20-byte address`),/^0x0{40}$/.test(n.address||"")&&e.push(`${s}.address is the zero address -- placeholder left in place?`),n.kind||e.push(`${s}.kind is required (router|quoter|factory|...)`),n.verified?(n.verified.method||e.push(`${s}.verified.method is required`),n.verified.source||e.push(`${s}.verified.source is required`),n.verified.date||r.push(`${s}.verified.date missing -- add one so staleness is visible`)):e.push(`${s} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let o=t.capabilities||{};for(let a of Object.keys(o))O.includes(a)?typeof o[a]!="function"&&e.push(`capability "${a}" must be a function`):e.push(`unknown capability "${a}"`);return Object.keys(o).length===0&&r.push("scanner implements no capabilities -- it can only be registered, not used"),o.prepareUnsignedTx&&!o.quote&&r.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),o.prepareUnsignedTx&&!o.sellSimulation&&r.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:e.length===0,errors:e,warnings:r}}function Pe(t){let{ok:e,errors:r,warnings:o}=Be(t);if(!e)throw new Error(`invalid scanner for ${t?.key??"<unknown>"}:
1
+ var O=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),v=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),m=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),$e=/^0x[0-9a-fA-F]{40}$/;function De(t={}){let e=[],r=[];if(!t||typeof t!="object")return{ok:!1,errors:["definition must be an object"],warnings:r};if((!Number.isInteger(t.chainId)||t.chainId<=0)&&e.push("chainId must be a positive integer"),(typeof t.key!="string"||!/^[a-z][a-z0-9-]*$/.test(t.key||""))&&e.push('key must be a lowercase slug (e.g. "base")'),(typeof t.name!="string"||!t.name.trim())&&e.push("name is required"),!Array.isArray(t.rpcEnv)||t.rpcEnv.length===0)e.push("rpcEnv must list at least one environment variable name");else for(let a of t.rpcEnv)(typeof a!="string"||!/^[A-Z][A-Z0-9_]*$/.test(a))&&e.push(`rpcEnv entry "${a}" should be an UPPER_SNAKE env var name`);if(t.nativeCurrency){let a=t.nativeCurrency;(typeof a.symbol!="string"||!a.symbol)&&e.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(a.decimals)||e.push("nativeCurrency.decimals must be an integer")}for(let[a,n]of(t.venues||[]).entries()){let s=`venues[${a}]`;if(!n||typeof n!="object"){e.push(`${s} must be an object`);continue}$e.test(n.address||"")||e.push(`${s}.address is not a valid 20-byte address`),/^0x0{40}$/.test(n.address||"")&&e.push(`${s}.address is the zero address -- placeholder left in place?`),n.kind||e.push(`${s}.kind is required (router|quoter|factory|...)`),n.verified?(n.verified.method||e.push(`${s}.verified.method is required`),n.verified.source||e.push(`${s}.verified.source is required`),n.verified.date||r.push(`${s}.verified.date missing -- add one so staleness is visible`)):e.push(`${s} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let o=t.capabilities||{};for(let a of Object.keys(o))O.includes(a)?typeof o[a]!="function"&&e.push(`capability "${a}" must be a function`):e.push(`unknown capability "${a}"`);return Object.keys(o).length===0&&r.push("scanner implements no capabilities -- it can only be registered, not used"),o.prepareUnsignedTx&&!o.quote&&r.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),o.prepareUnsignedTx&&!o.sellSimulation&&r.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:e.length===0,errors:e,warnings:r}}function Ve(t){let{ok:e,errors:r,warnings:o}=De(t);if(!e)throw new Error(`invalid scanner for ${t?.key??"<unknown>"}:
2
2
  - ${r.join(`
3
- - `)}`);let a=t.capabilities||{},n=O.filter(u=>typeof a[u]=="function"),s={key:t.key,chainId:t.chainId,name:t.name,rpcEnv:[...t.rpcEnv],nativeCurrency:t.nativeCurrency?{...t.nativeCurrency}:null,wrappedNative:t.wrappedNative||null,explorer:t.explorer||null,venues:(t.venues||[]).map(u=>({...u})),warnings:o,capabilities(){return{chainId:t.chainId,key:t.key,supported:[...n],unsupported:O.filter(u=>!n.includes(u))}},supports(u){return n.includes(u)}};for(let u of O)n.includes(u)?s[u]=async(...l)=>a[u](...l,{scanner:s}):s[u]=async()=>{throw new Error(`${t.key} (chain ${t.chainId}) does not implement "${u}". 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(s)}var P=new Map;function z(t){let e=Pe(t);return P.set(e.chainId,e),e}function wt(t){return P.get(Number(t))||null}function gt(){return[...P.values()]}function Et(){P.clear()}function St(){let t={};for(let e of P.values())t[e.chainId]={key:e.key,name:e.name,...e.capabilities(),venueCount:e.venues.length,failClosed:e.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:P.size,capabilities:[...O],chains:t}}import{createHash as Ve}from"node:crypto";import R from"node:net";import Fe from"node:dns";var Oe=new Set(["localhost","metadata.google.internal","metadata.goog"]);function M(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=c=>{if(!c)return[];let i=c.split(":"),p=i.at(-1);if(p?.includes(".")){let h=p.split(".").map(Number);if(h.length!==4||h.some(f=>!Number.isInteger(f)||f<0||f>255))return null;i.splice(i.length-1,1,(h[0]<<8|h[1]).toString(16),(h[2]<<8|h[3]).toString(16))}return i.some(h=>!/^[0-9a-f]{1,4}$/.test(h))?null:i.map(h=>Number.parseInt(h,16))},[o,a]=e.split("::"),n=r(o),s=r(a);if(!n||!s)return null;let u=e.includes("::"),l=8-n.length-s.length;if(!u&&l!==0||u&&l<1)return null;let d=[...n,...Array(Math.max(0,l)).fill(0),...s];return d.length!==8?null:Uint8Array.from(d.flatMap(c=>[c>>8,c&255]))}function K(t,e,r){let o=Math.floor(r/8),a=r%8;for(let s=0;s<o;s+=1)if(t[s]!==e[s])return!1;if(!a)return!0;let n=255<<8-a;return(t[o]&n)===(e[o]&n)}function Q(t){if(R.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(R.isIPv6(t)){let e=M(t);if(!e)return!1;let r=M("::ffff:0:0");return K(e,r,96)?Q([...e.slice(12)].join(".")):K(e,M("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([a,n])=>K(e,M(a),n)):!1}return!1}function $e(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Oe.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let o=R.isIP(r);return o!==0&&!Q(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:o!==0}}async function G(t,{lookupFn:e=Fe.promises.lookup}={}){let r=$e(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:R.isIPv6(r.host)?6:4}]};let o;try{o=await e(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(o)||o.length===0||o.some(a=>!Q(a.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:o}}async function Y({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,o;try{let i=await e();r=i.Agent,o=i.fetch}catch(i){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${i?.message||i}`);return null}if(typeof r!="function"||typeof o!="function"){if(t)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let a=i=>String(i).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),n=new Map,s=i=>(Array.isArray(i)?i:[i]).map(p=>typeof p=="string"?{address:p}:p).filter(p=>p&&p.address).map(p=>({address:p.address,family:p.family||(R.isIPv6(p.address)?6:4)})),u=(i,p,h)=>{n.set(a(i),s(typeof p=="string"?[{address:p,family:h}]:p))},l=i=>{let p=a(i);if(R.isIP(p))return[{address:p,family:R.isIPv6(p)?6:4}];let h=n.get(p);if(!h||!h.length)throw new Error(`refused: unpinned host ${i} during pinned fetch`);return h},d=new r({connect:{lookup(i,p,h){let f;try{f=l(i)}catch(v){return h(v)}return p?.all?h(null,f):h(null,f[0].address,f[0].family)}}}),c=De((i,p={})=>o(i,{...p,dispatcher:d}),u);return{dispatcher:d,fetch:c,pin:u,resolve:l,async close(){try{await d.destroy()}catch{}}}}var X=Symbol.for("oracle.egressGuard.pinCapableFetch");function De(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[X]=Object.freeze({pin:e}),t}function J(t){return typeof t=="function"&&typeof t[X]?.pin=="function"}function ce(t,e,r){if(!J(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[X].pin(e,r)}var He=new Set([408,425,429,500,502,503,504]),ue=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Me=2,le=4e3,fe=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],je=new Set([301,302,303,307,308]),de=3,We=64*1024;function ze(t){let e=String(t||"").toLowerCase();return fe.includes(e)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(e)}function Ke(t){let e={};for(let[r,o]of Object.entries(t||{}))ze(r)||(e[r]=o);return e}function Qe(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let r=new URL(String(t),String(e));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${r.protocol}`);return r.toString()}function Ge(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var Z=new Map;function Ye(t,e,r,o={}){let a={};for(let[c,i]of Object.entries(r||{}))a[c.toLowerCase()]=i;let n=Object.keys(a).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),u=[...new Set([...fe,...n])].sort().map(c=>`${c}=${a[c]??""}`).join(`
4
- `),l=Ve("sha256").update(u).digest("hex").slice(0,32),d=`${o.untrustedUrl?"untrusted":"trusted"}:${o.maxResponseBytes??"unbounded"}`;return`${t} ${e} ${d} ${l}`}function Xe(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,le):Math.min(250*2**t,le)+Math.floor(Math.random()*100)}var Je=t=>new Promise(e=>setTimeout(e,t));function $(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function ee(t,e,r){return $(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function D(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function Ze(t){return t?t.byteLength??t.length??0:0}async function pe(t,e,{url:r,truncate:o=!1,onOversize:a}={}){if(e==null)return await t.text();let n=Number(t.headers?.get?.("content-length"));if(Number.isFinite(n)&&n>e&&(D(t),!o))throw ee(r,`content-length ${n}`,e);let s=t.body?.getReader?.();if(!s){let i=await t.text(),p=Buffer.byteLength(i,"utf8");if(p>e){if(!o)throw ee(r,`body ${p} bytes`,e);return Buffer.from(i,"utf8").subarray(0,e).toString("utf8")}return i}let u=[],l=0,d=!1;try{for(;;){let{value:i,done:p}=await s.read();if(p)break;if(i&&(u.push(Buffer.from(i)),l+=Ze(i),l>e)){d=!0;break}}}finally{if(d)try{await s.cancel()}catch{}try{s.releaseLock?.()}catch{}}if(d&&(typeof a=="function"&&a(),!o))throw ee(r,`streamed ${l} bytes`,e);let c=Buffer.concat(u);return(d?c.subarray(0,e):c).toString("utf8")}function he(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function et(t,{fetchImpl:e,method:r,headers:o,body:a,timeoutMs:n,lookupFn:s,realFetch:u,untrustedUrl:l=!1,maxResponseBytes:d=null,importUndici:c,validateResponse:i,signal:p}){let h=new AbortController,f=setTimeout(()=>h.abort(),n),v=p?typeof AbortSignal.any=="function"?AbortSignal.any([p,h.signal]):p:h.signal,b=null,k=e,x=s?{lookupFn:s}:{};if(l&&!u&&!J(k))throw $(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let L=async(S,{status:E=null}={})=>{let g=await G(S,x);if(!g.ok)throw $(E==null?`HTTP refused ${S}: ${g.error}`:`HTTP redirect to ${S} ${g.error}`,E==null?{}:{status:E});let w=new URL(S).hostname;if(u){if(b&&(await b.close(),b=null),!b)try{b=await Y({requireUndici:!0,...c?{importUndici:c}:{}})}catch(A){throw $(E==null?`HTTP refused ${S}: ${A?.message||A}`:`HTTP redirect to ${S} refused: ${A?.message||A}`,E==null?{}:{status:E})}b.pin(w,g.addresses),k=b.fetch}else ce(k,w,g.addresses);return g};try{let S=String(t),E={...o||{}};l&&await L(S);for(let g=0;g<=de;g+=1){let w=await k(S,{method:r,headers:E,body:a,signal:v,redirect:"manual"});if(je.has(w.status)){if(r!=="GET"&&r!=="HEAD"){let U=await pe(w,d??We,{url:S,truncate:!0}),_=new Error(`HTTP ${w.status} ${r} ${S} redirected non-idempotent request`);throw _.status=w.status,_.body=he(U)??U.slice(0,300),_}if(g===de)throw D(w),new Error(`HTTP redirect loop for ${t}`);let C=w.headers?.get?.("location"),N;try{N=Qe(C,S)}catch(U){throw D(w),U}let F=!Ge(N,S);if(D(w),F&&(E=Ke(E)),l)await L(N,{status:w.status});else if(F){let U=await G(N,x);if(!U.ok){let _=new Error(`HTTP redirect from ${S} ${U.error}`);throw _.status=w.status,_.retryable=!1,_}u&&U.addresses?.length&&(b||(b=await Y(c?{importUndici:c}:{})),b&&(b.pin(new URL(N).hostname,U.addresses),k=b.fetch))}S=N;continue}if(typeof i=="function")try{await i(w,{url:S})}catch(C){throw D(w),$(C?.message||String(C))}let A=await pe(w,d,{url:S,onOversize:()=>h.abort()}),I=he(A);if(!w.ok){let C=new Error(`HTTP ${w.status} ${r} ${S}`);throw C.status=w.status,C.retryAfter=w.headers?.get?.("retry-after")??null,C.body=I??A.slice(0,300),C}return I??A}throw new Error(`HTTP redirect loop for ${t}`)}finally{clearTimeout(f),b&&await b.close()}}async function j(t,e={}){let r=e.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let o=e.timeoutMs??12e3,a=(e.method||"GET").toUpperCase(),n={Accept:"application/json",...e.headers||{}},s=e.body;s!=null&&typeof s!="string"&&(n["Content-Type"]=n["Content-Type"]||"application/json",s=JSON.stringify(s));let u=Number.isInteger(e.retries)?Math.max(e.retries,0):Me,l=e.lookupFn,d=!e.fetchImpl,c=e.untrustedUrl===!0,i=e.importUndici,p=e.validateResponse,h=e.signal,f=Number(e.maxResponseBytes),v=Number.isFinite(f)&&f>0?Math.floor(f):null,b=async()=>{let E;for(let g=0;g<=u;g++){h?.throwIfAborted?.();try{return await et(t,{fetchImpl:r,method:a,headers:n,body:s,timeoutMs:o,lookupFn:l,realFetch:d,untrustedUrl:c,maxResponseBytes:v,importUndici:i,validateResponse:p,signal:h})}catch(w){E=w;let A=w?.status,I=w?.name==="AbortError"||w?.name==="TimeoutError"||h?.aborted,C=new Set([408,425,429]),N=w?.retryable===!1?!1:A!=null?C.has(A)||He.has(A)&&ue.has(a):!I&&ue.has(a);if(g===u||!N)throw w;let F=Xe(g,w?.retryAfter);h?await new Promise((U,_)=>{let _e=setTimeout(U,F);h.addEventListener("abort",()=>{clearTimeout(_e),_(h.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await Je(F)}}throw E};if(!(e.dedupe!==!1&&!h&&a==="GET"&&s==null))return b();let x=Ye(a,t,n,{untrustedUrl:c,maxResponseBytes:v}),L=Z.get(x);if(L)return L;let S=b().finally(()=>Z.delete(x));return Z.set(x,S),S}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}},tt=new Map(Object.values(me).map(t=>[t.chainId,t]));function be(t){return tt.get(Number(t))||null}function ve(t,e=process.env){let r=be(t);if(!r)return null;for(let o of r.rpcEnv){let a=(e[o]||"").trim();if(a)return a}return null}import{Interface as rt,getAddress as nt}from"ethers";var ye=new rt(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function we(t,e){try{return nt(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var ot={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 at(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let o=ve(t,r);return o||ot[Number(t)]||null}var st=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function it(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!st.test(r))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}async function q(t,e,r=[],o={}){let a=String(e||"");it(a);let n=at(t,o);if(!n)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);let u=await j(n,{method:"POST",body:{jsonrpc:"2.0",id:1,method:e,params:r},fetchImpl:o.fetchImpl,timeoutMs:o.timeoutMs??12e3,signal:o.signal});if(u?.error){let l=new Error(u.error.message||JSON.stringify(u.error));throw l.code=u.error.code,l}return u.result}async function ge(t,e={}){let r=await q(t,"eth_blockNumber",[],e);return parseInt(r,16)}async function Ee(t,e,r={}){if(!e)throw new Error("rpcGetBalance requires address");let o=await q(t,"eth_getBalance",[e,"latest"],r);return{chainId:Number(t),address:e,balanceWei:BigInt(o).toString(),balanceHex:o}}async function Se(t={},e={}){let r=Number(t.chainId??e.chainId??1),o=we(t.token||t.tokenAddress,"token"),a=we(t.account||t.owner||t.address,"account"),n=ye.encodeFunctionData("balanceOf",[a]),s=await q(r,"eth_call",[{to:o,data:n},t.blockTag||"latest"],e),u=ye.decodeFunctionResult("balanceOf",s),l=BigInt(u[0]);return{chainId:r,token:o,account:a,balance:l.toString(),balanceHex:`0x${l.toString(16)}`,blockTag:t.blockTag||"latest"}}var ct=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function Ce(t,e){let r=String(t||"").toLowerCase(),o=String(e?.quote||e?.quoteToken?.address||"").toLowerCase(),a=String(e?.base||e?.baseToken?.address||"").toLowerCase();return o===r?{address:e.base||e.baseToken?.address,symbol:e.baseToken?.symbol}:a===r?{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}:{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}}function te(t,e=[],{stables:r=[],wrappedNative:o=null}={}){let a=String(t||"").toLowerCase(),n=new Set((r||[]).map(l=>String(l).toLowerCase())),s=String(o||"").toLowerCase(),u=(e||[]).map((l,d)=>{let c=Ce(a,l),i=String(c.address||"").toLowerCase(),p=String(c.symbol||"").toLowerCase(),h=Number(l.liquidityUsd??l.liquidity?.usd),f=Number.isFinite(h)?h:0,v=String(l.dex||l.dexId||"").toLowerCase(),b=0;return n.has(i)||ct.has(p)?b=300:s&&i===s&&(b=100),v.includes("v4")?b+=20:v.includes("v3")?b+=10:(v.includes("v2")||v.includes("raydium")||v.includes("orca")||v.includes("meteora"))&&(b+=8),{pool:l,score:b*1e12+f,index:d,otherAddr:i,liquidityUsd:f}});return u.sort((l,d)=>d.score-l.score||l.index-d.index),u.map(l=>l.pool)}function Ae(t,e=[]){let r=Array.isArray(e)?e:[];return r.length&&Ce(t,r[0]).address||null}var ut="https://api.dexscreener.com",$t=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function lt(t={}){return(t.baseUrl||process.env.DEXSCREENER_API_URL||ut).replace(/\/$/,"")}async function xe(t,e={}){if(!t)throw new Error("tokenAddress required");return j(`${lt(e)}/latest/dex/tokens/${t}`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var ne={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},T=t=>BigInt(t).toString(16).padStart(64,"0"),V=t=>t.slice(2).toLowerCase().padStart(64,"0");function dt(t,e){return`0x${ne.getAmountsOut}`+T(t)+T(64)+T(e.length)+e.map(V).join("")}function pt(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length<128)return null;let r=Number(BigInt(`0x${e.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let o=[];for(let a=0;a<r;a++){let n=128+a*64;if(e.length<n+64)return null;o.push(BigInt(`0x${e.slice(n,n+64)}`))}return o}function re(t,e="router"){return(t?.venues||[]).find(o=>o.kind===e)?.address??null}var oe=100;function ht(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>oe)throw new Error(`slippageBps ${r} exceeds the ${oe} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function Ie(t){let{chainId:e,wrappedNative:r}=t;async function o(a,n,s,u){let l=await q(e,"eth_call",[{to:a,data:dt(n,s)},"latest"],u);return pt(l?.result??l)}return{async quote({tokenIn:a,tokenOut:n,amountIn:s,path:u},l={}){let d=re(l.scanner);if(!d)return{chainId:e,evidence:y.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let c=u||[a,n];if(c.some(p=>!/^0x[0-9a-fA-F]{40}$/.test(p||"")))throw new Error("quote requires valid 20-byte addresses");let i=await o(d,s,c,l);return i?{chainId:e,router:d,path:c,amountIn:String(s),amountOut:i[i.length-1].toString(),hops:c.length-1,evidence:y.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:d,path:c,evidence:y.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:a,amountIn:n,base:s},u={}){let l=re(u.scanner),d=s||r;if(d&&String(a).toLowerCase()===String(d).toLowerCase())return{chainId:e,token:a,verdict:m.UNKNOWN,evidence:y.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!l||!d)return{chainId:e,token:a,verdict:m.UNKNOWN,evidence:y.UNAVAILABLE,reason:l?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let c=await o(l,n,[d,a],u);if(!c)return{chainId:e,token:a,verdict:m.FAIL,evidence:y.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let i=c[c.length-1];if(i===0n)return{chainId:e,token:a,verdict:m.FAIL,evidence:y.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await o(l,i,[a,d],u);if(!p)return{chainId:e,token:a,verdict:m.FAIL,evidence:y.LIVE,leg:"sell",bought:i.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=p[p.length-1],f=Number(h*10000n/BigInt(n)),v=m.PASS,b="round trip completes with expected fee/impact loss";return f<5e3?(v=m.FAIL,b=`round trip returns only ${(f/100).toFixed(2)}% -- punitive tax or no real liquidity`):f<9e3&&(v=m.CAUTION,b=`round trip returns ${(f/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:a,base:d,router:l,verdict:v,reason:b,amountIn:String(n),bought:i.toString(),returned:h.toString(),retentionBps:f,evidence:y.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:a,tokenOut:n,amountIn:s,recipient:u,slippageBps:l=50,deadlineSeconds:d=900,path:c},i={}){let p=i.scanner,h=re(p);if(!h)throw new Error(`chain ${e} 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(u||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=c||[a,n],v=await this.quote({tokenIn:a,tokenOut:n,amountIn:s,path:f},i);if(v.evidence!==y.LIVE)throw new Error(`cannot prepare without a live quote (${v.evidence}: ${v.reason??"no reason given"})`);let b=ht(v.amountOut,l);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let k=BigInt(Math.floor(Date.now()/1e3)+Number(d)),x=r&&f[0].toLowerCase()===r.toLowerCase()&&i.useNative,L=x?`0x${ne.swapExactETHForTokens}`+T(b)+T(128)+V(u)+T(k)+T(f.length)+f.map(V).join(""):`0x${ne.swapExactTokensForTokens}`+T(s)+T(b)+T(160)+V(u)+T(k)+T(f.length)+f.map(V).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:h,data:L,value:x?`0x${BigInt(s).toString(16)}`:"0x0"},guard:{quotedOut:v.amountOut,minOut:b.toString(),slippageBps:l,maxSlippageBps:oe,deadline:k.toString()},requires:x?[]:[{step:"approve",token:f[0],spender:h,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 ft=[100,500,3e3,1e4],Ne={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},B=t=>BigInt(t).toString(16).padStart(64,"0"),H=t=>t.slice(2).toLowerCase().padStart(64,"0"),ke=/^0x[0-9a-fA-F]{40}$/,se=100;function mt(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>se)throw new Error(`slippageBps ${r} exceeds the ${se} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function ae(t,e){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}function Te(t){let{chainId:e,wrappedNative:r}=t;async function o({quoter:n,tokenIn:s,tokenOut:u,amountIn:l,fee:d},c){let i=`0x${Ne.quoteExactInputSingle}`+H(s)+H(u)+B(l)+B(d)+B(0),p=await q(e,"eth_call",[{to:n,data:i},"latest"],c).catch(()=>null),h=p?.result??p;if(!h||h==="0x"||h.length<66)return null;let f=BigInt(`0x${h.slice(2,66)}`);return f>0n?f:null}async function a({quoter:n,tokenIn:s,tokenOut:u,amountIn:l},d){let c=[],i=null;for(let p of ft){let h=await o({quoter:n,tokenIn:s,tokenOut:u,amountIn:l,fee:p},d);c.push({fee:p,amountOut:h?h.toString():null}),h&&(!i||h>i.amountOut)&&(i={fee:p,amountOut:h})}return{best:i,tried:c}}return{async quote({tokenIn:n,tokenOut:s,amountIn:u},l={}){let d=ae(l.scanner,"quoter");if(!d)return{chainId:e,evidence:y.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let p of[n,s])if(!ke.test(p||""))throw new Error("quote requires valid 20-byte addresses");let{best:c,tried:i}=await a({quoter:d,tokenIn:n,tokenOut:s,amountIn:u},l);return c?{chainId:e,venue:"uniswap-v3",quoter:d,tokenIn:n,tokenOut:s,amountIn:String(u),amountOut:c.amountOut.toString(),fee:c.fee,useNative:!!r&&String(n).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:i,evidence:y.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:e,quoter:d,tokenIn:n,tokenOut:s,triedFeeTiers:i,evidence:y.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:n,amountIn:s,base:u},l={}){let d=ae(l.scanner,"quoter"),c=(t.stableQuoteAssets||[]).map(E=>String(E).toLowerCase()),i=null;!u&&typeof t.resolveQuoteAsset=="function"&&(i=await t.resolveQuoteAsset(n,l).catch(()=>null));let p=String(n).toLowerCase(),h=String(r||"").toLowerCase();if(h&&p===h)return{chainId:e,token:n,verdict:m.UNKNOWN,evidence:y.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let f=u||i||(c[0]&&p!==c[0]?c[0]:null)||r;if(f&&p===String(f).toLowerCase())return{chainId:e,token:n,verdict:m.UNKNOWN,evidence:y.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!d||!f)return{chainId:e,token:n,verdict:m.UNKNOWN,evidence:y.UNAVAILABLE,reason:d?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let v=await a({quoter:d,tokenIn:f,tokenOut:n,amountIn:s},l);if(!v.best){let E=c.find(g=>g&&g!==String(f).toLowerCase()&&g!==String(n).toLowerCase());if(E){let g=await a({quoter:d,tokenIn:E,tokenOut:n,amountIn:s},l);if(g.best){let w=await a({quoter:d,tokenIn:n,tokenOut:E,amountIn:g.best.amountOut},l);if(w.best){let A=w.best.amountOut,I=Number(A*10000n/BigInt(s)),C=m.PASS,N="round trip vs dollar book completes with expected fee/impact loss";return I<5e3?(C=m.FAIL,N=`round trip vs dollar book returns only ${(I/100).toFixed(2)}% -- punitive tax or no real liquidity`):I<9e3&&(C=m.CAUTION,N=`round trip vs dollar book returns ${(I/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:n,base:E,quoteAsset:E,verdict:C,reason:N,amountIn:String(s),bought:g.best.amountOut.toString(),returned:A.toString(),retentionBps:I,buyFee:g.best.fee,sellFee:w.best.fee,evidence:y.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:e,token:n,verdict:m.FAIL,evidence:y.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let b=await a({quoter:d,tokenIn:n,tokenOut:f,amountIn:v.best.amountOut},l);if(!b.best){let E=c.find(g=>g&&g!==String(f).toLowerCase()&&g!==String(n).toLowerCase());if(E){let g=await a({quoter:d,tokenIn:E,tokenOut:n,amountIn:s},l),w=g.best?await a({quoter:d,tokenIn:n,tokenOut:E,amountIn:g.best.amountOut},l):{best:null};if(g.best&&w.best){let A=w.best.amountOut,I=Number(A*10000n/BigInt(s)),C=m.PASS,N="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return I<5e3?(C=m.FAIL,N=`dollar-book round trip returns only ${(I/100).toFixed(2)}%`):I<9e3&&(C=m.CAUTION,N=`dollar-book round trip returns ${(I/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:n,base:E,quoteAsset:E,verdict:C,reason:N,amountIn:String(s),bought:g.best.amountOut.toString(),returned:A.toString(),retentionBps:I,buyFee:g.best.fee,sellFee:w.best.fee,evidence:y.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:e,token:n,verdict:m.FAIL,evidence:y.LIVE,leg:"sell",bought:v.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let k=b.best.amountOut,x=Number(k*10000n/BigInt(s)),L=m.PASS,S="round trip completes with expected fee/impact loss";return x<5e3?(L=m.FAIL,S=`round trip returns only ${(x/100).toFixed(2)}% -- punitive tax or no real liquidity`):x<9e3&&(L=m.CAUTION,S=`round trip returns ${(x/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:n,base:f,verdict:L,reason:S,amountIn:String(s),bought:v.best.amountOut.toString(),returned:k.toString(),retentionBps:x,buyFee:v.best.fee,sellFee:b.best.fee,evidence:y.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:n,tokenOut:s,amountIn:u,recipient:l,slippageBps:d=50,fee:c},i={}){let p=ae(i.scanner,"router");if(!p)throw new Error(`chain ${e} 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(!ke.test(l||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=await this.quote({tokenIn:n,tokenOut:s,amountIn:u},i);if(h.evidence!==y.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let f=c??h.fee,v=mt(h.amountOut,d);if(v<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(i.useNative||h.useNative)&&r&&String(n).toLowerCase()===String(r).toLowerCase(),k=`0x${Ne.exactInputSingle}`+H(n)+H(s)+B(f)+H(l)+B(u)+B(v)+B(0);return{unsigned:!0,signedBy:"user-wallet",chainId:e,venue:"uniswap-v3",tx:{to:p,data:k,value:b?String(u):"0x0"},guard:{quotedOut:h.amountOut,minOut:v.toString(),slippageBps:d,maxSlippageBps:se,fee:f},requires:b?[]:[{step:"approve",token:n,spender:p,amount:String(u)}],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 W={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Le(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function Ue(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length>=128){let o=Number(BigInt(`0x${e.slice(64,128)}`));if(o>0&&o<=256&&e.length>=128+o*2){let a=e.slice(128,128+o*2),n=Buffer.from(a,"hex").toString("utf8").replace(/\0+$/,"");if(n)return n}}return Buffer.from(e.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function bt(t){let{chainId:e}=t;async function r(o,a,n){return q(e,"eth_call",[{to:o,data:a},"latest"],n)}return{async blockNumber(o={}){let a=await ge(e,o);return{chainId:e,blockNumber:a?.blockNumber??a,evidence:y.LIVE}},async nativeBalance(o,a={}){let n=await Ee(e,o,a);return{chainId:e,address:o,wei:n?.wei??n?.balance??null,symbol:t.nativeCurrency?.symbol??null,decimals:t.nativeCurrency?.decimals??18,evidence:y.LIVE}},async tokenBalance({token:o,owner:a},n={}){let s=await Se({chainId:e,token:o,owner:a},n);return{chainId:e,token:o,owner:a,raw:s?.balance??s,evidence:y.LIVE}},async resolveToken(o,a={}){if(!/^0x[0-9a-fA-F]{40}$/.test(o||""))return{chainId:e,token:o,evidence:y.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[n,s,u,l]=await Promise.all([r(o,W.decimals,a).catch(()=>null),r(o,W.symbol,a).catch(()=>null),r(o,W.name,a).catch(()=>null),r(o,W.totalSupply,a).catch(()=>null)]),d=Le(n?.result??n),c=d!==null||s?.result||u?.result;return{chainId:e,address:o,decimals:d===null?null:Number(d),symbol:Ue(s?.result??s),name:Ue(u?.result??u),totalSupply:(Le(l?.result??l)??null)?.toString()??null,evidence:c?y.LIVE:y.UNKNOWN,warning:c?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(o,a={}){let n=t.dexscreenerSlug;if(!n)return{chainId:e,token:o,pools:[],evidence:y.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let s=await xe(o,a).catch(()=>null),l=(s?.pairs||s?.data?.pairs||[]).filter(c=>String(c.chainId).toLowerCase()===String(n).toLowerCase()).map(c=>({pair:c.pairAddress,dex:c.dexId,base:c.baseToken?.address,quote:c.quoteToken?.address,liquidityUsd:c.liquidity?.usd??null,priceUsd:c.priceUsd??null,volume24hUsd:c.volume?.h24??null,createdAt:c.pairCreatedAt??null})).sort((c,i)=>(i.liquidityUsd??0)-(c.liquidityUsd??0)),d=te(o,l,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:o,pools:d,topPool:d[0]||null,quoteAsset:Ae(o,d),evidence:d.length?y.LIVE:y.UNKNOWN}},async scanBlocks({fromBlock:o,toBlock:a,address:n,topics:s,chunkSize:u=2e3}={},l={}){if(!Number.isInteger(o)||!Number.isInteger(a))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(a<o)throw new Error("toBlock must be >= fromBlock");let d=[],c=[];for(let i=o;i<=a;i+=u){let p=Math.min(i+u-1,a);c.push([i,p])}for(let[i,p]of c){let h={fromBlock:`0x${i.toString(16)}`,toBlock:`0x${p.toString(16)}`};n&&(h.address=n),s&&(h.topics=s);let f=await q(e,"eth_getLogs",[h],l).catch(v=>({error:String(v?.message||v)}));if(f?.error)return{chainId:e,fromBlock:o,toBlock:a,logs:d,complete:!1,failedAt:[i,p],error:f.error,evidence:y.UNKNOWN};for(let v of f?.result??f??[])d.push(v)}return{chainId:e,fromBlock:o,toBlock:a,logs:d,complete:!0,chunks:c.length,evidence:y.LIVE}},async scoreRisk(o,a={}){let n=[],s=m.PASS,u=c=>{let i={[m.PASS]:0,[m.CAUTION]:1,[m.UNKNOWN]:2,[m.FAIL]:3};i[c]>i[s]&&(s=c)},l=await this.resolveToken(o,a);l.evidence!==y.LIVE?(n.push({check:"erc20-metadata",result:m.UNKNOWN,detail:l.warning}),u(m.UNKNOWN)):n.push({check:"erc20-metadata",result:m.PASS,detail:`${l.symbol} / ${l.decimals}d`});let d=await this.resolvePools(o,a);if(d.evidence===y.UNAVAILABLE)n.push({check:"liquidity",result:m.UNKNOWN,detail:d.reason}),u(m.UNKNOWN);else if(!d.pools.length)n.push({check:"liquidity",result:m.FAIL,detail:"no pool with liquidity found"}),u(m.FAIL);else{let c=d.pools[0],i=c.liquidityUsd??0;i<5e3?(n.push({check:"liquidity",result:m.CAUTION,detail:`top pool only $${i}`}),u(m.CAUTION)):n.push({check:"liquidity",result:m.PASS,detail:`$${i} on ${c.dex}`}),c.createdAt&&Date.now()-c.createdAt<24*3600*1e3&&(n.push({check:"age",result:m.CAUTION,detail:"pool under 24h old"}),u(m.CAUTION))}if(typeof this.sellSimulation=="function"){let c=await this.sellSimulation({token:o,amountIn:(10n**16n).toString()},a).catch(i=>({verdict:m.UNKNOWN,reason:String(i?.message||i)}));n.push({check:"sellability",result:c.verdict,detail:c.retentionBps!=null?`round trip returns ${(c.retentionBps/100).toFixed(2)}% -- ${c.reason}`:c.reason}),u(c.verdict)}else n.push({check:"sellability",result:m.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."}),u(m.UNKNOWN);return{chainId:e,token:o,verdict:s,checks:n,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function ie(t){let r={...bt(t)},o=new Set((t.venues||[]).map(n=>n.kind));t.venueKind==="uniswap-v3"&&o.has("quoter")&&o.has("router")?Object.assign(r,Te({chainId:t.chainId,wrappedNative:t.wrappedNative,stableQuoteAssets:t.stableQuoteAssets||[],resolveQuoteAsset:async(n,s)=>(await r.resolvePools(n,s)).quoteAsset||null})):t.venueKind==="uniswap-v2"&&o.has("router")&&Object.assign(r,Ie({chainId:t.chainId,wrappedNative:t.wrappedNative}));let a={};for(let[n,s]of Object.entries(r))a[n]=s.bind(r);return{key:t.key,chainId:t.chainId,name:t.name,rpcEnv:t.rpcEnv,nativeCurrency:t.nativeCurrency,explorer:t.explorer,venues:t.venues||[],capabilities:a}}var qe=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);function vt(){return qe.map(t=>z(ie(t)))}function yt(t){return z(ie(t))}export{qe as CHAIN_CONFIGS,y as EVIDENCE,m as RISK,O as SCANNER_CAPABILITIES,Et as __clearScanners,Pe as createScanner,wt as getScanner,gt as listScanners,vt as registerBuiltinScanners,yt as registerCustomChain,z as registerScanner,St as scannerCoverage,Be as validateScanner};
3
+ - `)}`);let a=t.capabilities||{},n=O.filter(d=>typeof a[d]=="function"),s={key:t.key,chainId:t.chainId,name:t.name,rpcEnv:[...t.rpcEnv],nativeCurrency:t.nativeCurrency?{...t.nativeCurrency}:null,wrappedNative:t.wrappedNative||null,explorer:t.explorer||null,venues:(t.venues||[]).map(d=>({...d})),warnings:o,capabilities(){return{chainId:t.chainId,key:t.key,supported:[...n],unsupported:O.filter(d=>!n.includes(d))}},supports(d){return n.includes(d)}};for(let d of O)n.includes(d)?s[d]=async(...u)=>a[d](...u,{scanner:s}):s[d]=async()=>{throw new Error(`${t.key} (chain ${t.chainId}) does not implement "${d}". 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(s)}var P=new Map;function z(t){let e=Ve(t);return P.set(e.chainId,e),e}function Lt(t){return P.get(Number(t))||null}function Ut(){return[...P.values()]}function _t(){P.clear()}function qt(){let t={};for(let e of P.values())t[e.chainId]={key:e.key,name:e.name,...e.capabilities(),venueCount:e.venues.length,failClosed:e.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:P.size,capabilities:[...O],chains:t}}import{createHash as le}from"node:crypto";import R from"node:net";import He from"node:dns";var Me=new Set(["localhost","metadata.google.internal","metadata.goog"]);function j(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=c=>{if(!c)return[];let i=c.split(":"),l=i.at(-1);if(l?.includes(".")){let h=l.split(".").map(Number);if(h.length!==4||h.some(f=>!Number.isInteger(f)||f<0||f>255))return null;i.splice(i.length-1,1,(h[0]<<8|h[1]).toString(16),(h[2]<<8|h[3]).toString(16))}return i.some(h=>!/^[0-9a-f]{1,4}$/.test(h))?null:i.map(h=>Number.parseInt(h,16))},[o,a]=e.split("::"),n=r(o),s=r(a);if(!n||!s)return null;let d=e.includes("::"),u=8-n.length-s.length;if(!d&&u!==0||d&&u<1)return null;let p=[...n,...Array(Math.max(0,u)).fill(0),...s];return p.length!==8?null:Uint8Array.from(p.flatMap(c=>[c>>8,c&255]))}function Q(t,e,r){let o=Math.floor(r/8),a=r%8;for(let s=0;s<o;s+=1)if(t[s]!==e[s])return!1;if(!a)return!0;let n=255<<8-a;return(t[o]&n)===(e[o]&n)}function G(t){if(R.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(R.isIPv6(t)){let e=j(t);if(!e)return!1;let r=j("::ffff:0:0");return Q(e,r,96)?G([...e.slice(12)].join(".")):Q(e,j("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([a,n])=>Q(e,j(a),n)):!1}return!1}function je(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Me.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let o=R.isIP(r);return o!==0&&!G(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:o!==0}}async function Y(t,{lookupFn:e=He.promises.lookup}={}){let r=je(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:R.isIPv6(r.host)?6:4}]};let o;try{o=await e(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(o)||o.length===0||o.some(a=>!G(a.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:o}}async function X({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,o;try{let i=await e();r=i.Agent,o=i.fetch}catch(i){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${i?.message||i}`);return null}if(typeof r!="function"||typeof o!="function"){if(t)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let a=i=>String(i).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),n=new Map,s=i=>(Array.isArray(i)?i:[i]).map(l=>typeof l=="string"?{address:l}:l).filter(l=>l&&l.address).map(l=>({address:l.address,family:l.family||(R.isIPv6(l.address)?6:4)})),d=(i,l,h)=>{n.set(a(i),s(typeof l=="string"?[{address:l,family:h}]:l))},u=i=>{let l=a(i);if(R.isIP(l))return[{address:l,family:R.isIPv6(l)?6:4}];let h=n.get(l);if(!h||!h.length)throw new Error(`refused: unpinned host ${i} during pinned fetch`);return h},p=new r({connect:{lookup(i,l,h){let f;try{f=u(i)}catch(y){return h(y)}return l?.all?h(null,f):h(null,f[0].address,f[0].family)}}}),c=We((i,l={})=>o(i,{...l,dispatcher:p}),d);return{dispatcher:p,fetch:c,pin:d,resolve:u,async close(){try{await p.destroy()}catch{}}}}var J=Symbol.for("oracle.egressGuard.pinCapableFetch");function We(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[J]=Object.freeze({pin:e}),t}function Z(t){return typeof t=="function"&&typeof t[J]?.pin=="function"}function ue(t,e,r){if(!Z(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[J].pin(e,r)}var Ke=new Set([408,425,429,500,502,503,504]),de=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),ze=2,pe=4e3,ve=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Qe=new Set([301,302,303,307,308]),he=3,Ge=64*1024;function Ye(t){let e=String(t||"").toLowerCase();return ve.includes(e)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(e)}function Xe(t){let e={};for(let[r,o]of Object.entries(t||{}))Ye(r)||(e[r]=o);return e}function Je(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let r=new URL(String(t),String(e));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${r.protocol}`);return r.toString()}function Ze(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var ee=new Map,et=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,tt=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function fe(t){let e=String(t?.method||"");return e?!et.test(e):!1}function rt(t,e){if(t==="GET"&&e==null)return!0;if(t!=="POST"||e==null)return!1;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return!1}return Array.isArray(r)?r.length>0&&r.every(fe):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?fe(r):typeof r.type=="string"&&tt.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function nt(t,e,r,o={},a=null){let n={};for(let[l,h]of Object.entries(r||{}))n[l.toLowerCase()]=h;let s=Object.keys(n).filter(l=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(l)),u=[...new Set([...ve,...s])].sort().map(l=>`${l}=${n[l]??""}`).join(`
4
+ `),p=le("sha256").update(u).digest("hex").slice(0,32),c=`${o.untrustedUrl?"untrusted":"trusted"}:${o.maxResponseBytes??"unbounded"}`,i=a==null?"-":le("sha256").update(String(a)).digest("hex").slice(0,32);return`${t} ${e} ${c} ${p} ${i}`}function ot(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,pe):Math.min(250*2**t,pe)+Math.floor(Math.random()*100)}var at=t=>new Promise(e=>setTimeout(e,t));function $(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function te(t,e,r){return $(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function D(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function st(t){return t?t.byteLength??t.length??0:0}async function me(t,e,{url:r,truncate:o=!1,onOversize:a}={}){if(e==null)return await t.text();let n=Number(t.headers?.get?.("content-length"));if(Number.isFinite(n)&&n>e&&(D(t),!o))throw te(r,`content-length ${n}`,e);let s=t.body?.getReader?.();if(!s){let i=await t.text(),l=Buffer.byteLength(i,"utf8");if(l>e){if(!o)throw te(r,`body ${l} bytes`,e);return Buffer.from(i,"utf8").subarray(0,e).toString("utf8")}return i}let d=[],u=0,p=!1;try{for(;;){let{value:i,done:l}=await s.read();if(l)break;if(i&&(d.push(Buffer.from(i)),u+=st(i),u>e)){p=!0;break}}}finally{if(p)try{await s.cancel()}catch{}try{s.releaseLock?.()}catch{}}if(p&&(typeof a=="function"&&a(),!o))throw te(r,`streamed ${u} bytes`,e);let c=Buffer.concat(d);return(p?c.subarray(0,e):c).toString("utf8")}function be(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function it(t,{fetchImpl:e,method:r,headers:o,body:a,timeoutMs:n,lookupFn:s,realFetch:d,untrustedUrl:u=!1,maxResponseBytes:p=null,importUndici:c,validateResponse:i,signal:l}){let h=new AbortController,f=setTimeout(()=>h.abort(),n),y=l?typeof AbortSignal.any=="function"?AbortSignal.any([l,h.signal]):l:h.signal,b=null,k=e,x=s?{lookupFn:s}:{};if(u&&!d&&!Z(k))throw $(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let L=async(S,{status:E=null}={})=>{let w=await Y(S,x);if(!w.ok)throw $(E==null?`HTTP refused ${S}: ${w.error}`:`HTTP redirect to ${S} ${w.error}`,E==null?{}:{status:E});let g=new URL(S).hostname;if(d){if(b&&(await b.close(),b=null),!b)try{b=await X({requireUndici:!0,...c?{importUndici:c}:{}})}catch(C){throw $(E==null?`HTTP refused ${S}: ${C?.message||C}`:`HTTP redirect to ${S} refused: ${C?.message||C}`,E==null?{}:{status:E})}b.pin(g,w.addresses),k=b.fetch}else ue(k,g,w.addresses);return w};try{let S=String(t),E={...o||{}};u&&await L(S);for(let w=0;w<=he;w+=1){let g=await k(S,{method:r,headers:E,body:a,signal:y,redirect:"manual"});if(Qe.has(g.status)){if(r!=="GET"&&r!=="HEAD"){let U=await me(g,p??Ge,{url:S,truncate:!0}),q=new Error(`HTTP ${g.status} ${r} ${S} redirected non-idempotent request`);throw q.status=g.status,q.body=be(U)??U.slice(0,300),q}if(w===he)throw D(g),new Error(`HTTP redirect loop for ${t}`);let A=g.headers?.get?.("location"),N;try{N=Je(A,S)}catch(U){throw D(g),U}let F=!Ze(N,S);if(D(g),F&&(E=Xe(E)),u)await L(N,{status:g.status});else if(F){let U=await Y(N,x);if(!U.ok){let q=new Error(`HTTP redirect from ${S} ${U.error}`);throw q.status=g.status,q.retryable=!1,q}d&&U.addresses?.length&&(b||(b=await X(c?{importUndici:c}:{})),b&&(b.pin(new URL(N).hostname,U.addresses),k=b.fetch))}S=N;continue}if(typeof i=="function")try{await i(g,{url:S})}catch(A){throw D(g),$(A?.message||String(A))}let C=await me(g,p,{url:S,onOversize:()=>h.abort()}),I=be(C);if(!g.ok){let A=new Error(`HTTP ${g.status} ${r} ${S}`);throw A.status=g.status,A.retryAfter=g.headers?.get?.("retry-after")??null,A.body=I??C.slice(0,300),A}return I??C}throw new Error(`HTTP redirect loop for ${t}`)}finally{clearTimeout(f),b&&await b.close()}}async function W(t,e={}){let r=e.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let o=e.timeoutMs??12e3,a=(e.method||"GET").toUpperCase(),n={Accept:"application/json",...e.headers||{}},s=e.body;s!=null&&typeof s!="string"&&(n["Content-Type"]=n["Content-Type"]||"application/json",s=JSON.stringify(s));let d=Number.isInteger(e.retries)?Math.max(e.retries,0):ze,u=e.lookupFn,p=!e.fetchImpl,c=e.untrustedUrl===!0,i=e.importUndici,l=e.validateResponse,h=e.signal,f=Number(e.maxResponseBytes),y=Number.isFinite(f)&&f>0?Math.floor(f):null,b=async()=>{let E;for(let w=0;w<=d;w++){h?.throwIfAborted?.();try{return await it(t,{fetchImpl:r,method:a,headers:n,body:s,timeoutMs:o,lookupFn:u,realFetch:p,untrustedUrl:c,maxResponseBytes:y,importUndici:i,validateResponse:l,signal:h})}catch(g){E=g;let C=g?.status,I=g?.name==="AbortError"||g?.name==="TimeoutError"||h?.aborted,A=new Set([408,425,429]),N=g?.retryable===!1?!1:C!=null?A.has(C)||Ke.has(C)&&de.has(a):!I&&de.has(a);if(w===d||!N)throw g;let F=ot(w,g?.retryAfter);h?await new Promise((U,q)=>{let Oe=setTimeout(U,F);h.addEventListener("abort",()=>{clearTimeout(Oe),q(h.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await at(F)}}throw E};if(!(e.dedupe!==!1&&!h&&rt(a,s)))return b();let x=nt(a,t,n,{untrustedUrl:c,maxResponseBytes:y},s),L=ee.get(x);if(L)return L;let S=b().finally(()=>ee.delete(x));return ee.set(x,S),S}async function ye(t,e,r){let o=Array.from(t),a=Math.max(1,Math.min(Number(e)||1,o.length||1)),n=new Array(o.length),s=0;return await Promise.all(Array.from({length:a},async()=>{for(;s<o.length;){let d=s++;n[d]=await r(o[d],d)}})),n}var ge={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}},ct=new Map(Object.values(ge).map(t=>[t.chainId,t]));function we(t){return ct.get(Number(t))||null}function Ee(t,e=process.env){let r=we(t);if(!r)return null;for(let o of r.rpcEnv){let a=(e[o]||"").trim();if(a)return a}return null}import{Interface as ut,getAddress as lt}from"ethers";var Se=new ut(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Ae(t,e){try{return lt(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var dt={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 pt(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let o=Ee(t,r);return o||dt[Number(t)]||null}var ht=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function ft(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!ht.test(r))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}var V=new Map,Ce=new Map;function mt(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function bt(t){if(t?.error)throw mt(t.error);return t?.result}function vt(t,e,r){return`${t}
5
+ ${e}
6
+ ${JSON.stringify(r??[])}`}async function yt(t,e,r){return W(t,{method:"POST",body:e,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function _(t,e,r=[],o={}){let a=String(e||""),n=ft(a),s=pt(t,o);if(!s)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);if(n==="eth_chainid"&&o.cacheChainId!==!1){let c=Ce.get(s);if(c!=null)return c}let u=o.dedupe!==!1&&!o.signal?vt(s,a,r):null;if(u&&V.has(u))return V.get(u);let p=(async()=>{let c=await yt(s,{jsonrpc:"2.0",id:1,method:e,params:r},o),i=bt(c);return n==="eth_chainid"&&typeof i=="string"&&Ce.set(s,i),i})();return u&&(V.set(u,p),p.finally(()=>{V.get(u)===p&&V.delete(u)}).catch(()=>{})),p}async function xe(t,e={}){let r=await _(t,"eth_blockNumber",[],e);return parseInt(r,16)}async function Ie(t,e,r={}){if(!e)throw new Error("rpcGetBalance requires address");let o=await _(t,"eth_getBalance",[e,"latest"],r);return{chainId:Number(t),address:e,balanceWei:BigInt(o).toString(),balanceHex:o}}async function Ne(t={},e={}){let r=Number(t.chainId??e.chainId??1),o=Ae(t.token||t.tokenAddress,"token"),a=Ae(t.account||t.owner||t.address,"account"),n=Se.encodeFunctionData("balanceOf",[a]),s=await _(r,"eth_call",[{to:o,data:n},t.blockTag||"latest"],e),d=Se.decodeFunctionResult("balanceOf",s),u=BigInt(d[0]);return{chainId:r,token:o,account:a,balance:u.toString(),balanceHex:`0x${u.toString(16)}`,blockTag:t.blockTag||"latest"}}var gt=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function ke(t,e){let r=String(t||"").toLowerCase(),o=String(e?.quote||e?.quoteToken?.address||"").toLowerCase(),a=String(e?.base||e?.baseToken?.address||"").toLowerCase();return o===r?{address:e.base||e.baseToken?.address,symbol:e.baseToken?.symbol}:a===r?{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}:{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}}function re(t,e=[],{stables:r=[],wrappedNative:o=null}={}){let a=String(t||"").toLowerCase(),n=new Set((r||[]).map(u=>String(u).toLowerCase())),s=String(o||"").toLowerCase(),d=(e||[]).map((u,p)=>{let c=ke(a,u),i=String(c.address||"").toLowerCase(),l=String(c.symbol||"").toLowerCase(),h=Number(u.liquidityUsd??u.liquidity?.usd),f=Number.isFinite(h)?h:0,y=String(u.dex||u.dexId||"").toLowerCase(),b=0;return n.has(i)||gt.has(l)?b=300:s&&i===s&&(b=100),y.includes("v4")?b+=20:y.includes("v3")?b+=10:(y.includes("v2")||y.includes("raydium")||y.includes("orca")||y.includes("meteora"))&&(b+=8),{pool:u,score:b*1e12+f,index:p,otherAddr:i,liquidityUsd:f}});return d.sort((u,p)=>p.score-u.score||u.index-p.index),d.map(u=>u.pool)}function Te(t,e=[]){let r=Array.isArray(e)?e:[];return r.length&&ke(t,r[0]).address||null}var wt="https://api.dexscreener.com",Yt=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function Et(t={}){return(t.baseUrl||process.env.DEXSCREENER_API_URL||wt).replace(/\/$/,"")}async function Le(t,e={}){if(!t)throw new Error("tokenAddress required");return W(`${Et(e)}/latest/dex/tokens/${t}`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var oe={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},T=t=>BigInt(t).toString(16).padStart(64,"0"),H=t=>t.slice(2).toLowerCase().padStart(64,"0");function St(t,e){return`0x${oe.getAmountsOut}`+T(t)+T(64)+T(e.length)+e.map(H).join("")}function At(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length<128)return null;let r=Number(BigInt(`0x${e.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let o=[];for(let a=0;a<r;a++){let n=128+a*64;if(e.length<n+64)return null;o.push(BigInt(`0x${e.slice(n,n+64)}`))}return o}function ne(t,e="router"){return(t?.venues||[]).find(o=>o.kind===e)?.address??null}var ae=100;function Ct(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>ae)throw new Error(`slippageBps ${r} exceeds the ${ae} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function Ue(t){let{chainId:e,wrappedNative:r}=t;async function o(a,n,s,d){let u=await _(e,"eth_call",[{to:a,data:St(n,s)},"latest"],d);return At(u?.result??u)}return{async quote({tokenIn:a,tokenOut:n,amountIn:s,path:d},u={}){let p=ne(u.scanner);if(!p)return{chainId:e,evidence:v.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let c=d||[a,n];if(c.some(l=>!/^0x[0-9a-fA-F]{40}$/.test(l||"")))throw new Error("quote requires valid 20-byte addresses");let i=await o(p,s,c,u);return i?{chainId:e,router:p,path:c,amountIn:String(s),amountOut:i[i.length-1].toString(),hops:c.length-1,evidence:v.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:p,path:c,evidence:v.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:a,amountIn:n,base:s},d={}){let u=ne(d.scanner),p=s||r;if(p&&String(a).toLowerCase()===String(p).toLowerCase())return{chainId:e,token:a,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!p)return{chainId:e,token:a,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:u?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let c=await o(u,n,[p,a],d);if(!c)return{chainId:e,token:a,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let i=c[c.length-1];if(i===0n)return{chainId:e,token:a,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let l=await o(u,i,[a,p],d);if(!l)return{chainId:e,token:a,verdict:m.FAIL,evidence:v.LIVE,leg:"sell",bought:i.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=l[l.length-1],f=Number(h*10000n/BigInt(n)),y=m.PASS,b="round trip completes with expected fee/impact loss";return f<5e3?(y=m.FAIL,b=`round trip returns only ${(f/100).toFixed(2)}% -- punitive tax or no real liquidity`):f<9e3&&(y=m.CAUTION,b=`round trip returns ${(f/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:a,base:p,router:u,verdict:y,reason:b,amountIn:String(n),bought:i.toString(),returned:h.toString(),retentionBps:f,evidence:v.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:a,tokenOut:n,amountIn:s,recipient:d,slippageBps:u=50,deadlineSeconds:p=900,path:c},i={}){let l=i.scanner,h=ne(l);if(!h)throw new Error(`chain ${e} 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(d||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=c||[a,n],y=await this.quote({tokenIn:a,tokenOut:n,amountIn:s,path:f},i);if(y.evidence!==v.LIVE)throw new Error(`cannot prepare without a live quote (${y.evidence}: ${y.reason??"no reason given"})`);let b=Ct(y.amountOut,u);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let k=BigInt(Math.floor(Date.now()/1e3)+Number(p)),x=r&&f[0].toLowerCase()===r.toLowerCase()&&i.useNative,L=x?`0x${oe.swapExactETHForTokens}`+T(b)+T(128)+H(d)+T(k)+T(f.length)+f.map(H).join(""):`0x${oe.swapExactTokensForTokens}`+T(s)+T(b)+T(160)+H(d)+T(k)+T(f.length)+f.map(H).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:h,data:L,value:x?`0x${BigInt(s).toString(16)}`:"0x0"},guard:{quotedOut:y.amountOut,minOut:b.toString(),slippageBps:u,maxSlippageBps:ae,deadline:k.toString()},requires:x?[]:[{step:"approve",token:f[0],spender:h,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 xt=[100,500,3e3,1e4],_e={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},B=t=>BigInt(t).toString(16).padStart(64,"0"),M=t=>t.slice(2).toLowerCase().padStart(64,"0"),qe=/^0x[0-9a-fA-F]{40}$/,ie=100;function It(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>ie)throw new Error(`slippageBps ${r} exceeds the ${ie} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function se(t,e){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}function Re(t){let{chainId:e,wrappedNative:r}=t;async function o({quoter:n,tokenIn:s,tokenOut:d,amountIn:u,fee:p},c){let i=`0x${_e.quoteExactInputSingle}`+M(s)+M(d)+B(u)+B(p)+B(0),l=await _(e,"eth_call",[{to:n,data:i},"latest"],c).catch(()=>null),h=l?.result??l;if(!h||h==="0x"||h.length<66)return null;let f=BigInt(`0x${h.slice(2,66)}`);return f>0n?f:null}async function a({quoter:n,tokenIn:s,tokenOut:d,amountIn:u},p){let c=await Promise.all(xt.map(async l=>{let h=await o({quoter:n,tokenIn:s,tokenOut:d,amountIn:u,fee:l},p);return{fee:l,amountOut:h?h.toString():null,out:h}})),i=null;for(let l of c)l.out&&(!i||l.out>i.amountOut)&&(i={fee:l.fee,amountOut:l.out});return{best:i,tried:c.map(({fee:l,amountOut:h})=>({fee:l,amountOut:h}))}}return{async quote({tokenIn:n,tokenOut:s,amountIn:d},u={}){let p=se(u.scanner,"quoter");if(!p)return{chainId:e,evidence:v.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let l of[n,s])if(!qe.test(l||""))throw new Error("quote requires valid 20-byte addresses");let{best:c,tried:i}=await a({quoter:p,tokenIn:n,tokenOut:s,amountIn:d},u);return c?{chainId:e,venue:"uniswap-v3",quoter:p,tokenIn:n,tokenOut:s,amountIn:String(d),amountOut:c.amountOut.toString(),fee:c.fee,useNative:!!r&&String(n).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:i,evidence:v.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:e,quoter:p,tokenIn:n,tokenOut:s,triedFeeTiers:i,evidence:v.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:n,amountIn:s,base:d},u={}){let p=se(u.scanner,"quoter"),c=(t.stableQuoteAssets||[]).map(E=>String(E).toLowerCase()),i=null;!d&&typeof t.resolveQuoteAsset=="function"&&(i=await t.resolveQuoteAsset(n,u).catch(()=>null));let l=String(n).toLowerCase(),h=String(r||"").toLowerCase();if(h&&l===h)return{chainId:e,token:n,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let f=d||i||(c[0]&&l!==c[0]?c[0]:null)||r;if(f&&l===String(f).toLowerCase())return{chainId:e,token:n,verdict:m.UNKNOWN,evidence:v.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(!p||!f)return{chainId:e,token:n,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:p?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let y=await a({quoter:p,tokenIn:f,tokenOut:n,amountIn:s},u);if(!y.best){let E=c.find(w=>w&&w!==String(f).toLowerCase()&&w!==String(n).toLowerCase());if(E){let w=await a({quoter:p,tokenIn:E,tokenOut:n,amountIn:s},u);if(w.best){let g=await a({quoter:p,tokenIn:n,tokenOut:E,amountIn:w.best.amountOut},u);if(g.best){let C=g.best.amountOut,I=Number(C*10000n/BigInt(s)),A=m.PASS,N="round trip vs dollar book completes with expected fee/impact loss";return I<5e3?(A=m.FAIL,N=`round trip vs dollar book returns only ${(I/100).toFixed(2)}% -- punitive tax or no real liquidity`):I<9e3&&(A=m.CAUTION,N=`round trip vs dollar book returns ${(I/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:n,base:E,quoteAsset:E,verdict:A,reason:N,amountIn:String(s),bought:w.best.amountOut.toString(),returned:C.toString(),retentionBps:I,buyFee:w.best.fee,sellFee:g.best.fee,evidence:v.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:e,token:n,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let b=await a({quoter:p,tokenIn:n,tokenOut:f,amountIn:y.best.amountOut},u);if(!b.best){let E=c.find(w=>w&&w!==String(f).toLowerCase()&&w!==String(n).toLowerCase());if(E){let w=await a({quoter:p,tokenIn:E,tokenOut:n,amountIn:s},u),g=w.best?await a({quoter:p,tokenIn:n,tokenOut:E,amountIn:w.best.amountOut},u):{best:null};if(w.best&&g.best){let C=g.best.amountOut,I=Number(C*10000n/BigInt(s)),A=m.PASS,N="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return I<5e3?(A=m.FAIL,N=`dollar-book round trip returns only ${(I/100).toFixed(2)}%`):I<9e3&&(A=m.CAUTION,N=`dollar-book round trip returns ${(I/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:n,base:E,quoteAsset:E,verdict:A,reason:N,amountIn:String(s),bought:w.best.amountOut.toString(),returned:C.toString(),retentionBps:I,buyFee:w.best.fee,sellFee:g.best.fee,evidence:v.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:e,token:n,verdict:m.FAIL,evidence:v.LIVE,leg:"sell",bought:y.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let k=b.best.amountOut,x=Number(k*10000n/BigInt(s)),L=m.PASS,S="round trip completes with expected fee/impact loss";return x<5e3?(L=m.FAIL,S=`round trip returns only ${(x/100).toFixed(2)}% -- punitive tax or no real liquidity`):x<9e3&&(L=m.CAUTION,S=`round trip returns ${(x/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:n,base:f,verdict:L,reason:S,amountIn:String(s),bought:y.best.amountOut.toString(),returned:k.toString(),retentionBps:x,buyFee:y.best.fee,sellFee:b.best.fee,evidence:v.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:n,tokenOut:s,amountIn:d,recipient:u,slippageBps:p=50,fee:c},i={}){let l=se(i.scanner,"router");if(!l)throw new Error(`chain ${e} 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(!qe.test(u||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=await this.quote({tokenIn:n,tokenOut:s,amountIn:d},i);if(h.evidence!==v.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let f=c??h.fee,y=It(h.amountOut,p);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(i.useNative||h.useNative)&&r&&String(n).toLowerCase()===String(r).toLowerCase(),k=`0x${_e.exactInputSingle}`+M(n)+M(s)+B(f)+M(u)+B(d)+B(y)+B(0);return{unsigned:!0,signedBy:"user-wallet",chainId:e,venue:"uniswap-v3",tx:{to:l,data:k,value:b?String(d):"0x0"},guard:{quotedOut:h.amountOut,minOut:y.toString(),slippageBps:p,maxSlippageBps:ie,fee:f},requires:b?[]:[{step:"approve",token:n,spender:l,amount:String(d)}],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 K={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Be(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function Pe(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length>=128){let o=Number(BigInt(`0x${e.slice(64,128)}`));if(o>0&&o<=256&&e.length>=128+o*2){let a=e.slice(128,128+o*2),n=Buffer.from(a,"hex").toString("utf8").replace(/\0+$/,"");if(n)return n}}return Buffer.from(e.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function Nt(t){let{chainId:e}=t;async function r(o,a,n){return _(e,"eth_call",[{to:o,data:a},"latest"],n)}return{async blockNumber(o={}){let a=await xe(e,o);return{chainId:e,blockNumber:a?.blockNumber??a,evidence:v.LIVE}},async nativeBalance(o,a={}){let n=await Ie(e,o,a);return{chainId:e,address:o,wei:n?.wei??n?.balance??null,symbol:t.nativeCurrency?.symbol??null,decimals:t.nativeCurrency?.decimals??18,evidence:v.LIVE}},async tokenBalance({token:o,owner:a},n={}){let s=await Ne({chainId:e,token:o,owner:a},n);return{chainId:e,token:o,owner:a,raw:s?.balance??s,evidence:v.LIVE}},async resolveToken(o,a={}){if(!/^0x[0-9a-fA-F]{40}$/.test(o||""))return{chainId:e,token:o,evidence:v.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[n,s,d,u]=await Promise.all([r(o,K.decimals,a).catch(()=>null),r(o,K.symbol,a).catch(()=>null),r(o,K.name,a).catch(()=>null),r(o,K.totalSupply,a).catch(()=>null)]),p=Be(n?.result??n),c=p!==null||s?.result||d?.result;return{chainId:e,address:o,decimals:p===null?null:Number(p),symbol:Pe(s?.result??s),name:Pe(d?.result??d),totalSupply:(Be(u?.result??u)??null)?.toString()??null,evidence:c?v.LIVE:v.UNKNOWN,warning:c?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(o,a={}){let n=t.dexscreenerSlug;if(!n)return{chainId:e,token:o,pools:[],evidence:v.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let s=await Le(o,a).catch(()=>null),u=(s?.pairs||s?.data?.pairs||[]).filter(c=>String(c.chainId).toLowerCase()===String(n).toLowerCase()).map(c=>({pair:c.pairAddress,dex:c.dexId,base:c.baseToken?.address,quote:c.quoteToken?.address,liquidityUsd:c.liquidity?.usd??null,priceUsd:c.priceUsd??null,volume24hUsd:c.volume?.h24??null,createdAt:c.pairCreatedAt??null})).sort((c,i)=>(i.liquidityUsd??0)-(c.liquidityUsd??0)),p=re(o,u,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:o,pools:p,topPool:p[0]||null,quoteAsset:Te(o,p),evidence:p.length?v.LIVE:v.UNKNOWN}},async scanBlocks({fromBlock:o,toBlock:a,address:n,topics:s,chunkSize:d=2e3}={},u={}){if(!Number.isInteger(o)||!Number.isInteger(a))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(a<o)throw new Error("toBlock must be >= fromBlock");let p=[],c=[];for(let l=o;l<=a;l+=d){let h=Math.min(l+d-1,a);c.push([l,h])}let i=await ye(c,4,async([l,h])=>{let f={fromBlock:`0x${l.toString(16)}`,toBlock:`0x${h.toString(16)}`};n&&(f.address=n),s&&(f.topics=s);let y=await _(e,"eth_getLogs",[f],u).catch(b=>({error:String(b?.message||b)}));return{start:l,end:h,res:y}});for(let{start:l,end:h,res:f}of i){if(f?.error)return{chainId:e,fromBlock:o,toBlock:a,logs:p,complete:!1,failedAt:[l,h],error:f.error,evidence:v.UNKNOWN};for(let y of f?.result??f??[])p.push(y)}return{chainId:e,fromBlock:o,toBlock:a,logs:p,complete:!0,chunks:c.length,evidence:v.LIVE}},async scoreRisk(o,a={}){let n=[],s=m.PASS,d=c=>{let i={[m.PASS]:0,[m.CAUTION]:1,[m.UNKNOWN]:2,[m.FAIL]:3};i[c]>i[s]&&(s=c)},[u,p]=await Promise.all([this.resolveToken(o,a),this.resolvePools(o,a)]);if(u.evidence!==v.LIVE?(n.push({check:"erc20-metadata",result:m.UNKNOWN,detail:u.warning}),d(m.UNKNOWN)):n.push({check:"erc20-metadata",result:m.PASS,detail:`${u.symbol} / ${u.decimals}d`}),p.evidence===v.UNAVAILABLE)n.push({check:"liquidity",result:m.UNKNOWN,detail:p.reason}),d(m.UNKNOWN);else if(!p.pools.length)n.push({check:"liquidity",result:m.FAIL,detail:"no pool with liquidity found"}),d(m.FAIL);else{let c=p.pools[0],i=c.liquidityUsd??0;i<5e3?(n.push({check:"liquidity",result:m.CAUTION,detail:`top pool only $${i}`}),d(m.CAUTION)):n.push({check:"liquidity",result:m.PASS,detail:`$${i} on ${c.dex}`}),c.createdAt&&Date.now()-c.createdAt<24*3600*1e3&&(n.push({check:"age",result:m.CAUTION,detail:"pool under 24h old"}),d(m.CAUTION))}if(typeof this.sellSimulation=="function"){let c=await this.sellSimulation({token:o,amountIn:(10n**16n).toString()},a).catch(i=>({verdict:m.UNKNOWN,reason:String(i?.message||i)}));n.push({check:"sellability",result:c.verdict,detail:c.retentionBps!=null?`round trip returns ${(c.retentionBps/100).toFixed(2)}% -- ${c.reason}`:c.reason}),d(c.verdict)}else n.push({check:"sellability",result:m.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."}),d(m.UNKNOWN);return{chainId:e,token:o,verdict:s,checks:n,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function ce(t){let r={...Nt(t)},o=new Set((t.venues||[]).map(n=>n.kind));t.venueKind==="uniswap-v3"&&o.has("quoter")&&o.has("router")?Object.assign(r,Re({chainId:t.chainId,wrappedNative:t.wrappedNative,stableQuoteAssets:t.stableQuoteAssets||[],resolveQuoteAsset:async(n,s)=>(await r.resolvePools(n,s)).quoteAsset||null})):t.venueKind==="uniswap-v2"&&o.has("router")&&Object.assign(r,Ue({chainId:t.chainId,wrappedNative:t.wrappedNative}));let a={};for(let[n,s]of Object.entries(r))a[n]=s.bind(r);return{key:t.key,chainId:t.chainId,name:t.name,rpcEnv:t.rpcEnv,nativeCurrency:t.nativeCurrency,explorer:t.explorer,venues:t.venues||[],capabilities:a}}var Fe=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);function kt(){return Fe.map(t=>z(ce(t)))}function Tt(t){return z(ce(t))}export{Fe as CHAIN_CONFIGS,v as EVIDENCE,m as RISK,O as SCANNER_CAPABILITIES,_t as __clearScanners,Ve as createScanner,Lt as getScanner,Ut as listScanners,kt as registerBuiltinScanners,Tt as registerCustomChain,z as registerScanner,qt as scannerCoverage,De as validateScanner};