@oracle-agent/oracle 0.22.15 → 0.22.16

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.
@@ -0,0 +1,39 @@
1
+ var Uo=Object.defineProperty;var S=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var re=(e,t)=>{for(var r in t)Uo(e,r,{get:t[r],enumerable:!0})};import{createHash as ea}from"node:crypto";function oa(e){let t=String(e||"").toLowerCase();return kr.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function aa(e){let t={};for(let[r,n]of Object.entries(e||{}))oa(r)||(t[r]=n);return t}function ia(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 sa(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function ca(e,t,r){let n={};for(let[c,u]of Object.entries(r||{}))n[c.toLowerCase()]=u;let o=Object.keys(n).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),s=[...new Set([...kr,...o])].sort().map(c=>`${c}=${n[c]??""}`).join(`
2
+ `),i=ea("sha256").update(s).digest("hex").slice(0,32);return`${e} ${t} ${i}`}function ua(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Ir):Math.min(250*2**e,Ir)+Math.floor(Math.random()*100)}async function da(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:a}){let s=new AbortController,i=setTimeout(()=>s.abort(),a);try{let c=String(e),u={...n||{}};for(let p=0;p<=Cr;p+=1){let d=await t(c,{method:r,headers:u,body:o,signal:s.signal,redirect:"manual"}),l=await d.text(),m=null;if(l)try{m=JSON.parse(l)}catch{m=null}if(na.has(d.status)){if(r!=="GET"&&r!=="HEAD"){let w=new Error(`HTTP ${d.status} ${r} ${c} redirected non-idempotent request`);throw w.status=d.status,w.body=m??l.slice(0,300),w}if(p===Cr)throw new Error(`HTTP redirect loop for ${e}`);let h=ia(d.headers?.get?.("location"),c);sa(h,c)||(u=aa(u)),c=h;continue}if(!d.ok){let h=new Error(`HTTP ${d.status} ${r} ${c}`);throw h.status=d.status,h.retryAfter=d.headers?.get?.("retry-after")??null,h.body=m??l.slice(0,300),h}return m??l}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(i)}}async function A(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,o=(t.method||"GET").toUpperCase(),a={Accept:"application/json",...t.headers||{}},s=t.body;s!=null&&typeof s!="string"&&(a["Content-Type"]=a["Content-Type"]||"application/json",s=JSON.stringify(s));let i=Number.isInteger(t.retries)?Math.max(t.retries,0):ra,c=async()=>{let m;for(let h=0;h<=i;h++)try{return await da(e,{fetchImpl:r,method:o,headers:a,body:s,timeoutMs:n})}catch(w){m=w;let f=w?.status,b=w?.name==="AbortError",g=new Set([408,425,429]),E=f!=null?g.has(f)||ta.has(f)&&Sr.has(o):!b&&Sr.has(o);if(h===i||!E)throw w;await la(ua(h,w?.retryAfter))}throw m};if(!(t.dedupe!==!1&&o==="GET"&&s==null))return c();let p=ca(o,e,a),d=St.get(p);if(d)return d;let l=c().finally(()=>St.delete(p));return St.set(p,l),l}var ta,Sr,ra,Ir,kr,na,Cr,St,la,q=S(()=>{ta=new Set([408,425,429,500,502,503,504]),Sr=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),ra=2,Ir=4e3,kr=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],na=new Set([301,302,303,307,308]),Cr=3;St=new Map;la=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as pa}from"node:fs";import{homedir as fa}from"node:os";import{join as Ue}from"node:path";function ma(){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=fa();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Ue(t,".config","oracle")).trim();return[e,Ue(r,"exec.env")].filter(Boolean)}return[e,Ue(t,".config","oracle","exec.env"),Ue(t,".config","mad-desk","exec.env")].filter(Boolean)}function W(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of ma())try{let a=pa(o,"utf8"),s=a.match(new RegExp(`^${t}=(.*)$`,"m"))||a.match(new RegExp(`^${r}=(.*)$`,"m"));if(s&&(n=s[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}var de=S(()=>{});function O(e,t,r="guard"){let n=Number(t);if(t==null||!Number.isFinite(n))throw new Error(`${r}: current time must be a finite number (got ${ha(t)})`);let o=Number(e?.issuedAtMs),a=Number(e?.expiresAtMs);if(!Number.isFinite(a))throw new Error(`${r}: expiresAtMs is required and must be a finite number`);if(n>a)throw new Error(`${r} expired at ${a}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${r}: issuedAtMs must be a finite number when present`);if(a<=o)throw new Error(`${r}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:a}}function ha(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var J=S(()=>{});import{createHash as wa,createHmac as _r,timingSafeEqual as ba}from"node:crypto";function qe(e){return Array.isArray(e)?`[${e.map(qe).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${qe(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Or(e,{required:t=!1}={}){try{return W(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Ct(e){let{signature:t,...r}=e;return r}function Tr(e,{secret:t}={}){let r=Or(t);return r?{...e,signature:_r("sha256",r).update(qe(Ct(e))).digest("hex")}:e}function Lr(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 wa("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function M(e,{chainId:t,venue:r,data:n,secret:o}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");if(Number(e.chainId)!==Number(t))throw new Error("auto-slippage guard chain mismatch");if(String(e.venue).toLowerCase()!==String(r||"").toLowerCase())throw new Error("auto-slippage guard venue mismatch");return Tr({...Ct(e),calldataHash:Lr(n)},{secret:o})}function ga(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:ba(r,n)}function It(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function Ea(e){let t=e==null?Pe: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,Pe)}function ne({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:o}={}){let a=It(e,0),s=a>0?a>=25e4?5:a>=1e5?10:a>=5e4?20:a>=1e4?40:70:n?30:10,i=Math.min(60,Math.abs(It(t,0))*2),c=Math.min(40,Math.floor(Math.max(0,It(r,0))/5e3)*5),u=Math.max(25,Math.ceil(20+s+i+c)),p=Ea(o);return{mode:"auto",requiredBps:u,selectedBps:Math.min(u,p),capBps:p,executable:u<=p}}function xa({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:o=0,quoteAgeMs:a=0,crossChain:s=!1,requestedCapBps:i,quotedAtMs:c=Date.now(),ttlMs:u=Nr,secret:p}={}){let d=BigInt(r??0);if(d<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let l=ne({liquidityUsd:n,priceChange5m:o,quoteAgeMs:a,crossChain:s,requestedCapBps:i});if(!l.executable)throw new Error(`auto-slippage requires ${l.requiredBps} bps above hard/requested cap ${l.capBps}; route blocked`);let m=Number(c);if(!Number.isFinite(m))throw new Error("auto-slippage: quotedAtMs must be a finite number");let h=Math.min(3e4,Math.max(1e3,Number(u)||Nr)),w=d*BigInt(1e4-l.selectedBps),f=w/10000n;if(w%10000n!==0n&&(f+=1n),f>d&&(f=d),d>0n&&f<=0n)throw new Error(`auto-slippage: quote ${d} is too small to express a ${l.selectedBps} bps floor without rounding to zero`);let b=Number((d-f)*10000n/(d===0n?1n:d));if(b>l.capBps)throw new Error(`auto-slippage: realised floor implies ${b} bps, above cap ${l.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Tr({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:d.toString(),minAmountOut:f.toString(),requiredBps:l.requiredBps,selectedBps:l.selectedBps,capBps:l.capBps,quotedAtMs:m,expiresAtMs:m+h},{secret:p})}function ya(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 a=10;a+64<=t.length;a+=64)n.push(t.slice(a,a+64));let o=a=>n[a]==null?null:BigInt("0x"+n[a]);switch(r){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let a=o(0);if(a==null)return null;let s=Number(a)/32;return!Number.isInteger(s)||s<0?null:o(s+4)}case"0xb858183f":{let a=o(0);if(a==null)return null;let s=Number(a)/32;return!Number.isInteger(s)||s<0?null:o(s+3)}case"0xa026383e":return o(6);case"0x38ed1739":case"0x5c11d795":return o(1);case"0x7ff36ab5":case"0xb6f9de95":return o(0);case"0x18cbafe5":case"0x791ac947":return o(1);default:return null}}function Me(e,{nowMs:t=Date.now(),chainId:r,venue:n,secret:o,tx:a,requireSigned:s=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let i=Or(o,{required:s});if(s&&!i)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(i){let m=_r("sha256",i).update(qe(Ct(e))).digest("hex");if(!ga(e.signature,m))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let c=Number(e.selectedBps),u=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>Pe)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(u)||u<0||u>Pe||c>u)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{O({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},t,"auto-slippage quote")}catch(m){throw new Error(`${m.message}; re-quote before signing`)}if(r!=null&&Number(e.chainId)!==Number(r))throw new Error("auto-slippage guard chain mismatch");if(n&&String(e.venue).toLowerCase()!==String(n).toLowerCase())throw new Error("auto-slippage guard venue mismatch");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 l=p*BigInt(1e4-c)/10000n;if(d<l)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(a?.data&&e.minAmountOut!=null)if(e.calldataHash!=null){if(String(e.calldataHash)!==Lr(a.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch")}else{let m=ya(a.data);if(m==null){let h=String(a.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${h}; refusing rather than trusting unbound calldata at an allowlisted venue`)}if(m!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${m}`)}return!0}function N(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:o,priceChange5m:a,crossChain:s,requestedCapBps:i,quotedAtMs:c=Date.now(),ttlMs:u}={}){let p=xa({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:o,priceChange5m:a,crossChain:s,requestedCapBps:i,quotedAtMs:c,ttlMs:u});return{...e,autoSlippage:p,amountOutMinimum:p.minAmountOut}}var Pe,Nr,D=S(()=>{de();J();Pe=100,Nr=2e4});function kt(e){let t=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:pe}var pe,Nt=S(()=>{pe="0x000000000000000000000000000000000000dEaD"});import{createHash as Aa,createHmac as va,timingSafeEqual as gu}from"node:crypto";function _t(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(_t).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${_t(e[r])}`).join(",")}}`}function Rr(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Br(e=process.env){return Rr(process.env)||Rr(e)}function Ca(e){let{oraclePrepared:t,prepareHash:r,prepareMac:n,note:o,...a}=e||{};return a}function ka(e){let t=Ca(e);return Aa("sha256").update(_t(t)).digest("hex")}function Na(e,t=Br()){return t?va("sha256",t).update(String(e)).digest("hex"):""}function C(e,{provider:t,kind:r,env:n=process.env}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let o={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1};if(!o.provider)throw new Error("stampPrepared: provider required");if(!o.kind)throw new Error("stampPrepared: kind required");let a=Date.now(),s=a+Ia,c={...o,preparedAt:a,expiresAt:s,prepareVersion:Sa},u=ka(c),p=Br(n),d=p?Na(u,p):void 0,l={...c,oraclePrepared:!0,prepareHash:u};return d&&(l.prepareMac=d),l}var Sa,Ia,Eu,V=S(()=>{Sa=2,Ia=300*1e3,Eu=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as _a,JsonRpcProvider as Oa}from"ethers";function $a(e){return Fa.test(String(e||""))}async function Fr(e,{contract:t=Ta,rpc:r=Ra,chainId:n=La,balanceOf:o}={}){if(!$a(e))throw new Error("invalid-address");if(o)return BigInt(await o(e));let a=new Oa(r,n,{staticNetwork:!0}),s=new _a(t,Ba,a);return BigInt(await s.balanceOf(e))}var Ta,La,Ra,Ba,Fa,$r=S(()=>{Ta="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",La=999,Ra="https://rpc.hyperliquid.xyz/evm",Ba=["function balanceOf(address owner) view returns (uint256)"],Fa=/^0x[a-fA-F0-9]{40}$/});import{existsSync as Da,readFileSync as Ua}from"node:fs";import{homedir as Pa}from"node:os";import{join as Dr}from"node:path";function Va(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Ur,t)?Ur[t]:Ma}function Ka(e=process.env){if(e[Pr])return String(e[Pr]);let t=e.ORACLE_CONFIG_DIR||Dr(Pa(),".config","oracle");return Dr(t,"fee-recipient")}function za(e=process.env){try{let t=Ka(e);if(!Da(t))return"";let r=Ua(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function Xa(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),qa)}function Ya({env:e=process.env,action:t="swap",admin:r=!1}={}){let n=String(e[ja]||"").trim(),o=String(e[Wa]||Ga).trim();if(r===!0)return{bps:0,recipient:"",integrator:o,action:t,applies:!1,reason:"admin-oracle"};let a=Va(t),s=Xa(e[Ha],{fallback:n?a:0}),i=Math.min(s,a);if(!i)return{bps:0,recipient:"",integrator:o,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{bps:0,recipient:"",integrator:o,action:t,applies:!1,reason:"no-recipient"};let c=za(e);return c&&c!==n.toLowerCase()?{bps:0,recipient:"",integrator:o,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:i,recipient:n,integrator:o,action:t,applies:!0,reason:"configured"}}async function Ve({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={},admin:o=!1}={}){let a=Ya({env:t,action:r,admin:o});if(o===!0)return{...a,holderVerificationStatus:"admin-oracle"};let s=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(s))return{...a,holderVerificationStatus:"wallet-required"};try{return BigInt(await Fr(s,n))>0n?{...a,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...a,holderVerificationStatus:"non-holder"}}catch{return{...a,holderVerificationStatus:"unavailable"}}}function qr(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 Mr(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function Vr(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var qa,Ma,Ur,Ha,ja,Wa,Pr,Ga,He=S(()=>{$r();qa=100,Ma=5,Ur=Object.freeze({swap:5,bridge:5,perps:0,nft:0});Ha="ORACLE_INTEGRATOR_FEE_BPS",ja="ORACLE_INTEGRATOR_FEE_RECIPIENT",Wa="ORACLE_INTEGRATOR_ID",Pr="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",Ga="oracle"});var Wr={};re(Wr,{LIFI_API:()=>jr,lifiChains:()=>ti,lifiHealth:()=>Za,lifiPrepare:()=>ei,lifiQuote:()=>je});function Tt(e={}){return(e.baseUrl||process.env.LIFI_API_URL||jr).replace(/\/$/,"")}function Qa(e){let t=String(e||Ot).toLowerCase();return t===Ot.toLowerCase()||t===Ja}function Hr(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 Za(e={}){let t=await A(`${Tt(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 je(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:o=Ot,toToken:a,fromAmount:s,fromAddress:i=pe}=e;if(r==null||!a||!s)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let c=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:o,toToken:a,fromAmount:String(s),fromAddress:i}),u=ne({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!u.executable)throw new Error(`lifi: route requires ${u.requiredBps} bps above cap ${u.capBps}`);c.set("slippage",String(u.selectedBps/1e4));let p=await Ve({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[f,b]of Object.entries(Mr(p)))c.set(f,b);let d=await A(`${Tt(t)}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),l=d?.estimate?.toAmount||d?.toAmount;if(!l)return{...d,autoSlippagePolicy:u,oracleFee:p};let m=d?.transactionRequest?.to||d?.estimate?.approvalAddress||"lifi",h=N(d,{chainId:Number(r),venue:m,amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),w=d?.estimate?.toAmountMin||d?.toAmountMin;if(w!=null&&BigInt(w)<BigInt(h.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...h,oracleFee:p}}async function ei(e={},t={}){let r=await je(e,t),n=r?.transactionRequest;if(!n?.to||!n?.data)throw new Error("lifi: quote did not return an executable transactionRequest");let o=Number(e.fromChain);if(n.chainId!=null&&Number(n.chainId)!==o)throw new Error("lifi: transaction chain mismatch");if(e.fromAddress&&n.from&&String(n.from).toLowerCase()!==String(e.fromAddress).toLowerCase())throw new Error("lifi: transaction sender mismatch");let a=null;if(!Qa(e.fromToken)){let s=r?.estimate?.approvalAddress||r?.approvalAddress;if(!s)throw new Error("lifi: ERC20 route missing approvalAddress");let i=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;a={token:Hr(i,"approval token"),spender:Hr(s,"approval spender"),amount:String(e.fromAmount)}}return C({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:o,quote:r,autoSlippage:r.autoSlippage,requiresApproval:a,transaction:{chainId:o,from:n.from||e.fromAddress,to:n.to,data:n.data,value:n.value??"0x0",...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:M(r.autoSlippage,{chainId:o,venue:n.to,data:n.data})}},{provider:"lifi",kind:"lifi-tx"})}async function ti(e={}){return A(`${Tt(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var jr,Ot,Ja,Lt=S(()=>{q();D();Nt();V();He();jr="https://li.quest/v1";Ot="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Ja="0x0000000000000000000000000000000000000000"});var zr={};re(zr,{PARASWAP_API:()=>Gr,paraswapHealth:()=>ni,paraswapPrepare:()=>ri,paraswapPrice:()=>We,paraswapTokens:()=>Kr});function oe(e,t){let r=String(e||"");if(!/^0x[0-9a-fA-F]{40}$/.test(r))throw new Error(`${t} must be a 20-byte token address`);return r.toLowerCase()}async function Kr(e={},t={}){let r=Number(e.chainId||1);return A(`${Rt(t)}/tokens/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function We(e={},t={}){let r=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let n=new URLSearchParams({srcToken:oe(e.srcToken,"srcToken"),destToken:oe(e.destToken,"destToken"),amount:String(e.amount),srcDecimals:String(Number(e.srcDecimals)),destDecimals:String(Number(e.destDecimals)),side:String(e.side||"SELL").toUpperCase(),network:String(r),version:String(e.version||"6.2")});e.includeDEXS&&n.set("includeDEXS",String(e.includeDEXS)),e.excludeDEXS&&n.set("excludeDEXS",String(e.excludeDEXS));let o=await Ve({wallet:e.userAddress||e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[i,c]of Object.entries(Vr(o)))n.set(i,c);let a=await A(`${Rt(t)}/prices?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),s=a?.priceRoute?.destAmount;return s?{...N(a,{chainId:r,venue:a?.priceRoute?.contractAddress||"paraswap-quote",amountOut:s,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,quoteAgeMs:0,requestedCapBps:e.maxSlippageBps??e.slippageBps}),executionReady:!1,executionBlocker:"call prepare to bind the price route to a validated transaction",oracleFee:o}:{...a,executionReady:!1,oracleFee:o}}async function ri(e={},t={}){if(String(e.side||"SELL").toUpperCase()!=="SELL")throw new Error("paraswap: agentic prepare currently supports exact-input SELL only");let r=Number(e.chainId||e.network||1),n=oe(e.userAddress,"userAddress"),o=await We(e,t),a=o?.priceRoute,s=String(a?.contractAddress||"").toLowerCase();if(!s)throw new Error("paraswap: price route missing contractAddress");let i={srcToken:oe(e.srcToken,"srcToken"),destToken:oe(e.destToken,"destToken"),srcAmount:String(a.srcAmount||e.amount),destAmount:String(o.amountOutMinimum),priceRoute:a,userAddress:n,ignoreChecks:!1,ignoreGasEstimate:!1};e.receiver&&(i.receiver=oe(e.receiver,"receiver"));let c=await A(`${Rt(t)}/transactions/${r}`,{method:"POST",body:i,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3});if(Number(c.chainId??r)!==r)throw new Error("paraswap: transaction chain mismatch");if(String(c.to||"").toLowerCase()!==s)throw new Error("paraswap: transaction target mismatch");if(c.from&&String(c.from).toLowerCase()!==n)throw new Error("paraswap: transaction sender mismatch");return C({provider:"paraswap",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,quote:o,autoSlippage:o.autoSlippage,requiresApproval:i.srcToken!=="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"?{token:i.srcToken,spender:a.tokenTransferProxy||s,amount:i.srcAmount}:null,transaction:{chainId:r,from:c.from||n,to:c.to,data:c.data,value:c.value??"0x0",...c.gas!=null?{gasLimit:c.gas}:{},slippageGuard:M(o.autoSlippage,{chainId:r,venue:c.to,data:c.data})}},{provider:"paraswap",kind:"paraswap-tx"})}async function ni(e={}){let t=await Kr({chainId:1},e),r=Array.isArray(t?.tokens)?t.tokens.length:Object.keys(t?.tokens||{}).length;return{ok:r>0,tokenSample:r}}var Gr,Rt,Bt=S(()=>{q();D();V();He();Gr="https://api.paraswap.io",Rt=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||Gr).replace(/\/$/,"")});function Ge({provider:e,defaultUrl:t,hosts:r=[],url:n,strict:o=!1}){let s=(String(n??"").trim()||String(t)).replace(/\/$/,"");if(s===String(t).replace(/\/$/,""))return{baseUrl:s,trusted:!0,host:Yr(t)};let i;try{i=new URL(s)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let c=i.host;if(!c)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([Yr(t),...r]).has(c)){let p=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return i.protocol==="http:"&&!p?{baseUrl:s,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:s,trusted:!0,host:c}}if(String(process.env[Xr]||"")==="1")return{baseUrl:s,trusted:!1,host:c};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${Xr}=1 to permit it)`);return{baseUrl:s,trusted:!1,host:c}}function Yr(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function Ke(e,t,r){let n={...e};if(!r)return n;for(let[o,a]of Object.entries(t||{}))a&&(n[o]=a);return n}var Xr,Ft=S(()=>{Xr="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});var rn={};re(rn,{ZEROX_API:()=>Jr,zeroxHealth:()=>oi,zeroxPrepare:()=>ai,zeroxPrice:()=>tn,zeroxQuote:()=>Xe});function Qr(e={}){return Ge({provider:"zerox",defaultUrl:Jr,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function Zr(e={}){return Qr(e).baseUrl}function ze(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function en(e={}){return Ke({"0x-version":"v2",accept:"application/json"},{"0x-api-key":ze(e)},Qr(e).trusted)}async function oi(e={}){if(!ze(e))return{ok:!1,configured:!1,error:"ZEROX_API_KEY not set"};try{let t=await tn({chainId:8453,sellToken:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",buyToken:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",sellAmount:"1000000000000000"},e);return{ok:!0,configured:!0,buyAmount:t.buyAmount||t.grossBuyAmount}}catch(t){return{ok:!1,configured:!0,error:String(t.message||t).slice(0,160)}}}async function tn(e={},t={}){if(!ze(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:a,taker:s}=e;if(!n||!o||!a)throw new Error("zeroxPrice requires sellToken, buyToken, sellAmount");let i=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:o,sellAmount:String(a)});return s&&i.set("taker",s),A(`${Zr(t)}/swap/allowance-holder/price?${i}`,{headers:en(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function Xe(e={},t={}){if(!ze(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:a,taker:s}=e;if(!n||!o||!a)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let i=ne({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!i.executable)throw new Error(`0x: route requires ${i.requiredBps} bps above cap ${i.capBps}`);let c=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:o,sellAmount:String(a),slippageBps:String(i.selectedBps)});s&&c.set("taker",s);let u=await A(`${Zr(t)}/swap/allowance-holder/quote?${c}`,{headers:en(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),p=u?.buyAmount||u?.grossBuyAmount;return p?N(u,{chainId:r,venue:u?.transaction?.to||u?.to||"0x",amountOut:p,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):{...u,autoSlippagePolicy:i}}async function ai(e={},t={}){if(!e.taker)throw new Error("0x: taker required for executable prepare");let r=await Xe(e,t),n=r?.transaction;if(!n?.to||!n?.data)throw new Error("0x: firm quote returned no transaction");let o=Number(e.chainId??8453),a=r?.issues?.allowance?.spender||r?.allowanceTarget;return C({provider:"zerox",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:o,quote:r,autoSlippage:r.autoSlippage,requiresApproval:r?.issues?.allowance?.actual!=null&&BigInt(r.issues.allowance.actual)<BigInt(e.sellAmount)?{token:e.sellToken,spender:a,amount:String(e.sellAmount)}:null,transaction:{chainId:o,from:e.taker,to:n.to,data:n.data,value:n.value??"0x0",...n.gas!=null?{gasLimit:n.gas}:{},slippageGuard:M(r.autoSlippage,{chainId:o,venue:n.to,data:n.data})}},{provider:"zerox",kind:"zerox-tx"})}var Jr,$t=S(()=>{q();D();Ft();V();Jr="https://api.0x.org"});var zu,sn=S(()=>{zu=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});var bn={};re(bn,{COW_CANCEL_TYPES:()=>pn,COW_HOSTS:()=>Ut,COW_ORDER_TYPES:()=>Ye,COW_SETTLEMENT:()=>un,COW_VAULT_RELAYER:()=>ln,cowCancelOrders:()=>xi,cowChains:()=>vi,cowHealth:()=>fi,cowOrder:()=>wn,cowOrderStatus:()=>hn,cowOrderUid:()=>hi,cowPrepareCancel:()=>gi,cowPrepareOrder:()=>mi,cowQuote:()=>me,cowSignCancel:()=>Ei,cowSignOrder:()=>wi,cowSubmitSignedOrder:()=>bi,cowVerifyOrderFill:()=>Ai});import{TypedDataEncoder as cn,getAddress as fe,isAddress as ui}from"ethers";function Je(e,t={}){if(t.baseUrl)return t.baseUrl.replace(/\/$/,"");let r=Ut[Number(e)];if(!r)throw new Error(`cowswap: unsupported chainId ${e}`);return r}function li(e,t="v1",r={}){let n=Je(e,r);return t==="v1"?n:n.replace(/\/api\/v1$/,`/api/${t}`)}function G(e,t){let r=String(e||"").trim();if(!ui(r))throw new Error(`cowswap: ${t} must be an address`);return fe(r).toLowerCase()}function ae(e,t){try{let r=BigInt(String(e));if(r<0n)throw new Error("negative");return r.toString()}catch{throw new Error(`cowswap: ${t} must be a non-negative integer string`)}}function fn(e,t){let r=String(e||"").trim();if(!/^0x[0-9a-fA-F]{64}$/.test(r))throw new Error(`cowswap: ${t} must be bytes32 hex`);return r.toLowerCase()}function mn(e,t="uid"){let r=String(e||"").trim();if(!/^0x[0-9a-fA-F]{112}$/.test(r))throw new Error(`cowswap: ${t} must be 56-byte order UID hex`);return r.toLowerCase()}function di({digest:e,owner:t,validTo:r}={}){let n=fn(e,"order digest").slice(2),o=G(t,"owner").slice(2).toLowerCase(),a=Number(r);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error("cowswap: validTo must fit uint32");return`0x${n}${o}${a.toString(16).padStart(8,"0")}`.toLowerCase()}function Pt(e){let t=un[Number(e)];if(!t)throw new Error(`cowswap: settlement contract not registered for chain ${e}`);return{name:"Gnosis Protocol",version:"v2",chainId:Number(e),verifyingContract:fe(t)}}function pi(e={},t,r){let n=G(e.sellToken,"sellToken"),o=G(e.buyToken,"buyToken"),a=G(e.receiver||r,"receiver"),s=Number(e.validTo);if(!Number.isInteger(s)||s<=0)throw new Error("cowswap: quote.validTo required");let i=fn(e.appData||e.appDataHash||`0x${"0".repeat(64)}`,"appData");return{sellToken:n,buyToken:o,receiver:a,sellAmount:ae(e.sellAmount,"sellAmount"),buyAmount:ae(e.buyAmount,"buyAmount"),validTo:s,appData:i,feeAmount:ae(e.feeAmount??"0","feeAmount"),kind:String(e.kind||"sell"),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance||"erc20"),buyTokenBalance:String(e.buyTokenBalance||"erc20")}}async function fi(e={}){try{let t=await me({chainId:1,sellToken:Dt[1],buyToken:dn[1],sellAmountBeforeFee:"1000000000000000",from:pe},e);return{ok:!0,buyAmount:t.quote?.buyAmount||t.buyAmount}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function me(e={},t={}){let r=Number(e.chainId??1),n=kt(e.from||e.owner),o=e.sellToken||Dt[r],a=e.buyToken||dn[r],s=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!o||!a||s==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(o)&&(o=Dt[r],!o))throw new Error("no WETH mapping for chain");let i={sellToken:o,buyToken:a,from:n,receiver:e.receiver||n,sellAmountBeforeFee:s,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},c=await A(`${Je(r,t)}/quote`,{method:"POST",body:i,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),u=c?.quote?.buyAmount||c?.buyAmount;return u?N(c,{chainId:r,venue:"cowswap-order",amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):c}async function mi(e={},t={}){let r=Number(e.chainId??1),n=G(kt(e.from||e.owner||e.signer),"owner"),o=await me({...e,chainId:r,from:n,signingScheme:e.signingScheme||"eip712"},t),a=pi(o?.quote||o,r,n),s=Pt(r),i={domain:s,types:Ye,primaryType:"Order",message:a},c=cn.hash(s,Ye,a),u=ln[r];if(!u)throw new Error(`cowswap: vault relayer not registered for chain ${r}`);return C({provider:"cowswap",orderReady:!0,executionReady:!1,chainId:r,owner:n,signingScheme:"eip712",settlement:s.verifyingContract.toLowerCase(),vaultRelayer:fe(u).toLowerCase(),quote:o,quoteId:o?.id??e.quoteId??null,typedData:i,cowGuard:{mode:"cow-order",version:1,provider:"cowswap",chainId:r,owner:n,settlement:s.verifyingContract.toLowerCase(),vaultRelayer:fe(u).toLowerCase(),sellToken:a.sellToken,buyToken:a.buyToken,sellAmount:a.sellAmount,buyAmount:a.buyAmount,validTo:a.validTo,quoteId:o?.id??e.quoteId??null,typedDataHash:c,issuedAtMs:Date.now(),expiresAtMs:Math.min(a.validTo*1e3,Date.now()+2e4)},requiresApproval:{token:a.sellToken,spender:fe(u).toLowerCase(),amount:a.sellAmount}},{provider:"cowswap",kind:"cow-order"})}async function hn(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrderStatus requires uid");return A(`${Je(r,t)}/orders/${encodeURIComponent(n)}/status`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function wn(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrder requires uid");return A(`${Je(r,t)}/orders/${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}function hi(e={}){let t=e.typedData||e,r=Number(e.chainId??t?.domain?.chainId),n=t?.message||e.order||e.message;if(!n)throw new Error("cowswap: typed order message required");let o=e.cowGuard?.typedDataHash||cn.hash(Pt(r),Ye,n),a=e.owner||e.from||e.signer||n.receiver;return di({digest:o,owner:a,validTo:n.validTo})}async function wi(e={},t={}){throw new Error("cowswap.cowSignOrder refused: @oracle-agent/oracle is prepare-only. Sign with the user wallet; do not pass private keys here.")}async function bi(e={},t={}){throw new Error("cowswap.cowSubmitSignedOrder refused: @oracle-agent/oracle is prepare-only. Submit signed orders from the user wallet or local operator.")}function gi(e={}){let t=Number(e.chainId??1),r=G(e.owner||e.from||e.signer,"owner"),n=(e.orderUids||e.uids||[e.uid]).filter(Boolean).map((s,i)=>mn(s,`orderUids[${i}]`));if(!n.length)throw new Error("cowswap: orderUids required");let o=Pt(t);return C({provider:"cowswap",chainId:t,owner:r,orderUids:n,signingScheme:"eip712",typedData:{domain:o,types:pn,primaryType:"OrderCancellations",message:{orderUids:n}},cancelReady:!0,executableArtifact:!0},{provider:"cowswap",kind:"cow-cancel"})}async function Ei(e={},t={}){throw new Error("cowswap.cowSignCancel refused: @oracle-agent/oracle is prepare-only. Cancel-sign with the user wallet.")}async function xi(e={},t={}){throw new Error("cowswap.cowCancelOrders refused: @oracle-agent/oracle is prepare-only. Cancel from the user wallet or local operator.")}function yi(e={}){return ae(e.buyAmount??e.executedBuyAmount??"0","trade.buyAmount")}async function Ai(e={},t={}){let r=Number(e.chainId??1),n=mn(e.uid||e.orderUid),o=t.order||await wn({chainId:r,uid:n},t),a=t.status||o.status||await hn({chainId:r,uid:n},t).catch(()=>null),s=t.trades||await A(`${li(r,"v2",t)}/trades?orderUid=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),i=Array.isArray(s)?s:[],c=e.expectedOwner?G(e.expectedOwner,"expectedOwner"):null;if(c&&G(o.owner||i[0]?.owner||c,"owner")!==c)return{ok:!1,provider:"cowswap",chainId:r,uid:n,reason:"owner mismatch",order:o,status:a,trades:i};let u=0n;for(let l of i.filter(m=>String(m.orderUid||"").toLowerCase()===n))u+=BigInt(yi(l));u===0n&&o.executedBuyAmount!=null&&(u=BigInt(ae(o.executedBuyAmount,"executedBuyAmount")));let p=e.minBuyAmount!=null?BigInt(ae(e.minBuyAmount,"minBuyAmount")):0n,d=u>=p&&String(o.status||a?.status||"").toLowerCase()!=="expired";return{ok:d,provider:"cowswap",chainId:r,uid:n,status:o.status||a?.status||null,executedBuyAmount:u.toString(),minBuyAmount:e.minBuyAmount??null,trades:i,settlementTxs:[...new Set(i.map(l=>l.txHash).filter(Boolean))],order:o,orderStatus:a,reason:d?null:"insufficient fill or expired order"}}function vi(){return Object.keys(Ut).map(Number)}var Ut,un,ln,Dt,dn,Ye,pn,qt=S(()=>{q();D();sn();Nt();V();Ut={1:"https://api.cow.fi/mainnet/api/v1",100:"https://api.cow.fi/xdai/api/v1",42161:"https://api.cow.fi/arbitrum_one/api/v1",8453:"https://api.cow.fi/base/api/v1"},un=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),ln=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),Dt={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},dn={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},Ye=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"}]}),pn=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function we(e){return gn.get(Number(e))||null}function be(e,t=process.env){let r=we(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}function Qe(e){return gn.has(Number(e))}var he,gn,Ze=S(()=>{he={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}},gn=new Map(Object.values(he).map(e=>[e.chainId,e]))});import{Interface as Si,getAddress as Ii}from"ethers";function xn(e,t){try{return Ii(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function ki(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=be(e,r);return n||Ci[Number(e)]||null}function _i(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!Ni.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}async function k(e,t,r=[],n={}){let o=String(t||"");_i(o);let a=ki(e,n);if(!a)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let i=await A(a,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:r},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3});if(i?.error){let c=new Error(i.error.message||JSON.stringify(i.error));throw c.code=i.error.code,c}return i.result}async function yn(e,t={}){let r=await k(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function An(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await k(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function vn(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=xn(e.token||e.tokenAddress,"token"),o=xn(e.account||e.owner||e.address,"account"),a=En.encodeFunctionData("balanceOf",[o]),s=await k(r,"eth_call",[{to:n,data:a},e.blockTag||"latest"],t),i=En.decodeFunctionResult("balanceOf",s),c=BigInt(i[0]);return{chainId:r,token:n,account:o,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var En,Ci,Ni,ie=S(()=>{q();Ze();En=new Si(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);Ci={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"};Ni=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/});function Ri(e,t,r){let n=R(t),o=R(r),a=R(e?.baseToken?.address),s=R(e?.quoteToken?.address);return a===n&&s===o||a===o&&s===n}function Bi(e){let t=Number(e?.liquidity?.usd);return Number.isFinite(t)&&t>=0?t:null}function Fi(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Oi).replace(/\/$/,"")}async function Mt(e,t={}){if(!e)throw new Error("tokenAddress required");return A(`${Fi(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function et({chainId:e,tokenA:t,tokenB:r,dexIds:n=[]}={},o={}){if(e==null||!t||!r)throw new Error("chainId, tokenA, and tokenB required");let a=R(Ti[Number(e)]||e),s=new Set(Li(n).filter(Boolean).map(R)),i=[...new Set([t,r].map(l=>String(l)).filter(Boolean))],c=await Promise.allSettled(i.map(l=>Mt(l,{...o,baseUrl:o.dexscreenerBaseUrl,timeoutMs:o.dexscreenerTimeoutMs??Math.min(Number(o.timeoutMs??4e3),4e3)}))),u=new Set,p=[];for(let l of c)if(l.status==="fulfilled")for(let m of l.value?.pairs||l.value?.data?.pairs||[]){let h=`${R(m?.chainId)}:${R(m?.dexId)}:${R(m?.pairAddress)}`;u.has(h)||(u.add(h),p.push(m))}return p.filter(l=>R(l?.chainId)===a).filter(l=>Ri(l,t,r)).filter(l=>!s.size||s.has(R(l?.dexId))).map(l=>({pairAddress:l.pairAddress??null,dexId:l.dexId??null,chainId:l.chainId??null,liquidityUsd:Bi(l),pairCreatedAt:l.pairCreatedAt??null})).filter(l=>l.liquidityUsd!=null).sort((l,m)=>m.liquidityUsd-l.liquidityUsd)[0]??null}var Oi,Ti,R,Li,tt=S(()=>{q();Oi="https://api.dexscreener.com",Ti=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"}),R=e=>String(e??"").toLowerCase(),Li=e=>Array.isArray(e)?e:e==null?[]:[e]});var Tn={};re(Tn,{PANCAKE_FEE_TIERS:()=>rt,UNI_V3_CHAINS:()=>T,UNI_V3_FEE_TIERS:()=>Cn,UNI_V3_VENUES:()=>_n,uniV3Chains:()=>Vi,uniV3EthUsdc:()=>On,uniV3Health:()=>Mi,uniV3PrepareExactIn:()=>qi,uniV3QuoteExactIn:()=>Ee,uniV3QuoteExactInPath:()=>Pi});import{Interface as In,getAddress as ge,isAddress as $i}from"ethers";function Ht(e,t){let r=Number(e),n=T[r];if(!n)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys(T).join(", ")})`);let o=_n[r]||{};if(!t){if(!n.quoter||!n.router){let c=Object.keys(o).join(", ")||"none registered";throw new Error(`uniswap-v3: chain ${r} (${n.name}) has no canonical Uniswap v3 deployment -- name a venue explicitly (known: ${c})`)}return{chainId:r,venue:n.name,...n}}let a=String(t).toLowerCase();if(a===n.name&&n.quoter&&n.router)return{chainId:r,venue:n.name,...n};let s=o,i=s[a];if(!i){let c=[...n.quoter&&n.router?[n.name]:[],...Object.keys(s)].join(", ");throw new Error(`uniswap-v3: unknown venue "${t}" on chain ${r} (known: ${c})`)}return{chainId:r,venue:a,...n,quoter:i.quoter,router:i.router,feeTiers:i.feeTiers||null}}function Vt(e,t){let r=T[Number(t)];if(!e||e===kn||e===Nn||/^eth$/i.test(String(e)))return ge(r.weth);let n=String(e);if(/^weth$/i.test(n))return ge(r.weth);if(/^usdc$/i.test(n))return ge(r.usdc);if(!$i(n))throw new Error(`invalid token address: ${e}`);return ge(n)}function Di(e){let t=String(e||"uniswap").toLowerCase();return t==="uniswap"?["uniswap-v3","uniswap"]:t==="pancakeswap"?["pancakeswap-v3","pancakeswap"]:t==="hyperswap"?["hyperswap-v3","hyperswap"]:[t,`${t}-v3`]}function Ui(e,t){if(e.length!==t.length+1)throw new Error("path: fees.length must be tokens.length - 1");let r="0x";for(let n=0;n<t.length;n++)r+=e[n].slice(2).toLowerCase(),r+=Number(t[n]).toString(16).padStart(6,"0");return r+=e[e.length-1].slice(2).toLowerCase(),r}async function Ee(e={},t={}){let{chainId:r,quoter:n,router:o,feeTiers:a}=Ht(e.chainId??8453,e.venue),s=Vt(e.tokenIn||"WETH",r),i=Vt(e.tokenOut||T[r].usdc,r),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");let u=a&&a.length?a:Cn,p=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[u[Math.min(2,u.length-1)]]:[...u],d=[],l=null;for(let w of p){let f=nt.encodeFunctionData("quoteExactInputSingle",[{tokenIn:s,tokenOut:i,amountIn:c,fee:w,sqrtPriceLimitX96:0n}]);try{let b=await k(r,"eth_call",[{to:n,data:f},"latest"],t);if(!b||b==="0x"){d.push({fee:w,ok:!1,error:"empty result"});continue}let g=nt.decodeFunctionResult("quoteExactInputSingle",b),E={fee:w,ok:!0,amountOut:g[0].toString(),sqrtPriceX96After:g[1].toString(),initializedTicksCrossed:Number(g[2]),gasEstimate:g[3].toString()};d.push(E),(!l||BigInt(E.amountOut)>BigInt(l.amountOut))&&(l=E)}catch(b){d.push({fee:w,ok:!1,error:String(b.message||b).slice(0,160)})}}if(!l){let w=d.map(f=>`${f.fee}:${f.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${r}: ${w}`)}let m=e.liquidityUsd==null?await et({chainId:r,tokenA:s,tokenB:i,dexIds:Di(e.venue)},t).catch(()=>null):null,h=e.liquidityUsd??m?.liquidityUsd??null;return N({venue:"uniswap-v3",chainId:r,chain:T[r].name,quoter:n,tokenIn:s,tokenOut:i,amountIn:c.toString(),fee:l.fee,amountOut:l.amountOut,gasEstimate:l.gasEstimate,liquidityUsd:h,liquiditySource:m,sqrtPriceX96After:l.sqrtPriceX96After,initializedTicksCrossed:l.initializedTicksCrossed,triedFees:d,best:!0},{chainId:r,venue:o,amountOut:l.amountOut,liquidityUsd:h,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Pi(e={},t={}){let{chainId:r,quoter:n,router:o}=Ht(e.chainId??8453),a=(e.tokens||[]).map(l=>Vt(l,r)),s=(e.fees||[]).map(Number);if(a.length<2)throw new Error("tokens[] need at least 2 addresses");let i=BigInt(e.amountIn??0);if(i<=0n)throw new Error("amountIn required");let c=Ui(a,s),u=nt.encodeFunctionData("quoteExactInput",[c,i]),p=await k(r,"eth_call",[{to:n,data:u},"latest"],t),d=nt.decodeFunctionResult("quoteExactInput",p);return N({venue:"uniswap-v3",chainId:r,chain:T[r].name,quoter:n,tokens:a,fees:s,path:c,amountIn:i.toString(),amountOut:d[0].toString(),gasEstimate:d[3].toString()},{chainId:r,venue:o,amountOut:d[0].toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function On(e={},t={}){let r=Number(e.chainId??8453),n=e.amountIn??"1000000000000000",o=await Ee({chainId:r,tokenIn:T[r].weth,tokenOut:T[r].usdc,amountIn:n,fee:e.fee},t),a=Number(o.amountOut)/1e6;return{...o,amountOutUsdc:a,pair:"WETH/USDC"}}async function qi(e={},t={}){let r=Number(e.chainId??8453),n=Ht(r,e.venue),o=ge(e.recipient),a=String(e.tokenIn||"WETH"),s=!e.tokenIn||a===kn||a===Nn||/^eth$/i.test(a),i=await Ee(e,t),c=Sn.encodeFunctionData("exactInputSingle",[{tokenIn:i.tokenIn,tokenOut:i.tokenOut,fee:i.fee,recipient:o,amountIn:BigInt(i.amountIn),amountOutMinimum:BigInt(i.amountOutMinimum),sqrtPriceLimitX96:0n}]),u=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),d=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+u,l=Sn.encodeFunctionData("multicall",[d,[c]]);return C({provider:"uniswap-v3",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:d,quote:i,autoSlippage:i.autoSlippage,requiresApproval:s?null:{token:i.tokenIn,spender:n.router,amount:i.amountIn},transaction:{chainId:r,from:o,to:n.router,data:l,value:s?i.amountIn:"0",slippageGuard:M(i.autoSlippage,{chainId:r,venue:n.router,data:l})}},{provider:"uniswap-v3",kind:"univ3-swap-tx"})}async function Mi(e={}){let t=Number(e.chainId??8453);try{let r=await On({chainId:t,amountIn:"1000000000000000"},e);return{ok:!0,chainId:t,fee:r.fee,amountOutUsdc:r.amountOutUsdc,midPxHint:r.amountOutUsdc/.001}}catch(r){return{ok:!1,chainId:t,error:String(r.message||r).slice(0,200)}}}async function Vi(){return Object.entries(T).map(([e,t])=>({chainId:Number(e),name:t.name,quoter:t.quoter,weth:t.weth,usdc:t.usdc}))}var T,Cn,nt,Sn,kn,Nn,rt,_n,ot=S(()=>{ie();tt();D();V();T={1:{name:"ethereum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},8453:{name:"base",quoter:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",router:"0x2626664c2603336E57B271c5C0b26F421741e481",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},4663:{name:"robinhood",quoter:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",router:"0xcaf681a66d020601342297493863e78c959e5cb2",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"},999:{name:"hyperevm",weth:"0x5555555555555555555555555555555555555555",usdc:"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb"},10:{name:"optimism",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",quoter:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",router:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},43114:{name:"avalanche",quoter:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",router:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"}},Cn=[100,500,3e3,1e4],nt=new In(["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)"]),Sn=new In(["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)"]),kn="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Nn="0x0000000000000000000000000000000000000000",rt=[100,500,2500,1e4],_n={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:rt}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:rt}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:rt}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}}});var Un={};re(Un,{UNI_V4_CHAINS:()=>H,UNI_V4_FEE_TIERS:()=>Fn,computeV4PoolId:()=>Dn,uniV4Chains:()=>Qi,uniV4Health:()=>Zi,uniV4PrepareExactIn:()=>Ji,uniV4QuoteExactIn:()=>it});import{AbiCoder as Hi,Interface as Bn,getAddress as B,isAddress as at,keccak256 as ji}from"ethers";function jt(e){let t=Number(e),r=H[t];if(!r)throw new Error(`uniswap-v4: unsupported chainId ${e} (supported: ${Object.keys(H).join(", ")})`);return{chainId:t,...r}}function Rn(e,t){let r=H[Number(t)];if(!e||e===$n||e===Q||/^eth$/i.test(String(e)))return B(r.weth);let n=String(e);if(/^weth$/i.test(n))return B(r.weth);if(/^usdc$/i.test(n)||/^usdg$/i.test(n))return B(r.usdc);if(!at(n))throw new Error(`invalid token address: ${e}`);return B(n)}function Dn({currency0:e,currency1:t,fee:r,tickSpacing:n,hooks:o=Q}){let a=B(e),s=B(t);if(a.toLowerCase()===s.toLowerCase())throw new Error("poolKey currencies must differ");let[i,c]=a.toLowerCase()<s.toLowerCase()?[a,s]:[s,a],u=o&&at(o)?B(o):Q;return ji(xe.encode(["address","address","uint24","int24","address"],[i,c,Number(r),Number(n),u]))}function Xi({tokenIn:e,tokenOut:t,fee:r,tickSpacing:n,hooks:o=Q}){let a=B(e),s=B(t),[i,c]=a.toLowerCase()<s.toLowerCase()?[a,s]:[s,a],u=a.toLowerCase()===i.toLowerCase();return{poolKey:{currency0:i,currency1:c,fee:Number(r),tickSpacing:Number(n),hooks:o&&at(o)?B(o):Q},zeroForOne:u}}async function it(e={},t={}){let{chainId:r,quoter:n,poolManager:o,universalRouter:a}=jt(e.chainId??8453),s=Rn(e.tokenIn||"WETH",r),i=Rn(e.tokenOut||H[r].usdc,r),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");if(c>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let u=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...Fn],p=e.hooks||Q,d=[],l=null;for(let w of u){let{poolKey:f,zeroForOne:b}=Xi({tokenIn:s,tokenOut:i,fee:w.fee,tickSpacing:w.tickSpacing,hooks:p}),g=Ln.encodeFunctionData("quoteExactInputSingle",[{poolKey:f,zeroForOne:b,exactAmount:c,hookData:"0x"}]);try{let E=await k(r,"eth_call",[{to:n,data:g},"latest"],t);if(!E||E==="0x"){d.push({...w,ok:!1,error:"empty result"});continue}let _=Ln.decodeFunctionResult("quoteExactInputSingle",E),v={fee:w.fee,tickSpacing:w.tickSpacing,ok:!0,amountOut:_[0].toString(),gasEstimate:_[1].toString(),poolKey:f,zeroForOne:b,poolId:Dn({...f})};d.push(v),(!l||BigInt(v.amountOut)>BigInt(l.amountOut))&&(l=v)}catch(E){d.push({...w,ok:!1,error:String(E.message||E).slice(0,160)})}}if(!l){let w=d.map(f=>`${f.fee}/${f.tickSpacing}:${f.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 quote failed chain=${r}: ${w}`)}let m=e.liquidityUsd==null?await et({chainId:r,tokenA:s,tokenB:i,dexIds:Yi},t).catch(()=>null):null,h=e.liquidityUsd??m?.liquidityUsd??null;return N({venue:"uniswap-v4",chainId:r,chain:H[r].name,poolManager:o,quoter:n,universalRouter:a||null,tokenIn:s,tokenOut:i,amountIn:c.toString(),fee:l.fee,tickSpacing:l.tickSpacing,hooks:l.poolKey.hooks,poolId:l.poolId,zeroForOne:l.zeroForOne,amountOut:l.amountOut,gasEstimate:l.gasEstimate,liquidityUsd:h,liquiditySource:m,triedTiers:d,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&at(e.recipient)&&e.slippageBps!=null},{chainId:r,venue:a||n,amountOut:l.amountOut,liquidityUsd:h,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Ji(e={},t={}){let r=Number(e.chainId??8453),n=jt(r);if(!e.recipient)throw new Error("uniswap-v4 prepare requires recipient");let o=B(e.recipient);if(e.slippageBps==null)throw new Error("uniswap-v4 prepare requires explicit slippageBps");let a=Number(e.slippageBps);if(!Number.isInteger(a)||a<0||a>=1e4)throw new Error("slippageBps must be an integer from 0 through 9999");let s=String(e.tokenIn||"");if(!s||s===$n||s===Q||/^eth$/i.test(s))throw new Error("uniswap-v4 prepare currently requires an ERC-20 tokenIn; native input is not inferred");let i=await it(e,t);if(!n.universalRouter)throw new Error(`uniswap-v4: no Universal Router on chain ${r}`);let c=BigInt(i.amountOut)*BigInt(1e4-a)/10000n,u={currency0:i.zeroForOne?i.tokenIn:i.tokenOut,currency1:i.zeroForOne?i.tokenOut:i.tokenIn,fee:i.fee,tickSpacing:i.tickSpacing,hooks:i.hooks},d=xe.encode(["tuple(tuple(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 amountIn,uint128 amountOutMinimum,uint256 minHopPriceX36,bytes hookData)"],[[u,i.zeroForOne,BigInt(i.amountIn),c,0n,"0x"]]),l=xe.encode(["address","uint256"],[i.tokenIn,BigInt(i.amountIn)]),m=xe.encode(["address","uint256"],[i.tokenOut,c]),h=xe.encode(["bytes","bytes[]"],[Ki,[d,l,m]]),w=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),b=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+w,g=Wi.encodeFunctionData("execute",[Gi,[h],b]);return C({provider:"uniswap-v4",prepareReady:!0,calldataReady:!0,executionReady:!1,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:b,quote:{...i,amountOutMinimum:c.toString(),slippageBps:a},requiresApproval:{token:i.tokenIn,spender:zi,amount:i.amountIn,note:"Universal Router V4 settlement uses Permit2; Permit2 authorization for the Universal Router is also required"},transaction:{chainId:r,from:o,to:n.universalRouter,data:g,value:"0"}},{provider:"uniswap-v4",kind:"univ4-swap-tx"})}async function Qi(){return Object.entries(H).map(([e,t])=>({chainId:Number(e),name:t.name,poolManager:t.poolManager,quoter:t.quoter,stateView:t.stateView||null,universalRouter:t.universalRouter||null,weth:t.weth,usdc:t.usdc}))}async function Zi(e={}){let t=jt(e.chainId??8453),r=await k(t.chainId,"eth_getCode",[t.quoter,"latest"],e),n=typeof r=="string"&&r!=="0x"&&r.length>4;return{ok:n,chainId:t.chainId,quoter:t.quoter,poolManager:t.poolManager,codeBytes:n?(r.length-2)/2:0}}var xe,Q,H,Fn,Ln,Wi,Gi,Ki,zi,$n,Yi,Wt=S(()=>{ie();tt();D();V();xe=Hi.defaultAbiCoder(),Q="0x0000000000000000000000000000000000000000",H={1:{name:"ethereum",poolManager:"0x000000000004444c5dc75cB358380D2e3dE08A90",quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",stateView:"0x7ffe42c4a5deea5b0fec41c94c136cf115597227",universalRouter:"0x66a9893cc07d91d95644aedd05d03f95e1dba8af",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},10:{name:"optimism",poolManager:"0x9a13f98cb987694c9f086b1f5eb990eea8264ec3",quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",stateView:"0xc18a3169788f4f75a170290584eca6395c75ecdb",universalRouter:"0x851116d9223fabed8e56c0e6b8ad0c31d98b3507",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",poolManager:"0x28e2ea090877bf75740558f6bfb36a5ffee9e9df",quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",stateView:"0xd13dd3d6e93f276fafc9db9e6bb47c1180aee0c4",universalRouter:"0x1906c1d672b88cd1b9ac7593301ca990f94eae07",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",poolManager:"0x67366782805870060151383f4bbff9dab53e5cd6",quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",stateView:"0x5ea1bd7974c8a611cbab0bdcafcb1d9cc9b3ba5a",universalRouter:"0x1095692a6237d83c6a72f3f5efedb9a670c49223",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},8453:{name:"base",poolManager:"0x498581fF718922c3f8e6A244956aF099B2652b2b",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",stateView:"0xa3c0c9b65bad0b08107aa264b0f3db444b867a71",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",poolManager:"0x360e68faccca8ca495c1b759fd9eee466db9fb32",quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",stateView:"0x76fd297e2d437cd7f76d50f01afe6160f86e9990",universalRouter:"0xa51afafe0263b40edaef0df8781ea9aa03e381a3",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},43114:{name:"avalanche",poolManager:"0x06380c0e0912312b5150364b9dc4542ba0dbbc85",quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",stateView:"0xc3c9e198c735a4b97e3e683f391ccbdd60b69286",universalRouter:"0x94b75331ae8d42c1b61065089b7d48fe14aa73b7",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"},4663:{name:"robinhood",poolManager:"0x8366a39cc670b4001a1121b8f6a443a643e40951",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",stateView:"0xf3334192d15450cdd385c8b70e03f9a6bd9e673b",universalRouter:"0x8876789976dEcBfCbBbe364623C63652db8C0904",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"}},Fn=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],Ln=new Bn(["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)"]),Wi=new Bn(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),Gi="0x10",Ki="0x060c0f",zi="0x000000000022D473030F116dDEE9F6B43aC78BA3",$n="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";Yi=["uniswap-v4","uniswapv4"]});import{createCipheriv as Mc,createDecipheriv as Po,randomBytes as Vc,scryptSync as qo,timingSafeEqual as Hc}from"node:crypto";var gt="ORACLE-VAULT",mr=1,Mo=1<<17,Vo=8,Ho=1,jo=256*1024*1024,Wo=32;function Go(e,t,r={}){let n=String(e??"");if(n.length<8)throw new Error("local-vault: passphrase must be at least 8 characters");return qo(n,t,Wo,{N:r.N??Mo,r:r.r??Vo,p:r.p??Ho,maxmem:jo})}function fr(e,t,r){let n=Po("aes-256-gcm",e,Buffer.from(t.iv,"base64"));return r&&n.setAAD(Buffer.from(r,"utf8")),n.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([n.update(Buffer.from(t.ct,"base64")),n.final()])}function Et(e,t){if(!e||e.magic!==gt)throw new Error("local-vault: not an Oracle vault file");if(Number(e.version)!==mr)throw new Error(`local-vault: unsupported vault version ${e.version}`);let r=e.kdf||{};if(r.name!=="scrypt")throw new Error(`local-vault: unsupported kdf ${r.name}`);let{wrappedDek:n,payload:o,...a}=e,s=JSON.stringify(a),i=Go(t,Buffer.from(r.salt,"base64"),r),c;try{c=fr(i,n,s)}catch{throw i.fill(0),new Error("local-vault: wrong passphrase or tampered vault")}i.fill(0);try{return fr(c,o,s)}catch{throw new Error("local-vault: vault payload failed authentication")}finally{c.fill(0)}}function xt(e){try{return(typeof e=="string"?JSON.parse(e):e)?.magic===gt}catch{return!1}}import $ from"node:fs";import hr from"node:fs";import Ko from"node:os";import Y from"node:path";function wr(e=process.env){return e.ORACLE_CONFIG_DIR?Y.resolve(e.ORACLE_CONFIG_DIR):e.ORACLE_FAKE_HOME?Y.join(Y.resolve(e.ORACLE_FAKE_HOME),".config","oracle"):Y.join(Ko.homedir(),".config","oracle")}function yt(e=process.env){let t=wr(e);hr.mkdirSync(t,{recursive:!0,mode:448});try{hr.chmodSync(t,448)}catch{}return t}function _e(e=process.env){return Y.join(yt(e),"keys","default.vault")}function Oe(e=process.env){return Y.join(yt(e),"local-session.json")}function Te(e=process.env){return Y.join(yt(e),"local-arm.json")}var Zc=1800*1e3;function Le(e){return JSON.parse($.readFileSync(e,"utf8"))}function Re(e=process.env){let t=e.ORACLE_VAULT_PATH||_e(e),r=Oe(e),n=Te(e),o=!1,a=null;try{$.existsSync(t)&&(o=!0,a=JSON.parse($.readFileSync(t,"utf8"))?.meta||null)}catch{o=$.existsSync(t)}let s=!1,i=null,c=null;try{if($.existsSync(r)){let d=Le(r);d?.expiresAt&&Date.parse(d.expiresAt)>Date.now()&&d?.vaultPath&&(s=!0,i=d.expiresAt,c=d.address||null)}}catch{s=!1}let u=!1,p=null;try{$.existsSync(n)&&(p=Le(n),u=p?.armed===!0,u&&p.expiresAt&&Date.parse(p.expiresAt)<=Date.now()&&(u=!1))}catch{u=!1}return{vaultPath:t,vaultExists:o,vaultMeta:a,unlocked:s,sessionExpiresAt:i,address:c,armed:u,arm:p,plane:"local-self-custody",note:"Keys never leave this machine. Public HTTP plane stays prepare-only."}}function Be(e=process.env,t={}){let r=Oe(e);if(!$.existsSync(r))throw new Error("local-vault: locked \u2014 run oracle vault unlock");let n=Le(r);if(!n?.vaultPath||!n.expiresAt||Date.parse(n.expiresAt)<=Date.now()){try{$.unlinkSync(r)}catch{}throw new Error("local-vault: session expired \u2014 run oracle vault unlock")}let o=t.passphrase??e.ORACLE_LOCAL_VAULT_PASS;if(!o)throw new Error("local-vault: passphrase required to decrypt vault for signing");let a=n.vaultPath||e.ORACLE_VAULT_PATH||_e(e),s=$.readFileSync(a,"utf8");if(!xt(s))throw new Error("local-vault: vault file is not an Oracle vault envelope");let i=Et(JSON.parse(s),o),c=i.toString("utf8").trim();return i.fill(0),{material:c,address:n.address||null,expiresAt:n.expiresAt,vaultPath:a}}function Fe(e=process.env){let t=Te(e);if(!$.existsSync(t))throw new Error("local-vault: disarmed \u2014 run oracle arm --max <eth> --chain <id>");let r=Le(t);if(r.armed!==!0)throw new Error("local-vault: disarmed \u2014 run oracle arm");if(r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())throw new Error("local-vault: arm session expired \u2014 re-arm");return r}import{Wallet as Ro,JsonRpcProvider as Bc,getAddress as ur,isAddress as Fc,parseUnits as Bo}from"ethers";var $e=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),y=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),x=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Jo=/^0x[0-9a-fA-F]{40}$/;function Qo(e={}){let t=[],r=[];if(!e||typeof e!="object")return{ok:!1,errors:["definition must be an object"],warnings:r};if((!Number.isInteger(e.chainId)||e.chainId<=0)&&t.push("chainId must be a positive integer"),(typeof e.key!="string"||!/^[a-z][a-z0-9-]*$/.test(e.key||""))&&t.push('key must be a lowercase slug (e.g. "base")'),(typeof e.name!="string"||!e.name.trim())&&t.push("name is required"),!Array.isArray(e.rpcEnv)||e.rpcEnv.length===0)t.push("rpcEnv must list at least one environment variable name");else for(let o of e.rpcEnv)(typeof o!="string"||!/^[A-Z][A-Z0-9_]*$/.test(o))&&t.push(`rpcEnv entry "${o}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let o=e.nativeCurrency;(typeof o.symbol!="string"||!o.symbol)&&t.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(o.decimals)||t.push("nativeCurrency.decimals must be an integer")}for(let[o,a]of(e.venues||[]).entries()){let s=`venues[${o}]`;if(!a||typeof a!="object"){t.push(`${s} must be an object`);continue}Jo.test(a.address||"")||t.push(`${s}.address is not a valid 20-byte address`),/^0x0{40}$/.test(a.address||"")&&t.push(`${s}.address is the zero address -- placeholder left in place?`),a.kind||t.push(`${s}.kind is required (router|quoter|factory|...)`),a.verified?(a.verified.method||t.push(`${s}.verified.method is required`),a.verified.source||t.push(`${s}.verified.source is required`),a.verified.date||r.push(`${s}.verified.date missing -- add one so staleness is visible`)):t.push(`${s} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let n=e.capabilities||{};for(let o of Object.keys(n))$e.includes(o)?typeof n[o]!="function"&&t.push(`capability "${o}" must be a function`):t.push(`unknown capability "${o}"`);return Object.keys(n).length===0&&r.push("scanner implements no capabilities -- it can only be registered, not used"),n.prepareUnsignedTx&&!n.quote&&r.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),n.prepareUnsignedTx&&!n.sellSimulation&&r.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:t.length===0,errors:t,warnings:r}}function Zo(e){let{ok:t,errors:r,warnings:n}=Qo(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
3
+ - ${r.join(`
4
+ - `)}`);let o=e.capabilities||{},a=$e.filter(i=>typeof o[i]=="function"),s={key:e.key,chainId:e.chainId,name:e.name,rpcEnv:[...e.rpcEnv],nativeCurrency:e.nativeCurrency?{...e.nativeCurrency}:null,explorer:e.explorer||null,venues:(e.venues||[]).map(i=>({...i})),warnings:n,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...a],unsupported:$e.filter(i=>!a.includes(i))}},supports(i){return a.includes(i)}};for(let i of $e)a.includes(i)?s[i]=async(...c)=>o[i](...c,{scanner:s}):s[i]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${i}". Supported: ${a.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(s)}var At=new Map;function br(e){let t=Zo(e);return At.set(t.chainId,t),t}function De(e){return At.get(Number(e))||null}function gr(){return[...At.values()]}var P=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),xr={1:"coingecko:ethereum",10:"coingecko:ethereum",56:"coingecko:binancecoin",137:"coingecko:matic-network",8453:"coingecko:ethereum",42161:"coingecko:ethereum",43114:"coingecko:avalanche-2",999:"coingecko:ethereum"},le=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function Er(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:o=null,feeUsd:a=null,oracleFeeBps:s=0,estimatedGas:i=null,liquidityUsd:c=null,error:u=null,executionReady:p=!1,meta:d={}}=e||{};if(u||r==null)return{source:t,quality:P.FAILED,amountOut:null,error:u||"no amountOut returned"};let l=le(r);if(l==null||l<=0n)return{source:t,quality:P.FAILED,amountOut:null,error:"non-positive amountOut"};let m=Number(s);return{source:t,quality:o==null?P.NO_GAS:P.FULL,amountOut:l.toString(),minOut:le(n)?.toString()??null,gasUsd:o,feeUsd:a,oracleFeeBps:Number.isFinite(m)&&m>0?Math.floor(m):0,estimatedGas:i==null?null:String(i),liquidityUsd:c==null?null:Number(c),executionReady:p,meta:d}}async function yr(e,t,{divisor:r=1000n}={}){let n=le(t);if(n==null||n<=0n)return null;let o=n/r>0n?n/r:1n;if(o>=n)return null;let a,s;try{[a,s]=await Promise.all([e(o),e(n)])}catch{return null}let i=le(a),c=le(s);if(i==null||c==null||i<=0n)return null;let u=Number(i)/Number(o),p=Number(c)/Number(n);return!Number.isFinite(u)||!Number.isFinite(p)||u<=0?null:{impactPct:(1-p/u)*100,probeAmountIn:o.toString(),probeAmountOut:i.toString(),fullAmountOut:c.toString()}}function Ar(e,t,{maxImpactPct:r=25}={}){let n=[],o=[],a=(e.routes??[]).filter(i=>{let c=t?.[i.source];return c?c.impactPct>r?(n.push({source:i.source,impactPct:Number(c.impactPct.toFixed(2)),reason:`price impact ${c.impactPct.toFixed(1)}% exceeds ${r}% ceiling -- the venue cannot absorb this size near the quoted price`}),!1):!0:(o.push(i.source),!0)}),s=[...e.warnings??[]];return n.length&&s.push(`dropped ${n.length} route(s) on price impact: `+n.map(i=>`${i.source} (${i.impactPct}%)`).join(", ")),o.length&&s.push(`price impact NOT measured for: ${o.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:a,best:a[0]??null,impactRejected:n,impactUnmeasured:o,warnings:s}}function vr(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:o=50}={}){let a=e.filter(b=>b.quality!==P.FAILED),s=e.filter(b=>b.quality===P.FAILED),i=t!=null&&t>0&&r!=null&&r>=0,c=a.map(b=>{let g=BigInt(b.amountOut),E=0n,_=!1,v=BigInt(b.oracleFeeBps??0),F=v>0n?g*v/10000n:0n;if(i){let pr=(b.gasUsd??0)+(b.feeUsd??0);if(pr>0){let bt=pr/t*10**r;Number.isFinite(bt)&&bt>=0&&(E=BigInt(Math.floor(bt)),_=!0)}else b.gasUsd===0&&(_=!0)}let ue=E+F,Ne=g>ue?g-ue:0n;return{...b,grossOut:g.toString(),netOut:Ne.toString(),costInDest:E.toString(),oracleFeeInDest:F.toString(),costAccounted:_}}),u=Number(o)>0?Number(o):0,p=c.reduce((b,g)=>BigInt(g.netOut)>b?BigInt(g.netOut):b,0n),d=b=>p>0n?Number((p-BigInt(b))*10000n/p):0,l=[],m=c.slice().sort((b,g)=>BigInt(g.netOut)>BigInt(b.netOut)?1:-1)[0]??null;c.sort((b,g)=>{let E=d(b.netOut)<=u?0:1,_=d(g.netOut)<=u?0:1;if(n&&u>0&&E!==_)return E-_;if(n&&u>0){let v=b.liquidityUsd??-1,F=g.liquidityUsd??-1;if(v!==F)return F-v}return BigInt(g.netOut)>BigInt(b.netOut)?1:-1}),n&&u>0&&m&&c[0]&&c[0].source!==m.source&&l.push(`liquidity-first: chose ${c[0].source} (liquidity $${c[0].liquidityUsd??"unknown"}) over best-price ${m.source} within ${u} bps`);let h=c.filter(b=>!b.costAccounted).map(b=>b.source);i?h.length&&l.push(`gas not reported by: ${h.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):l.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let w=null,f=null;if(c.length>=2&&c[0].costAccounted&&c[1].costAccounted){let b=BigInt(c[0].netOut),g=BigInt(c[1].netOut);g>0n&&(w=Number((b-g)*10000n/g),f=`${c[0].source} vs ${c[1].source}`)}return{best:c[0]??null,routes:c,failed:s,improvementBps:w,spreadBasis:f,rankedOn:i?"net-of-cost":"gross",warnings:l}}async function vt(e,{timeoutMs:t=12e3}={}){let r=(o,a)=>Promise.race([o,new Promise((s,i)=>setTimeout(()=>i(new Error(`${a}: timeout`)),t))]);return(await Promise.allSettled(e.map(o=>r(Promise.resolve().then(o.run),o.source)))).map((o,a)=>{let s=e[a].source;return o.status==="rejected"?Er({source:s,error:String(o.reason?.message||o.reason)}):Er({source:s,...o.value})})}Lt();Bt();$t();q();D();Ft();V();var ii="https://api.1inch.dev/swap/v6.0";function nn(e={}){return Ge({provider:"oneinch",defaultUrl:ii,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function si(e={}){return nn(e).baseUrl}function on(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function ci(e={}){let t=on(e);return Ke({accept:"application/json"},{Authorization:t?`Bearer ${t}`:""},nn(e).trusted)}async function an(e={},t={}){if(!on(t))throw new Error("ONEINCH_API_KEY required for 1inch");let r=Number(e.chainId??1),{src:n,dst:o,amount:a}=e;if(!n||!o||!a)throw new Error("oneinchQuote requires src, dst, amount");let s=new URLSearchParams({src:n,dst:o,amount:String(a)}),i=await A(`${si(t)}/${r}/quote?${s}`,{headers:ci(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});return i?.dstAmount?N(i,{chainId:r,venue:"1inch-quote",amountOut:i.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):i}qt();ot();Wt();q();var es="https://coins.llama.fi";function ts(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||es).replace(/\/$/,"")}async function st(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return A(`${ts(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}var Gt=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function Pn(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let o=Gt(n?.amountUSD);o!=null&&(t+=o,r=!0)}return r?t:null}async function qn(e,t={}){let r=xr[Number(e)];if(!r)return null;try{let n=await st([r],t);return Gt(n?.coins?.[r]?.price)}catch{return null}}var Rl=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"]});function Kt({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,slippageBps:a,decimalsIn:s,decimalsOut:i,nativePriceUsd:c=null,destDecimalsPromise:u=null,opts:p={}}){let d=[];return d.push({source:"lifi",run:async()=>{let l=await je({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n},p),m=l?.estimate??l?.[0]?.estimate;return{amountOut:m?.toAmount,minOut:m?.toAmountMin,gasUsd:Pn(m?.gasCosts),feeUsd:Pn(m?.feeCosts),oracleFeeBps:l?.oracleFee?.applies?l.oracleFee.bps:0,meta:{tool:l?.tool??l?.toolDetails?.name,oracleFee:l?.oracleFee??null}}}}),s!=null&&d.push({source:"paraswap",run:async()=>{let l=i??(await Promise.resolve(u))?.decimals;if(l==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let m=await We({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:s,destDecimals:l},p),h=m?.priceRoute;return{amountOut:h?.destAmount,gasUsd:Gt(h?.gasCostUSD),oracleFeeBps:m?.oracleFee?.applies?m.oracleFee.bps:0,meta:{bestRoute:h?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange,oracleFee:m?.oracleFee??null}}}}),process.env.ZEROX_API_KEY&&d.push({source:"0x",run:async()=>{let l=await Xe({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:o},p),m=null,h=l?.totalNetworkFee,w=await Promise.resolve(c);return h!=null&&w&&(m=Number(h)/1e18*w),{amountOut:l?.buyAmount,minOut:l?.minBuyAmount,gasUsd:m,meta:{source:l?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&d.push({source:"1inch",run:async()=>{let l=await an({chainId:e,src:t,dst:r,amount:n},p),m=null;return l?.gas!=null&&c&&(m=null),{amountOut:l?.dstAmount,gasUsd:m,meta:{gasUnits:l?.gas}}}}),d.push({source:"cow",run:async()=>{let l=await me({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:o},p),m=l?.quote??l,h=m?.feeAmount;return{amountOut:m?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:h,settlement:"solver-executed"}}}}),T[Number(e)]&&d.push({source:"uniswap-v3",run:async()=>{let l=await Ee({chainId:e,tokenIn:t,tokenOut:r,amountIn:n},p);return{amountOut:l?.amountOut,minOut:l?.minOut??l?.amountOutMinimum??null,gasUsd:null,liquidityUsd:l?.liquidityUsd??null,meta:{onchain:!0,fee:l?.fee,gasUnits:l?.gasEstimate,quoter:l?.quoter}}}}),H[Number(e)]&&d.push({source:"uniswap-v4",run:async()=>{let l=await it({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o,slippageBps:a},p);return{amountOut:l?.amountOut,minOut:l?.minOut??l?.amountOutMinimum??null,gasUsd:null,liquidityUsd:l?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:l?.fee,tickSpacing:l?.tickSpacing,poolId:l?.poolId,hooks:l?.hooks,gasUnits:l?.gasEstimate,quoter:l?.quoter,poolManager:l?.poolManager,prepareReady:l?.prepareReady===!0,executionReady:!1}}}}),d}He();var rs={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function ns(e,t,r){let n=rs[Number(e)];if(!n)return{priceUsd:null,decimals:null};let o=`${n}:${t}`;try{let s=(await st([o],r))?.coins?.[o],i=Number(s?.price),c=Number(s?.decimals);return{priceUsd:Number.isFinite(i)?i:null,decimals:Number.isFinite(c)?c:null}}catch{return{priceUsd:null,decimals:null}}}async function Vn(e,t={}){let{chainId:r,tokenIn:n,tokenOut:o,amountIn:a}=e;if(r==null||!n||!o||a==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let s=qn(r,t),i=ns(r,o,t),c=Kt({...e,nativePriceUsd:s,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:t}),[u,p]=await Promise.all([vt(c,{timeoutMs:t.timeoutMs??12e3}),i]);s.catch(()=>{});let d=vr(u,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50}),l=t.maxImpactPct===void 0?25:t.maxImpactPct;if(l!=null&&d.best){let m=d.best.source,w=await yr(async f=>{let b=Kt({...e,amountIn:f.toString(),nativePriceUsd:s,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:t}).filter(E=>E.source===m);return b.length?(await vt(b,{timeoutMs:t.timeoutMs??12e3}))?.[0]?.amountOut??null:null},a);if(w){let f=Ar(d,{[m]:w},{maxImpactPct:l});return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(a),...f,sourcesTried:c.length,sourcesAnswered:u.filter(b=>b.quality!==P.FAILED).length,note:Mn(f,c.length),priceImpact:{[m]:Number(w.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(a),...d,sourcesTried:c.length,sourcesAnswered:u.filter(m=>m.quality!==P.FAILED).length,note:Mn(d,c.length)}}function os(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${qr(t)}`:""}function Mn(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=os(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 o=e.improvementBps,a=o/100;if(o<.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=a>=.01?`${a.toFixed(2)}%`:`${o.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}V();var K=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),as=100,zt={"uniswap-v3":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{uniV3PrepareExactIn:s}=await Promise.resolve().then(()=>(ot(),Tn)),i=await s({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o},a);return{artifactKind:K.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.amountOut??null,minOut:i.quote?.amountOutMinimum??null}},"uniswap-v4":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,slippageBps:a,fee:s,tickSpacing:i,hooks:c},u)=>{let{uniV4PrepareExactIn:p}=await Promise.resolve().then(()=>(Wt(),Un)),d=await p({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o,slippageBps:a,fee:s,tickSpacing:i,hooks:c},u);return{artifactKind:K.TRANSACTION,transaction:d.transaction,requiresApproval:d.requiresApproval,amountOut:d.quote?.amountOut??null,minOut:d.quote?.amountOutMinimum??null,prepareReady:!0,executionReady:!1}},lifi:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{lifiPrepare:s}=await Promise.resolve().then(()=>(Lt(),Wr)),i=await s({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n,fromAddress:o},a);return{artifactKind:K.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.estimate?.toAmount??null,minOut:i.quote?.estimate?.toAmountMin??null}},paraswap:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,decimalsIn:a,decimalsOut:s},i)=>{let{paraswapPrepare:c}=await Promise.resolve().then(()=>(Bt(),zr)),u=await c({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:a,destDecimals:s,userAddress:o,side:"SELL"},i);return{artifactKind:K.TRANSACTION,transaction:u.transaction,requiresApproval:u.requiresApproval??null,amountOut:u.quote?.priceRoute?.destAmount??null,minOut:u.quote?.amountOutMinimum??null}},"0x":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{zeroxPrepare:s}=await Promise.resolve().then(()=>($t(),rn)),i=await s({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:o},a);return{artifactKind:K.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.buyAmount??null,minOut:i.quote?.minBuyAmount??null}},cow:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{cowPrepareOrder:s}=await Promise.resolve().then(()=>(qt(),bn)),i=await s({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:o},a);return{artifactKind:K.TYPED_DATA_ORDER,typedData:i.typedData,requiresApproval:{token:t,spender:i.vaultRelayer,amount:String(n),note:"CoW pulls funds via the vault relayer, not the settlement contract"},settlement:i.settlement,amountOut:i.quote?.quote?.buyAmount??null,minOut:null,submission:"sign the typed data, then submit the order to the CoW API"}}};var is=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),ss=/^0x[0-9a-fA-F]{40}$/;async function Hn(e,t={}){let{taker:r}=e;if(!r)throw new Error("prepareBestRoute requires taker: a prepared transaction is built FOR an address, and the quote-only placeholder must never end up in one");if(!ss.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(is.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. It is valid for quoting but not for preparing -- that would build a transaction for an address nobody controls. Pass the real wallet that will sign.`);let n=await Vn(e,t);if(!n.best){let f=n.impactRejected??[];return{ok:!1,reason:f.length?f[0].reason:"no source returned a usable route",priceImpactBlocked:f.length>0,impactRejected:f,comparison:n}}let o=e.source||n.best.source,a=n.routes.find(f=>f.source===o);if(!a)return{ok:!1,reason:`source "${o}" did not return a usable route`,comparison:n};let s=zt[o];if(!s){let f=n.routes.find(b=>zt[b.source]&&b.source!==o);return{ok:!1,reason:`${o} won the comparison but has no prepare path in this build. `+(f?`Next preparable route is ${f.source}; pass source:"${f.source}" to use it.`:"No route in this comparison can be prepared."),comparison:n,winner:o}}let i;try{i=await s(e,t)}catch(f){let b=typeof f?.body=="string"?f.body:f?.body?JSON.stringify(f.body):"",g=[String(f?.message||f),b].filter(Boolean).join(" :: "),E=/allowance/i.test(g),_=!E&&/not enough|insufficient|balance/i.test(g),v,F;E?(F="approval-required-first",v=`${o} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${g}`):_?(F="taker-not-funded",v=`${o} refused to build the transaction: ${g}. This venue verifies the taker holds the input token. Quoting works for any address; preparing needs the real funded wallet.`):(F="provider-error",v=`${o} prepare failed: ${g}`);let ue=n.routes.find(Ne=>zt[Ne.source]&&Ne.source!==o);return{ok:!1,reason:v,failureKind:F,...ue?{alternative:ue.source}:{},comparison:n}}let c=e.driftToleranceBps??as,u=null,p=null;if(i.amountOut!=null&&a.grossOut!=null)try{let f=BigInt(a.grossOut),b=BigInt(i.amountOut);f>0n&&(u=Number((b-f)*10000n/f),u<-c&&(p=`route moved ${(u/100).toFixed(2)}% against you between the comparison and this prepare (tolerance ${(c/100).toFixed(2)}%). The ranking may no longer hold -- re-run the comparison before signing.`))}catch{}let d=n.routes.filter(f=>f.source!==o).map(f=>({source:f.source,netOut:f.netOut,gasUsd:f.gasUsd})),m=n.routes.map(f=>({source:f.source,liquidityUsd:f.liquidityUsd??null})).reduce((f,b)=>Math.max(f,b.liquidityUsd??0),0)||null,h=a.liquidityUsd??null,w=h!=null&&m>0?Math.round(h/m*100):null;return C({ok:!0,chosen:{source:o,wasWinner:o===n.best.source,netOut:a.netOut,grossOut:a.grossOut,gasUsd:a.gasUsd,liquidityUsd:a.liquidityUsd??null},liquidity:{chosenUsd:h,maxUsd:m,sharePct:w},priceImpact:n.priceImpact??null,impactUnmeasured:n.impactUnmeasured??[],...i,unsigned:!0,signedBy:"user-wallet",destination:i.artifactKind===K.TRANSACTION?i.transaction?.to??null:i.settlement??null,driftBps:u,warnings:[...p?[p]:[],...n.warnings||[],...i.artifactKind===K.TYPED_DATA_ORDER?["This is an ORDER to sign, not a transaction to broadcast. Signing it authorizes a solver to settle on your behalf."]:[]],runnersUp:d,comparison:{rankedOn:n.rankedOn,sourcesAnswered:n.sourcesAnswered,sourcesTried:n.sourcesTried,improvementBps:n.improvementBps},note:"UNSIGNED. Verify the destination address and minOut against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."},{provider:"router",kind:"best-route"})}ie();tt();ie();var Yt={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},L=e=>BigInt(e).toString(16).padStart(64,"0"),ye=e=>e.slice(2).toLowerCase().padStart(64,"0");function cs(e,t){return`0x${Yt.getAmountsOut}`+L(e)+L(64)+L(t.length)+t.map(ye).join("")}function us(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let r=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let n=[];for(let o=0;o<r;o++){let a=128+o*64;if(t.length<a+64)return null;n.push(BigInt(`0x${t.slice(a,a+64)}`))}return n}function Xt(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var Jt=100;function ls(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Jt)throw new Error(`slippageBps ${r} exceeds the ${Jt} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(r))/10000n}function jn(e){let{chainId:t,wrappedNative:r}=e;async function n(o,a,s,i){let c=await k(t,"eth_call",[{to:o,data:cs(a,s)},"latest"],i);return us(c?.result??c)}return{async quote({tokenIn:o,tokenOut:a,amountIn:s,path:i},c={}){let u=Xt(c.scanner);if(!u)return{chainId:t,evidence:y.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let p=i||[o,a];if(p.some(l=>!/^0x[0-9a-fA-F]{40}$/.test(l||"")))throw new Error("quote requires valid 20-byte addresses");let d=await n(u,s,p,c);return d?{chainId:t,router:u,path:p,amountIn:String(s),amountOut:d[d.length-1].toString(),hops:p.length-1,evidence:y.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:p,evidence:y.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:a,base:s},i={}){let c=Xt(i.scanner),u=s||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:x.UNKNOWN,evidence:y.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!u)return{chainId:t,token:o,verdict:x.UNKNOWN,evidence:y.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let p=await n(c,a,[u,o],i);if(!p)return{chainId:t,token:o,verdict:x.FAIL,evidence:y.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=p[p.length-1];if(d===0n)return{chainId:t,token:o,verdict:x.FAIL,evidence:y.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let l=await n(c,d,[o,u],i);if(!l)return{chainId:t,token:o,verdict:x.FAIL,evidence:y.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let m=l[l.length-1],h=Number(m*10000n/BigInt(a)),w=x.PASS,f="round trip completes with expected fee/impact loss";return h<5e3?(w=x.FAIL,f=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(w=x.CAUTION,f=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:u,router:c,verdict:w,reason:f,amountIn:String(a),bought:d.toString(),returned:m.toString(),retentionBps:h,evidence:y.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:a,amountIn:s,recipient:i,slippageBps:c=50,deadlineSeconds:u=900,path:p},d={}){let l=d.scanner,m=Xt(l);if(!m)throw new Error(`chain ${t} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(i||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=p||[o,a],w=await this.quote({tokenIn:o,tokenOut:a,amountIn:s,path:h},d);if(w.evidence!==y.LIVE)throw new Error(`cannot prepare without a live quote (${w.evidence}: ${w.reason??"no reason given"})`);let f=ls(w.amountOut,c);if(f<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=BigInt(Math.floor(Date.now()/1e3)+Number(u)),g=r&&h[0].toLowerCase()===r.toLowerCase()&&d.useNative,E=g?`0x${Yt.swapExactETHForTokens}`+L(f)+L(128)+ye(i)+L(b)+L(h.length)+h.map(ye).join(""):`0x${Yt.swapExactTokensForTokens}`+L(s)+L(f)+L(160)+ye(i)+L(b)+L(h.length)+h.map(ye).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:m,data:E,value:g?`0x${BigInt(s).toString(16)}`:"0x0"},guard:{quotedOut:w.amountOut,minOut:f.toString(),slippageBps:c,maxSlippageBps:Jt,deadline:b.toString()},requires:g?[]:[{step:"approve",token:h[0],spender:m,amount:String(s)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}ie();var ds=[100,500,3e3,1e4],Wn={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},Z=e=>BigInt(e).toString(16).padStart(64,"0"),Ae=e=>e.slice(2).toLowerCase().padStart(64,"0"),Gn=/^0x[0-9a-fA-F]{40}$/,Zt=100;function ps(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Zt)throw new Error(`slippageBps ${r} exceeds the ${Zt} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(r))/10000n}function Qt(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function Kn(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:a,tokenIn:s,tokenOut:i,amountIn:c,fee:u},p){let d=`0x${Wn.quoteExactInputSingle}`+Ae(s)+Ae(i)+Z(c)+Z(u)+Z(0),l=await k(t,"eth_call",[{to:a,data:d},"latest"],p).catch(()=>null),m=l?.result??l;if(!m||m==="0x"||m.length<66)return null;let h=BigInt(`0x${m.slice(2,66)}`);return h>0n?h:null}async function o({quoter:a,tokenIn:s,tokenOut:i,amountIn:c},u){let p=[],d=null;for(let l of ds){let m=await n({quoter:a,tokenIn:s,tokenOut:i,amountIn:c,fee:l},u);p.push({fee:l,amountOut:m?m.toString():null}),m&&(!d||m>d.amountOut)&&(d={fee:l,amountOut:m})}return{best:d,tried:p}}return{async quote({tokenIn:a,tokenOut:s,amountIn:i},c={}){let u=Qt(c.scanner,"quoter");if(!u)return{chainId:t,evidence:y.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let l of[a,s])if(!Gn.test(l||""))throw new Error("quote requires valid 20-byte addresses");let{best:p,tried:d}=await o({quoter:u,tokenIn:a,tokenOut:s,amountIn:i},c);return p?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:a,tokenOut:s,amountIn:String(i),amountOut:p.amountOut.toString(),fee:p.fee,triedFeeTiers:d,evidence:y.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:a,tokenOut:s,triedFeeTiers:d,evidence:y.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:a,amountIn:s,base:i},c={}){let u=Qt(c.scanner,"quoter"),p=i||r;if(p&&String(a).toLowerCase()===String(p).toLowerCase())return{chainId:t,token:a,verdict:x.UNKNOWN,evidence:y.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!p)return{chainId:t,token:a,verdict:x.UNKNOWN,evidence:y.UNAVAILABLE,reason:u?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let d=await o({quoter:u,tokenIn:p,tokenOut:a,amountIn:s},c);if(!d.best)return{chainId:t,token:a,verdict:x.FAIL,evidence:y.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let l=await o({quoter:u,tokenIn:a,tokenOut:p,amountIn:d.best.amountOut},c);if(!l.best)return{chainId:t,token:a,verdict:x.FAIL,evidence:y.LIVE,leg:"sell",bought:d.best.amountOut.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let m=l.best.amountOut,h=Number(m*10000n/BigInt(s)),w=x.PASS,f="round trip completes with expected fee/impact loss";return h<5e3?(w=x.FAIL,f=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(w=x.CAUTION,f=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:a,base:p,verdict:w,reason:f,amountIn:String(s),bought:d.best.amountOut.toString(),returned:m.toString(),retentionBps:h,buyFee:d.best.fee,sellFee:l.best.fee,evidence:y.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:a,tokenOut:s,amountIn:i,recipient:c,slippageBps:u=50,fee:p},d={}){let l=Qt(d.scanner,"router");if(!l)throw new Error(`chain ${t} has no verified V3 router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!Gn.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let m=await this.quote({tokenIn:a,tokenOut:s,amountIn:i},d);if(m.evidence!==y.LIVE)throw new Error(`cannot prepare without a live quote (${m.evidence}: ${m.reason??"no reason given"})`);let h=p??m.fee,w=ps(m.amountOut,u);if(w<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let f=`0x${Wn.exactInputSingle}`+Ae(a)+Ae(s)+Z(h)+Ae(c)+Z(i)+Z(w)+Z(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:l,data:f,value:"0x0"},guard:{quotedOut:m.amountOut,minOut:w.toString(),slippageBps:u,maxSlippageBps:Zt,fee:h},requires:[{step:"approve",token:a,spender:l,amount:String(i)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var ct={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function zn(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function Xn(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length>=128){let n=Number(BigInt(`0x${t.slice(64,128)}`));if(n>0&&n<=256&&t.length>=128+n*2){let o=t.slice(128,128+n*2),a=Buffer.from(o,"hex").toString("utf8").replace(/\0+$/,"");if(a)return a}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function fs(e){let{chainId:t}=e;async function r(n,o,a){return k(t,"eth_call",[{to:n,data:o},"latest"],a)}return{async blockNumber(n={}){let o=await yn(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:y.LIVE}},async nativeBalance(n,o={}){let a=await An(t,n,o);return{chainId:t,address:n,wei:a?.wei??a?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:y.LIVE}},async tokenBalance({token:n,owner:o},a={}){let s=await vn({chainId:t,token:n,owner:o},a);return{chainId:t,token:n,owner:o,raw:s?.balance??s,evidence:y.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:y.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[a,s,i,c]=await Promise.all([r(n,ct.decimals,o).catch(()=>null),r(n,ct.symbol,o).catch(()=>null),r(n,ct.name,o).catch(()=>null),r(n,ct.totalSupply,o).catch(()=>null)]),u=zn(a?.result??a),p=u!==null||s?.result||i?.result;return{chainId:t,address:n,decimals:u===null?null:Number(u),symbol:Xn(s?.result??s),name:Xn(i?.result??i),totalSupply:(zn(c?.result??c)??null)?.toString()??null,evidence:p?y.LIVE:y.UNKNOWN,warning:p?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(n,o={}){let a=e.dexscreenerSlug;if(!a)return{chainId:t,token:n,pools:[],evidence:y.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let s=await Mt(n,o).catch(()=>null),c=(s?.pairs||s?.data?.pairs||[]).filter(u=>String(u.chainId).toLowerCase()===String(a).toLowerCase()).map(u=>({pair:u.pairAddress,dex:u.dexId,base:u.baseToken?.address,quote:u.quoteToken?.address,liquidityUsd:u.liquidity?.usd??null,priceUsd:u.priceUsd??null,volume24hUsd:u.volume?.h24??null,createdAt:u.pairCreatedAt??null})).sort((u,p)=>(p.liquidityUsd??0)-(u.liquidityUsd??0));return{chainId:t,token:n,pools:c,evidence:c.length?y.LIVE:y.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:o,address:a,topics:s,chunkSize:i=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(o))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(o<n)throw new Error("toBlock must be >= fromBlock");let u=[],p=[];for(let d=n;d<=o;d+=i){let l=Math.min(d+i-1,o);p.push([d,l])}for(let[d,l]of p){let m={fromBlock:`0x${d.toString(16)}`,toBlock:`0x${l.toString(16)}`};a&&(m.address=a),s&&(m.topics=s);let h=await k(t,"eth_getLogs",[m],c).catch(w=>({error:String(w?.message||w)}));if(h?.error)return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!1,failedAt:[d,l],error:h.error,evidence:y.UNKNOWN};for(let w of h?.result??h??[])u.push(w)}return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!0,chunks:p.length,evidence:y.LIVE}},async scoreRisk(n,o={}){let a=[],s=x.PASS,i=p=>{let d={[x.PASS]:0,[x.CAUTION]:1,[x.UNKNOWN]:2,[x.FAIL]:3};d[p]>d[s]&&(s=p)},c=await this.resolveToken(n,o);c.evidence!==y.LIVE?(a.push({check:"erc20-metadata",result:x.UNKNOWN,detail:c.warning}),i(x.UNKNOWN)):a.push({check:"erc20-metadata",result:x.PASS,detail:`${c.symbol} / ${c.decimals}d`});let u=await this.resolvePools(n,o);if(u.evidence===y.UNAVAILABLE)a.push({check:"liquidity",result:x.UNKNOWN,detail:u.reason}),i(x.UNKNOWN);else if(!u.pools.length)a.push({check:"liquidity",result:x.FAIL,detail:"no pool with liquidity found"}),i(x.FAIL);else{let p=u.pools[0],d=p.liquidityUsd??0;d<5e3?(a.push({check:"liquidity",result:x.CAUTION,detail:`top pool only $${d}`}),i(x.CAUTION)):a.push({check:"liquidity",result:x.PASS,detail:`$${d} on ${p.dex}`}),p.createdAt&&Date.now()-p.createdAt<24*3600*1e3&&(a.push({check:"age",result:x.CAUTION,detail:"pool under 24h old"}),i(x.CAUTION))}if(typeof this.sellSimulation=="function"){let p=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:x.UNKNOWN,reason:String(d?.message||d)}));a.push({check:"sellability",result:p.verdict,detail:p.retentionBps!=null?`round trip returns ${(p.retentionBps/100).toFixed(2)}% -- ${p.reason}`:p.reason}),i(p.verdict)}else a.push({check:"sellability",result:x.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),i(x.UNKNOWN);return{chainId:t,token:n,verdict:s,checks:a,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function Yn(e){let r={...fs(e)},n=new Set((e.venues||[]).map(a=>a.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,Kn({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,jn({chainId:e.chainId,wrappedNative:e.wrappedNative}));let o={};for(let[a,s]of Object.entries(r))o[a]=s.bind(r);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:o}}var ms=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);function Jn(){return ms.map(e=>br(Yn(e)))}ot();var er=/^0x[0-9a-fA-F]{40}$/,hs=24,Qn=!1;function to(){Qn||(Jn(),Qn=!0)}var I=class extends Error{constructor(t,r){super(r),this.status=t}};function ws(e){if(to(),e==null||e==="")throw new I(400,"chainId is required");let t=Number(e);if(Number.isFinite(t)&&De(t))return t;let r=gr().find(n=>n.key===String(e).toLowerCase());if(r)return r.chainId;throw new I(400,`unknown chain "${e}"`)}function Zn(e,t){if(typeof e!="string")throw new I(400,`${t} is required`);let r=e.trim();if(r==="")throw new I(400,`${t} is invalid`);if(er.test(r))return r;if(r.length>hs)throw new I(400,`${t} is invalid`);if(!/^[A-Za-z0-9._-]+$/.test(r))throw new I(400,`${t} is invalid`);return r}function bs(e,t){let r=String(e).trim();if(!/^\d+(\.\d+)?$/.test(r))throw new I(400,"sellAmount must be a positive decimal number");if(Number(r)<=0)throw new I(400,"sellAmount must be greater than zero");let n=Number.isFinite(Number(t))?Number(t):18,[o,a=""]=r.split(".");if(a.length>n)throw new I(400,`sellAmount has more precision than the token's ${n} decimals`);let s=a.padEnd(n,"0"),i=(BigInt(o)*10n**BigInt(n)+BigInt(s||"0")).toString();if(i==="0")throw new I(400,"sellAmount rounds to zero at this token's precision");return i}async function eo(e,t){if(to(),er.test(t)){let u=await De(e).resolveToken(t).catch(()=>null),p=Number(u?.decimals);return{address:t,decimals:Number.isFinite(p)?p:null}}let r=T[e];if(!r)return null;let n=t.toLowerCase(),o=n==="usdc"?r.usdc:n==="weth"||n==="eth"?r.weth:null;if(!o)return null;let s=await De(e).resolveToken(o).catch(()=>null),i=Number(s?.decimals);return{address:o,decimals:Number.isFinite(i)?i:null}}async function ro(e={},t={}){let r=ws(e.chainId??e.chain),n=Zn(e.sellSymbol??e.sellToken,"sellSymbol"),o=Zn(e.buySymbol??e.buyToken,"buySymbol");if(n.toLowerCase()===o.toLowerCase())throw new I(400,"sell and buy assets must differ");let a=typeof e.taker=="string"?e.taker.trim():"";if(!er.test(a))throw new I(400,"taker must be the wallet address that will sign");let[s,i]=await Promise.all([eo(r,n),eo(r,o)]);if(!s)throw new I(400,`could not resolve sell asset "${n}" on chain ${r}`);if(!i)throw new I(400,`could not resolve buy asset "${o}" on chain ${r}`);let c=bs(e.sellAmount,s.decimals),u=await Hn({chainId:r,tokenIn:s.address||n,tokenOut:i.address||o,amountIn:c,taker:a,decimalsIn:s.decimals??null,decimalsOut:i.decimals??null,source:typeof e.source=="string"&&e.source.trim()!==""?e.source.trim():void 0},t);if(!u.ok)return{ok:!1,reason:u.reason,priceImpactBlocked:!!u.priceImpactBlocked,requiresWalletSignature:!0,backendSigner:!1};let p=i.decimals??18,d=u.minOut??u.chosen?.netOut??u.chosen?.grossOut??null;return{ok:!0,requiresWalletSignature:!0,backendSigner:!1,quote:{sellSymbol:n,buySymbol:o,sellAmount:String(e.sellAmount),buyAmount:d==null?null:String(d),buyAmountFormatted:d==null?null:(Number(d)/10**p).toString(),routeLabel:u.chosen?.source??null,priceImpactPct:Number.isFinite(Number(u.chosen?.priceImpactPct))?Number(u.chosen.priceImpactPct):null,slippageBps:Number.isFinite(Number(u.slippageBps))?Number(u.slippageBps):null,intentHash:u.intentHash??null,minOut:u.minOut??null,requiresApproval:u.requiresApproval??null,warnings:Array.isArray(u.warnings)?u.warnings:[]},transaction:u.transaction??null}}Ze();import{readFileSync as dc,writeFileSync as Oo,mkdirSync as ir,renameSync as pc,unlinkSync as fc,rmSync as mc}from"node:fs";import{dirname as To,join as hc}from"node:path";var gs=["0x000000000022d473030f116ddee9f6b43ac78ba3"],Es={4663:["0xcaf681a66d020601342297493863e78c959e5cb2","0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7","0x1f7d7550b1b028f7571e69a784071f0205fd2efa","0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360d0400a0fd4f2af552add042d716f1d168","0xb477751b76cf82d00a686a1232f5fcd772414af3","0xff5cb29241f002ffed2eaa224e3e996d24a6e8d1"],8453:["0x2626664c2603336e57b271c5c0b26f421741e481","0x6ff5693b99212da76ad316178a184ab56d299b43","0x3d4e44eb1374240ce5f1b871ab261cd16335b76a","0x33128a8fc17869897dce68ed026d694621f6fdfd","0x4200000000000000000000000000000000000006","0x833589fcd6edb6e08f4c7c32d4f71b54bda02913","0xbe6d8f0d05cc4be24d5167a3ef062215be6d18a5","0x254cf9e1e6e233aa1ac962cb9b05b2cfeaae15b0","0x5e7bb104d84c7cb9b682aac2f3d509f5f406809a","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x888888888889758f76e7103c6cbf23abbf58f946","0x3f170631ed9821ca51a59d996ab095162438dc10","0x4f37a9d177470499a2dd084621020b023fcffc1f","0xc92e8bdf79f0507f65a392b0ab4667716bfe0110"],42161:["0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45","0x61ffe014ba17989e743c5f6cb21bf9697530b21e","0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0xaf88d065e77c8cc2239327c5edb3a432268e5831","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9","0x888888888889758f76e7103c6cbf23abbf58f946","0xeaedc32a51c510d35ebc11088fd5ff2b47aacf2e","0x2191718cd32d02b8e60badffea33e4b5dd9a0a0d","0xc92e8bdf79f0507f65a392b0ab4667716bfe0110","0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41","0x7452c558d45f8afc8c83dae62c3f8a5be19c71f6"],1:["0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x4cd00e387622c35bddb9b4c962c136462338bc31","0x6a000f20005980200259b80c5102003040001068","0xae563e3f8219521950555f5962419c8919758ea2","0x45312ea0eff7e09c83cbe249fa1d7598c4c8cd4e","0xc92e8bdf79f0507f65a392b0ab4667716bfe0110"],137:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x0dcded3545d565ba3b19e683431381007245d983"],10:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xe2fa4e1d17725e72dcdafe943ecf45df4b9e285b","0x0dcded3545d565ba3b19e683431381007245d983"],56:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xa72c85c258a81761433b4e8da60505fe3dd551cc"],43114:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xf39ca6ede9bf7820a952b52f3c94af526bab9015","0x0dcded3545d565ba3b19e683431381007245d983","0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2","0x820f5ffc5b525cd4d88cd91acf2c28f16530cc68"],999:["0x0a0758d937d1059c356d4714e57f5df0239bce1a","0xd2002373543ce3527023c75e7518c274a51ce712"],2741:["0x4f8c9056bb8a3616693a76922fa35d53c056e5b3"],988:["0x026f252016a7c47cdef1f05a3fc9e20c92a49c37","0xff5cb29241f002ffed2eaa224e3e996d24a6e8d1","0x817997ca8394e26cce3de3a076a4889b27dbf9de","0x3dea4be5615974f31624404ef288ba3b36dfeb83","0xeaf7ac0fdf150cdd89340fb762d83848de6a7b83","0x779ded0c9e1022225f8e0630b35a9b54be713736","0xbc6f7725f08232c151b528bdfcaaf89993ca86ee"]},xs={1:["0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x4cd00e387622c35bddb9b4c962c136462338bc31","0x6a000f20005980200259b80c5102003040001068","0xae563e3f8219521950555f5962419c8919758ea2","0x45312ea0eff7e09c83cbe249fa1d7598c4c8cd4e"],10:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xe2fa4e1d17725e72dcdafe943ecf45df4b9e285b","0x0dcded3545d565ba3b19e683431381007245d983"],56:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xa72c85c258a81761433b4e8da60505fe3dd551cc"],137:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x0dcded3545d565ba3b19e683431381007245d983"],988:["0x026f252016a7c47cdef1f05a3fc9e20c92a49c37","0xff5cb29241f002ffed2eaa224e3e996d24a6e8d1","0x3dea4be5615974f31624404ef288ba3b36dfeb83","0xbc6f7725f08232c151b528bdfcaaf89993ca86ee"],999:["0x0a0758d937d1059c356d4714e57f5df0239bce1a","0xd2002373543ce3527023c75e7518c274a51ce712"],2741:["0x4f8c9056bb8a3616693a76922fa35d53c056e5b3"],4663:["0xcaf681a66d020601342297493863e78c959e5cb2","0xb477751b76cf82d00a686a1232f5fcd772414af3","0xff5cb29241f002ffed2eaa224e3e996d24a6e8d1"],8453:["0x2626664c2603336e57b271c5c0b26f421741e481","0x6ff5693b99212da76ad316178a184ab56d299b43","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x888888888889758f76e7103c6cbf23abbf58f946","0x3f170631ed9821ca51a59d996ab095162438dc10","0x4f37a9d177470499a2dd084621020b023fcffc1f"],42161:["0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x888888888889758f76e7103c6cbf23abbf58f946","0xeaedc32a51c510d35ebc11088fd5ff2b47aacf2e","0x2191718cd32d02b8e60badffea33e4b5dd9a0a0d"],43114:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xf39ca6ede9bf7820a952b52f3c94af526bab9015","0x0dcded3545d565ba3b19e683431381007245d983"]};function no(e,t){let r=String(t||"").trim().toLowerCase();return r?(xs[Number(e)]||[]).includes(r):!1}function se(e){let t=Es[Number(e)]||[];return new Set([...t,...gs].map(r=>String(r).trim().toLowerCase()).filter(Boolean))}import{existsSync as ys}from"node:fs";import{homedir as tr}from"node:os";import{join as ve}from"node:path";var oo=process.env.ORACLE_PUBLIC_DESKTOP==="1",ao=oo?process.env.ORACLE_CONFIG_DIR||ve(tr(),".config","oracle"):ve(tr(),".config","oracle"),As=oo?ao:ve(tr(),".config","mad-desk");function ee(e,t,r=""){let n=process.env[e];if(n!=null&&String(n).trim()!=="")return n;let o=t?process.env[t]:void 0;return o!=null&&String(o).trim()!==""?o:r}function io(e,t){return String(ee(e,t,""))}function so(e,t,r){let n=ee(t,r,"");if(n)return n;let o=ve(ao,e);return ys(o)?o:ve(As,e)}D();import{Interface as Qs,MaxUint256 as Zs,isAddress as ec,keccak256 as Fd,toUtf8Bytes as $d}from"ethers";import{createHmac as Rs,timingSafeEqual as Bs}from"node:crypto";import{Interface as Fs,isAddress as $s}from"ethers";D();de();J();import{createHash as vs,createHmac as Ss,timingSafeEqual as Is}from"node:crypto";import{isAddress as Cs}from"ethers";function lt(e){return Array.isArray(e)?`[${e.map(lt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${lt(e[t])}`).join(",")}}`:JSON.stringify(e)}function ut(e,t){let r=String(e||"").trim();if(!Cs(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function ks(e){let t=String(e||"0x").toLowerCase();if(!/^0x(?:[0-9a-f]{2})*$/.test(t))throw new Error("route attestation calldata must be hex bytes");return t}function co(e){return`0x${vs("sha256").update(String(e)).digest("hex")}`}function Ns(e,t){return`0x${Ss("sha256",String(e)).update(t).digest("hex")}`}function _s(e,t){let r=Buffer.from(String(e||"").replace(/^0x/,""),"hex"),n=Buffer.from(String(t||"").replace(/^0x/,""),"hex");return r.length===n.length&&r.length>0&&Is(r,n)}function Os(e){return W(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}function Ts(e){let{signature:t,...r}=e;return r}function Se(e){return co(ks(e))}function Ls(e){if(!e)throw new Error("route attestation requires slippage guard");return co(lt(e))}function uo(e,t={},{chainId:r,nowMs:n=Date.now(),secret:o}={}){if(O(e||{},n,"route attestation"),!e||e.mode!=="route-attestation")throw new Error("route attestation required");if(Number(e.expiresAtMs)<=Number(n))throw new Error("route attestation expired");if(Number(e.chainId)!==Number(r??t.chainId))throw new Error("route attestation chain mismatch");let a=ut(t.to,"route tx.to");if(ut(e.destination,"route destination")!==a)throw new Error("route attestation destination mismatch");if(t.from&&e.sender&&ut(e.sender,"route sender")!==ut(t.from,"route tx.from"))throw new Error("route attestation sender mismatch");if(String(e.value)!==String(t.value??"0"))throw new Error("route attestation value mismatch");if(e.calldataHash!==Se(t.data||"0x"))throw new Error("route attestation calldata mismatch");if(e.slippageHash!==Ls(t.slippageGuard??t.madSlippage))throw new Error("route attestation slippage mismatch");let s=Ns(Os(o),lt(Ts(e)));if(!_s(e.signature,s))throw new Error("route attestation signature mismatch");return Me(t.slippageGuard??t.madSlippage,{chainId:Number(r??t.chainId),venue:a,nowMs:n,secret:o,tx:{...t,chainId:Number(r??t.chainId),to:a,data:t.data},requireSigned:!0}),!0}de();J();var Ds=new Fs(["function approve(address spender,uint256 amount) returns (bool)"]);function dt(e){return Array.isArray(e)?`[${e.map(dt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${dt(e[t])}`).join(",")}}`:JSON.stringify(e)}function z(e,t){let r=String(e||"").trim();if(!$s(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Us(e,t="vault amount"){try{let r=BigInt(String(e));if(r<=0n)throw new Error("nonpositive");return r.toString()}catch{throw new Error(`${t} must be a positive integer string`)}}function Ps(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x095ea7b3"))throw new Error("approval calldata required");let[r,n]=Ds.decodeFunctionData("approve",t);return{spender:z(r,"approval spender"),amount:Us(n,"approval amount")}}function lo(e,t){return`0x${Rs("sha256",String(e)).update(t).digest("hex")}`}function po(e,t){let r=Buffer.from(String(e||"").replace(/^0x/,""),"hex"),n=Buffer.from(String(t||"").replace(/^0x/,""),"hex");return r.length===n.length&&r.length>0&&Bs(r,n)}function fo(e){return W(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}function mo(e){let{signature:t,...r}=e;return r}function ho(e,t={},{chainId:r,nowMs:n=Date.now(),secret:o}={}){if(O(e||{},n,"vault attestation"),!e||e.mode!=="vault-attestation")throw new Error("vault attestation required");if(Number(e.expiresAtMs)<=Number(n))throw new Error("vault attestation expired");let a=Number(r??t.chainId);if(Number(e.chainId)!==a)throw new Error("vault attestation chain mismatch");let s=z(t.to,"vault tx.to");if(z(e.vault,"vault")!==s)throw new Error("vault attestation destination mismatch");if(t.from&&z(e.owner,"vault owner")!==z(t.from,"vault tx.from"))throw new Error("vault attestation owner mismatch");if((t.value==null?"0":String(BigInt((String(t.value).startsWith("0x"),String(t.value)))))!=="0")throw new Error("vault attestation value mismatch");if(e.calldataHash!==Se(t.data||"0x"))throw new Error("vault attestation calldata mismatch");let c=lo(fo(o),dt(mo(e)));if(!po(e.signature,c))throw new Error("vault attestation signature mismatch");return!0}function wo(e,t={},r={},{chainId:n,nowMs:o=Date.now(),secret:a}={}){if(!e||e.mode!=="vault-attestation")throw new Error("vault attestation required");if(String(e.action)!=="deposit")throw new Error("vault approval requires deposit attestation");if(O(e,o,"vault approval attestation"),Number(e.expiresAtMs)<=Number(o))throw new Error("vault attestation expired");let s=lo(fo(a),dt(mo(e)));if(!po(e.signature,s))throw new Error("vault attestation signature mismatch");let i=Number(t.chainId??n);if(Number(e.chainId)!==i)throw new Error("vault attestation chain mismatch");let c=Ps(t.data);if(z(e.asset,"vault asset")!==z(t.to,"approval token"))throw new Error("vault attestation asset mismatch");if(z(e.vault,"vault")!==c.spender)throw new Error("vault attestation spender mismatch");if(String(e.amount)!==c.amount||String(r.amount)!==c.amount)throw new Error("vault attestation amount mismatch");if(r.provider&&String(r.provider)!==String(e.provider))throw new Error("vault attestation provider mismatch");return!0}import{createHmac as qs,timingSafeEqual as Ms}from"node:crypto";import{Interface as Vs,isAddress as Hs}from"ethers";de();J();var js=new Vs(["function approve(address spender,uint256 amount) returns (bool)"]),Ws=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function rr(e){return Array.isArray(e)?`[${e.map(rr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${rr(e[t])}`).join(",")}}`:JSON.stringify(e)}function j(e,t){let r=String(e||"").trim();if(!Hs(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Gs(e,t="gmx amount"){try{let r=BigInt(String(e));if(r<=0n)throw new Error("nonpositive");return r.toString()}catch{throw new Error(`${t} must be a positive integer string`)}}function Ks(e,t){return`0x${qs("sha256",String(e)).update(t).digest("hex")}`}function zs(e,t){let r=Buffer.from(String(e||"").replace(/^0x/,""),"hex"),n=Buffer.from(String(t||"").replace(/^0x/,""),"hex");return r.length===n.length&&r.length>0&&Ms(r,n)}function Xs(e){return W(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}function Ys(e){let{signature:t,...r}=e;return r}function Js(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x095ea7b3"))throw new Error("approval calldata required");let[r,n]=js.decodeFunctionData("approve",t);return{spender:j(r,"approval spender"),amount:Gs(n,"approval amount")}}function nr(e,t){let r=Ws[Number(e)];return!!r&&j(t,"gmx exchange router")===r}function bo(e,t){let r=Ks(Xs(t),rr(Ys(e)));if(!zs(e.signature,r))throw new Error("gmx attestation signature mismatch")}function go(e,t={},{chainId:r,nowMs:n=Date.now(),secret:o}={}){if(!e||e.mode!=="gmx-order-attestation")throw new Error("gmx order attestation required");if(Number(e.expiresAtMs)<=Number(n))throw new Error("gmx attestation expired");bo(e,o);let a=Number(r??t.chainId);if(Number(e.chainId)!==a)throw new Error("gmx attestation chain mismatch");let s=j(t.to,"gmx tx.to");if(j(e.exchangeRouter,"gmx exchangeRouter")!==s)throw new Error("gmx attestation destination mismatch");if(!nr(a,s))throw new Error("gmx exchangeRouter mismatch for chain");if(t.from&&j(e.account,"gmx account")!==j(t.from,"gmx tx.from"))throw new Error("gmx attestation account mismatch");O(e||{},n,"gmx order attestation");let i=t.value==null?"0":String(BigInt((String(t.value).startsWith("0x"),String(t.value))));if(String(e.value)!==i||String(e.executionFee)!==i)throw new Error("gmx attestation value mismatch");if(e.calldataHash!==Se(t.data||"0x"))throw new Error("gmx attestation calldata mismatch");return!0}function Eo(e,t={},r={},{chainId:n,nowMs:o=Date.now(),secret:a}={}){if(!e||e.mode!=="gmx-order-attestation")throw new Error("gmx order attestation required");if(O(e,o,"gmx approval attestation"),Number(e.expiresAtMs)<=Number(o))throw new Error("gmx attestation expired");bo(e,a);let s=Number(t.chainId??n);if(Number(e.chainId)!==s)throw new Error("gmx attestation chain mismatch");let i=Js(t.data);if(j(e.initialCollateralToken,"gmx collateral")!==j(t.to,"approval token"))throw new Error("gmx attestation collateral mismatch");if(j(e.router,"gmx router")!==i.spender)throw new Error("gmx attestation spender mismatch");if(String(e.initialCollateralDeltaAmount)!==i.amount||String(r.amount)!==i.amount)throw new Error("gmx attestation amount mismatch");if(r.provider&&String(r.provider)!==String(e.provider))throw new Error("gmx attestation provider mismatch");return!0}function xo(e,t="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let r=String(e??"").trim();if(r==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(r)&&!/^0x[0-9a-fA-F]+$/.test(r))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(r)}`);try{return BigInt(r)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(r)}`)}}J();var Vd=new Qs(["function approve(address spender,uint256 amount) returns (bool)"]);function Ie(e,t){let r=String(e||"").trim();if(!ec(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function yo(e,t="approval amount",{allowZero:r=!1}={}){let n=xo(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=Zs)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var tc=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]);function Ce(e){let t=String(e||"").toLowerCase();return t.length<10?!1:tc.has(t.slice(0,10))}function or(e){if(!Ce(e))throw new Error("approval calldata required");let t=String(e||"").toLowerCase(),r=t.slice(0,10),n=t.slice(10).match(/.{1,64}/g)||[],o=c=>n[c]?"0x"+n[c].slice(24):null,a=c=>n[c]?BigInt("0x"+n[c]):null,s=null,i=null;switch(r){case"0x095ea7b3":case"0x39509351":s=o(0),i=a(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":s=o(1),i=a(2);break;case"0xd505accf":s=o(1),i=a(2);break;case"0x8fcbaf0c":{s=o(1),i=a(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":s=o(1),i=a(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(s==null||i==null)throw new Error("invalid approve calldata");return{spender:Ie(s,"approval spender"),amount:yo(i,"approval amount",{allowZero:!0}),selector:r}}function Ao(e,t={},{chainId:r,nowMs:n=Date.now()}={}){if(!e||e.mode!=="approval")throw new Error("approval guard required");let o=Number(t.chainId??r);if(Number(e.chainId)!==o)throw new Error(`approval chain mismatch: expected ${o}, got ${e.chainId}`);let a=Ie(t.to,"approval token");if(Ie(e.token,"approval token")!==a)throw new Error("approval token mismatch");let s=or(t.data);if(Ie(e.spender,"approval spender")!==s.spender)throw new Error("approval spender mismatch");let i=String(e.purpose||"")==="revoke";if(s.amount==="0"&&!i)throw new Error("zero approval amount requires revoke purpose");if(yo(e.amount,"approval amount",{allowZero:i})!==s.amount)throw new Error("approval amount mismatch");if((t.value==null?0n:BigInt((String(t.value).startsWith("0x"),String(t.value))))!==0n)throw new Error("approval tx value must be zero");let{now:u}=O(e,n,"approval guard");if(Number(e.issuedAtMs)>u+5e3)throw new Error("approval guard issued in the future");let p=se(o);if(!p.has(s.spender)){if(i)return{chainId:o,token:a,spender:s.spender,amount:s.amount,provider:e.provider||null,purpose:"revoke"};if(String(e.provider||"")==="morpho")return wo(t.madVault||t.vaultGuard,t,e,{chainId:o,nowMs:n}),{chainId:o,token:a,spender:s.spender,amount:s.amount,provider:e.provider||null,purpose:e.purpose||null};throw new Error(`approval spender ${s.spender} not allowlisted for chain ${o}`)}if(String(e.provider||"")==="gmx"&&Eo(t.madGmx||t.gmxGuard,t,e,{chainId:o,nowMs:n}),e.routeVenue&&!p.has(Ie(e.routeVenue,"approval route venue")))throw new Error(`approval route venue ${e.routeVenue} not allowlisted for chain ${o}`);return{chainId:o,token:a,spender:s.spender,amount:s.amount,provider:e.provider||null,purpose:e.purpose||null}}import{Interface as rc,isAddress as nc}from"ethers";J();var oc=new rc(["function setApprovalForAll(address operator,bool approved)"]),ac="0xa22cb465";function pt(e,t){let r=String(e||"").trim();if(!nc(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function vo(e,t){if(e===!0||e===!1)return e;if(e===1||e==="1"||e===1n)return!0;if(e===0||e==="0"||e===0n)return!1;throw new Error(`${t} must be boolean`)}function ke(e){let t=String(e||"").toLowerCase();return t.length>=10&&t.slice(0,10)===ac}function ar(e){if(!ke(e))throw new Error("setApprovalForAll calldata required");let[t,r]=oc.decodeFunctionData("setApprovalForAll",e);return{operator:pt(t,"nft operator"),approved:vo(r,"nft approved")}}function So(e,t={},{chainId:r,nowMs:n=Date.now()}={}){if(!e||e.mode!=="nft-operator-approval")throw new Error("nft operator guard required");let o=Number(t.chainId??r);if(Number(e.chainId)!==o)throw new Error(`nft operator chain mismatch: expected ${o}, got ${e.chainId}`);let a=pt(t.to,"nft collection");if(pt(e.collection,"nft collection")!==a)throw new Error("nft collection mismatch");let s=ar(t.data);if(pt(e.operator,"nft operator")!==s.operator)throw new Error("nft operator mismatch");if(vo(e.approved,"nft approved")!==s.approved)throw new Error("nft approved mismatch");if((t.value==null?0n:BigInt((String(t.value).startsWith("0x"),String(t.value))))!==0n)throw new Error("nft operator approval tx value must be zero");let{now:c}=O(e,n,"nft operator guard");if(Number(e.issuedAtMs)>c+5e3)throw new Error("nft operator guard issued in the future");let u=String(e.purpose||"");if(!s.approved&&u==="revoke")return{chainId:o,collection:a,operator:s.operator,approved:!1,purpose:"revoke",provider:e.provider||null};if(!se(o).has(s.operator))throw new Error(`nft operator ${s.operator} not allowlisted for chain ${o}`);return{chainId:o,collection:a,operator:s.operator,approved:s.approved,purpose:u||"grant",provider:e.provider||null}}import{Interface as ic,MaxUint256 as sc,isAddress as cc}from"ethers";var Co="0xa9059cbb",ko="0x23b872dd";var Io=new ic(["function transfer(address to,uint256 amount) returns (bool)","function transferFrom(address from,address to,uint256 amount) returns (bool)"]);function te(e,t){let r=String(e||"").trim();if(!cc(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function ce(e,t="token transfer amount",{allowZero:r=!1}={}){if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`)}let n;try{n=BigInt(String(e))}catch{throw new Error(`${t} must be an integer string`)}if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=sc)throw new Error("unbounded token transfer amount refused");return n.toString()}function uc(e={}){let t=e.value==null?"0":String(e.value);return BigInt(t)}function No(e){let t=String(e||"").toLowerCase();return t.startsWith(Co)||t.startsWith(ko)}function lc(e){let t=String(e||"").toLowerCase();try{if(t.startsWith(Co)){let[r,n]=Io.decodeFunctionData("transfer",e);return{kind:"transfer",recipient:te(r,"token transfer recipient"),amount:ce(n)}}if(t.startsWith(ko)){let[r,n,o]=Io.decodeFunctionData("transferFrom",e);return{kind:"transferFrom",from:te(r,"token transfer source"),recipient:te(n,"token transfer recipient"),amount:ce(o)}}}catch(r){throw/token transfer/.test(String(r?.message||r))?r:new Error("invalid token transfer calldata")}throw new Error("token transfer calldata required")}function _o(e,t={},{chainId:r,nowMs:n=Date.now()}={}){if(!e||e.mode!=="token-transfer")throw new Error("token transfer guard required");let o=Number(n);if(!Number.isFinite(o))throw new Error("token transfer guard: current time must be a finite number");let a=Number(e.issuedAtMs),s=Number(e.expiresAtMs);if(!Number.isFinite(a)||!Number.isFinite(s))throw new Error("token transfer guard: issuedAtMs and expiresAtMs are required and must be finite");if(s<=a)throw new Error("token transfer guard: expiry must be after issuance");if(o>s)throw new Error(`token transfer guard expired at ${s}, now ${o}`);let i=Number(t.chainId??r);if(Number(e.chainId)!==i)throw new Error(`token transfer chain mismatch: expected ${i}, got ${e.chainId}`);let c=te(t.to,"token transfer token");if(te(e.token,"token transfer token")!==c)throw new Error("token transfer token mismatch");let u=lc(t.data);if(String(e.kind)!==u.kind)throw new Error("token transfer kind mismatch");if(te(e.recipient,"token transfer recipient")!==u.recipient)throw new Error("token transfer recipient mismatch");if(u.kind==="transferFrom"&&te(e.from,"token transfer source")!==u.from)throw new Error("token transfer source mismatch");if(e.amount==null&&e.maxAmount==null)throw new Error("token transfer guard must bind an amount or a maxAmount \u2014 a capless guard authorizes any size");if(e.amount!=null&&e.maxAmount!=null&&BigInt(ce(e.amount))>BigInt(ce(e.maxAmount)))throw new Error("token transfer guard amount exceeds its own maxAmount");if(e.amount!=null&&ce(e.amount)!==u.amount)throw new Error("token transfer amount mismatch");if(e.maxAmount!=null&&BigInt(u.amount)>BigInt(ce(e.maxAmount)))throw new Error("token transfer amount exceeds guard maxAmount");if(uc(t)!==0n)throw new Error("token transfer tx value must be zero");if(Number(e.expiresAtMs)<=Number(n))throw new Error("token transfer guard expired");if(Number(e.issuedAtMs)>Number(n)+5e3)throw new Error("token transfer guard issued in the future");return{chainId:i,token:c,kind:u.kind,from:u.from||null,recipient:u.recipient,amount:u.amount,provider:e.provider||null,purpose:e.purpose||null}}var wc=[1,8453,42161,137,10,56,43114,999,4663,2741,988];function bc(e,t){return new Set(io(e,t).split(",").map(r=>r.trim().toLowerCase()).filter(Boolean))}function gc(){let e=String(ee("ORACLE_ALLOWED_CHAINS","MAD_ALLOWED_CHAINS","")).trim();return e?new Set(e.split(",").map(t=>Number(t.trim())).filter(Number.isFinite)):new Set(wc.map(Number))}function mt(e,t,r){let n=String(ee(e,t,"")).trim();try{return BigInt(n||r)}catch{return BigInt(r)}}function Ec(){return mt("ORACLE_MAX_TX_VALUE_WEI","MAD_MAX_TX_VALUE_WEI","50000000000000000")}function xc(){return mt("ORACLE_MAX_DAILY_VALUE_WEI","MAD_MAX_DAILY_VALUE_WEI","150000000000000000")}function yc(){return mt("ORACLE_MAX_GAS_LIMIT","MAD_MAX_GAS_LIMIT","5000000")}function Ac(){return mt("ORACLE_MAX_TX_FEE_WEI","MAD_MAX_TX_FEE_WEI","5000000000000000")}function ht(){return so("policy-daily.json","ORACLE_POLICY_STATE","MAD_POLICY_STATE")}function ft(e){if(e==null)return 0n;if(typeof e=="number"&&(!Number.isInteger(e)||!Number.isSafeInteger(e)))throw new Error(`exec-policy: value ${e} is not an exact integer \u2014 pass wei as a decimal string or BigInt`);try{return typeof e=="string"&&e.startsWith("0x"),BigInt(e)}catch{throw new Error(`exec-policy: cannot interpret ${JSON.stringify(String(e))} as an integer wei amount`)}}function sr(e,t){if(e==null||e==="")return null;try{let r=(typeof e=="string"&&e.startsWith("0x"),BigInt(e));if(r<0n)throw new Error("negative");return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}}function vc(e={}){let t=sr(e.gasLimit??e.gas,"gasLimit");if(t!=null){let n=yc();if(t>n)throw new Error(`policy: gasLimit ${t} exceeds cap ${n} (ORACLE_MAX_GAS_LIMIT)`)}let r=sr(e.maxFeePerGas??e.gasPrice,"maxFeePerGas/gasPrice");if(t!=null&&r!=null){let n=t*r,o=Ac();if(n>o)throw new Error(`policy: gas fee ceiling ${n} exceeds max tx fee ${o} (ORACLE_MAX_TX_FEE_WEI)`)}}var X=!1;function Sc(){let e=()=>({windowStart:Date.now(),spentWei:"0"}),t;try{t=JSON.parse(dc(ht(),"utf8"))}catch(o){if(o?.code==="ENOENT")return e();throw X=!0,new Error(`policy: daily spend ledger cannot be read or is corrupt: ${o?.message||o}`)}let r=Number(t?.windowStart),n;try{n=BigInt(t?.spentWei)}catch{throw X=!0,new Error("policy: daily spend ledger is corrupt: invalid spentWei")}if(!Number.isFinite(r)||r<=0||n<0n)throw X=!0,new Error("policy: daily spend ledger is corrupt: invalid window");return Date.now()-r>1440*60*1e3?e():(X=!1,{windowStart:r,spentWei:n.toString()})}function Ic(e){let t=ht(),r=`${t}.${process.pid}.tmp`;try{ir(To(t),{recursive:!0}),Oo(r,JSON.stringify(e),{mode:384}),pc(r,t),X=!1}catch(n){X=!0;try{fc(r)}catch{}throw new Error(`policy: daily spend ledger cannot be written or persisted: ${n?.message||n}`)}}function Cc(e){let t=ht(),r=`${t}.lock`,n=hc(r,"owner.json");function o(){Oo(n,JSON.stringify({pid:process.pid,createdAtMs:Date.now()}),{mode:384})}function a(){mc(r,{recursive:!0,force:!0})}function s(){ir(To(t),{recursive:!0}),ir(r,{mode:448});try{o()}catch(i){try{a()}catch(c){throw new Error(`owner metadata write failed (${i?.message||i}); new lock cleanup also failed (${c?.message||c})`)}throw i}}try{s()}catch(i){throw i?.code!=="EEXIST"?new Error(`policy: daily spend ledger lock cannot be acquired: ${i?.message||i}`):new Error(`policy: daily spend ledger lock is busy or stale at ${r}; manual operator recovery required`)}try{return e()}finally{try{a()}catch(i){throw X=!0,new Error(`policy: daily spend ledger lock cannot be released: ${i?.message||i}`)}}}function kc(e){if(X&&String(process.env.ORACLE_ALLOW_EPHEMERAL_CAPS||"")!=="1")throw new Error(`policy: refusing to ${e} \u2014 the daily spend ledger at ${ht()} is not writable, so the daily cap would reset on restart. Fix the path, or set ORACLE_ALLOW_EPHEMERAL_CAPS=1 to accept memory-only caps.`)}function Nc(e={},{chainId:t,to:r,from:n,data:o}={}){if(e?.emergencyCancel?.mode!=="cancel")return!1;if(o!=="0x")throw new Error("policy: emergency cancel must carry empty calldata");if(!/^0x[0-9a-f]{40}$/.test(String(r||"")))throw new Error("policy: emergency cancel target must be the sender");if(r!==n)throw new Error("policy: emergency cancel must send to self");if(Number(e.emergencyCancel.chainId??e.chainId)!==Number(t))throw new Error("policy: emergency cancel chain mismatch");if(ft(e.value)!==0n)throw new Error("policy: emergency cancel value must be zero");if(sr(e.nonce??e.emergencyCancel.nonce,"nonce")==null)throw new Error("policy: emergency cancel nonce required");return!0}function wt(e={},t="broadcast"){let r=String(t??"").trim().toLowerCase();if(r!=="sign"&&r!=="broadcast")throw new Error(`policy: unknown phase ${JSON.stringify(t)}, expected "sign" or "broadcast"`);t=r,kc(t);let n=Number(e.chainId);if(!gc().has(n))throw new Error(`policy: chainId ${n} not in ORACLE_ALLOWED_CHAINS`);let o=String(e.to||"").toLowerCase(),a=String(e.data||"0x").toLowerCase(),s=a!=="0x"&&Ce(a),i=a!=="0x"&&ke(a),c=String(e.from||"").toLowerCase(),u=null,p=null;vc(e),s&&(u=Ao(e.madApproval||e.approvalGuard,{...e,chainId:n,to:o,data:a},{chainId:n})),i&&(p=So(e.nftApprovalGuard||e.madNftApproval,{...e,chainId:n,to:o,data:a},{chainId:n})),!s&&a!=="0x"&&No(a)&&_o(e.madTokenTransfer||e.tokenTransferGuard,{...e,chainId:n,to:o,data:a},{chainId:n}),!s&&o&&nr(n,o)&&go(e.madGmx||e.gmxGuard,{...e,chainId:n,to:o,data:a},{chainId:n});let d=bc("ORACLE_DEST_ALLOWLIST","MAD_DEST_ALLOWLIST");for(let f of se(n))d.add(f);if(!e.to||String(e.to).trim()===""){if(!(String(ee("ORACLE_ALLOW_CREATE","MAD_ALLOW_CREATE","0")).trim()==="1"))throw new Error("policy: contract creation (tx without `to`) is disabled \u2014 set ORACLE_ALLOW_CREATE=1 to permit deploys");if(ft(e.value)>0n)throw new Error("policy: contract creation may not carry native value")}if(o&&!d.has(o)){let f=u?.purpose==="revoke"||p?.purpose==="revoke",b=Nc(e,{chainId:n,to:o,from:c,data:a}),g=e.madRoute||e.routeAttestation,E=e.madVault||e.vaultGuard;if(!(f||b)){if(!g&&!E)throw d.size===0?new Error(`policy: no destination allowlist configured for chain ${n} \u2014 set ORACLE_DEST_ALLOWLIST or add the chain's venues before sending`):new Error(`policy: destination ${o} not allowlisted for chain ${n} (env ORACLE_DEST_ALLOWLIST or venues.mjs)`)}!f&&!b&&(g?uo(g,{...e,chainId:n,to:o,data:a},{chainId:n}):ho(E,{...e,chainId:n,to:o,data:a},{chainId:n}))}if(o&&a!=="0x"&&no(n,o))try{Me(e.slippageGuard??e.madSlippage,{chainId:n,venue:o,tx:{...e,chainId:n,to:o,data:a},requireSigned:!0})}catch(f){let b=String(f?.message||f);throw/required/.test(b)?f:new Error(`policy: ${b}`)}if(!(String(ee("ORACLE_VALUE_CAPS_ENABLED","MAD_VALUE_CAPS_ENABLED","1")).trim()!=="0"))return!0;let h=ft(e.value),w=Ec();if(h>w)throw new Error(`policy: tx value ${h} exceeds per-tx cap ${w} (ORACLE_MAX_TX_VALUE_WEI)`);return t==="broadcast"&&h>0n&&Cc(()=>{let f=Sc(),b=ft(f.spentWei),g=xc();if(b+h>g)throw new Error(`policy: daily native spend ${b+h} would exceed cap ${g} (ORACLE_MAX_DAILY_VALUE_WEI)`);Ic({windowStart:f.windowStart,spentWei:(b+h).toString()})}),!0}import{isAddress as _c}from"ethers";function Lo(e){return(Array.isArray(e)?e:String(e||"").split(",")).map(r=>String(r||"").trim()).filter(Boolean).map(r=>{if(!_c(r))throw new Error(`arm policy address ${r} is invalid`);return r.toLowerCase()})}function Oc(e){return(Array.isArray(e)?e:String(e||"").split(",")).map(r=>String(r||"").trim().toLowerCase()).filter(Boolean).map(r=>{if(!/^0x[0-9a-f]{8}$/.test(r))throw new Error(`arm policy selector ${r} is invalid`);return r})}function Tc(e,t={}){let r=Number(e.chainId),n=Array.isArray(t.chains)?t.chains.map(o=>Number(o)).filter(Number.isFinite):[];if(n.length&&!n.includes(r))throw new Error(`arm policy: chain ${r} not allowed`)}function Lc(e={}){return e?.emergencyCancel?.mode==="cancel"||e?.madApproval?.purpose==="revoke"||e?.approvalGuard?.purpose==="revoke"||e?.nftApprovalGuard?.purpose==="revoke"||e?.madNftApproval?.purpose==="revoke"}function Rc(e){if(e==null||e==="")return 0n;if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error("arm policy: tx value must be exact wei");return BigInt(e)}let t=String(e);return t.startsWith("0x"),BigInt(t)}function cr(e={},t={}){if(t.armed!==!0)throw new Error("arm policy: local vault is disarmed");Tc(e,t);let r=Lc(e),n=String(e.to||"").toLowerCase(),o=String(e.data||"0x").toLowerCase(),a=t.maxSpendWei!=null?BigInt(String(t.maxSpendWei)):null;if(a!=null&&Rc(e.value)>a)throw new Error(`arm policy: tx value exceeds maxSpendWei ${a}`);let s=Lo(t.destinations||t.destinationAllowlist||[]);if(!r&&s.length&&!s.includes(n))throw new Error(`arm policy: destination ${n} not allowed`);let i=Oc(t.selectors||t.selectorAllowlist||[]);if(!r&&i.length&&o!=="0x"&&!i.includes(o.slice(0,10)))throw new Error(`arm policy: selector ${o.slice(0,10)} not allowed`);let c=Lo(t.spenders||t.operators||t.spenderAllowlist||[]);if(!r&&c.length&&Ce(o)){let u=or(o);if(!c.includes(u.spender))throw new Error(`arm policy: approval spender ${u.spender} not allowed`)}if(!r&&c.length&&ke(o)){let u=ar(o);if(u.approved&&!c.includes(u.operator))throw new Error(`arm policy: nft operator ${u.operator} not allowed`)}return!0}function Fo(e){if(e==null||e==="")return null;if(/^\d+$/.test(String(e)))return Number(e);let t=String(e).toLowerCase(),r=Object.entries(he).find(([n,o])=>n===t||String(o.name).toLowerCase()===t);return r?r[1].chainId:null}function $o(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("snipe: amount must be a positive number (ETH/native units)");return t}async function lr(e={}){let t=e.env||process.env,r=Re(t),n=Fo(e.chain||e.chainId||r.arm?.chains?.[0]||"base");if(!n||!Qe(n))return{ok:!1,failureKind:"unsupported-chain",error:`unsupported or unknown chain ${e.chain??""} \u2014 register or pick a known EVM chain`};let o=String(e.token||e.ca||"").trim();if(!o)return{ok:!1,failureKind:"token-required",error:"token CA or symbol required"};let a=null,s=null;if(e.execute){try{a=Fe(t),s=Be(t,{passphrase:e.passphrase})}catch(f){return{ok:!1,failureKind:"not-ready",error:f.message,status:r}}if(Array.isArray(a.chains)&&a.chains.length){let f=a.chains.map(b=>Fo(b)).filter(Boolean);if(f.length&&!f.includes(n))return{ok:!1,failureKind:"chain-not-allowed",error:`chain ${n} not in arm allowlist ${a.chains.join(",")}`}}}let i=e.amount!=null?String(e.amount):a?.maxSpendEth!=null?String(a.maxSpendEth):"0.01";if(a?.maxSpendEth!=null&&$o(i)>$o(a.maxSpendEth)+1e-12)return{ok:!1,failureKind:"spend-cap",error:`amount ${i} exceeds arm maxSpendEth ${a.maxSpendEth}`};let c=e.taker||s?.address||null;if(e.execute&&s?.material)try{c=new Ro(Do(s.material)).address}catch(f){return{ok:!1,failureKind:"bad-key",error:`vault key is not a usable EVM key: ${f.message}`}}if(!c)return{ok:!1,failureKind:"taker-required",error:"prepare-only: pass --taker <addr>, or unlock vault so address is known",prepared:!1,execute:!1};let u=e.sellSymbol||e.sell||$c(n),p=Fc(o)?ur(o):o,d;try{d=await ro({chainId:n,sellSymbol:u,buySymbol:p,sellAmount:i,taker:c,source:e.source||void 0})}catch(f){if(f instanceof I)return{ok:!1,failureKind:"prepare-error",error:f.message,chainId:n,token:p};throw f}if(!d?.ok)return{ok:!1,failureKind:"prepare-refused",error:d?.reason||"could not prepare route",chainId:n,token:p,prepared:d};let l={ok:!0,mode:e.execute?"local-execute":"prepare-only",chainId:n,chain:we(n)?.name||String(n),token:p,taker:c,amount:i,quote:d.quote,tx:d.transaction||d.tx||d.unsignedTx||null,requiresWalletSignature:!e.execute,backendSigner:!1,localVault:!0,prepared:!0};if(!e.execute)return l.note="Prepared only. Unlock vault + arm, then: oracle snipe <token> --execute",l;let m=Do(s.material),h=e.rpcUrl||be(n,t);if(!h)return{ok:!1,failureKind:"rpc-missing",error:`no RPC for chain ${n} \u2014 set the chain RPC env (e.g. BASE_RPC_URL)`,prepared:l};let w=l.tx;if(!w||!w.to)return{ok:!1,failureKind:"no-tx",error:"prepare succeeded but no unsigned tx payload to sign",prepared:l};try{let f=new Bc(h,n),b=new Ro(m,f);if(c&&ur(b.address)!==ur(c))return{ok:!1,failureKind:"taker-mismatch",error:`vault address ${b.address} != taker ${c}`};let g=Dc({...w,to:w.to,data:w.data||"0x",value:w.value!=null?w.value:0n,gasLimit:w.gas||w.gasLimit||void 0,maxFeePerGas:w.maxFeePerGas||void 0,maxPriorityFeePerGas:w.maxPriorityFeePerGas||void 0,nonce:w.nonce!=null?w.nonce:void 0,chainId:n,from:b.address},e);cr(g,a),wt(g,"sign"),wt(g,"broadcast");let E={...g};delete E.from,delete E.madApproval,delete E.approvalGuard,delete E.slippageGuard,delete E.madSlippage,delete E.routeAttestation,delete E.madRoute,delete E.vaultGuard,delete E.madVault,delete E.nftApprovalGuard,delete E.madNftApproval;let _=await b.sendTransaction(E),v=e.wait===!1?null:await _.wait();return{...l,ok:!0,executed:!0,hash:_.hash,receipt:v?{status:v.status,blockNumber:v.blockNumber,gasUsed:v.gasUsed?.toString?.()}:null,note:"Signed and broadcast from local vault session. Public cloud never saw your key."}}catch(f){return{ok:!1,failureKind:"execute-failed",error:f.message||String(f),prepared:l}}}function Do(e){let t=String(e||"").trim();if(t.startsWith("{"))try{let r=JSON.parse(t);t=r.privateKey||r.private_key||r.key||t}catch{}return!t.startsWith("0x")&&/^[0-9a-fA-F]{64}$/.test(t)&&(t=`0x${t}`),t}function $c(e){return Number(e)===56?"BNB":Number(e)===43114?"AVAX":Number(e)===999?"HYPE":"ETH"}function Dc(e={},t={}){let r={...e};if(t.priorityGwei!=null&&(r.maxPriorityFeePerGas=Bo(String(t.priorityGwei),"gwei")),t.maxFeeGwei!=null&&(r.maxFeePerGas=Bo(String(t.maxFeeGwei),"gwei")),t.gasMultiplier!=null&&r.gasLimit!=null){let n=Number(t.gasMultiplier);Number.isFinite(n)&&n>0&&n<=5&&(r.gasLimit=BigInt(r.gasLimit)*BigInt(Math.ceil(n*100))/100n)}return r}import{Wallet as Ap,JsonRpcProvider as vp,getAddress as Sp,isAddress as Ip,parseUnits as Cp}from"ethers";Ze();var dr=`oracle snipe <CA|symbol> [options]
5
+
6
+ Prepare a buy for a token. With local vault unlocked + armed, --execute signs
7
+ and broadcasts from THIS machine only.
8
+
9
+ oracle snipe 0xToken... --chain base --amount 0.01 --taker 0xYourWallet
10
+ oracle snipe 0xToken... --chain base --execute
11
+ oracle snipe PEPE --chain base --amount 0.02 --execute
12
+
13
+ Options:
14
+ --chain <id|name> default: first armed chain or base
15
+ --amount <native> default: arm maxSpendEth or 0.01
16
+ --sell <symbol> sell asset (default native/WETH path)
17
+ --taker <addr> required for prepare-only without unlock
18
+ --execute sign+broadcast via local unlocked vault
19
+ --pass-env <VAR> env var holding local vault passphrase for --execute
20
+ --rpc <url> override RPC
21
+ --priority-gwei N local EIP-1559 priority fee override for speed
22
+ --max-fee-gwei N local EIP-1559 max fee override for speed
23
+ --gas-multiplier N multiply prepared gasLimit, max 5x
24
+ --json
25
+ `;function U(e,t){let r=e.find(o=>o.startsWith(`--${t}=`));if(r)return r.split("=").slice(1).join("=");let n=e.indexOf(`--${t}`);return n>=0&&e[n+1]&&!e[n+1].startsWith("--")?e[n+1]:null}function Uc(e){let t=U(e,"pass-env");if(t){let r=process.env[t];if(!r)throw new Error(`env ${t} is empty`);return r}return process.env.ORACLE_LOCAL_VAULT_PASS||void 0}var zp={name:"snipe",summary:"prepare or locally execute a token buy",group:"local",usage:dr,async run(e){let t=e.argv||[];if(!t.length||t.includes("--help")||t.includes("-h"))return process.stdout.write(dr+`
26
+ `),0;let r=t.find(s=>!s.startsWith("--"));if(!r)return process.stderr.write(dr+`
27
+ `),1;let n=t.includes("--execute")||t.includes("--fire"),o=t.includes("--json"),a=await lr({token:r,chain:U(t,"chain"),amount:U(t,"amount"),sellSymbol:U(t,"sell"),taker:U(t,"taker"),execute:n,passphrase:n?Uc(t):void 0,rpcUrl:U(t,"rpc"),priorityGwei:U(t,"priority-gwei"),maxFeeGwei:U(t,"max-fee-gwei"),gasMultiplier:U(t,"gas-multiplier"),source:U(t,"source")||void 0,wait:!t.includes("--no-wait")});if(o){let s={...a};return delete s.material,process.stdout.write(JSON.stringify(s,null,2)+`
28
+ `),a.ok?0:1}return a.ok?(process.stdout.write(`mode: ${a.mode}
29
+ `),process.stdout.write(`chain: ${a.chain} (${a.chainId})
30
+ `),process.stdout.write(`token: ${a.token}
31
+ `),process.stdout.write(`taker: ${a.taker}
32
+ `),process.stdout.write(`amount: ${a.amount}
33
+ `),a.quote&&(process.stdout.write(`route: ${a.quote.routeLabel||a.quote.sellSymbol+"\u2192"+a.quote.buySymbol}
34
+ `),a.quote.buyAmountFormatted&&process.stdout.write(`out: ~${a.quote.buyAmountFormatted}
35
+ `)),a.tx?.to&&process.stdout.write(`tx.to: ${a.tx.to}
36
+ `),a.hash&&process.stdout.write(`tx.hash: ${a.hash}
37
+ `),a.note&&process.stdout.write(`${a.note}
38
+ `),0):(process.stderr.write(`snipe failed: ${a.error||a.failureKind}
39
+ `),1)}};export{zp as default};