@oracle-agent/oracle 0.35.26 → 0.35.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- var 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 a=f.split(":"),u=a.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;a.splice(a.length-1,1,(l[0]<<8|l[1]).toString(16),(l[2]<<8|l[3]).toString(16))}return a.some(l=>!/^[0-9a-f]{1,4}$/.test(l))?null:a.map(l=>Number.parseInt(l,16))},[n,i]=t.split("::"),o=r(n),s=r(i);if(!o||!s)return null;let c=t.includes("::"),p=8-o.length-s.length;if(!c&&p!==0||c&&p<1)return null;let d=[...o,...Array(Math.max(0,p)).fill(0),...s];return d.length!==8?null:Uint8Array.from(d.flatMap(f=>[f>>8,f&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 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 a=await t();r=a.Agent,n=a.fetch}catch(a){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${a?.message||a}`);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=a=>String(a).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,s=a=>(Array.isArray(a)?a:[a]).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=(a,u,l)=>{o.set(i(a),s(typeof u=="string"?[{address:u,family:l}]:u))},p=a=>{let u=i(a);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 ${a} during pinned fetch`);return l},d=new r({connect:{lookup(a,u,l){let w;try{w=p(a)}catch(y){return l(y)}return u?.all?l(null,w):l(null,w[0].address,w[0].family)}}}),f=It((a,u={})=>n(a,{...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 Tt(e){let t={};for(let[r,n]of Object.entries(e||{}))Nt(r)||(t[r]=n);return t}function _t(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 Fe(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(Fe):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?Fe(r):typeof r.type=="string"&&Pt.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function Ut(e,t,r,n={},i=null){let o={};for(let[u,l]of Object.entries(r||{}))o[u.toLowerCase()]=l;let s=Object.keys(o).filter(u=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(u)),p=[...new Set([...qe,...s])].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"}`,a=i==null?"-":Pe("sha256").update(String(i)).digest("hex").slice(0,32);return`${e} ${t} ${f} ${d} ${a}`}function Lt(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Ue):Math.min(250*2**e,Ue)+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 s=e.body?.getReader?.();if(!s){let a=await e.text(),u=Buffer.byteLength(a,"utf8");if(u>t){if(!n)throw me(r,`body ${u} bytes`,t);return Buffer.from(a,"utf8").subarray(0,t).toString("utf8")}return a}let c=[],p=0,d=!1;try{for(;;){let{value:a,done:u}=await s.read();if(u)break;if(a&&(c.push(Buffer.from(a)),p+=Dt(a),p>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 ${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:s,realFetch:c,untrustedUrl:p=!1,maxResponseBytes:d=null,importUndici:f,validateResponse:a,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=s?{lookupFn:s}:{};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<=Le;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}),T=new Error(`HTTP ${g.status} ${r} ${b} redirected non-idempotent request`);throw T.status=g.status,T.body=Me(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=_t(I,b)}catch(C){throw K(g),C}let B=!Bt(O,b);if(K(g),B&&(S=Tt(S)),p)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}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 a=="function")try{await a(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||{}},s=t.body;s!=null&&typeof s!="string"&&(o["Content-Type"]=o["Content-Type"]||"application/json",s=JSON.stringify(s));let c=Number.isInteger(t.retries)?Math.max(t.retries,0):kt,p=t.lookupFn,d=!t.fetchImpl,f=t.untrustedUrl===!0,a=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:s,timeoutMs:n,lookupFn:p,realFetch:d,untrustedUrl:f,maxResponseBytes:y,importUndici:a,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=Lt(x,g?.retryAfter);l?await new Promise((C,T)=>{let X=setTimeout(C,B);l.addEventListener("abort",()=>{clearTimeout(X),T(l.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await Ft(B)}}throw S};if(!(t.dedupe!==!1&&!l&&$t(i,s)))return m();let v=Ut(i,e,o,{untrustedUrl:f,maxResponseBytes:y},s),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,Ue,qe,vt,Le,Ot,fe,Rt,Pt,Ft,$=R(()=>{Re();Ct=new Set([408,425,429,500,502,503,504]),$e=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),kt=2,Ue=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]),Le=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"]);Ft=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"),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 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 s=Number(e.selectedBps),c=Number(e.capBps);if(!Number.isInteger(s)||s<0||s>J||!Number.isInteger(c)||c<0||c>J||s>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-s),a=f/10000n;if(f%10000n!==0n&&(a+=1n),d<a)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),s=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+s+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:s=!1,requestedCapBps:c,quotedAtMs:p=Date.now(),ttlMs:d=Ve,secret:f}={}){let a=BigInt(r??0);if(a<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let u=M({liquidityUsd:n,priceChange5m:i,quoteAgeMs:o,crossChain:s,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=a*BigInt(1e4-u.selectedBps),m=y/10000n;if(y%10000n!==0n&&(m+=1n),m>a&&(m=a),a>0n&&m<=0n)throw new Error(`auto-slippage: quote ${a} is too small to express a ${u.selectedBps} bps floor without rounding to zero`);let E=Number((a-m)*10000n/(a===0n?1n:a));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:a.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 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:c,quotedAtMs:p=Date.now(),ttlMs:d}={}){let f=Yt({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:i,priceChange5m:o,crossChain:s,requestedCapBps:c,quotedAtMs:p,ttlMs:d});return{...e,autoSlippage:f,amountOutMinimum:f.minAmountOut}}var J,Ve,L=R(()=>{je();ze();J=100,Ve=2e4});var V,ee=R(()=>{V="0x000000000000000000000000000000000000dEaD"});import{createHash as Qt,createHmac as Jt,timingSafeEqual as Tn}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 _(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 c={...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(!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,U=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 sr}from"ethers";function pr(e){return dr.test(String(e||""))}async function Qe(e,{contract:t=ar,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 sr(r,n,{staticNetwork:!0}),s=new ir(t,lr,o);return BigInt(await s.balanceOf(e))}var ar,cr,ur,lr,dr,Je=R(()=>{ar="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),s=Cr(e[yr],{fallback:n?o:0}),c=Math.min(s,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 s=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(s))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await Qe(s,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 st={};ve(st,{LIFI_API:()=>it,lifiChains:()=>_r,lifiHealth:()=>Nr,lifiPrepare:()=>Tr,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:s,fromAddress:c=V}=e;if(r==null||!o||!s)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let p=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:i,toToken:o,fromAmount:String(s),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 a=await k(`${Ae(t)}/quote?${p}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=a?.estimate?.toAmount||a?.toAmount;if(!u)return{...a,autoSlippagePolicy:d,oracleFee:f};let l=a?.transactionRequest?.to||a?.estimate?.approvalAddress||"lifi",w=P(a,{chainId:Number(r),venue:l,amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),y=a?.estimate?.toAmountMin||a?.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 Tr(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 s=r?.estimate?.approvalAddress||r?.approvalAddress;if(!s)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(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 _r(e={}){return k(`${Ae(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var it,Ee,vr,xe=R(()=>{$();L();ee();U();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:s}=e;if(!r||i==null||o==null||!s)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(s)}),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 s=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??s});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}),a=f?.estimatedRecieved||f?.estimatedReceived;return a?P(f,{chainId:Number(e.originChainId||e.chainId||Hr[i]||0),venue:f?.tx?.to||"hop",amountOut:a,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:i!==o,requestedCapBps:e.maxSlippageBps??e.slippageBps??s}):{...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:s="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(/\/$/,""),a=await k(`${f}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(i),originCurrency:o,destinationCurrency:s,amount:String(c),tradeType:p,slippageTolerance:String(d.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=a?.details?.currencyOut?.amount;return!u||!/^\d+$/.test(String(u))?{...a,autoSlippagePolicy:d}:P(a,{chainId:Number(n),venue:a?.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 s=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 _({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 lt,dt,pt,Hr,oe=R(()=>{$();L();ee();U();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"]),sn=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),an=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:c=null,liquidityUsd:p=null,error:d=null,executionReady:f=!1,meta:a={}}=e||{};if(d||r==null)return{source:t,quality:F.FAILED,amountOut:null,error:d||"no amountOut returned"};let u=Oe(r);if(u==null||u<=0n)return{source:t,quality:F.FAILED,amountOut:null,error:"non-positive amountOut"};let l=Number(s);return{source:t,quality:i==null?F.NO_GAS:F.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:a}}function Te(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:i=50,gasPriceWei:o=null,nativePriceUsd:s=null}={}){let c=e.filter(h=>h.quality!==F.FAILED),p=e.filter(h=>h.quality===F.FAILED),d=t!=null&&t>0&&r!=null&&r>=0,f=Number(o),a=Number(s),u=Number.isFinite(f)&&f>0&&Number.isFinite(a)&&a>0,l=c.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&&u&&Number.isFinite(se)&&se>0){let j=se*f/1e18*a;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,yt=A>X?A-X:0n;return{...h,grossOut:A.toString(),netOut:yt.toString(),costInDest:I.toString(),oracleFeeInDest:T.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 _e(e,{timeoutMs:t=12e3}={}){let r=(i,o)=>Promise.race([i,new Promise((s,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 s=e[o].source;return i.status==="rejected"?Ne({source:s,error:String(i.reason?.message||i.reason)}):Ne({source:s,...i.value})})}xe();$();L();U();te();$();L();U();$();L();U();$();L();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();U();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 at={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(at).map(e=>[e.chainId,e]));import{Interface as Pr,getAddress as Uo}from"ethers";var Lo=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"});L();U();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 Lr,Interface as Se,getAddress as ni,isAddress as oi,keccak256 as ii}from"ethers";L();U();var li=Lr.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 Fr="https://coins.llama.fi",Dr="https://api.llama.fi";function Mr(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Fr).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 s=n.find(p=>q(p?.slug)===o||q(p?.name)===o),c=H(s?.tvl);if(c!=null)return{liquidityUsd:c,protocol:s?.name??s?.slug??o}}for(let o of i){let s=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(s?.tvl);if(c!=null)return{liquidityUsd:c,protocol:s?.name??s?.slug??o}}return null}function gt({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:i,taker:o,opts:s={}}){let c=[],p=null,d=async(f,a={})=>(p||=Kr(s),Yr(await p,f,a));return c.push({source:"lifi",run:async()=>{let f=await re({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:i},s),a=f?.estimate??f?.[0]?.estimate,u={tool:f?.tool??f?.toolDetails?.name,durationSeconds:H(a?.executionDuration)},l=await d("lifi",u);return{amountOut:a?.toAmount,minOut:a?.toAmountMin,gasUsd:ht(a?.gasCosts),feeUsd:ht(a?.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)},s))?.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)),a=await f({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(i)},s),u=a?.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(a?.estimatedFillTimeSec),limits:a?.limits?{min:a.limits.minDeposit,max:a.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 s=(await Ie([i],r))?.coins?.[i],c=Number(s?.price),p=Number(s?.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: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 c=Qr(n,o,t),p=gt({...e,opts:t}),[d,f]=await Promise.all([_e(p,{timeoutMs:t.timeoutMs??15e3}),c]),a=Te(d,{destPriceUsd:f.priceUsd,destDecimals:e.decimalsOut??f.decimals,liquidityBandBps:t.liquidityBandBps??50}),u=a.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(s),...a,durations:u,sourcesTried:p.length,sourcesAnswered:d.filter(l=>l.quality!==F.FAILED).length,note:Zr(a,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 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}U();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},s)=>{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)},s);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:s},c)=>{let{lifiPrepare:p}=await Promise.resolve().then(()=>(xe(),st)),d=await p({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:i,fromAddress:o,isHolder:s,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 rs(){return Object.keys(ie)}async function ns(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 s=e.source||o.best.source,c=o.routes.find(m=>m.source===s);if(!c)return{ok:!1,reason:`source "${s}" returned no usable route`,comparison:o};let p=ie[s];if(!p){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 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!==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 f=d.transactions||[];if(!f.length)return{ok:!1,reason:`${s} returned no executable transaction for this route`,failureKind:"provider-error",comparison:o};let a=f.filter(m=>m.chainId!=null&&Number(m.chainId)!==Number(n));if(a.length)return{ok:!1,reason:`${s} returned a transaction for chain ${a[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.`),_({ok:!0,chosen:{source:s,wasWinner:s===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!==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. ${f.length} transaction(s) on chain ${n}, crediting chain ${i}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge"})}export{ns as prepareBestBridgeRoute,rs 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 xt 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 a=f.split(":"),u=a.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;a.splice(a.length-1,1,(l[0]<<8|l[1]).toString(16),(l[2]<<8|l[3]).toString(16))}return a.some(l=>!/^[0-9a-f]{1,4}$/.test(l))?null:a.map(l=>Number.parseInt(l,16))},[n,i]=t.split("::"),o=r(n),s=r(i);if(!o||!s)return null;let c=t.includes("::"),p=8-o.length-s.length;if(!c&&p!==0||c&&p<1)return null;let d=[...o,...Array(Math.max(0,p)).fill(0),...s];return d.length!==8?null:Uint8Array.from(d.flatMap(f=>[f>>8,f&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 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(At.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=xt.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 a=await t();r=a.Agent,n=a.fetch}catch(a){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${a?.message||a}`);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=a=>String(a).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,s=a=>(Array.isArray(a)?a:[a]).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=(a,u,l)=>{o.set(i(a),s(typeof u=="string"?[{address:u,family:l}]:u))},p=a=>{let u=i(a);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 ${a} during pinned fetch`);return l},d=new r({connect:{lookup(a,u,l){let w;try{w=p(a)}catch(y){return l(y)}return u?.all?l(null,w):l(null,w[0].address,w[0].family)}}}),f=It((a,u={})=>n(a,{...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 At,de,Re=R(()=>{At=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 Tt(e){let t={};for(let[r,n]of Object.entries(e||{}))Nt(r)||(t[r]=n);return t}function _t(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 Fe(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(Fe):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?Fe(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 s=Object.keys(o).filter(u=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(u)),p=[...new Set([...qe,...s])].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"}`,a=i==null?"-":Pe("sha256").update(String(i)).digest("hex").slice(0,32);return`${e} ${t} ${f} ${d} ${a}`}function Ut(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 K(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function me(e,t,r){return K(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function G(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&&(G(e),!n))throw me(r,`content-length ${o}`,t);let s=e.body?.getReader?.();if(!s){let a=await e.text(),u=Buffer.byteLength(a,"utf8");if(u>t){if(!n)throw me(r,`body ${u} bytes`,t);return Buffer.from(a,"utf8").subarray(0,t).toString("utf8")}return a}let c=[],p=0,d=!1;try{for(;;){let{value:a,done:u}=await s.read();if(u)break;if(a&&(c.push(Buffer.from(a)),p+=Dt(a),p>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 ${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:s,realFetch:c,untrustedUrl:p=!1,maxResponseBytes:d=null,importUndici:f,validateResponse:a,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=s?{lookupFn:s}:{};if(p&&!c&&!pe(E))throw K(`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 A=await ue(b,v);if(!A.ok)throw K(S==null?`HTTP refused ${b}: ${A.error}`:`HTTP redirect to ${b} ${A.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 K(S==null?`HTTP refused ${b}: ${h?.message||h}`:`HTTP redirect to ${b} refused: ${h?.message||h}`,S==null?{}:{status:S})}m.pin(g,A.addresses),E=m.fetch}else Be(E,g,A.addresses);return A};try{let b=String(e),S={...n||{}};p&&await N(b);for(let A=0;A<=Ue;A+=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}),T=new Error(`HTTP ${g.status} ${r} ${b} redirected non-idempotent request`);throw T.status=g.status,T.body=Me(C)??C.slice(0,300),T}if(A===Ue)throw G(g),new Error(`HTTP redirect loop for ${e}`);let I=g.headers?.get?.("location"),O;try{O=_t(I,b)}catch(C){throw G(g),C}let B=!Bt(O,b);if(G(g),B&&(S=Tt(S)),p)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}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 a=="function")try{await a(g,{url:b})}catch(I){throw G(g),K(I?.message||String(I))}let h=await De(g,d,{url:b,onOversize:()=>l.abort()}),x=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=x??h.slice(0,300),I}return x??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 c=Number.isInteger(t.retries)?Math.max(t.retries,0):kt,p=t.lookupFn,d=!t.fetchImpl,f=t.untrustedUrl===!0,a=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 A=0;A<=c;A++){l?.throwIfAborted?.();try{return await Mt(e,{fetchImpl:r,method:i,headers:o,body:s,timeoutMs:n,lookupFn:p,realFetch:d,untrustedUrl:f,maxResponseBytes:y,importUndici:a,validateResponse:u,signal:l})}catch(g){S=g;let h=g?.status,x=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):!x&&$e.has(i);if(A===c||!O)throw g;let B=Ut(A,g?.retryAfter);l?await new Promise((C,T)=>{let X=setTimeout(C,B);l.addEventListener("abort",()=>{clearTimeout(X),T(l.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await Ft(B)}}throw S};if(!(t.dedupe!==!1&&!l&&$t(i,s)))return m();let v=Lt(i,e,o,{untrustedUrl:f,maxResponseBytes:y},s),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,Ue,Ot,fe,Rt,Pt,Ft,$=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]),Ue=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"]);Ft=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"),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 je=R(()=>{});var ze=R(()=>{});import{createHash as zt,createHmac as Ke,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 Ge(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=Ge(t);return r?{...e,signature:Ke("sha256",r).update(Z(we(e))).digest("hex")}:e}function Kt(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=Ge(i);if(o){let l=Ke("sha256",o).update(Z(we(e))).digest("hex");if(!Gt(e.signature,l))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let s=Number(e.selectedBps),c=Number(e.capBps);if(!Number.isInteger(s)||s<0||s>J||!Number.isInteger(c)||c<0||c>J||s>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-s),a=f/10000n;if(f%10000n!==0n&&(a+=1n),d<a)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:Kt(n)},{secret:i})}function Gt(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),s=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+s+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:s=!1,requestedCapBps:c,quotedAtMs:p=Date.now(),ttlMs:d=Ve,secret:f}={}){let a=BigInt(r??0);if(a<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let u=M({liquidityUsd:n,priceChange5m:i,quoteAgeMs:o,crossChain:s,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=a*BigInt(1e4-u.selectedBps),m=y/10000n;if(y%10000n!==0n&&(m+=1n),m>a&&(m=a),a>0n&&m<=0n)throw new Error(`auto-slippage: quote ${a} is too small to express a ${u.selectedBps} bps floor without rounding to zero`);let E=Number((a-m)*10000n/(a===0n?1n:a));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:a.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 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:c,quotedAtMs:p=Date.now(),ttlMs:d}={}){let f=Yt({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:i,priceChange5m:o,crossChain:s,requestedCapBps:c,quotedAtMs:p,ttlMs:d});return{...e,autoSlippage:f,amountOutMinimum:f.minAmountOut}}var J,Ve,U=R(()=>{je();ze();J=100,Ve=2e4});var V,ee=R(()=>{V="0x000000000000000000000000000000000000dEaD"});import{createHash as Qt,createHmac as Jt,timingSafeEqual as Tn}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 _(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 c={...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(!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 sr}from"ethers";function pr(e){return dr.test(String(e||""))}async function Qe(e,{contract:t=ar,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 sr(r,n,{staticNetwork:!0}),s=new ir(t,lr,o);return BigInt(await s.balanceOf(e))}var ar,cr,ur,lr,dr,Je=R(()=>{ar="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[xr]||Ar).trim();if(r===!0)return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"admin-oracle"};let o=br(t),s=Cr(e[yr],{fallback:n?o:0}),c=Math.min(s,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 s=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(s))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await Qe(s,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,xr,tt,Ar,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",xr="ORACLE_INTEGRATOR_ID",tt="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",Ar="oracle"});var st={};ve(st,{LIFI_API:()=>it,lifiChains:()=>_r,lifiHealth:()=>Nr,lifiPrepare:()=>Tr,lifiQuote:()=>re});function xe(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(`${xe(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:c=V}=e;if(r==null||!o||!s)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let p=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:i,toToken:o,fromAmount:String(s),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 a=await k(`${xe(t)}/quote?${p}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=a?.estimate?.toAmount||a?.toAmount;if(!u)return{...a,autoSlippagePolicy:d,oracleFee:f};let l=a?.transactionRequest?.to||a?.estimate?.approvalAddress||"lifi",w=P(a,{chainId:Number(r),venue:l,amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),y=a?.estimate?.toAmountMin||a?.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 Tr(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 s=r?.estimate?.approvalAddress||r?.approvalAddress;if(!s)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(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 _r(e={}){return k(`${xe(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var it,Ee,vr,Ae=R(()=>{$();U();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:()=>Kr,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:s}=e;if(!r||i==null||o==null||!s)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(s)}),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 s=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??s});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}),a=f?.estimatedRecieved||f?.estimatedReceived;return a?P(f,{chainId:Number(e.originChainId||e.chainId||Hr[i]||0),venue:f?.tx?.to||"hop",amountOut:a,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:i!==o,requestedCapBps:e.maxSlippageBps??e.slippageBps??s}):{...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:s="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(/\/$/,""),a=await k(`${f}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(i),originCurrency:o,destinationCurrency:s,amount:String(c),tradeType:p,slippageTolerance:String(d.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=a?.details?.currencyOut?.amount;return!u||!/^\d+$/.test(String(u))?{...a,autoSlippagePolicy:d}:P(a,{chainId:Number(n),venue:a?.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 Kr(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 s=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 _({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 lt,dt,pt,Hr,oe=R(()=>{$();U();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"]),sn=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),an=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:c=null,liquidityUsd:p=null,error:d=null,executionReady:f=!1,meta:a={}}=e||{};if(d||r==null)return{source:t,quality:F.FAILED,amountOut:null,error:d||"no amountOut returned"};let u=Oe(r);if(u==null||u<=0n)return{source:t,quality:F.FAILED,amountOut:null,error:"non-positive amountOut"};let l=Number(s);return{source:t,quality:i==null?F.NO_GAS:F.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:a}}function Te(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:i=50,gasPriceWei:o=null,nativePriceUsd:s=null}={}){let c=e.filter(h=>h.quality!==F.FAILED),p=e.filter(h=>h.quality===F.FAILED),d=t!=null&&t>0&&r!=null&&r>=0,f=Number(o),a=Number(s),u=Number.isFinite(f)&&f>0&&Number.isFinite(a)&&a>0,l=c.map(h=>{let x=BigInt(h.amountOut),I=0n,O=!1,B=!1,C=BigInt(h.oracleFeeBps??0),T=C>0n?x*C/10000n:0n;if(d){let Y=h.gasUsd,se=Number(h.meta?.gasUnits??h.estimatedGas);if(Y==null&&u&&Number.isFinite(se)&&se>0){let j=se*f/1e18*a;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,yt=x>X?x-X:0n;return{...h,grossOut:x.toString(),netOut:yt.toString(),costInDest:I.toString(),oracleFeeInDest:T.toString(),costAccounted:O,gasEstimated:B}}),w=Number(i)>0?Number(i):0,y=l.reduce((h,x)=>BigInt(x.netOut)>h?BigInt(x.netOut):h,0n),m=h=>y>0n?Number((y-BigInt(h))*10000n/y):0,E=[],v=l.slice().sort((h,x)=>BigInt(x.netOut)>BigInt(h.netOut)?1:-1)[0]??null;l.sort((h,x)=>{let I=m(h.netOut)<=w?0:1,O=m(x.netOut)<=w?0:1;if(n&&w>0&&I!==O)return I-O;if(n&&w>0){let B=h.liquidityUsd??-1,C=x.liquidityUsd??-1;if(B!==C)return C-B}return BigInt(x.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(x=>x.costAccounted&&m(x.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 A=null,g=null;if(l.length>=2&&l[0].costAccounted&&l[1].costAccounted){let h=BigInt(l[0].netOut),x=BigInt(l[1].netOut);x>0n&&(A=Number((h-x)*10000n/x),g=`${l[0].source} vs ${l[1].source}`)}return{best:l[0]??null,routes:l,failed:p,improvementBps:A,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,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 s=e[o].source;return i.status==="rejected"?Ne({source:s,error:String(i.reason?.message||i.reason)}):Ne({source:s,...i.value})})}Ae();$();U();L();te();$();U();L();$();U();L();$();U();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 Ko,isAddress as Go}from"ethers";$();var at={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(at).map(e=>[e.chainId,e]));import{Interface as Pr,getAddress as Lo}from"ethers";var Uo=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"});U();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 Ur,Interface as Se,getAddress as ni,isAddress as oi,keccak256 as ii}from"ethers";U();L();var li=Ur.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 Fr="https://coins.llama.fi",Dr="https://api.llama.fi";function Mr(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Fr).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 Gr(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 s=n.find(p=>q(p?.slug)===o||q(p?.name)===o),c=H(s?.tvl);if(c!=null)return{liquidityUsd:c,protocol:s?.name??s?.slug??o}}for(let o of i){let s=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(s?.tvl);if(c!=null)return{liquidityUsd:c,protocol:s?.name??s?.slug??o}}return null}function gt({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:i,taker:o,opts:s={}}){let c=[],p=null,d=async(f,a={})=>(p||=Gr(s),Yr(await p,f,a));return c.push({source:"lifi",run:async()=>{let f=await re({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:i},s),a=f?.estimate??f?.[0]?.estimate,u={tool:f?.tool??f?.toolDetails?.name,durationSeconds:H(a?.executionDuration)},l=await d("lifi",u);return{amountOut:a?.toAmount,minOut:a?.toAmountMin,gasUsd:ht(a?.gasCosts),feeUsd:ht(a?.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)},s))?.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)),a=await f({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(i)},s),u=a?.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(a?.estimatedFillTimeSec),limits:a?.limits?{min:a.limits.minDeposit,max:a.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 s=(await Ie([i],r))?.coins?.[i],c=Number(s?.price),p=Number(s?.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: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 c=Qr(n,o,t),p=gt({...e,opts:t}),[d,f]=await Promise.all([_e(p,{timeoutMs:t.timeoutMs??15e3}),c]),a=Te(d,{destPriceUsd:f.priceUsd,destDecimals:e.decimalsOut??f.decimals,liquidityBandBps:t.liquidityBandBps??50}),u=a.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(s),...a,durations:u,sourcesTried:p.length,sourcesAnswered:d.filter(l=>l.quality!==F.FAILED).length,note:Zr(a,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 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 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},s)=>{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)},s);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:s},c)=>{let{lifiPrepare:p}=await Promise.resolve().then(()=>(Ae(),st)),d=await p({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:i,fromAddress:o,isHolder:s,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 rs(){return Object.keys(ie)}async function ns(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 s=e.source||o.best.source,c=o.routes.find(m=>m.source===s);if(!c)return{ok:!1,reason:`source "${s}" returned no usable route`,comparison:o};let p=ie[s];if(!p){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 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(A=>ie[A.source]&&A.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 f=d.transactions||[];if(!f.length)return{ok:!1,reason:`${s} returned no executable transaction for this route`,failureKind:"provider-error",comparison:o};let a=f.filter(m=>m.chainId!=null&&Number(m.chainId)!==Number(n));if(a.length)return{ok:!1,reason:`${s} returned a transaction for chain ${a[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.`),_({ok:!0,chosen:{source:s,wasWinner:s===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!==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. ${f.length} transaction(s) on chain ${n}, crediting chain ${i}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge"})}export{ns as prepareBestBridgeRoute,rs as supportedBridgePreparers};
@@ -3,4 +3,4 @@ var O=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken"
3
3
  - `)}`);let s=t.capabilities||{},n=O.filter(d=>typeof s[d]=="function"),a={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)?a[d]=async(...u)=>s[d](...u,{scanner:a}):a[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(a)}var P=new Map;function K(t){let e=Ve(t);return P.set(e.chainId,e),e}function Ut(t){return P.get(Number(t))||null}function Lt(){return[...P.values()]}function qt(){P.clear()}function _t(){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 f=l.split(".").map(Number);if(f.length!==4||f.some(h=>!Number.isInteger(h)||h<0||h>255))return null;i.splice(i.length-1,1,(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16))}return i.some(f=>!/^[0-9a-f]{1,4}$/.test(f))?null:i.map(f=>Number.parseInt(f,16))},[o,s]=e.split("::"),n=r(o),a=r(s);if(!n||!a)return null;let d=e.includes("::"),u=8-n.length-a.length;if(!d&&u!==0||d&&u<1)return null;let p=[...n,...Array(Math.max(0,u)).fill(0),...a];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),s=r%8;for(let a=0;a<o;a+=1)if(t[a]!==e[a])return!1;if(!s)return!0;let n=255<<8-s;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(([s,n])=>Q(e,j(s),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(s=>!G(s.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 s=i=>String(i).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),n=new Map,a=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,f)=>{n.set(s(i),a(typeof l=="string"?[{address:l,family:f}]:l))},u=i=>{let l=s(i);if(R.isIP(l))return[{address:l,family:R.isIPv6(l)?6:4}];let f=n.get(l);if(!f||!f.length)throw new Error(`refused: unpinned host ${i} during pinned fetch`);return f},p=new r({connect:{lookup(i,l,f){let h;try{h=u(i)}catch(y){return f(y)}return l?.all?f(null,h):f(null,h[0].address,h[0].family)}}}),c=ze((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 ze(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 We=new Set([408,425,429,500,502,503,504]),de=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Ke=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]),fe=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 he(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(he):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?he(r):typeof r.type=="string"&&tt.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function nt(t,e,r,o={},s=null){let n={};for(let[l,f]of Object.entries(r||{}))n[l.toLowerCase()]=f;let a=Object.keys(n).filter(l=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(l)),u=[...new Set([...ve,...a])].sort().map(l=>`${l}=${n[l]??""}`).join(`
4
4
  `),p=le("sha256").update(u).digest("hex").slice(0,32),c=`${o.untrustedUrl?"untrusted":"trusted"}:${o.maxResponseBytes??"unbounded"}`,i=s==null?"-":le("sha256").update(String(s)).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 st=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 at(t){return t?t.byteLength??t.length??0:0}async function me(t,e,{url:r,truncate:o=!1,onOversize:s}={}){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 a=t.body?.getReader?.();if(!a){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 a.read();if(l)break;if(i&&(d.push(Buffer.from(i)),u+=at(i),u>e)){p=!0;break}}}finally{if(p)try{await a.cancel()}catch{}try{a.releaseLock?.()}catch{}}if(p&&(typeof s=="function"&&s(),!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:s,timeoutMs:n,lookupFn:a,realFetch:d,untrustedUrl:u=!1,maxResponseBytes:p=null,importUndici:c,validateResponse:i,signal:l}){let f=new AbortController,h=setTimeout(()=>f.abort(),n),y=l?typeof AbortSignal.any=="function"?AbortSignal.any([l,f.signal]):l:f.signal,b=null,k=e,x=a?{lookupFn:a}:{};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 U=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 U(S);for(let w=0;w<=fe;w+=1){let g=await k(S,{method:r,headers:E,body:s,signal:y,redirect:"manual"});if(Qe.has(g.status)){if(r!=="GET"&&r!=="HEAD"){let L=await me(g,p??Ge,{url:S,truncate:!0}),_=new Error(`HTTP ${g.status} ${r} ${S} redirected non-idempotent request`);throw _.status=g.status,_.body=be(L)??L.slice(0,300),_}if(w===fe)throw D(g),new Error(`HTTP redirect loop for ${t}`);let A=g.headers?.get?.("location"),N;try{N=Je(A,S)}catch(L){throw D(g),L}let F=!Ze(N,S);if(D(g),F&&(E=Xe(E)),u)await U(N,{status:g.status});else if(F){let L=await Y(N,x);if(!L.ok){let _=new Error(`HTTP redirect from ${S} ${L.error}`);throw _.status=g.status,_.retryable=!1,_}d&&L.addresses?.length&&(b||(b=await X(c?{importUndici:c}:{})),b&&(b.pin(new URL(N).hostname,L.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:()=>f.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(h),b&&await b.close()}}async function z(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,s=(e.method||"GET").toUpperCase(),n={Accept:"application/json",...e.headers||{}},a=e.body;a!=null&&typeof a!="string"&&(n["Content-Type"]=n["Content-Type"]||"application/json",a=JSON.stringify(a));let d=Number.isInteger(e.retries)?Math.max(e.retries,0):Ke,u=e.lookupFn,p=!e.fetchImpl,c=e.untrustedUrl===!0,i=e.importUndici,l=e.validateResponse,f=e.signal,h=Number(e.maxResponseBytes),y=Number.isFinite(h)&&h>0?Math.floor(h):null,b=async()=>{let E;for(let w=0;w<=d;w++){f?.throwIfAborted?.();try{return await it(t,{fetchImpl:r,method:s,headers:n,body:a,timeoutMs:o,lookupFn:u,realFetch:p,untrustedUrl:c,maxResponseBytes:y,importUndici:i,validateResponse:l,signal:f})}catch(g){E=g;let C=g?.status,I=g?.name==="AbortError"||g?.name==="TimeoutError"||f?.aborted,A=new Set([408,425,429]),N=g?.retryable===!1?!1:C!=null?A.has(C)||We.has(C)&&de.has(s):!I&&de.has(s);if(w===d||!N)throw g;let F=ot(w,g?.retryAfter);f?await new Promise((L,_)=>{let Oe=setTimeout(L,F);f.addEventListener("abort",()=>{clearTimeout(Oe),_(f.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await st(F)}}throw E};if(!(e.dedupe!==!1&&!f&&rt(s,a)))return b();let x=nt(s,t,n,{untrustedUrl:c,maxResponseBytes:y},a),U=ee.get(x);if(U)return U;let S=b().finally(()=>ee.delete(x));return ee.set(x,S),S}async function ye(t,e,r){let o=Array.from(t),s=Math.max(1,Math.min(Number(e)||1,o.length||1)),n=new Array(o.length),a=0;return await Promise.all(Array.from({length:s},async()=>{for(;a<o.length;){let d=a++;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 s=(e[o]||"").trim();if(s)return s}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 ft=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function ht(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!ft.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
5
  ${e}
6
- ${JSON.stringify(r??[])}`}async function yt(t,e,r){return z(t,{method:"POST",body:e,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function q(t,e,r=[],o={}){let s=String(e||""),n=ht(s),a=pt(t,o);if(!a)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(a);if(c!=null)return c}let u=o.dedupe!==!1&&!o.signal?vt(a,s,r):null;if(u&&V.has(u))return V.get(u);let p=(async()=>{let c=await yt(a,{jsonrpc:"2.0",id:1,method:e,params:r},o),i=bt(c);return n==="eth_chainid"&&typeof i=="string"&&Ce.set(a,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 q(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 q(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"),s=Ae(t.account||t.owner||t.address,"account"),n=Se.encodeFunctionData("balanceOf",[s]),a=await q(r,"eth_call",[{to:o,data:n},t.blockTag||"latest"],e),d=Se.decodeFunctionResult("balanceOf",a),u=BigInt(d[0]);return{chainId:r,token:o,account:s,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(),s=String(e?.base||e?.baseToken?.address||"").toLowerCase();return o===r?{address:e.base||e.baseToken?.address,symbol:e.baseToken?.symbol}:s===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 s=String(t||"").toLowerCase(),n=new Set((r||[]).map(u=>String(u).toLowerCase())),a=String(o||"").toLowerCase(),d=(e||[]).map((u,p)=>{let c=ke(s,u),i=String(c.address||"").toLowerCase(),l=String(c.symbol||"").toLowerCase(),f=Number(u.liquidityUsd??u.liquidity?.usd),h=Number.isFinite(f)?f:0,y=String(u.dex||u.dexId||"").toLowerCase(),b=0;return n.has(i)||gt.has(l)?b=300:a&&i===a&&(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+h,index:p,otherAddr:i,liquidityUsd:h}});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 Ue(t,e={}){if(!t)throw new Error("tokenAddress required");return z(`${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 s=0;s<r;s++){let n=128+s*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 se=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>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 Le(t){let{chainId:e,wrappedNative:r}=t;async function o(s,n,a,d){let u=await q(e,"eth_call",[{to:s,data:St(n,a)},"latest"],d);return At(u?.result??u)}return{async quote({tokenIn:s,tokenOut:n,amountIn:a,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||[s,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,a,c,u);return i?{chainId:e,router:p,path:c,amountIn:String(a),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:s,amountIn:n,base:a},d={}){let u=ne(d.scanner),p=a||r;if(p&&String(s).toLowerCase()===String(p).toLowerCase())return{chainId:e,token:s,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:s,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,s],d);if(!c)return{chainId:e,token:s,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:s,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let l=await o(u,i,[s,p],d);if(!l)return{chainId:e,token:s,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 f=l[l.length-1],h=Number(f*10000n/BigInt(n)),y=m.PASS,b="round trip completes with expected fee/impact loss";return h<5e3?(y=m.FAIL,b=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(y=m.CAUTION,b=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:s,base:p,router:u,verdict:y,reason:b,amountIn:String(n),bought:i.toString(),returned:f.toString(),retentionBps:h,evidence:v.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:n,amountIn:a,recipient:d,slippageBps:u=50,deadlineSeconds:p=900,path:c},i={}){let l=i.scanner,f=ne(l);if(!f)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 h=c||[s,n],y=await this.quote({tokenIn:s,tokenOut:n,amountIn:a,path:h},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&&h[0].toLowerCase()===r.toLowerCase()&&i.useNative,U=x?`0x${oe.swapExactETHForTokens}`+T(b)+T(128)+H(d)+T(k)+T(h.length)+h.map(H).join(""):`0x${oe.swapExactTokensForTokens}`+T(a)+T(b)+T(160)+H(d)+T(k)+T(h.length)+h.map(H).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:f,data:U,value:x?`0x${BigInt(a).toString(16)}`:"0x0"},guard:{quotedOut:y.amountOut,minOut:b.toString(),slippageBps:u,maxSlippageBps:se,deadline:k.toString()},requires:x?[]:[{step:"approve",token:h[0],spender:f,amount:String(a)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var xt=[100,500,3e3,1e4],qe={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},B=t=>BigInt(t).toString(16).padStart(64,"0"),M=t=>t.slice(2).toLowerCase().padStart(64,"0"),_e=/^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 ae(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:a,tokenOut:d,amountIn:u,fee:p},c){let i=`0x${qe.quoteExactInputSingle}`+M(a)+M(d)+B(u)+B(p)+B(0),l=await q(e,"eth_call",[{to:n,data:i},"latest"],c).catch(()=>null),f=l?.result??l;if(!f||f==="0x"||f.length<66)return null;let h=BigInt(`0x${f.slice(2,66)}`);return h>0n?h:null}async function s({quoter:n,tokenIn:a,tokenOut:d,amountIn:u},p){let c=await Promise.all(xt.map(async l=>{let f=await o({quoter:n,tokenIn:a,tokenOut:d,amountIn:u,fee:l},p);return{fee:l,amountOut:f?f.toString():null,out:f}})),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:f})=>({fee:l,amountOut:f}))}}return{async quote({tokenIn:n,tokenOut:a,amountIn:d},u={}){let p=ae(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,a])if(!_e.test(l||""))throw new Error("quote requires valid 20-byte addresses");let{best:c,tried:i}=await s({quoter:p,tokenIn:n,tokenOut:a,amountIn:d},u);return c?{chainId:e,venue:"uniswap-v3",quoter:p,tokenIn:n,tokenOut:a,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:a,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:a,base:d},u={}){let p=ae(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(),f=String(r||"").toLowerCase();if(f&&l===f)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 h=d||i||(c[0]&&l!==c[0]?c[0]:null)||r;if(h&&l===String(h).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||!h)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 s({quoter:p,tokenIn:h,tokenOut:n,amountIn:a},u);if(!y.best){let E=c.find(w=>w&&w!==String(h).toLowerCase()&&w!==String(n).toLowerCase());if(E){let w=await s({quoter:p,tokenIn:E,tokenOut:n,amountIn:a},u);if(w.best){let g=await s({quoter:p,tokenIn:n,tokenOut:E,amountIn:w.best.amountOut},u);if(g.best){let C=g.best.amountOut,I=Number(C*10000n/BigInt(a)),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(a),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 s({quoter:p,tokenIn:n,tokenOut:h,amountIn:y.best.amountOut},u);if(!b.best){let E=c.find(w=>w&&w!==String(h).toLowerCase()&&w!==String(n).toLowerCase());if(E){let w=await s({quoter:p,tokenIn:E,tokenOut:n,amountIn:a},u),g=w.best?await s({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(a)),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(a),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(a)),U=m.PASS,S="round trip completes with expected fee/impact loss";return x<5e3?(U=m.FAIL,S=`round trip returns only ${(x/100).toFixed(2)}% -- punitive tax or no real liquidity`):x<9e3&&(U=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:h,verdict:U,reason:S,amountIn:String(a),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:a,amountIn:d,recipient:u,slippageBps:p=50,fee:c},i={}){let l=ae(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(!_e.test(u||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:n,tokenOut:a,amountIn:d},i);if(f.evidence!==v.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let h=c??f.fee,y=It(f.amountOut,p);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(i.useNative||f.useNative)&&r&&String(n).toLowerCase()===String(r).toLowerCase(),k=`0x${qe.exactInputSingle}`+M(n)+M(a)+B(h)+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:f.amountOut,minOut:y.toString(),slippageBps:p,maxSlippageBps:ie,fee:h},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 W={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 s=e.slice(128,128+o*2),n=Buffer.from(s,"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,s,n){return q(e,"eth_call",[{to:o,data:s},"latest"],n)}return{async blockNumber(o={}){let s=await xe(e,o);return{chainId:e,blockNumber:s?.blockNumber??s,evidence:v.LIVE}},async nativeBalance(o,s={}){let n=await Ie(e,o,s);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:s},n={}){let a=await Ne({chainId:e,token:o,owner:s},n);return{chainId:e,token:o,owner:s,raw:a?.balance??a,evidence:v.LIVE}},async resolveToken(o,s={}){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,a,d,u]=await Promise.all([r(o,W.decimals,s).catch(()=>null),r(o,W.symbol,s).catch(()=>null),r(o,W.name,s).catch(()=>null),r(o,W.totalSupply,s).catch(()=>null)]),p=Be(n?.result??n),c=p!==null||a?.result||d?.result;return{chainId:e,address:o,decimals:p===null?null:Number(p),symbol:Pe(a?.result??a),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,s={}){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 a=await Ue(o,s).catch(()=>null),u=(a?.pairs||a?.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:s,address:n,topics:a,chunkSize:d=2e3}={},u={}){if(!Number.isInteger(o)||!Number.isInteger(s))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(s<o)throw new Error("toBlock must be >= fromBlock");let p=[],c=[];for(let l=o;l<=s;l+=d){let f=Math.min(l+d-1,s);c.push([l,f])}let i=await ye(c,4,async([l,f])=>{let h={fromBlock:`0x${l.toString(16)}`,toBlock:`0x${f.toString(16)}`};n&&(h.address=n),a&&(h.topics=a);let y=await q(e,"eth_getLogs",[h],u).catch(b=>({error:String(b?.message||b)}));return{start:l,end:f,res:y}});for(let{start:l,end:f,res:h}of i){if(h?.error)return{chainId:e,fromBlock:o,toBlock:s,logs:p,complete:!1,failedAt:[l,f],error:h.error,evidence:v.UNKNOWN};for(let y of h?.result??h??[])p.push(y)}return{chainId:e,fromBlock:o,toBlock:s,logs:p,complete:!0,chunks:c.length,evidence:v.LIVE}},async scoreRisk(o,s={}){let n=[],a=m.PASS,d=c=>{let i={[m.PASS]:0,[m.CAUTION]:1,[m.UNKNOWN]:2,[m.FAIL]:3};i[c]>i[a]&&(a=c)},[u,p]=await Promise.all([this.resolveToken(o,s),this.resolvePools(o,s)]);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()},s).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:a,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,a)=>(await r.resolvePools(n,a)).quoteAsset||null})):t.venueKind==="uniswap-v2"&&o.has("router")&&Object.assign(r,Le({chainId:t.chainId,wrappedNative:t.wrappedNative}));let s={};for(let[n,a]of Object.entries(r))s[n]=a.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:s}}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=>K(ce(t)))}function Tt(t){return K(ce(t))}export{Fe as CHAIN_CONFIGS,v as EVIDENCE,m as RISK,O as SCANNER_CAPABILITIES,qt as __clearScanners,Ve as createScanner,Ut as getScanner,Lt as listScanners,kt as registerBuiltinScanners,Tt as registerCustomChain,K as registerScanner,_t as scannerCoverage,De as validateScanner};
6
+ ${JSON.stringify(r??[])}`}async function yt(t,e,r){return z(t,{method:"POST",body:e,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function q(t,e,r=[],o={}){let s=String(e||""),n=ht(s),a=pt(t,o);if(!a)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(a);if(c!=null)return c}let u=o.dedupe!==!1&&!o.signal?vt(a,s,r):null;if(u&&V.has(u))return V.get(u);let p=(async()=>{let c=await yt(a,{jsonrpc:"2.0",id:1,method:e,params:r},o),i=bt(c);return n==="eth_chainid"&&typeof i=="string"&&Ce.set(a,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 q(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 q(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"),s=Ae(t.account||t.owner||t.address,"account"),n=Se.encodeFunctionData("balanceOf",[s]),a=await q(r,"eth_call",[{to:o,data:n},t.blockTag||"latest"],e),d=Se.decodeFunctionResult("balanceOf",a),u=BigInt(d[0]);return{chainId:r,token:o,account:s,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(),s=String(e?.base||e?.baseToken?.address||"").toLowerCase();return o===r?{address:e.base||e.baseToken?.address,symbol:e.baseToken?.symbol}:s===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 s=String(t||"").toLowerCase(),n=new Set((r||[]).map(u=>String(u).toLowerCase())),a=String(o||"").toLowerCase(),d=(e||[]).map((u,p)=>{let c=ke(s,u),i=String(c.address||"").toLowerCase(),l=String(c.symbol||"").toLowerCase(),f=Number(u.liquidityUsd??u.liquidity?.usd),h=Number.isFinite(f)?f:0,y=String(u.dex||u.dexId||"").toLowerCase(),b=0;return n.has(i)||gt.has(l)?b=300:a&&i===a&&(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+h,index:p,otherAddr:i,liquidityUsd:h}});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 Ue(t,e={}){if(!t)throw new Error("tokenAddress required");return z(`${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 s=0;s<r;s++){let n=128+s*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 se=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>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 Le(t){let{chainId:e,wrappedNative:r}=t;async function o(s,n,a,d){let u=await q(e,"eth_call",[{to:s,data:St(n,a)},"latest"],d);return At(u?.result??u)}return{async quote({tokenIn:s,tokenOut:n,amountIn:a,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||[s,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,a,c,u);return i?{chainId:e,router:p,path:c,amountIn:String(a),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:s,amountIn:n,base:a},d={}){let u=ne(d.scanner),p=a||r;if(p&&String(s).toLowerCase()===String(p).toLowerCase())return{chainId:e,token:s,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:s,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,s],d);if(!c)return{chainId:e,token:s,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:s,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let l=await o(u,i,[s,p],d);if(!l)return{chainId:e,token:s,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 f=l[l.length-1],h=Number(f*10000n/BigInt(n)),y=m.PASS,b="round trip completes with expected fee/impact loss";return h<5e3?(y=m.FAIL,b=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(y=m.CAUTION,b=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:s,base:p,router:u,verdict:y,reason:b,amountIn:String(n),bought:i.toString(),returned:f.toString(),retentionBps:h,evidence:v.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:n,amountIn:a,recipient:d,slippageBps:u=50,deadlineSeconds:p=900,path:c},i={}){let l=i.scanner,f=ne(l);if(!f)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 h=c||[s,n],y=await this.quote({tokenIn:s,tokenOut:n,amountIn:a,path:h},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&&h[0].toLowerCase()===r.toLowerCase()&&i.useNative,U=x?`0x${oe.swapExactETHForTokens}`+T(b)+T(128)+H(d)+T(k)+T(h.length)+h.map(H).join(""):`0x${oe.swapExactTokensForTokens}`+T(a)+T(b)+T(160)+H(d)+T(k)+T(h.length)+h.map(H).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:f,data:U,value:x?`0x${BigInt(a).toString(16)}`:"0x0"},guard:{quotedOut:y.amountOut,minOut:b.toString(),slippageBps:u,maxSlippageBps:se,deadline:k.toString()},requires:x?[]:[{step:"approve",token:h[0],spender:f,amount:String(a)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var xt=[100,500,3e3,1e4],qe={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},B=t=>BigInt(t).toString(16).padStart(64,"0"),M=t=>t.slice(2).toLowerCase().padStart(64,"0"),_e=/^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 ae(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:a,tokenOut:d,amountIn:u,fee:p},c){let i=`0x${qe.quoteExactInputSingle}`+M(a)+M(d)+B(u)+B(p)+B(0),l=await q(e,"eth_call",[{to:n,data:i},"latest"],c).catch(()=>null),f=l?.result??l;if(!f||f==="0x"||f.length<66)return null;let h=BigInt(`0x${f.slice(2,66)}`);return h>0n?h:null}async function s({quoter:n,tokenIn:a,tokenOut:d,amountIn:u},p){let c=await Promise.all(xt.map(async l=>{let f=await o({quoter:n,tokenIn:a,tokenOut:d,amountIn:u,fee:l},p);return{fee:l,amountOut:f?f.toString():null,out:f}})),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:f})=>({fee:l,amountOut:f}))}}return{async quote({tokenIn:n,tokenOut:a,amountIn:d},u={}){let p=ae(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,a])if(!_e.test(l||""))throw new Error("quote requires valid 20-byte addresses");let{best:c,tried:i}=await s({quoter:p,tokenIn:n,tokenOut:a,amountIn:d},u);return c?{chainId:e,venue:"uniswap-v3",quoter:p,tokenIn:n,tokenOut:a,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:a,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:a,base:d},u={}){let p=ae(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(),f=String(r||"").toLowerCase();if(f&&l===f)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 h=d||i||(c[0]&&l!==c[0]?c[0]:null)||r;if(h&&l===String(h).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||!h)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 s({quoter:p,tokenIn:h,tokenOut:n,amountIn:a},u);if(!y.best){let E=c.find(w=>w&&w!==String(h).toLowerCase()&&w!==String(n).toLowerCase());if(E){let w=await s({quoter:p,tokenIn:E,tokenOut:n,amountIn:a},u);if(w.best){let g=await s({quoter:p,tokenIn:n,tokenOut:E,amountIn:w.best.amountOut},u);if(g.best){let C=g.best.amountOut,I=Number(C*10000n/BigInt(a)),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(a),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 s({quoter:p,tokenIn:n,tokenOut:h,amountIn:y.best.amountOut},u);if(!b.best){let E=c.find(w=>w&&w!==String(h).toLowerCase()&&w!==String(n).toLowerCase());if(E){let w=await s({quoter:p,tokenIn:E,tokenOut:n,amountIn:a},u),g=w.best?await s({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(a)),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(a),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(a)),U=m.PASS,S="round trip completes with expected fee/impact loss";return x<5e3?(U=m.FAIL,S=`round trip returns only ${(x/100).toFixed(2)}% -- punitive tax or no real liquidity`):x<9e3&&(U=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:h,verdict:U,reason:S,amountIn:String(a),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:a,amountIn:d,recipient:u,slippageBps:p=50,fee:c},i={}){let l=ae(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(!_e.test(u||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:n,tokenOut:a,amountIn:d},i);if(f.evidence!==v.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let h=c??f.fee,y=It(f.amountOut,p);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(i.useNative||f.useNative)&&r&&String(n).toLowerCase()===String(r).toLowerCase(),k=`0x${qe.exactInputSingle}`+M(n)+M(a)+B(h)+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:f.amountOut,minOut:y.toString(),slippageBps:p,maxSlippageBps:ie,fee:h},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 W={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 s=e.slice(128,128+o*2),n=Buffer.from(s,"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,s,n){return q(e,"eth_call",[{to:o,data:s},"latest"],n)}return{async blockNumber(o={}){let s=await xe(e,o);return{chainId:e,blockNumber:s?.blockNumber??s,evidence:v.LIVE}},async nativeBalance(o,s={}){let n=await Ie(e,o,s);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:s},n={}){let a=await Ne({chainId:e,token:o,owner:s},n);return{chainId:e,token:o,owner:s,raw:a?.balance??a,evidence:v.LIVE}},async resolveToken(o,s={}){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,a,d,u]=await Promise.all([r(o,W.decimals,s).catch(()=>null),r(o,W.symbol,s).catch(()=>null),r(o,W.name,s).catch(()=>null),r(o,W.totalSupply,s).catch(()=>null)]),p=Be(n?.result??n),c=p!==null||a?.result||d?.result,i={chainId:e,address:o,decimals:p===null?null:Number(p),symbol:Pe(a?.result??a),name:Pe(d?.result??d),totalSupply:(Be(u?.result??u)??null)?.toString()??null,evidence:c?v.LIVE:v.UNKNOWN};return c||(i.warning="no ERC-20 metadata returned -- may not be a token contract"),i},async resolvePools(o,s={}){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 a=await Ue(o,s).catch(()=>null),u=(a?.pairs||a?.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:s,address:n,topics:a,chunkSize:d=2e3}={},u={}){if(!Number.isInteger(o)||!Number.isInteger(s))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(s<o)throw new Error("toBlock must be >= fromBlock");let p=[],c=[];for(let l=o;l<=s;l+=d){let f=Math.min(l+d-1,s);c.push([l,f])}let i=await ye(c,4,async([l,f])=>{let h={fromBlock:`0x${l.toString(16)}`,toBlock:`0x${f.toString(16)}`};n&&(h.address=n),a&&(h.topics=a);let y=await q(e,"eth_getLogs",[h],u).catch(b=>({error:String(b?.message||b)}));return{start:l,end:f,res:y}});for(let{start:l,end:f,res:h}of i){if(h?.error)return{chainId:e,fromBlock:o,toBlock:s,logs:p,complete:!1,failedAt:[l,f],error:h.error,evidence:v.UNKNOWN};for(let y of h?.result??h??[])p.push(y)}return{chainId:e,fromBlock:o,toBlock:s,logs:p,complete:!0,chunks:c.length,evidence:v.LIVE}},async scoreRisk(o,s={}){let n=[],a=m.PASS,d=c=>{let i={[m.PASS]:0,[m.CAUTION]:1,[m.UNKNOWN]:2,[m.FAIL]:3};i[c]>i[a]&&(a=c)},[u,p]=await Promise.all([this.resolveToken(o,s),this.resolvePools(o,s)]);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()},s).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:a,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,a)=>(await r.resolvePools(n,a)).quoteAsset||null})):t.venueKind==="uniswap-v2"&&o.has("router")&&Object.assign(r,Le({chainId:t.chainId,wrappedNative:t.wrappedNative}));let s={};for(let[n,a]of Object.entries(r))s[n]=a.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:s}}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=>K(ce(t)))}function Tt(t){return K(ce(t))}export{Fe as CHAIN_CONFIGS,v as EVIDENCE,m as RISK,O as SCANNER_CAPABILITIES,qt as __clearScanners,Ve as createScanner,Ut as getScanner,Lt as listScanners,kt as registerBuiltinScanners,Tt as registerCustomChain,K as registerScanner,_t as scannerCoverage,De as validateScanner};
@@ -0,0 +1 @@
1
+ var L=Object.freeze(["draft","shadow","confirm","autonomous","halted"]),D=Object.freeze([["anthropic-oauth","oauth"],["openai-codex","oauth"],["xai-oauth","oauth"],["openrouter","api-key"],["openai","api-key"],["anthropic","api-key"],["xai","api-key"],["deepseek","api-key"],["gemini","api-key"],["kimi","api-key"],["mistral","api-key"],["nous","api-key"]].map(([e,r])=>Object.freeze({id:e,auth:r}))),Y=[["market.scan","Read bounded market observations"],["sentiment.read","Read cited public sentiment"],["wallet.watch","Observe public wallet activity"],["contract.read","Inspect public contract state"],["nft.inspect","Inspect public mint state"],["strategy.analyze","Analyze a strategy without executing it"],["strategy.backtest","Backtest against supplied history"],["risk.evaluate","Evaluate an intent against policy"],["intent.prepare","Prepare a non-executable intent"],["operator.handoff","Create an operator confirmation handoff"]],M=Object.freeze(Y.map(([e,r])=>Object.freeze({id:e,description:r,signs:!1,broadcasts:!1}))),V=[["hyperliquid-markets","Research Hyperliquid market evidence"],["social-sentiment","Score cited public sentiment"],["wallet-monitoring","Analyze public wallet activity"],["contract-research","Research public contract state"],["mint-research","Research public mint state"],["bounded-strategy-analysis","Analyze bounded strategy evidence"],["bounded-backtesting","Backtest against supplied history"],["bounded-risk","Evaluate evidence against fixed policy"],["prepare-only-execution","Prepare an operator confirmation handoff"]],$=Object.freeze(V.map(([e,r])=>Object.freeze({id:e,description:r,signs:!1,broadcasts:!1}))),B=Object.freeze({autonomousOptIn:!1,requiresWalletConfirmation:!0,killSwitchRequired:!0,maxNotionalUsd:100,maxDailyLossUsd:10,chainAllowlist:Object.freeze(["ethereum"]),expiresAt:41024448e5});function v({id:e,name:r,scannerName:a,scannerTool:d,scannerSkill:u,scannerArtifact:f,chainAllowlist:x}){return Object.freeze({id:e,name:r,mode:"draft",agents:Object.freeze([Object.freeze({id:"scanner",name:a,role:"scanner",runtime:"deterministic",soul:"Collect bounded public evidence with source times.",toolIds:Object.freeze([d]),skillIds:Object.freeze([u])}),Object.freeze({id:"sentiment",name:"Grok Sentiment",role:"sentiment",runtime:"model",provider:"xai",model:"grok-4.6",soul:"Score narrative direction and cite every claim.",toolIds:Object.freeze(["sentiment.read"]),skillIds:Object.freeze(["social-sentiment"])}),Object.freeze({id:"strategy",name:"Strategy Analyst",role:"strategy",runtime:"model",provider:"openai",model:"gpt-5.6-sol",soul:"Produce a falsifiable thesis from typed evidence.",toolIds:Object.freeze(["strategy.analyze"]),skillIds:Object.freeze(["bounded-strategy-analysis"])}),Object.freeze({id:"risk",name:"Risk Gate",role:"risk",runtime:"policy",soul:"Enforce every cap exactly and reject unsupported intent.",toolIds:Object.freeze(["risk.evaluate"]),skillIds:Object.freeze(["bounded-risk"])}),Object.freeze({id:"executor",name:"Executor",role:"executor",runtime:"operator",soul:"Prepare an exact operator handoff. Never sign or broadcast.",toolIds:Object.freeze(["intent.prepare","operator.handoff"]),skillIds:Object.freeze(["prepare-only-execution"])})]),edges:Object.freeze([Object.freeze({from:"scanner",to:"sentiment",artifactKind:f}),Object.freeze({from:"sentiment",to:"strategy",artifactKind:"scored-thesis"}),Object.freeze({from:"strategy",to:"risk",artifactKind:"strategy-analysis"}),Object.freeze({from:"risk",to:"executor",artifactKind:"approved-intent"})]),policy:Object.freeze({...B,chainAllowlist:Object.freeze(x)})})}var J=Object.freeze([v({id:"hyperliquid-alpha",name:"Hyperliquid Alpha",scannerName:"Market Scanner",scannerTool:"market.scan",scannerSkill:"hyperliquid-markets",scannerArtifact:"market-evidence",chainAllowlist:["hyperliquid"]}),v({id:"wallet-watch",name:"Wallet Watch",scannerName:"Wallet Monitor",scannerTool:"wallet.watch",scannerSkill:"wallet-monitoring",scannerArtifact:"wallet-flow",chainAllowlist:["ethereum","base"]}),v({id:"evm-launch-radar",name:"EVM Launch Radar",scannerName:"Launch Scanner",scannerTool:"contract.read",scannerSkill:"contract-research",scannerArtifact:"contract-evidence",chainAllowlist:["ethereum","base","arbitrum"]}),v({id:"nft-mint-guard",name:"NFT Mint Guard",scannerName:"Mint Scanner",scannerTool:"nft.inspect",scannerSkill:"mint-research",scannerArtifact:"mint-evidence",chainAllowlist:["ethereum","base"]})]);import{createHash as Q}from"node:crypto";var X=/^[a-z0-9][a-z0-9._-]{0,63}$/,Z=new Set(["deterministic","model","policy","operator"]),ee=new Set(M.map(({id:e})=>e)),te=new Set($.map(({id:e})=>e)),re=new Set(D.map(({id:e})=>e)),ne=["secret","privatekey","seed","seedphrase","mnemonic","password","passphrase","credential","apikey","apitoken","accesstoken","authtoken","authorization","signingmaterial","walletexport","keymaterial"],q=/(?:\bshell\b|terminal|raw[ _.-]?http|\bmcp\b|private[ _.-]?key|seed[ _.-]?phrase|mnemonic|key[ _.-]?(?:import|export)|wallet[ _.-]?(?:key|custody)|\bcustod(?:y|ial)\b|\bsign(?:ing|er)?\b|\bbroadcast(?:ing)?\b|(?:execute|place)[ _.-]?(?:transaction|trade|order|swap)s?|submit[ _.-]?transactions?|transfer[ _.-]?(?:funds|assets|tokens|coins)|hold[ _.-]?(?:keys|funds|assets)|ignore (?:the )?policy|bypass|widen (?:the )?(?:cap|policy)|reveal (?:credential|secret))/i,oe=Object.freeze(["market-evidence","wallet-flow","contract-evidence","mint-evidence","scored-thesis","strategy-analysis","risk-decision","approved-intent","prepared-intent","receipt"]),ae=new Set(oe);function o(e){throw new TypeError(e)}function z(e,r){(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&o(`${r} must be a plain object`)}function ie(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function F(e){let r=ie(e);return r==="auth"||ne.some(a=>r.includes(a))}function C(e,r="team",a=new Set){if(e&&typeof e=="object"){a.has(e)&&o(`unsafe cyclic field at ${r}`),a.add(e);for(let[d,u]of Object.entries(e))F(d)&&o(`forbidden secret-like field ${r}.${d}`),C(u,`${r}.${d}`,a);a.delete(e)}}function g(e){return e===null||typeof e=="string"||typeof e=="boolean"?e:typeof e=="number"?(Number.isFinite(e)||o("value must be finite"),e):Array.isArray(e)?e.map(g):(z(e,"value"),Object.fromEntries(Object.keys(e).sort().map(r=>(F(r)&&o(`forbidden secret-like field ${r}`),[r,g(e[r])]))))}function E(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let r of Object.values(e))E(r);Object.freeze(e)}return e}function j(e){return Q("sha256").update(JSON.stringify(g(e))).digest("hex")}function T(e,r,a=500){return(typeof e!="string"||!e.trim()||e.length>a)&&o(`${r} is invalid`),e}function O(e,r){return T(e,r,64),X.test(e)||o(`${r} is invalid`),e}function se(e){let r=String.raw`(?:sign(?:ing)?|broadcast(?:ing)?|(?:execute|place|submit|transfer|hold|assume)\b[^.!?\n]*?\b(?:transactions?|trades?|orders?|swaps?|funds|assets|tokens|coins|keys|custody))`,a=e.replace(new RegExp(String.raw`\b(?:never|do not|don't|cannot|can't|must not|may not)\s+(?:directly\s+)?${r}(?:\s+or\s+${r})?`,"gi"),"");return q.test(a)||new RegExp(String.raw`\b${r}\b`,"i").test(a)}function K(e){return O(e,"artifact kind"),ae.has(e)||o(`artifact kind ${e} is not allowed`),e}function N(e,{nowMs:r=Date.now(),mode:a="shadow"}={}){z(e,"policy"),C(e,"policy");let d=["autonomousOptIn","requiresWalletConfirmation","killSwitchRequired"];for(let f of d)typeof e[f]!="boolean"&&o(`policy.${f} must be boolean`);(!e.requiresWalletConfirmation||!e.killSwitchRequired)&&o("unsafe policy: wallet confirmation and kill switch are required");for(let f of["maxNotionalUsd","maxDailyLossUsd"])(!Number.isFinite(e[f])||e[f]<=0)&&o(`policy.${f} must be a positive finite cap`);(!Array.isArray(e.chainAllowlist)||!e.chainAllowlist.length)&&o("policy.chainAllowlist must be bounded");let u=e.chainAllowlist.map(f=>O(f,"chain id"));return new Set(u).size!==u.length&&o("duplicate chain id"),(!Number.isSafeInteger(e.expiresAt)||e.expiresAt<=r)&&o("policy expiry must be in the future"),a==="autonomous"&&!e.autonomousOptIn&&o("autonomous mode requires explicit opt-in"),{autonomousOptIn:e.autonomousOptIn,requiresWalletConfirmation:!0,killSwitchRequired:!0,maxNotionalUsd:e.maxNotionalUsd,maxDailyLossUsd:e.maxDailyLossUsd,chainAllowlist:u,expiresAt:e.expiresAt}}function P(e,{nowMs:r=Date.now()}={}){z(e,"team"),C(e),O(e.id,"team id"),T(e.name,"team name",120),L.includes(e.mode)||o("unsupported team mode"),(!Array.isArray(e.agents)||!e.agents.length)&&o("agents must be non-empty");let a=new Set,d=e.agents.map((t,h)=>{z(t,`agent ${h}`);let w=O(t.id,"agent id");a.has(w)&&o(`duplicate agent id ${w}`),a.add(w),T(t.name,"agent name",120),O(t.role,"agent role"),Z.has(t.runtime)||o("invalid agent runtime");let b=T(t.soul,"agent Soul",2e3);se(b)&&o("unsafe Soul authority"),(!Array.isArray(t.toolIds)||!Array.isArray(t.skillIds))&&o("tool and skill IDs must be arrays");let H=t.toolIds.map(y=>(O(y,"tool id"),(!ee.has(y)||q.test(y))&&o(`forbidden tool ${y}`),y)),R=t.skillIds.map(y=>(O(y,"skill id"),(!te.has(y)||q.test(y))&&o(`forbidden skill ${y}`),y));(new Set(H).size!==H.length||new Set(R).size!==R.length)&&o("duplicate tool or skill ID");let G=t.runtime==="model";return G?(T(t.provider,"model provider",100),re.has(t.provider)||o("unsupported model provider"),T(t.model,"model",160)):(t.provider!==void 0||t.model!==void 0)&&o("provider/model only allowed for model runtime"),t.role==="executor"&&t.runtime!=="operator"&&o("executor must use operator runtime"),t.runtime==="operator"&&t.role!=="executor"&&o("operator runtime is reserved for the executor"),t.role!=="executor"&&H.some(y=>y==="intent.prepare"||y==="operator.handoff")&&o("executor tools require operator authority"),{id:w,name:t.name,role:t.role,runtime:t.runtime,...G?{provider:t.provider,model:t.model}:{},soul:b,toolIds:H,skillIds:R}}),u=d.filter(t=>t.role==="executor");u.length!==1&&o("exactly one executor operator is required");let f=u[0];(!f.toolIds.includes("intent.prepare")||!f.toolIds.includes("operator.handoff"))&&o("executor requires prepare-only handoff tools"),Array.isArray(e.edges)||o("edges must be an array");let x=new Set,A=new Map([...a].map(t=>[t,[]])),l=e.edges.map(t=>{z(t,"edge"),O(t.from,"edge source"),O(t.to,"edge target");let h=K(t.artifactKind);(!a.has(t.from)||!a.has(t.to))&&o("broken edge references unknown agent"),t.from===t.to&&o("cycle in team DAG");let w=`${t.from}\0${t.to}\0${h}`;return x.has(w)&&o("duplicate edge"),x.add(w),A.get(t.from).push(t.to),{from:t.from,to:t.to,artifactKind:h}}),i=new Set,n=new Set;function s(t){if(i.has(t)&&o("cycle in team DAG"),!n.has(t)){i.add(t);for(let h of A.get(t))s(h);i.delete(t),n.add(t)}}for(let t of a)s(t);A.get(f.id).length&&o("executor must be the terminal team agent");let c=t=>{let h=[t],w=new Set;for(;h.length;){let b=h.shift();if(b===f.id)return!0;w.has(b)||(w.add(b),h.push(...A.get(b)))}return!1};for(let t of a)c(t)||o(`agent ${t} is disconnected from executor`);let m=d.filter(t=>!l.some(h=>h.to===t.id));m.length!==1&&o("team pipeline requires exactly one root agent");for(let t of d){let h=l.filter(b=>b.to===t.id).length,w=l.filter(b=>b.from===t.id).length;(t.id===m[0].id?h!==0:h!==1)&&o("team pipeline requires exactly one incoming handoff per non-root agent"),(t.id===f.id?w!==0:w!==1)&&o("team pipeline requires exactly one outgoing handoff per non-executor agent")}let p=l.filter(t=>t.to===f.id);(p.length!==1||p[0].artifactKind!=="approved-intent")&&o("executor requires exactly one approved-intent input"),d.find(t=>t.id===p[0].from)?.runtime!=="policy"&&o("executor input must come from a policy agent");let k=N(e.policy,{nowMs:r,mode:e.mode}),I=g({id:e.id,name:e.name,mode:e.mode,agents:d,edges:l,policy:k});return E({team:I,teamHash:j(I),execution:{executionAllowed:!1,backendSigner:!1,signingReady:!1,broadcastReady:!1,requiresOperatorConfirmation:!0}})}var ce=/^[a-z0-9][a-z0-9._:-]{0,127}$/i,de=/^[0-9a-f]{64}$/,fe=/^evidence:sha256:[0-9a-f]{64}$/,le=new Set(["approved-intent","prepared-intent"]);function _(e,r){if(typeof e!="string"||!ce.test(e))throw new TypeError(`${r} is invalid`);return e}function me(e,r){if(typeof e!="string"||!de.test(e))throw new TypeError(`${r} is invalid`);return e}function ue(e,r){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("intent payload must be an object");if(typeof e.chainId!="string"||!r.chainAllowlist.includes(e.chainId))throw new TypeError("intent chain is outside policy allowlist");if(!Number.isFinite(e.notionalUsd)||e.notionalUsd<=0||e.notionalUsd>r.maxNotionalUsd)throw new TypeError("intent notional exceeds policy cap");if(!Number.isFinite(e.maxLossUsd)||e.maxLossUsd<0||e.maxLossUsd>r.maxDailyLossUsd)throw new TypeError("intent loss exceeds policy cap")}function U(e,{compiled:r}={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("handoff must be an object");if(!r?.team||typeof r.teamHash!="string")throw new TypeError("compiled team snapshot is required");let a=e.nowMs??Date.now();if(!Number.isSafeInteger(a))throw new TypeError("nowMs is invalid");if(!Number.isSafeInteger(e.ttlMs)||e.ttlMs<=0||e.ttlMs>6e4)throw new TypeError("TTL must be bounded to 60 seconds");let d=_(e.teamId,"teamId"),u=me(e.teamHash,"teamHash");if(r.team.id!==d||r.teamHash!==u)throw new TypeError("handoff team snapshot mismatch");let f=_(e.sourceAgentId,"sourceAgentId"),x=_(e.targetAgentId,"targetAgentId"),A=K(e.artifactKind);if(!r.team.edges.some(m=>m.from===f&&m.to===x&&m.artifactKind===A))throw new TypeError("handoff does not match compiled team edge");if(!Array.isArray(e.evidenceRefs)||!e.evidenceRefs.length)throw new TypeError("evidenceRefs must be non-empty");let l=e.evidenceRefs.map(m=>{if(typeof m!="string"||!fe.test(m))throw new TypeError("evidence reference must be a SHA-256 content hash");return m});if(new Set(l).size!==l.length)throw new TypeError("duplicate evidence reference");let i=g(e.payload),n=N(r.team.policy,{nowMs:a,mode:r.team.mode}),s=a+e.ttlMs;if(s>n.expiresAt)throw new TypeError("handoff TTL exceeds policy expiry");le.has(A)&&ue(i,n);let c={teamId:d,teamHash:u,runId:_(e.runId,"runId"),sourceAgentId:f,targetAgentId:x,artifactKind:A,payload:i,payloadHash:j(i),evidenceRefs:l,ttlMs:e.ttlMs,issuedAt:a,expiresAt:s,policy:n,policyHash:j(n)};return E(g({...c,handoffHash:j(c),executionAllowed:!1,backendSigner:!1,signingReady:!1,broadcastReady:!1,requiresOperatorConfirmation:!0}))}import{randomUUID as pe}from"node:crypto";function W(e,r,a){if(a>=r.compiled.team.policy.expiresAt)throw e.status="expired",e.updatedAt=a,new Error("team policy expired")}function he({now:e=Date.now,storage:r}={}){let a=r??new Map,d=new Map,u=new Map,f=async(i,n)=>a.set(i,g(n)),x=async i=>a.get(i),A=async()=>a instanceof Map?[...a.values()]:a.list(),l=i=>E(g(i));return Object.freeze({async save(i){let n=P(i,{nowMs:e()});return await f(n.team.id,n),l(n)},async list(){return l(await A())},async get(i){let n=await x(i);return n===void 0?null:l(n)},async start(i){let n=await x(i);if(!n)throw new Error(`unknown team ${i}`);let s=E(g(n));if(s.team.mode==="draft")throw new Error("draft team must be promoted before running");if(s.team.mode==="halted")throw new Error("team kill switch is active");let c=e();if(c>=s.team.policy.expiresAt)throw new Error("team policy expired");let m=s.team.agents.find(S=>!s.team.edges.some(k=>k.to===S.id));if(!m)throw new Error("team pipeline has no root agent");let p={id:pe(),teamId:i,teamHash:s.teamHash,status:s.team.mode==="shadow"?"shadowing":"running",mode:s.team.mode,startedAt:c,updatedAt:c,expiresAt:s.team.policy.expiresAt,maxSteps:s.team.edges.length,steps:[],executionAllowed:!1,backendSigner:!1,signingReady:!1,broadcastReady:!1,requiresOperatorConfirmation:!0};return d.set(p.id,p),u.set(p.id,{compiled:s,currentAgentId:m.id,previousHandoffHash:null,consumedHandoffHashes:new Set}),l(p)},async step(i,n){let s=d.get(i),c=u.get(i);if(!s||!c)throw new Error(`unknown run ${i}`);if(s.status==="halted")throw new Error("run is halted");if(s.status==="paused")throw new Error("run is paused");if(s.status!=="running"&&s.status!=="shadowing")throw new Error("run cannot step from its current state");let m=e();if(W(s,c,m),s.steps.length>=s.maxSteps)throw new Error("run step budget exhausted");if(n?.agentId!==c.currentAgentId)throw new TypeError("step agent is out of order");let p=c.compiled.team.edges.find(t=>t.from===n.agentId);if(!p||p.to!==n?.targetAgentId||p.artifactKind!==n?.artifactKind)throw new TypeError("artifact does not match the exact next team edge");let S,k=null;if(c.previousHandoffHash===null){if(n.inputHandoffHash!==void 0)throw new TypeError("root step cannot consume a prior handoff");S=n.evidenceRefs}else{if(n.inputHandoffHash!==c.previousHandoffHash)throw new TypeError("step must consume the exact prior handoff");if(c.consumedHandoffHashes.has(n.inputHandoffHash))throw new TypeError("handoff was already consumed");k=n.inputHandoffHash,S=[`evidence:sha256:${n.inputHandoffHash}`]}let I=U({teamId:s.teamId,teamHash:s.teamHash,runId:i,sourceAgentId:p.from,targetAgentId:p.to,artifactKind:p.artifactKind,payload:n.payload,evidenceRefs:S,ttlMs:n.ttlMs,nowMs:m},{compiled:c.compiled});return k!==null&&c.consumedHandoffHashes.add(k),s.steps.push(I),s.updatedAt=m,c.currentAgentId=p.to,c.previousHandoffHash=I.handoffHash,p.to===c.compiled.team.agents.find(t=>t.role==="executor").id&&(s.status="prepared",s.completedAt=m),l(s)},async pause(i){let n=d.get(i);if(!n)throw new Error(`unknown run ${i}`);if(n.status!=="running"&&n.status!=="shadowing")throw new Error("only an active run can be paused");return n.resumeStatus=n.status,n.status="paused",n.updatedAt=e(),l(n)},async resume(i){let n=d.get(i),s=u.get(i);if(!n||!s)throw new Error(`unknown run ${i}`);if(n.status!=="paused")throw new Error("only a paused run can be resumed");let c=e();return W(n,s,c),n.status=n.resumeStatus==="shadowing"?"shadowing":"running",delete n.resumeStatus,n.updatedAt=c,l(n)},async halt(i){let n=d.get(i);if(!n)throw new Error(`unknown run ${i}`);return n.status="halted",delete n.resumeStatus,n.updatedAt=e(),l(n)}})}export{$ as CRYPTO_SKILL_CATALOG,M as CRYPTO_TOOL_CATALOG,D as MODEL_PROVIDER_CATALOG,L as TEAM_MODES,J as TEAM_TEMPLATES,P as compileTeamDefinition,U as createTeamHandoff,he as createTeamService};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oracle-agent/oracle",
3
- "version": "0.35.26",
3
+ "version": "0.35.28",
4
4
  "description": "Oracle: standalone multichain agent control plane with an optional encrypted, loopback-only self-hosted signer.",
5
5
  "license": "BUSL-1.1",
6
6
  "type": "module",
@@ -96,6 +96,7 @@
96
96
  "./signals": "./dist/signals/index.mjs",
97
97
  "./strategy": "./dist/strategy/index.mjs",
98
98
  "./launch-radar": "./dist/launch-radar/index.mjs",
99
+ "./teams": "./dist/teams/index.mjs",
99
100
  "./agent-grants": "./dist/public-api/agent-grants.mjs",
100
101
  "./session-orchestrator": "./dist/public-control/session-orchestrator.mjs",
101
102
  "./control-plane": "./dist/control-plane/index.mjs",