@oracle-agent/oracle 0.22.12 → 0.22.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
var Td=Object.defineProperty;var w=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var z=(e,t)=>{for(var r in t)Td(e,r,{get:t[r],enumerable:!0})};import{createHash as Dd}from"node:crypto";function jd(e){let t=String(e||"").toLowerCase();return ri.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function Hd(e){let t={};for(let[r,n]of Object.entries(e||{}))jd(r)||(t[r]=n);return t}function zd(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 Vd(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Kd(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)),a=[...new Set([...ri,...o])].sort().map(c=>`${c}=${n[c]??""}`).join(`
|
|
3
3
|
`),i=Dd("sha256").update(a).digest("hex").slice(0,32);return`${e} ${t} ${i}`}function Wd(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,ei):Math.min(250*2**e,ei)+Math.floor(Math.random()*100)}async function Gd(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:s}){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let c=String(e),u={...n||{}};for(let p=0;p<=ti;p+=1){let l=await t(c,{method:r,headers:u,body:o,signal:a.signal,redirect:"manual"}),d=await l.text(),f=null;if(d)try{f=JSON.parse(d)}catch{f=null}if(Md.has(l.status)){if(r!=="GET"&&r!=="HEAD"){let y=new Error(`HTTP ${l.status} ${r} ${c} redirected non-idempotent request`);throw y.status=l.status,y.body=f??d.slice(0,300),y}if(p===ti)throw new Error(`HTTP redirect loop for ${e}`);let h=zd(l.headers?.get?.("location"),c);Vd(h,c)||(u=Hd(u)),c=h;continue}if(!l.ok){let h=new Error(`HTTP ${l.status} ${r} ${c}`);throw h.status=l.status,h.retryAfter=l.headers?.get?.("retry-after")??null,h.body=f??d.slice(0,300),h}return f??d}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(i)}}async function v(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,o=(t.method||"GET").toUpperCase(),s={Accept:"application/json",...t.headers||{}},a=t.body;a!=null&&typeof a!="string"&&(s["Content-Type"]=s["Content-Type"]||"application/json",a=JSON.stringify(a));let i=Number.isInteger(t.retries)?Math.max(t.retries,0):Fd,c=async()=>{let f;for(let h=0;h<=i;h++)try{return await Gd(e,{fetchImpl:r,method:o,headers:s,body:a,timeoutMs:n})}catch(y){f=y;let g=y?.status,b=y?.name==="AbortError",S=new Set([408,425,429]),I=g!=null?S.has(g)||Ld.has(g)&&Zs.has(o):!b&&Zs.has(o);if(h===i||!I)throw y;await Qd(Wd(h,y?.retryAfter))}throw f};if(!(t.dedupe!==!1&&o==="GET"&&a==null))return c();let p=Kd(o,e,s),l=Wn.get(p);if(l)return l;let d=c().finally(()=>Wn.delete(p));return Wn.set(p,d),d}async function Ir(e,t,r){let n=Array.from(e),o=Math.max(1,Math.min(Number(t)||1,n.length||1)),s=new Array(n.length),a=0;return await Promise.all(Array.from({length:o},async()=>{for(;a<n.length;){let i=a++;s[i]=await r(n[i],i)}})),s}var Ld,Zs,Fd,ei,ri,Md,ti,Wn,Qd,F=w(()=>{Ld=new Set([408,425,429,500,502,503,504]),Zs=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Fd=2,ei=4e3,ri=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Md=new Set([301,302,303,307,308]),ti=3;Wn=new Map;Qd=e=>new Promise(t=>setTimeout(t,e))});function Jd({testnet:e,baseUrl:t}={}){if(t)return t.replace(/\/$/,"").endsWith("/info")?t:`${t.replace(/\/$/,"")}/info`;if(process.env.HL_INFO_URL)return process.env.HL_INFO_URL;if(process.env.HL_API_URL){let r=process.env.HL_API_URL.replace(/\/$/,"");return r.endsWith("/info")?r:`${r}/info`}return e||process.env.HL_TESTNET==="1"?Xd:Yd}async function Qn(e,t={}){if(!e||!e.type)throw new Error("hlInfo requires body.type");let r=Jd(t);return v(r,{method:"POST",body:e,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function ni(e={}){return Qn({type:"meta"},e)}async function oi({coin:e,interval:t="1h",startTime:r,endTime:n},o={}){if(!e)throw new Error("hlCandleSnapshot requires coin");let s={type:"candleSnapshot",req:{coin:String(e),interval:t,startTime:r??Date.now()-24*3600*1e3,endTime:n??Date.now()}};return Qn(s,o)}async function si({coin:e,startTime:t,endTime:r},n={}){if(!e)throw new Error("hlFundingHistory requires coin");return Qn({type:"fundingHistory",coin:String(e),startTime:t??Date.now()-24*3600*1e3,endTime:r??Date.now()},n)}var Yd,Xd,Gn=w(()=>{F();Yd="https://api.hyperliquid.xyz/info",Xd="https://api.hyperliquid-testnet.xyz/info"});import{createHash as Zd}from"node:crypto";function $e(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function wt(e){return typeof e=="number"&&Number.isFinite(e)}function Jn(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)Jn(t);return Object.freeze(e)}for(let t of Object.keys(e))Jn(e[t]);return Object.freeze(e)}function nt(e){if(Array.isArray(e))return e.map(nt);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=nt(e[r]);return t}return e}function Yn(e){return{netPnlUsd:e.metrics.netPnlUsd,netPnlPct:e.metrics.netPnlPct,maxDrawdownPct:e.metrics.maxDrawdownPct,winRate:e.metrics.winRate,profitFactor:e.metrics.profitFactor,tradeCount:e.metrics.tradeCount,sharpe:e.metrics.sharpe,turnoverUsd:e.metrics.turnoverUsd,exposurePct:e.metrics.exposurePct}}function ii(e){return{feesUsd:e.costs.feesUsd,builderFeesUsd:e.costs.builderFeesUsd,fundingUsd:e.costs.fundingUsd,slippageUsd:e.costs.slippageUsd}}function tp(e){return(e.feesUsd||0)+(e.builderFeesUsd||0)+Math.max(0,e.fundingUsd||0)+(e.slippageUsd||0)}function rp(e){let t=0;for(let r of e.trades)r.grossPnlUsd>0&&(t+=r.grossPnlUsd);return t}function np(e,t,r){return!(!e||e.tradeCount<Math.max(1,Math.min(r,3))||!(e.netPnlUsd>0)||!(e.profitFactor>1)||!(e.maxDrawdownPct<=t.maxDailyLossPct))}function ci(e){if(!$e(e))throw new TypeError("evidence artifact must be a plain object");if(!ep.includes(e.status))throw new TypeError("evidence artifact status is invalid");for(let t of["strategyHash","compilerHash","barsHash"])if(typeof e[t]!="string"||!/^[0-9a-f]{64}$/.test(e[t]))throw new TypeError(`evidence artifact ${t} must be a sha256 hash`);if(!$e(e.split))throw new TypeError("evidence artifact split required");if(!Array.isArray(e.flags))throw new TypeError("evidence artifact flags must be an array");if(!$e(e.walkForward)||!Array.isArray(e.walkForward.windows))throw new TypeError("evidence artifact walkForward windows required");if(e.status==="pass_live_eligible"&&(!$e(e.train)||!$e(e.holdout)))throw new TypeError("live-eligible evidence artifact requires train and holdout facts");return nt({barsHash:e.barsHash,compilerHash:e.compilerHash,flags:e.flags.map(t=>nt(t)),holdout:e.holdout??null,split:e.split,status:e.status,strategyHash:e.strategyHash,train:e.train??null,walkForward:{passRate:e.walkForward.passRate,windowsRun:e.walkForward.windowsRun??e.walkForward.windows.length,windows:e.walkForward.windows.map(t=>({index:t.index,trainStartIndex:t.trainStartIndex,trainEndIndex:t.trainEndIndex,passed:t.passed,reason:t.reason,evalStartIndex:t.evalStartIndex,evalEndIndex:t.evalEndIndex,metrics:t.metrics}))}})}function ui(e){return Zd("sha256").update(JSON.stringify(ci(e)),"utf8").digest("hex")}function xe(e,t,r=0){if(!Number.isInteger(e)||e<r)throw new Error(`${t} must be an integer >= ${r}`);return e}function Xn(e,t){if(!$e(e)||!$e(e.metrics))throw new Error(`${t} metrics required`);let r=xe(e.tradeCount,`${t}.tradeCount`);if(e.metrics.tradeCount!==r)throw new Error(`${t} tradeCount contradicts metrics.tradeCount`);for(let n of["netPnlUsd","profitFactor","maxDrawdownPct"])if(!wt(e.metrics[n]))throw new Error(`${t}.metrics.${n} must be finite`);if(e.metrics.maxDrawdownPct<0)throw new Error(`${t}.metrics.maxDrawdownPct must be >= 0`);return e.metrics}function op(e,{maxDailyLossPct:t}={}){let r=e.split,n=xe(r.trainStartIndex,"split.trainStartIndex"),o=xe(r.trainEndIndex,"split.trainEndIndex"),s=xe(r.trainBarCount,"split.trainBarCount",1),a=xe(r.holdoutStartIndex,"split.holdoutStartIndex"),i=xe(r.holdoutEndIndex,"split.holdoutEndIndex"),c=xe(r.holdoutBarCount,"split.holdoutBarCount",1);if(n!==0||o-n+1!==s||a!==o+1||i-a+1!==c)throw new Error("evidence split must be contiguous, chronological, and count-consistent");if(!wt(r.trainFraction)||r.trainFraction<=0||r.trainFraction>=1)throw new Error("split.trainFraction must be in (0,1)");Xn(e.train,"train");let u=Xn(e.holdout,"holdout");if(u.tradeCount<1||u.netPnlUsd<=0||u.profitFactor<=1)throw new Error("live-eligible holdout metrics do not pass");if(wt(t)&&u.maxDrawdownPct>t)throw new Error("live-eligible holdout drawdown exceeds strategy risk");if(e.flags.length>0)throw new Error("live-eligible evidence cannot contain failure flags");let p=e.walkForward,l=p.windows;if(l.length<1||p.windowsRun!==l.length)throw new Error("live-eligible walk-forward windowsRun must match nonempty windows");let d=0,f=-1;for(let y=0;y<l.length;y++){let g=l[y];if(!$e(g)||g.index!==y||typeof g.passed!="boolean")throw new Error("walk-forward windows must be ordered and structurally valid");let b=xe(g.trainStartIndex,`walkForward.windows[${y}].trainStartIndex`),S=xe(g.trainEndIndex,`walkForward.windows[${y}].trainEndIndex`),I=xe(g.evalStartIndex,`walkForward.windows[${y}].evalStartIndex`),A=xe(g.evalEndIndex,`walkForward.windows[${y}].evalEndIndex`);if(b!==0||S>=I||I>A||I<=f)throw new Error("walk-forward windows must be chronological and disjoint");if(f=A,g.passed){if(d+=1,g.reason!=="pass")throw new Error("passed walk-forward window reason must be pass");let O=Xn({metrics:g.metrics,tradeCount:g.metrics?.tradeCount},`walkForward.windows[${y}]`);if(O.tradeCount<1||O.netPnlUsd<=0||O.profitFactor<=1)throw new Error("passed walk-forward window metrics do not pass");if(wt(t)&&O.maxDrawdownPct>t)throw new Error("passed walk-forward drawdown exceeds strategy risk")}else if(g.reason==="pass")throw new Error("failed walk-forward window cannot have pass reason")}let h=d/l.length;if(!wt(p.passRate)||Math.abs(p.passRate-h)>Number.EPSILON||h<.6)throw new Error("walk-forward passRate contradicts concrete windows or is below live threshold")}function li(e,t={}){if(typeof e?.id!="string"||!/^[0-9a-f]{64}$/.test(e.id))throw new Error("evidence.id must be a sha256 evidence artifact hash");let r=ci(e),n=nt({id:e.id,...r});if(JSON.stringify(nt(e))!==JSON.stringify(n))throw new Error("evidence artifact contains fields unbound from its deterministic identity");let o=ui(e);if(e.id!==o)throw new Error("evidence.id does not match its deterministic artifact facts digest");return e.status==="pass_live_eligible"&&op(e,t),e}function Zn({strategy:e,bars:t,backtestOptions:r={},trainFraction:n=.7,walkForwardWindows:o=3,minTrades:s=10}={}){let a=[];if(!$e(e))throw new TypeError("strategy must be a plain object");if(!Array.isArray(t))throw new TypeError("bars must be an array");if(!$e(r))throw new TypeError("backtestOptions must be a plain object");if(!wt(n)||n<=0||n>=1)throw new TypeError("trainFraction must be in (0,1)");if(!Number.isInteger(o)||o<1)throw new TypeError("walkForwardWindows must be a positive integer");if(!Number.isInteger(s)||s<0)throw new TypeError("minTrades must be an integer >= 0");let i=ue(e),c=xt(i),u=Qt(t),p=t.length,l=(B=[],H={})=>ai({status:"fail",strategy:i,sHash:c,barsHash:u,split:H.split||{trainStartIndex:0,trainEndIndex:-1,trainBarCount:0,holdoutStartIndex:0,holdoutEndIndex:-1,holdoutBarCount:0,trainFraction:n},train:H.train||null,holdout:H.holdout||null,walkForward:H.walkForward||{windows:[],passRate:0},flags:[...a,...B]});if(p<10)return l([{type:"insufficient_bars",message:"need at least 10 bars for evidence"}]);let d=Math.floor(p*n),f=d,h=p-f;if(d<5||h<3)return l([{type:"invalid_windowing",message:"train/holdout split too small",trainCount:d,holdoutCount:h}]);let y=t.slice(0,d),g=t.slice(f),b,S;try{b=We(i,y,r),S=We(i,g,r)}catch(B){return l([{type:"backtest_error",message:String(B.message||B)}])}let I={metrics:Yn(b),costs:ii(b),tradeCount:b.metrics.tradeCount},A={metrics:Yn(S),costs:ii(S),tradeCount:S.metrics.tradeCount},O={trainStartIndex:0,trainEndIndex:d-1,trainBarCount:d,holdoutStartIndex:f,holdoutEndIndex:p-1,holdoutBarCount:h,trainFraction:n},_=[],m=Math.floor(p/(o+1));if(m<3)a.push({type:"invalid_windowing",message:"walk-forward window size too small",wfSize:m});else for(let B=0;B<o;B++){let H=m*(B+1),ie=H,re=Math.min(p,ie+m);if(re-ie<3||H<3){_.push({index:B,trainStartIndex:0,trainEndIndex:H-1,evalStartIndex:ie,evalEndIndex:re-1,passed:!1,reason:"window_too_small",metrics:null});continue}let Re=t.slice(ie,re),Er;try{Er=We(i,Re,r)}catch{_.push({index:B,trainStartIndex:0,trainEndIndex:H-1,evalStartIndex:ie,evalEndIndex:re-1,passed:!1,reason:"backtest_error",metrics:null});continue}let kr=Yn(Er),Ar=np(kr,i.risk,s);_.push({index:B,trainStartIndex:0,trainEndIndex:H-1,evalStartIndex:ie,evalEndIndex:re-1,passed:Ar,reason:Ar?"pass":"fail_metrics",metrics:kr})}let T=_.filter(B=>B.passed).length,j=_.length===0?0:T/_.length,se={windows:_,passRate:j,windowsRun:_.length};A.metrics.tradeCount===0&&I.metrics.tradeCount===0&&a.push({type:"no_trades",message:"no trades in train or holdout"}),A.metrics.tradeCount===0&&a.push({type:"absent_oos_trades",message:"holdout produced no trades"}),A.metrics.netPnlUsd<0&&a.push({type:"holdout_loss",message:"holdout netPnlUsd is negative"}),I.metrics.netPnlUsd>0&&A.metrics.netPnlUsd<0&&I.metrics.netPnlUsd>Math.abs(A.metrics.netPnlUsd)*.25?a.push({type:"overfit",message:"profitable train with losing holdout (OOS collapse)"}):I.metrics.netPnlUsd>0&&A.metrics.netPnlUsd>0&&A.metrics.netPnlUsd<I.metrics.netPnlUsd*.1&&I.metrics.tradeCount>=s&&a.push({type:"severe_oos_collapse",message:"holdout pnl collapsed vs train"});let Te=tp(A.costs),x=rp(S);x>0&&Te>x&&a.push({type:"costs_exceed_gross",message:"holdout costs exceed gross gains"});let N=a.some(B=>["insufficient_bars","invalid_windowing","absent_oos_trades","holdout_loss","no_trades","severe_oos_collapse","backtest_error"].includes(B.type)),L=a.some(B=>B.type==="overfit"),K="fail";return A.metrics.tradeCount>=s&&A.metrics.netPnlUsd>0&&A.metrics.profitFactor>1&&A.metrics.maxDrawdownPct<=i.risk.maxDailyLossPct&&j>=.6&&!(x>0&&Te>x)&&!L&&!a.some(B=>B.type==="severe_oos_collapse"||B.type==="invalid_windowing")?K="pass_live_eligible":!N&&A.metrics.tradeCount>0&&I.metrics.tradeCount>0&&Number.isFinite(A.metrics.netPnlUsd)?(K="pass_paper_only",A.metrics.tradeCount<s&&a.push({type:"undersampled",message:"holdout trades below minTrades"})):L&&A.metrics.tradeCount>0&&I.metrics.netPnlUsd>0?K="fail":A.metrics.tradeCount>0&&I.metrics.tradeCount>0&&!N?K="pass_paper_only":K="fail",A.metrics.netPnlUsd<0&&(K=K==="pass_live_eligible"?"fail":K==="pass_paper_only"?"pass_paper_only":"fail",K="fail"),ai({status:K,strategy:i,sHash:c,barsHash:u,split:O,train:I,holdout:A,walkForward:se,flags:a})}function ai({status:e,strategy:t,sHash:r,barsHash:n,split:o,train:s,holdout:a,walkForward:i,flags:c}){let u={status:e,strategyHash:r,compilerHash:st,barsHash:n,split:o,train:s,holdout:a,walkForward:i,flags:c};return u.id=ui(u),Jn(nt(JSON.parse(JSON.stringify(u))))}var ep,eo=w(()=>{it();ot();_r();ep=Object.freeze(["fail","pass_paper_only","pass_live_eligible"])});import{createHash as sp,createHmac as ip,timingSafeEqual as aw}from"node:crypto";function to(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(to).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${to(e[r])}`).join(",")}}`}function di(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function pi(e=process.env){return di(process.env)||di(e)}function up(e){let{oraclePrepared:t,prepareHash:r,prepareMac:n,note:o,...s}=e||{};return s}function lp(e){let t=up(e);return sp("sha256").update(to(t)).digest("hex")}function dp(e,t=pi()){return t?ip("sha256",t).update(String(e)).digest("hex"):""}function Q(e,{provider:t,kind:r,env:n=process.env}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let o={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1};if(!o.provider)throw new Error("stampPrepared: provider required");if(!o.kind)throw new Error("stampPrepared: kind required");let s=Date.now(),a=s+cp,c={...o,preparedAt:s,expiresAt:a,prepareVersion:ap},u=lp(c),p=pi(n),l=p?dp(u,p):void 0,d={...c,oraclePrepared:!0,prepareHash:u};return l&&(d.prepareMac=l),d}var ap,cp,cw,de=w(()=>{ap=2,cp=300*1e3,cw=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});function Gt(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function fp(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function no(e,t="value"){if(Array.isArray(e)){e.forEach((r,n)=>no(r,`${t}[${n}]`));return}if(Gt(e))for(let[r,n]of Object.entries(e)){let o=fp(r);if(pp.some(s=>o.includes(s)))throw new Error(`handoff: forbidden secret-like field at ${t}.${r}`);no(n,`${t}.${r}`)}}function ro(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function fi({strategy:e,evidence:t,shadow:r,caps:n,nowMs:o=Date.now(),env:s=process.env}={}){if(no({strategy:e,evidence:t,shadow:r,caps:n},"handoff"),!Gt(e))throw new Error("handoff: strategy required");if(!Gt(t))throw new Error("handoff: evidence required");if(!Gt(r))throw new Error("handoff: shadow required");if(!Gt(n))throw new Error("handoff: caps required");if(typeof r.id!="string"||!r.id.trim())throw new Error("handoff: shadow.id required");if(typeof r.stateHash!="string"||!/^[0-9a-f]{64}$/.test(r.stateHash))throw new Error("handoff: shadow.stateHash must be a sha256 hash");if(r.status!=="running")throw new Error("handoff: shadow.status must be running");if(!Number.isInteger(r.cursor)||r.cursor<=0)throw new Error("handoff: shadow.cursor must be a positive integer");if(!Number.isInteger(r.updatedAt)||r.updatedAt<=0||r.updatedAt>o)throw new Error("handoff: shadow.updatedAt must be a positive integer <= nowMs");let a=ue(e,{nowMs:o}),i=le(a);if(li(t,{maxDailyLossPct:a.risk.maxDailyLossPct}),t.status!=="pass_live_eligible")throw new Error("handoff: evidence.status must be pass_live_eligible");if(t.strategyHash!==i.strategyHash)throw new Error("handoff: evidence.strategyHash mismatch");if(t.compilerHash!==i.compilerHash)throw new Error("handoff: evidence.compilerHash mismatch");let c=["perStrategyNotionalUsd","maxLeverage","dailyLossCapUsd","chainAllowlist","assetAllowlist","expiresAt","killSwitchRequired"];for(let d of c)if(!(d in n)||n[d]==null)throw new Error(`handoff: caps.${d} required`);if(!ro(n.perStrategyNotionalUsd))throw new Error("handoff: caps.perStrategyNotionalUsd must be positive");if(n.perStrategyNotionalUsd>i.strategy.risk.maxNotionalUsd)throw new Error("handoff: caps.perStrategyNotionalUsd exceeds strategy.risk.maxNotionalUsd");if(!ro(n.maxLeverage))throw new Error("handoff: caps.maxLeverage must be positive");if(n.maxLeverage>i.strategy.risk.maxLeverage)throw new Error("handoff: caps.maxLeverage exceeds strategy.risk.maxLeverage");if(!ro(n.dailyLossCapUsd))throw new Error("handoff: caps.dailyLossCapUsd must be positive");let u=i.strategy.risk.maxNotionalUsd*(i.strategy.risk.maxDailyLossPct/100);if(n.dailyLossCapUsd>u)throw new Error("handoff: caps.dailyLossCapUsd exceeds strategy daily loss ceiling");if(!Array.isArray(n.chainAllowlist)||n.chainAllowlist.length===0)throw new Error("handoff: caps.chainAllowlist must be a non-empty array");if(!n.chainAllowlist.every(d=>d==="hyperliquid"))throw new Error("handoff: caps.chainAllowlist must include only hyperliquid");if(!n.chainAllowlist.includes("hyperliquid"))throw new Error("handoff: caps.chainAllowlist must include hyperliquid");if(!Array.isArray(n.assetAllowlist)||n.assetAllowlist.length===0)throw new Error("handoff: caps.assetAllowlist must be a non-empty array");if(n.assetAllowlist.length!==1||n.assetAllowlist[0]!==i.strategy.market.coin)throw new Error("handoff: caps.assetAllowlist must contain only the strategy market coin");if(!Number.isInteger(n.expiresAt)||!(n.expiresAt>o))throw new Error("handoff: caps.expiresAt must be an integer > nowMs");if(n.expiresAt>i.strategy.risk.expiresAt)throw new Error("handoff: caps.expiresAt exceeds strategy.risk.expiresAt");if(n.killSwitchRequired!==!0)throw new Error("handoff: caps.killSwitchRequired must be exactly true");let p={perStrategyNotionalUsd:n.perStrategyNotionalUsd,maxLeverage:n.maxLeverage,dailyLossCapUsd:n.dailyLossCapUsd,chainAllowlist:[...n.chainAllowlist],assetAllowlist:[...n.assetAllowlist],expiresAt:n.expiresAt,killSwitchRequired:!0},l={strategyHash:i.strategyHash,compilerHash:i.compilerHash,evidence:JSON.parse(JSON.stringify(t)),shadow:{id:r.id,stateHash:r.stateHash,status:r.status,cursor:r.cursor,updatedAt:r.updatedAt},compiled:{strategyHash:i.strategyHash,compilerHash:i.compilerHash,compilerVersion:Yt,venue:"hyperliquid",market:{coin:i.strategy.market.coin,kind:"perp",interval:i.strategy.market.interval},risk:{...i.strategy.risk},strategy:JSON.parse(JSON.stringify(i.strategy))},arming:{liveBroadcast:!1,requiresExplicitUserArm:!0,caps:p},requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1};return Q(l,{provider:"hl-strategy",kind:"strategy-live-handoff",env:s})}var pp,mi=w(()=>{it();eo();ot();de();pp=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"]});function St(e,t){let r=Number(e);if(!Number.isFinite(r))throw new TypeError(`${t} must be finite`);return r}function Et(e,t){if(!Number.isSafeInteger(e)||e<0)throw new TypeError(`${t} must be a non-negative safe integer`);return e}function Xt(e){if(Array.isArray(e))for(let t of e)Xt(t);else if(e&&typeof e=="object")for(let t of Object.values(e))Xt(t);return Object.freeze(e)}function hp(e){let t=mp[e];if(!t)throw new TypeError(`unsupported strategy interval: ${e}`);return t}function gp(e,{endTime:t=Number.MAX_SAFE_INTEGER}={}){if(!Array.isArray(e))throw new TypeError("Hyperliquid candles must be an array");Et(t,"endTime");let r=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`candles[${n}] must be an object`);let s=Et(Number(o.t),`candles[${n}].t`);if(Et(Number(o.T),`candles[${n}].T`)>t)continue;let i={t:s,o:St(o.o,`candles[${n}].o`),h:St(o.h,`candles[${n}].h`),l:St(o.l,`candles[${n}].l`),c:St(o.c,`candles[${n}].c`),v:St(o.v,`candles[${n}].v`)};if(i.h<Math.max(i.o,i.c,i.l))throw new TypeError(`candles[${n}].h is below another price`);if(i.l>Math.min(i.o,i.c,i.h))throw new TypeError(`candles[${n}].l is above another price`);if(i.v<0)throw new TypeError(`candles[${n}].v must be non-negative`);let c=r.get(s);if(c&&JSON.stringify(c)!==JSON.stringify(i))throw new TypeError(`conflicting duplicate candle at timestamp ${s}`);c||r.set(s,i)}return Xt([...r.values()].sort((n,o)=>n.t-o.t))}function yp(e,t){if(!Array.isArray(e))throw new TypeError("Hyperliquid funding history must be an array");let r=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`funding[${n}] must be an object`);let s=Et(Number(o.time),`funding[${n}].time`);s>t||r.set(s,{time:s,fundingRate:St(o.fundingRate,`funding[${n}].fundingRate`)})}return[...r.values()].sort((n,o)=>n.time-o.time)}async function bp({coin:e,startTime:t,endTime:r},n){let o=[],s=Math.max(0,t-288e5),a=!1;for(let i=0;i<16&&s<=r;i++){let c=await si({coin:e,startTime:s,endTime:r},n);if(!Array.isArray(c))throw new TypeError("Hyperliquid funding history must be an array");o.push(...c);let u=s;for(let p of c){let l=Number(p?.time);Number.isSafeInteger(l)&&l>u&&(u=l)}if(c.length<500||u>=r){a=!0;break}if(u<=s)throw new Error("Hyperliquid funding history pagination did not advance");s=u+1}if(!a)throw new Error("strategy history exceeds the bounded funding history limit");return yp(o,r)}function wp(e,t,r){let n=0,o=null;return e.map(s=>{let a=s.t+r,i=0;for(;n<t.length&&t[n].time<a;){let c=t[n];o=c.fundingRate,c.time>=s.t&&(i+=c.fundingRate),n+=1}return o==null?{...s,fundingPaymentRate:i}:{...s,fundingRate:o,fundingPaymentRate:i}})}async function hi(e,t={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy history input must be an object");let r=String(e.coin||"").trim().toUpperCase();if(!/^[A-Z0-9][A-Z0-9._-]{0,11}$/.test(r))throw new TypeError("coin must be an uppercase Hyperliquid asset id");let n=String(e.interval||"15m"),o=hp(n);if(e.endTime==null)throw new TypeError("endTime is required for deterministic history");let s=Et(e.endTime,"endTime"),a=e.count==null?1500:e.count;if(!Number.isInteger(a)||a<20||a>5e3)throw new TypeError("count must be an integer from 20 to 5000");let i=e.startTime==null?Math.max(0,s-a*o):Et(e.startTime,"startTime");if(i>=s)throw new TypeError("startTime must be before endTime");let[c,u]=await Promise.all([oi({coin:r,interval:n,startTime:i,endTime:s},t),bp({coin:r,startTime:i,endTime:s},t)]),p=gp(c,{endTime:s}),l=Xt(wp(p,u,o));return Xt({coin:r,interval:n,range:{startTime:i,endTime:s},bars:l})}var mp,gi=w(()=>{Gn();mp=Object.freeze({"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"8h":288e5,"12h":432e5,"1d":864e5})});function Ep(e){let t=[];if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,errors:[{path:"market",message:"must be a plain object"}],market:null};for(let r of Object.keys(e))Sp.has(r)||t.push({path:`market.${r}`,message:"unknown field is not allowed"});return(typeof e.coin!="string"||e.coin.length===0||e.coin.length>32)&&t.push({path:"market.coin",message:"must be a non-empty string max 32"}),(typeof e.interval!="string"||!xp.has(e.interval))&&t.push({path:"market.interval",message:"must be a supported interval"}),t.length?{ok:!1,errors:t,market:null}:{ok:!0,errors:[],market:{coin:e.coin,interval:e.interval}}}async function kp(e={}){let t=await ni(e);if(!t||!Array.isArray(t.universe))throw new TypeError("Hyperliquid market metadata must contain universe");return Object.freeze(t.universe.map((r,n)=>{if(!r||typeof r.name!="string"||!r.name)throw new TypeError(`Hyperliquid market metadata universe[${n}].name is invalid`);return r.name}))}var xp,Sp,yi,bi=w(()=>{Gn();mi();gi();xp=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),Sp=new Set(["coin","interval"]);yi=Object.freeze({id:"hyperliquid",validateMarket:Ep,fetchBars:hi,listMarkets:kp,prepareIntent(e){return fi(e)}})});function vp(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy venue adapter must be an object");if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id))throw new TypeError("strategy venue adapter id is malformed");for(let t of Ap.slice(1))if(typeof e[t]!="function")throw new TypeError(`strategy venue adapter ${e.id} requires ${t}()`);for(let t of["fetchBars","listMarkets"])if(e[t]!=null&&typeof e[t]!="function")throw new TypeError(`strategy venue adapter ${e.id} ${t} must be a function`);return e}function oo(e){return typeof e!="string"?null:Ip.get(e)??null}function so(e){let t=oo(e);if(!t)throw new Error(`unknown strategy venue: ${String(e)}`);return t}var Ap,wi,Ip,Ew,io=w(()=>{bi();Ap=Object.freeze(["id","validateMarket","prepareIntent"]);wi=[yi].map(vp),Ip=new Map(wi.map(e=>[e.id,e])),Ew=Object.freeze([...wi])});import{createHash as _p}from"node:crypto";function ye(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Z(e){return typeof e=="number"&&Number.isFinite(e)}function _i(e){return Number.isInteger(e)&&e>0}function po(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)po(t);return Object.freeze(e)}for(let t of Object.keys(e))po(e[t]);return Object.freeze(e)}function fo(e){if(Array.isArray(e))return e.map(fo);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=fo(e[r]);return t}return e}function E(e,t,r){e.push({path:t,message:r})}function Qe(e,t,r,n){for(let o of Object.keys(e))t.has(o)||E(n,r?`${r}.${o}`:o,"unknown field is not allowed")}function Ri(e,t,r,n){if(!Z(e)||!Z(t)||!Z(r)||!Z(n)||n<=0||e<t||e>r)return!1;let o=(e-t)/n;if(!Number.isFinite(o))return!1;let s=Math.round(o);return Math.abs(o-s)<=1e-9}function lo(e,t,r,n){if(ye(e)){if(Qe(e,new Set(["param"]),t,n),typeof e.param!="string"||!e.param)return E(n,`${t}.param`,"must be a parameter name string"),null;if(!Object.prototype.hasOwnProperty.call(r,e.param))return E(n,`${t}.param`,`unknown parameter "${e.param}"`),null;let o=r[e.param];return!ye(o)||![o.value,o.min,o.max,o.step].every(_i)?(E(n,`${t}.param`,"referenced period parameter value min max and step must be positive integers"),null):{param:e.param}}return _i(e)?e:(E(n,t,"must be a positive integer or {param}"),null)}function Ci(e,t,r,n){return ye(e)?(Qe(e,new Set(["param"]),t,n),typeof e.param!="string"||!e.param?(E(n,`${t}.param`,"must be a parameter name string"),null):Object.prototype.hasOwnProperty.call(r,e.param)?{param:e.param}:(E(n,`${t}.param`,`unknown parameter "${e.param}"`),null)):Z(e)?e:(E(n,t,"must be a finite number or {param}"),null)}function Cr(e){switch(e.type){case"input":case"constant":return[];case"indicator":return e.input?[e.input]:[];case"compare":case"cross":return[e.left,e.right].filter(Boolean);case"logic":return Array.isArray(e.inputs)?[...e.inputs]:[];default:return[]}}function Bp(e){let t=new Map,r=n=>{let o=t.get(n)||0;if(o===1)return!0;if(o===2)return!1;t.set(n,1);let s=e.get(n);if(s){for(let a of Cr(s))if(e.has(a)&&r(a))return!0}return t.set(n,2),!1};for(let n of e.keys())if(r(n))return!0;return!1}function Up(e,t){if(!ye(e))return E(t,"parameters","must be a plain object"),null;let r=Object.keys(e);if(r.length>Ai)return E(t,"parameters",`too many parameters (max ${Ai})`),null;let n={};for(let o of r){if(!Oi.test(o)){E(t,`parameters.${o}`,"parameter name is malformed");continue}let s=e[o],a=`parameters.${o}`;if(!ye(s)){E(t,a,"must be a plain object");continue}Qe(s,Si,a,t);for(let l of Si)l in s||E(t,`${a}.${l}`,"required field is missing");let{value:i,min:c,max:u,step:p}=s;Z(c)||E(t,`${a}.min`,"must be a finite number"),Z(u)||E(t,`${a}.max`,"must be a finite number"),(!Z(p)||p<=0)&&E(t,`${a}.step`,"must be a positive finite number"),Z(i)||E(t,`${a}.value`,"must be a finite number"),Z(c)&&Z(u)&&c>u&&E(t,`${a}.min`,"min must be <= max"),Z(i)&&Z(c)&&Z(u)&&Z(p)&&p>0&&(Ri(i,c,u,p)||E(t,`${a}.value`,"value must lie on the declared min/max/step grid")),n[o]={value:i,min:c,max:u,step:p}}return n}function Dp(e,t,r,n){let o=`nodes.${t}`;if(!ye(e))return E(n,o,"must be a plain object"),null;if(typeof e.type!="string"||!ki[e.type])return E(n,`${o}.type`,"unknown or missing node type"),Qe(e,qp,o,n),null;switch(Qe(e,ki[e.type],o,n),(typeof e.id!="string"||!Ti.test(e.id))&&E(n,`${o}.id`,"must be a 1-64 char id starting with alphanumeric"),e.type){case"input":return(typeof e.field!="string"||!Cp.has(e.field))&&E(n,`${o}.field`,"must be one of open|high|low|close|volume|fundingRate|openInterest"),{id:e.id,type:"input",field:e.field};case"constant":{let s=Ci(e.value,`${o}.value`,r,n);return{id:e.id,type:"constant",value:s}}case"indicator":{(typeof e.indicator!="string"||!Op.has(e.indicator))&&E(n,`${o}.indicator`,"must be one of sma|ema|rsi|macd|bollinger|atr");let s=e.indicator,a={id:e.id,type:"indicator",indicator:s};if(s==="atr"){"input"in e&&(typeof e.input!="string"||!e.input?E(n,`${o}.input`,"must be a node id string when provided"):a.input=e.input);let i=lo(e.period,`${o}.period`,r,n);i!=null&&(a.period=i)}else typeof e.input!="string"||!e.input?E(n,`${o}.input`,"must be a node id string"):a.input=e.input;if((s==="sma"||s==="ema"||s==="rsi"||s==="bollinger"||s==="atr")&&("period"in e,s!=="macd"))if(!("period"in e))E(n,`${o}.period`,"required field is missing");else{let i=lo(e.period,`${o}.period`,r,n);i!=null&&(a.period=i)}if(s==="macd"){for(let i of["fastPeriod","slowPeriod","signalPeriod"])if(!(i in e))E(n,`${o}.${i}`,"required field is missing");else{let c=lo(e[i],`${o}.${i}`,r,n);c!=null&&(a[i]=c)}"output"in e?$p.has(e.output)?a.output=e.output:E(n,`${o}.output`,"must be line|signal|histogram"):E(n,`${o}.output`,"required field is missing"),"period"in e&&E(n,`${o}.period`,"forbidden for macd"),"stdDev"in e&&E(n,`${o}.stdDev`,"forbidden for macd")}else if(s==="bollinger"){if(!("stdDev"in e))E(n,`${o}.stdDev`,"required field is missing");else{let i=Ci(e.stdDev,`${o}.stdDev`,r,n);i!=null&&(typeof i=="number"&&i<=0?E(n,`${o}.stdDev`,"must be > 0"):a.stdDev=i)}"output"in e?Pp.has(e.output)?a.output=e.output:E(n,`${o}.output`,"must be upper|middle|lower"):E(n,`${o}.output`,"required field is missing");for(let i of["fastPeriod","slowPeriod","signalPeriod"])i in e&&E(n,`${o}.${i}`,`forbidden for ${s}`)}else{"output"in e&&E(n,`${o}.output`,`forbidden for ${s}`),"stdDev"in e&&s!=="bollinger"&&E(n,`${o}.stdDev`,`forbidden for ${s}`);for(let i of["fastPeriod","slowPeriod","signalPeriod"])i in e&&E(n,`${o}.${i}`,`forbidden for ${s}`)}return a}case"compare":return(typeof e.op!="string"||!Tp.has(e.op))&&E(n,`${o}.op`,"must be gt|gte|lt|lte|eq"),(typeof e.left!="string"||!e.left)&&E(n,`${o}.left`,"must be a node id"),(typeof e.right!="string"||!e.right)&&E(n,`${o}.right`,"must be a node id"),{id:e.id,type:"compare",op:e.op,left:e.left,right:e.right};case"logic":{if((typeof e.op!="string"||!Rp.has(e.op))&&E(n,`${o}.op`,"must be and|or|not"),!Array.isArray(e.inputs))return E(n,`${o}.inputs`,"must be an array of node ids"),{id:e.id,type:"logic",op:e.op,inputs:[]};let s=[];for(let a=0;a<e.inputs.length;a++){let i=e.inputs[a];typeof i!="string"||!i?E(n,`${o}.inputs.${a}`,"must be a node id"):s.push(i)}return e.op==="not"?s.length!==1&&E(n,`${o}.inputs`,"not requires exactly one input"):(e.op==="and"||e.op==="or")&&s.length<2&&E(n,`${o}.inputs`,`${e.op} requires at least two inputs`),{id:e.id,type:"logic",op:e.op,inputs:s}}case"cross":return(typeof e.direction!="string"||!Np.has(e.direction))&&E(n,`${o}.direction`,"must be above|below"),(typeof e.left!="string"||!e.left)&&E(n,`${o}.left`,"must be a node id"),(typeof e.right!="string"||!e.right)&&E(n,`${o}.right`,"must be a node id"),{id:e.id,type:"cross",direction:e.direction,left:e.left,right:e.right};default:return null}}function Lp(e,t,r){if(!ye(e))return E(t,"risk","must be a plain object"),null;Qe(e,Ei,"risk",t);for(let d of Ei)(!(d in e)||e[d]==null)&&E(t,`risk.${d}`,"required field is missing");let n={},o=e.maxLeverage;!Z(o)||o<=0||o>50?E(t,"risk.maxLeverage","must be a number > 0 and <= 50"):n.maxLeverage=o;let s=e.maxNotionalUsd;!Z(s)||s<=0?E(t,"risk.maxNotionalUsd","must be a number > 0"):n.maxNotionalUsd=s;let a=e.positionSizePct;!Z(a)||a<=0||a>100?E(t,"risk.positionSizePct","must be a number > 0 and <= 100"):n.positionSizePct=a;let i=e.stopLossPct;!Z(i)||i<=0||i>100?E(t,"risk.stopLossPct","must be a number > 0 and <= 100"):n.stopLossPct=i;let c=e.takeProfitPct;!Z(c)||c<=0||c>1e3?E(t,"risk.takeProfitPct","must be a number > 0 and <= 1000"):n.takeProfitPct=c;let u=e.cooldownBars;!Number.isInteger(u)||u<0||u>1e5?E(t,"risk.cooldownBars","must be an integer >= 0 and <= 100000"):n.cooldownBars=u;let p=e.maxDailyLossPct;!Z(p)||p<=0||p>100?E(t,"risk.maxDailyLossPct","must be a number > 0 and <= 100"):n.maxDailyLossPct=p;let l=e.expiresAt;return!Number.isInteger(l)||l<=0?E(t,"risk.expiresAt","must be an integer epoch milliseconds > 0"):(r.nowMs!==void 0&&(Number.isInteger(r.nowMs)?l<=r.nowMs&&E(t,"risk.expiresAt","must be strictly greater than nowMs"):E(t,"nowMs","must be an integer epoch milliseconds")),n.expiresAt=l),n}function mo(e,t={}){let r=[];if(!ye(e))return E(r,"","strategy must be a plain object"),{ok:!1,errors:r,strategy:null};Qe(e,xi,"",r);for(let l of xi)(!(l in e)||e[l]==null)&&E(r,l,"required field is missing");e.version!==ao&&E(r,"version",`must be ${ao}`),(typeof e.id!="string"||!Oi.test(e.id))&&E(r,"id","must match /^[a-z0-9][a-z0-9._-]{0,63}$/"),(typeof e.name!="string"||e.name.length===0||e.name.length>Ii)&&E(r,"name",`must be a non-empty string max ${Ii}`);let n=oo(e.venue);n||E(r,"venue",`unknown strategy venue "${String(e.venue)}"`);let o=null;if(!n)ye(e.market)||E(r,"market","must be a plain object");else{let l=n.validateMarket(e.market);if(!l||typeof l.ok!="boolean"||!Array.isArray(l.errors))E(r,"market",`venue ${n.id} returned an invalid market validation result`);else if(l.ok)o=l.market;else for(let d of l.errors)E(r,d.path,d.message)}let s=Up(e.parameters,r),a=null,i=new Map;if(!Array.isArray(e.nodes))E(r,"nodes","must be an array");else if(e.nodes.length>vi)E(r,"nodes",`too many nodes (max ${vi})`);else{a=[];for(let l=0;l<e.nodes.length;l++){let d=Dp(e.nodes[l],l,s||{},r);d&&(typeof d.id=="string"&&Ti.test(d.id)&&(i.has(d.id)?E(r,`nodes.${l}.id`,`duplicate node id "${d.id}"`):i.set(d.id,d)),a.push(d))}for(let l=0;l<a.length;l++){let d=a[l],f=`nodes.${l}`;for(let h of Cr(d))i.has(h)||E(r,f,`unknown node ref "${h}"`);if(d.type==="indicator"||d.type==="compare"||d.type==="cross")for(let h of Cr(d)){let y=i.get(h);y&&co.has(y.type)&&E(r,f,`node ref "${h}" must be numeric`)}if(d.type==="logic")for(let h of Cr(d)){let y=i.get(h);y&&!co.has(y.type)&&E(r,f,`node ref "${h}" must be boolean`)}}Bp(i)&&E(r,"nodes","graph contains a cycle")}let c=null;if(!ye(e.rules))E(r,"rules","must be a plain object");else{Qe(e.rules,uo,"rules",r);for(let l of uo)l in e.rules||E(r,`rules.${l}`,"required field is missing");c={};for(let l of uo){let d=e.rules[l];if(d===null){c[l]=null;continue}if(typeof d!="string"||!d){E(r,`rules.${l}`,"must be a node id or null"),c[l]=d;continue}if(!i.has(d)){E(r,`rules.${l}`,`unknown node ref "${d}"`),c[l]=d;continue}let f=i.get(d);co.has(f.type)||E(r,`rules.${l}`,`rule must reference a boolean node, not ${f.type}`),c[l]=d}}let u=Lp(e.risk,r,t);if(r.length)return{ok:!1,errors:r,strategy:null};let p=po({version:ao,id:e.id,name:e.name,venue:n.id,market:o,parameters:s,nodes:a,rules:c,risk:u});return{ok:!0,errors:[],strategy:p}}function ue(e,t={}){let r=mo(e,t);if(!r.ok)throw new kt(r.errors);return r.strategy}function Fp(e){let t=ue(e);return JSON.stringify(fo(t))}function xt(e){let t=Fp(e);return _p("sha256").update(t,"utf8").digest("hex")}function Jt(e,t){if(!ye(e))throw new kt([{path:"",message:"strategy must be a plain object"}]);if(!ye(t))throw new kt([{path:"overrides",message:"must be a plain object"}]);let r=ue(e),n={};for(let[s,a]of Object.entries(r.parameters))n[s]={value:a.value,min:a.min,max:a.max,step:a.step};let o=[];for(let[s,a]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(n,s)){E(o,s,`unknown parameter "${s}"`);continue}let i=n[s];if(!Z(a)){E(o,s,"override must be a finite number");continue}if(!Ri(a,i.min,i.max,i.step)){E(o,s,"override must lie on the declared min/max/step grid");continue}n[s]={...i,value:a}}if(o.length)throw new kt(o);return ue({version:r.version,id:r.id,name:r.name,venue:r.venue,market:{coin:r.market.coin,interval:r.market.interval},parameters:n,nodes:r.nodes.map(s=>{let a={...s};return Array.isArray(s.inputs)&&(a.inputs=[...s.inputs]),a}),rules:{...r.rules},risk:{...r.risk}})}var ao,Oi,Ti,Cp,Op,Tp,Rp,Np,$p,Pp,co,xi,Si,uo,Ei,qp,ki,Ai,vi,Ii,kt,ot=w(()=>{io();ao=1,Oi=/^[a-z0-9][a-z0-9._-]{0,63}$/,Ti=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Cp=new Set(["open","high","low","close","volume","fundingRate","openInterest"]),Op=new Set(["sma","ema","rsi","macd","bollinger","atr"]),Tp=new Set(["gt","gte","lt","lte","eq"]),Rp=new Set(["and","or","not"]),Np=new Set(["above","below"]),$p=new Set(["line","signal","histogram"]),Pp=new Set(["upper","middle","lower"]),co=new Set(["compare","logic","cross"]),xi=new Set(["version","id","name","venue","market","parameters","nodes","rules","risk"]),Si=new Set(["value","min","max","step"]),uo=new Set(["entryLong","entryShort","exitLong","exitShort"]),Ei=new Set(["maxLeverage","maxNotionalUsd","positionSizePct","stopLossPct","takeProfitPct","cooldownBars","maxDailyLossPct","expiresAt"]),qp=new Set(["id","type"]),ki={input:new Set(["id","type","field"]),constant:new Set(["id","type","value"]),indicator:new Set(["id","type","indicator","input","period","fastPeriod","slowPeriod","signalPeriod","stdDev","output"]),compare:new Set(["id","type","op","left","right"]),logic:new Set(["id","type","op","inputs"]),cross:new Set(["id","type","direction","left","right"])},Ai=16,vi=128,Ii=100,kt=class extends Error{constructor(t){let r=t.map(n=>`${n.path}: ${n.message}`);super(`invalid strategy (${t.length} error${t.length===1?"":"s"}): ${r.join("; ")}`),this.name="StrategyValidationError",this.errors=t}}});function Zt(e){if(!Array.isArray(e))throw new TypeError("values must be an array");for(let t=0;t<e.length;t++){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))throw new TypeError(`values[${t}] must be a finite number`)}}function Ge(e){if(!Number.isInteger(e)||e<=0)throw new TypeError("period must be a positive integer")}function Mp(e){if(!Array.isArray(e))throw new TypeError("bars must be an array");for(let t=0;t<e.length;t++){let r=e[t];if(r==null||typeof r!="object")throw new TypeError(`bars[${t}] must be an object`);for(let n of["o","h","l","c"]){let o=r[n];if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`bars[${t}].${n} must be a finite number`)}if(r.h<r.l)throw new TypeError(`bars[${t}] high must be >= low`)}}function $i(e,t){Zt(e),Ge(t);let r=new Array(e.length).fill(null);if(e.length<t)return r;let n=0;for(let o=0;o<e.length;o++)n+=e[o],o>=t&&(n-=e[o-t]),o>=t-1&&(r[o]=n/t);return r}function Or(e,t){Zt(e),Ge(t);let r=new Array(e.length).fill(null);if(e.length<t)return r;let n=0;for(let a=0;a<t;a++)n+=e[a];let o=n/t;r[t-1]=o;let s=2/(t+1);for(let a=t;a<e.length;a++)o=s*e[a]+(1-s)*o,r[a]=o;return r}function Pi(e,t){Zt(e),Ge(t);let r=new Array(e.length).fill(null);if(e.length<=t)return r;let n=0,o=0;for(let i=1;i<=t;i++){let c=e[i]-e[i-1];c>=0?n+=c:o-=c}let s=n/t,a=o/t;r[t]=Ni(s,a);for(let i=t+1;i<e.length;i++){let c=e[i]-e[i-1],u=c>0?c:0,p=c<0?-c:0;s=(s*(t-1)+u)/t,a=(a*(t-1)+p)/t,r[i]=Ni(s,a)}return r}function Ni(e,t){return e===0&&t===0?50:t===0?100:e===0?0:100-100/(1+e/t)}function qi(e,t={}){Zt(e);let r=t.fastPeriod,n=t.slowPeriod,o=t.signalPeriod;if(Ge(r),Ge(n),Ge(o),r>=n)throw new TypeError("fastPeriod must be < slowPeriod");let s=Or(e,r),a=Or(e,n),i=new Array(e.length).fill(null);for(let l=0;l<e.length;l++)s[l]!=null&&a[l]!=null&&(i[l]=s[l]-a[l]);let c=new Array(e.length).fill(null),u=new Array(e.length).fill(null),p=[];for(let l=0;l<i.length;l++)i[l]!=null&&p.push(l);if(p.length>=o){let l=0;for(let y=0;y<o;y++)l+=i[p[y]];let d=l/o,f=p[o-1];c[f]=d,u[f]=i[f]-d;let h=2/(o+1);for(let y=o;y<p.length;y++){let g=p[y];d=h*i[g]+(1-h)*d,c[g]=d,u[g]=i[g]-d}}return{line:i,signal:c,histogram:u}}function Bi(e,t={}){Zt(e);let r=t.period,n=t.stdDev;if(Ge(r),typeof n!="number"||!Number.isFinite(n)||n<=0)throw new TypeError("stdDev must be a finite number > 0");let o=new Array(e.length).fill(null),s=new Array(e.length).fill(null),a=new Array(e.length).fill(null);if(e.length<r)return{upper:s,middle:o,lower:a};let i=0,c=0;for(let u=0;u<e.length;u++){let p=e[u];if(i+=p,c+=p*p,u>=r){let l=e[u-r];i-=l,c-=l*l}if(u>=r-1){let l=i/r,d=c/r-l*l;d<0&&d>-1e-12&&(d=0);let f=Math.sqrt(d);o[u]=l,s[u]=l+n*f,a[u]=l-n*f}}return{upper:s,middle:o,lower:a}}function Ui(e,t){Mp(e),Ge(t);let r=new Array(e.length).fill(null);if(e.length<t)return r;let n=new Array(e.length);for(let a=0;a<e.length;a++){let i=e[a];if(a===0)n[a]=i.h-i.l;else{let c=e[a-1].c;n[a]=Math.max(i.h-i.l,Math.abs(i.h-c),Math.abs(i.l-c))}}let o=0;for(let a=0;a<t;a++)o+=n[a];let s=o/t;r[t-1]=s;for(let a=t;a<e.length;a++)s=(s*(t-1)+n[a])/t,r[a]=s;return r}var Di=w(()=>{});import{createHash as jp}from"node:crypto";var ho,Hp,zp,Vp,Li,Fi=w(()=>{ho=2,Hp="93f9c998260e73756c13871dc1a84dd6cdb26ec6113bd1941f023519939db440",zp="68f5b412a9975f04024cf9b9b6209b4bccedd52f176e95f34f786b3f53479c6a",Vp="f197a38ff1c0f4ebe13326db8cbb8167ea3dd5d62e6033fe97c2fee8d23d96b5",Li=jp("sha256").update(JSON.stringify({version:ho,compilerSourceHash:Hp,indicatorsSourceHash:zp,schemaSourceHash:Vp})).digest("hex")});function Se(e){return typeof e=="number"&&Number.isFinite(e)}function Qp(e){let t=new Map(e.map(i=>[i.id,i])),r=i=>{switch(i.type){case"indicator":return i.input?[i.input]:[];case"compare":case"cross":return[i.left,i.right];case"logic":return[...i.inputs];default:return[]}},n=new Map,o=new Map;for(let i of e)n.set(i.id,0),o.set(i.id,[]);for(let i of e)for(let c of r(i))t.has(c)&&(o.get(c).push(i.id),n.set(i.id,n.get(i.id)+1));let s=[];for(let[i,c]of n)c===0&&s.push(i);let a=[];for(;s.length;){let i=s.shift();a.push(i);for(let c of o.get(i))n.set(c,n.get(c)-1),n.get(c)===0&&s.push(c)}if(a.length!==e.length)throw new Error("strategy graph is cyclic");return a}function At(e,t){return e!=null&&typeof e=="object"&&"param"in e?t[e.param].value:e}function Gp(e,t,r){if(!Array.isArray(e)||e.length===0)throw new TypeError("bars must be a non-empty array");if(!Number.isInteger(t)||t<0||t>=e.length)throw new RangeError("index out of range");let n=null;for(let o=0;o<=t;o++){let s=e[o];if(s==null||typeof s!="object"||Array.isArray(s))throw new TypeError(`bars[${o}] must be an object`);let{t:a,o:i,h:c,l:u,c:p,v:l}=s;if(!Se(a)&&(typeof a=="number"&&Number.isFinite(a)),!Number.isFinite(a))throw new TypeError(`bars[${o}].t must be finite`);for(let[d,f]of[["o",i],["h",c],["l",u],["c",p],["v",l]])if(!Se(f))throw new TypeError(`bars[${o}].${d} must be a finite number`);for(let[d,f]of[["o",i],["h",c],["l",u],["c",p]])if(!(f>0))throw new TypeError(`bars[${o}].${d} price must be positive`);if(l<0)throw new TypeError(`bars[${o}].v volume must be non-negative`);if(c<Math.max(i,p,u))throw new TypeError(`bars[${o}] high must be >= max(open, close, low)`);if(u>Math.min(i,p,c))throw new TypeError(`bars[${o}] low must be <= min(open, close, high)`);if(n!=null){if(!(a>n))throw new TypeError("bars t must be strictly increasing");if(a-n!==Wp[r])throw new TypeError(`bars t must match ${r} cadence`)}if(n=a,"fundingRate"in s&&s.fundingRate!=null&&!Se(s.fundingRate))throw new TypeError(`bars[${o}].fundingRate must be finite when present`);if("openInterest"in s&&s.openInterest!=null){if(!Se(s.openInterest))throw new TypeError(`bars[${o}].openInterest must be finite when present`);if(s.openInterest<0)throw new TypeError(`bars[${o}].openInterest must be non-negative`)}}}function at(e,t,r,n,o,s){if(s.has(e))return s.get(e);let a=t.get(e),i;switch(a.type){case"input":{let c=Kp[a.field];i=new Array(o+1);for(let u=0;u<=o;u++){let p=n[u][c];i[u]=p===void 0?null:p}break}case"constant":{let c=At(a.value,r);i=new Array(o+1).fill(c);break}case"indicator":{let c=a.period!=null?At(a.period,r):void 0;if(a.indicator==="atr"){let l=[];for(let d=0;d<=o;d++){let f=n[d];l.push({o:f.o,h:f.h,l:f.l,c:f.c})}i=Ui(l,c);break}let p=at(a.input,t,r,n,o,s).map((l,d)=>{if(l==null||!Se(l))throw new TypeError(`indicator input ${a.input} has non-finite value at ${d}`);return l});if(a.indicator==="sma")i=$i(p,c);else if(a.indicator==="ema")i=Or(p,c);else if(a.indicator==="rsi")i=Pi(p,c);else if(a.indicator==="macd")i=qi(p,{fastPeriod:At(a.fastPeriod,r),slowPeriod:At(a.slowPeriod,r),signalPeriod:At(a.signalPeriod,r)})[a.output];else if(a.indicator==="bollinger")i=Bi(p,{period:c,stdDev:At(a.stdDev,r)})[a.output];else throw new Error(`unsupported indicator ${a.indicator}`);break}case"compare":{let c=at(a.left,t,r,n,o,s),u=at(a.right,t,r,n,o,s);i=new Array(o+1);for(let p=0;p<=o;p++){let l=c[p],d=u[p];if(l==null||d==null||!Se(l)||!Se(d)){i[p]=!1;continue}switch(a.op){case"gt":i[p]=l>d;break;case"gte":i[p]=l>=d;break;case"lt":i[p]=l<d;break;case"lte":i[p]=l<=d;break;case"eq":i[p]=l===d;break;default:i[p]=!1}}break}case"logic":{let c=a.inputs.map(u=>at(u,t,r,n,o,s));i=new Array(o+1);for(let u=0;u<=o;u++)if(a.op==="not"){let p=c[0][u];i[u]=p===!0?!1:p===!1}else if(a.op==="and"){let p=!0;for(let l of c)if(l[u]!==!0){p=!1;break}i[u]=p}else if(a.op==="or"){let p=!1;for(let l of c)if(l[u]===!0){p=!0;break}i[u]=p}else i[u]=!1;break}case"cross":{let c=at(a.left,t,r,n,o,s),u=at(a.right,t,r,n,o,s);i=new Array(o+1),i[0]=!1;for(let p=1;p<=o;p++){let l=c[p-1],d=u[p-1],f=c[p],h=u[p];if(l==null||d==null||f==null||h==null||!Se(l)||!Se(d)||!Se(f)||!Se(h)){i[p]=!1;continue}a.direction==="above"?i[p]=l<=d&&f>h:i[p]=l>=d&&f<h}break}default:throw new Error(`unknown node type ${a.type}`)}return s.set(e,i),i}function le(e,t={}){let r=ue(e);t&&Object.keys(t).length&&(r=Jt(r,t));let n=new Map(r.nodes.map(f=>[f.id,f])),o=Object.freeze(Qp(r.nodes)),s=r.parameters,a=new Set(r.nodes.filter(f=>f.type==="input").map(f=>f.field));if(r.nodes.some(f=>f.type==="indicator"&&f.indicator==="atr"))for(let f of["open","high","low","close"])a.add(f);let i=Object.freeze([...a].sort()),c=xt(r);function u(f,h){let y={};for(let b of o){let S=f.get(b);y[b]=S[h]}let g=b=>b!=null&&y[b]===!0;return{values:y,signals:{entryLong:g(r.rules.entryLong),entryShort:g(r.rules.entryShort),exitLong:g(r.rules.exitLong),exitShort:g(r.rules.exitShort)}}}function p(f,h){Gp(f,h,r.market.interval);let y=new Map;for(let g of o)at(g,n,s,f,h,y);return y}function l(f,h){return u(p(f,h),h)}function d(f){if(!Array.isArray(f)||f.length===0)throw new TypeError("bars must be a non-empty array");let h=f.length-1,y=p(f,h);return Object.freeze(f.map((g,b)=>Object.freeze(u(y,b))))}return Object.freeze({strategy:r,strategyHash:c,compilerVersion:Yt,compilerHash:st,requiredSeries:i,nodeOrder:o,evaluate:l,evaluateAll:d})}var Yt,st,Kp,Wp,it=w(()=>{ot();Di();Fi();Yt=ho,st=Li,Kp=Object.freeze({open:"o",high:"h",low:"l",close:"c",volume:"v",fundingRate:"fundingRate",openInterest:"openInterest"}),Wp=Object.freeze({"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"8h":288e5,"12h":432e5,"1d":864e5})});import{createHash as Yp}from"node:crypto";function Jp(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Pe(e){return typeof e=="number"&&Number.isFinite(e)}function go(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)go(t);return Object.freeze(e)}for(let t of Object.keys(e))go(e[t]);return Object.freeze(e)}function Tr(e){if(Array.isArray(e))return e.map(Tr);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Tr(e[r]);return t}return e}function yo(e,t="result"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`non-finite backtest result at ${t}`);return}if(!(e==null||typeof e!="object")){if(Array.isArray(e)){e.forEach((r,n)=>yo(r,`${t}[${n}]`));return}for(let[r,n]of Object.entries(e))yo(n,`${t}.${r}`)}}function ji(e){if(!Array.isArray(e)||e.length===0)throw new TypeError("bars must be a non-empty array");let t=null;for(let r=0;r<e.length;r++){let n=e[r];if(n==null||typeof n!="object"||Array.isArray(n))throw new TypeError(`bars[${r}] must be an object`);let{t:o,o:s,h:a,l:i,c,v:u}=n;if(!Pe(o))throw new TypeError(`bars[${r}].t must be finite`);for(let[p,l]of[["o",s],["h",a],["l",i],["c",c],["v",u]])if(!Pe(l))throw new TypeError(`bars[${r}].${p} must be a finite number`);for(let[p,l]of[["o",s],["h",a],["l",i],["c",c]])if(!(l>0))throw new TypeError(`bars[${r}].${p} price must be positive`);if(u<0)throw new TypeError(`bars[${r}].v volume must be non-negative`);if(a<Math.max(s,c,i))throw new TypeError(`bars[${r}] high must be >= max(open, close, low)`);if(i>Math.min(s,c,a))throw new TypeError(`bars[${r}] low must be <= min(open, close, high)`);if(t!=null&&!(o>t))throw new TypeError("bars t must be strictly increasing");if(t=o,"fundingRate"in n&&n.fundingRate!=null&&!Pe(n.fundingRate))throw new TypeError(`bars[${r}].fundingRate must be finite when present`);if("fundingPaymentRate"in n&&n.fundingPaymentRate!=null&&!Pe(n.fundingPaymentRate))throw new TypeError(`bars[${r}].fundingPaymentRate must be finite when present`);if("openInterest"in n&&n.openInterest!=null&&!Pe(n.openInterest))throw new TypeError(`bars[${r}].openInterest must be finite when present`)}}function Qt(e){if(!Array.isArray(e))throw new TypeError("bars must be an array");return e.length>0&&ji(e),Yp("sha256").update(JSON.stringify(Tr(e)),"utf8").digest("hex")}function Zp(e){if(e==null&&(e={}),!Jp(e))throw new TypeError("options must be a plain object");let t={...Xp},r=new Set(["initialEquityUsd","takerFeeBps","builderFeeBps","slippageBps","latencyBars","maxVolumeParticipationPct","nowMs"]);for(let n of Object.keys(e))if(!r.has(n))throw new TypeError(`unknown option "${n}"`);if("initialEquityUsd"in e){if(!Pe(e.initialEquityUsd)||e.initialEquityUsd<=0)throw new TypeError("initialEquityUsd must be a positive finite number");t.initialEquityUsd=e.initialEquityUsd}for(let n of["takerFeeBps","builderFeeBps","slippageBps"])if(n in e){let o=e[n];if(!Pe(o)||o<0)throw new TypeError(`${n} must be a finite number >= 0`);if(n==="slippageBps"?o>=1e4:o>1e4)throw new TypeError(`${n} exceeds its safe basis-point bound`);t[n]=o}if("latencyBars"in e){let n=e.latencyBars;if(!Number.isInteger(n)||n<1)throw new TypeError("latencyBars must be an integer >= 1");t.latencyBars=n}if("maxVolumeParticipationPct"in e){let n=e.maxVolumeParticipationPct;if(!Pe(n)||n<=0||n>100)throw new TypeError("maxVolumeParticipationPct must be in (0,100]");t.maxVolumeParticipationPct=n}if("nowMs"in e){if(!Number.isInteger(e.nowMs))throw new TypeError("nowMs must be an integer epoch milliseconds");t.nowMs=e.nowMs}return t}function Rr(e){return e/1e4}function ef(e,t,r){let n=Rr(r);return t==="long"?e*(1+n):e*(1-n)}function tf(e,t,r){let n=Rr(r);return t==="long"?e*(1-n):e*(1+n)}function Mi(e,t,r){let n=Math.abs(e)*Rr(t),o=Math.abs(e)*Rr(r);return{taker:n,builder:o,total:n+o}}function rf(e,t){let r=e*(t.positionSizePct/100)*t.maxLeverage;return Math.min(r,t.maxNotionalUsd)}function nf(e,t,r){let n=r/100;return t==="long"?e*(1-n):e*(1+n)}function of(e,t,r){let n=r/100;return t==="long"?e*(1+n):e*(1-n)}function sf(e,t,r,n){if(!(r>0))return t==="long"?0:Number.POSITIVE_INFINITY;let o=Math.min(.99,1/(2*r)+n/1e4);return t==="long"?e*(1-1/r)/(1-o):e*(1+1/r)/(1+o)}function af(e,t,r){return t==="long"?e.l<=r:e.h>=r}function cf(e,t,r){return t==="long"?e.h>=r:e.l<=r}function uf(e,t,r){return t==="long"?e.l<=r:e.h>=r}function er(e,t){for(let r of e.requiredSeries)if(["fundingRate","openInterest"].includes(r)&&!t.every(n=>Pe(n?.[r])))throw new Error(`strategy required series is absent: ${r}`)}function lf(e){if(e.length<3)return 0;let t=[];for(let a=1;a<e.length;a++){let i=e[a-1].equity,c=e[a].equity;i>0&&t.push((c-i)/i)}if(t.length<2)return 0;let r=0;for(let a of t)r+=a;let n=r/t.length,o=0;for(let a of t)o+=(a-n)**2;let s=Math.sqrt(o/(t.length-1));return s>0?n/s:0}function df(e){let t=-1/0,r=0;for(let n of e){let o=n.equity;if(o>t&&(t=o),t>0){let s=(t-o)/t*100;s>r&&(r=s)}}return r}function We(e,t,r={}){let n=Zp(r);ji(t);let o=Qt(t);n.nowMs!==void 0&&ue(e,{nowMs:n.nowMs});let s=le(e);if(er(s,t),n.nowMs!==void 0&&s.strategy.risk.expiresAt<=n.nowMs)throw new Error("strategy is expired: risk.expiresAt must be strictly greater than nowMs");let a=s.strategy.risk,i=s.evaluateAll(t),c=n.latencyBars,u=n.slippageBps,p=n.takerFeeBps,l=n.builderFeeBps,d=n.initialEquityUsd,f=0,h=0,y=0,g=0,b=0,S=[],I=[],A=[],O=[],_=[],m=null,T=0,j=null,se=d,Te=!1,x=0,N=0,L=[],K=new Array(t.length).fill(0);function W(k){L.push(k)}function B(k){let q=t[k].v*(n.maxVolumeParticipationPct/100);return Math.max(0,q-K[k])}function H(k){if(!m)return d;let q=m.side==="long"?(k-m.entryPrice)*m.qty:(m.entryPrice-k)*m.qty;return d+q}function ie(k,q,C){let Y=C.o,U=rf(d,a);if(!(U>0)||!(Y>0))return;let X=ef(Y,q,u),V=U/X,ne=B(k),Ht=X*ne;if(V>ne){A.push({kind:"entry",barIndex:k,time:C.t,side:q,requestedNotionalUsd:U,maxFillNotionalUsd:Ht,reason:"volume_participation"});return}K[k]+=V;let Ne=Math.abs(X-Y)*V,Le=Mi(U,p,l);d-=Le.total,f+=Le.taker,h+=Le.builder,g+=Ne,b+=U,m={lifecycleEpoch:++N,side:q,entryBarIndex:k,entryReferencePrice:Y,entryPrice:X,qty:V,notionalUsd:U,stop:nf(X,q,a.stopLossPct),take:of(X,q,a.takeProfitPct),liq:sf(X,q,a.maxLeverage,p+l),entryFees:Le.taker,entryBuilderFees:Le.builder,entrySlippageUsd:Ne,fundingAccrued:0}}function re(k,q,C,Y){if(!m)return!1;let U=m.side,X=q,V=X;C!=="liquidation"&&Y&&(V=tf(X,U,u));let ne=m.qty,Ht=ne*V;if(C!=="liquidation"){let js=B(k),Od=V*js;if(ne>js)return A.push({kind:"exit",barIndex:k,time:t[k].t,side:U,requestedNotionalUsd:Ht,maxFillNotionalUsd:Od,reason:"volume_participation",triggerReason:C}),!1;K[k]+=ne}let Ne=Mi(Ht,p,l),Le=C==="liquidation"?0:Math.abs(V-X)*ne,zt,Mn;U==="long"?(zt=(X-m.entryReferencePrice)*ne,Mn=(V-m.entryPrice)*ne):(zt=(m.entryReferencePrice-X)*ne,Mn=(m.entryPrice-V)*ne),d+=Mn,d-=Ne.total,f+=Ne.taker,h+=Ne.builder,g+=Le,b+=Ht;let Cd={side:U,entryBarIndex:m.entryBarIndex,entryTime:t[m.entryBarIndex].t,entryPrice:m.entryPrice,exitBarIndex:k,exitTime:t[k].t,exitPrice:V,exitReason:C,qty:ne,notionalUsd:m.notionalUsd,grossPnlUsd:zt,feesUsd:m.entryFees+Ne.taker,builderFeesUsd:m.entryBuilderFees+Ne.builder,fundingUsd:m.fundingAccrued,slippageUsd:m.entrySlippageUsd+Le,netPnlUsd:zt-(m.entryFees+Ne.taker+m.entryBuilderFees+Ne.builder)-m.fundingAccrued-(m.entrySlippageUsd+Le)};return S.push(Cd),C==="liquidation"&&I.push({barIndex:k,time:t[k].t,side:U,price:V,tradeIndex:S.length-1}),m=null,N+=1,x=k+1+(a.cooldownBars||0),!0}function Re(k,q,C,Y){let U=k+1;if(U>=t.length)return;L.some(V=>V.kind==="exit"&&V.side===q&&V.fillBar===U&&V.epoch===Y)||W({kind:"exit",side:q,signalBar:k,fillBar:U,reason:C,epoch:Y})}function Er(k){let q=L.filter(C=>C.fillBar===k);for(let C=L.length-1;C>=0;C--)L[C].fillBar===k&&L.splice(C,1);q.sort((C,Y)=>{let U=X=>X.kind==="exit"?0:1;return U(C)-U(Y)});for(let C of q)if(C.kind==="exit"){if(!m||m.side!==C.side||m.lifecycleEpoch!==C.epoch)continue;let Y=C.reason||"rule";re(k,t[k].o,Y,!0)||Re(k,C.side,Y,C.epoch)}else if(C.kind==="entry"){if(m||C.epoch!==N||k<x)continue;ie(k,C.side,t[k])}}function kr(k){if(!m)return;let q=t[k],C=q.fundingPaymentRate;if(C==null||!Pe(C)||C===0)return;let Y=Math.abs(m.qty*q.c),U=C*Y;m.side==="long"?(d-=U,m.fundingAccrued+=U,y+=U):(d+=U,m.fundingAccrued-=U,y-=U)}function Ar(k){if(!m)return;let q=t[k].o;(m.side==="long"?q<=m.liq:q>=m.liq)&&re(k,q,"liquidation",!1)}function Us(k){if(!m)return;let q=t[k],C=m.side,Y=uf(q,C,m.liq),U=af(q,C,m.stop),X=cf(q,C,m.take),V=ne=>C==="long"?Math.min(ne,q.o):Math.max(ne,q.o);if(Y){re(k,V(m.liq),"liquidation",!1);return}if(U&&X){re(k,V(m.stop),"stop_loss",!0)||Re(k,C,"stop_loss",m.lifecycleEpoch);return}if(U){re(k,V(m.stop),"stop_loss",!0)||Re(k,C,"stop_loss",m.lifecycleEpoch);return}X&&(re(k,m.take,"take_profit",!0)||Re(k,C,"take_profit",m.lifecycleEpoch))}for(let k=0;k<t.length;k++){let q=Math.floor(t[k].t/864e5);q!==j&&(j=q,se=H(t[k].o),Te=!1),Ar(k),Er(k),Us(k),kr(k),!Te&&H(t[k].c)<=se*(1-a.maxDailyLossPct/100)&&(Te=!0,O.push({type:"daily_loss_limit",barIndex:k,time:t[k].t,message:"daily loss limit reached; new entries blocked for UTC day"}));let C=i[k].signals,Y=k+c;if(m)(m.side==="long"&&C.exitLong===!0||m.side==="short"&&C.exitShort===!0)&&Y<t.length&&(L.some(ne=>ne.kind==="exit"&&ne.side===m.side&&ne.fillBar===Y&&ne.epoch===m.lifecycleEpoch)||W({kind:"exit",side:m.side,signalBar:k,fillBar:Y,reason:"rule",epoch:m.lifecycleEpoch}));else{let X=C.entryLong===!0,V=C.entryShort===!0;X&&V?O.push({type:"conflicting_entry_signals",barIndex:k,time:t[k].t,message:"conflicting entry signals; no position opened"}):!Te&&(X||V)&&Y<t.length&&k>=x&&W({kind:"entry",side:X?"long":"short",signalBar:k,fillBar:Y,epoch:N})}let U=d;m&&(T+=1,U=H(t[k].c)),_.push({barIndex:k,time:t[k].t,equity:U,positionSide:m?m.side:null})}let Ds=null;if(m){let k=t.length-1;if(re(k,t[k].c,"end_of_data",!0))_[k]={barIndex:k,time:t[k].t,equity:d,positionSide:null};else{let C=H(t[k].c);Ds={side:m.side,entryBarIndex:m.entryBarIndex,entryTime:t[m.entryBarIndex].t,entryPrice:m.entryPrice,qty:m.qty,notionalUsd:m.notionalUsd,markPrice:t[k].c,markedEquityUsd:C},O.push({type:"open_position_at_end",barIndex:k,time:t[k].t,message:"end-of-data exit missed; position remains open and marked"})}}let Ls=(m?H(t[t.length-1].c):d)-n.initialEquityUsd,Ad=Ls/n.initialEquityUsd*100,Fs=0,Un=0,Dn=0;for(let k of S)k.netPnlUsd>0?(Fs+=1,Un+=k.netPnlUsd):k.netPnlUsd<0&&(Dn+=-k.netPnlUsd);let Ln=S.length,vd=Ln===0?0:Fs/Ln,Fn=0;Dn>0?Fn=Un/Dn:Un>0&&(Fn=1e12);let Id={netPnlUsd:Ls,netPnlPct:Ad,maxDrawdownPct:df(_),winRate:vd,profitFactor:Fn,tradeCount:Ln,sharpe:lf(_),turnoverUsd:b,exposurePct:T/t.length*100},_d={initialEquityUsd:n.initialEquityUsd,takerFeeBps:n.takerFeeBps,builderFeeBps:n.builderFeeBps,slippageBps:n.slippageBps,latencyBars:n.latencyBars,maxVolumeParticipationPct:n.maxVolumeParticipationPct},Ms={barsHash:o,strategyHash:s.strategyHash,compilerHash:st,compilerVersion:Yt,config:_d,trades:S,equityCurve:_,metrics:Id,costs:{feesUsd:f,builderFeesUsd:h,fundingUsd:y,slippageUsd:g},liquidations:I,missedFills:A,openPositionAtEnd:Ds,flags:O};return yo(Ms),go(Tr(Ms))}var Xp,_r=w(()=>{it();ot();Xp=Object.freeze({initialEquityUsd:1e4,takerFeeBps:3.5,builderFeeBps:2,slippageBps:2,latencyBars:1,maxVolumeParticipationPct:100})});import{createHash as pf}from"node:crypto";function xf(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function bo(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)bo(t);return Object.freeze(e)}for(let t of Object.keys(e))bo(e[t]);return Object.freeze(e)}function Sf(e){return String(e).trim().replace(/\s+/g," ")}function Ef(e){let t=e.match(/\b(long|short)\b/i);return t?t[1].toLowerCase():null}function kf(e){for(let r of mf)if(new RegExp(`\\b${r}\\b`,"i").test(e))return r;let t=e.match(/\b([A-Z][A-Z0-9]{1,11})\b/);return t?t[1]:null}function Af(e){let t=e.match(/\bon\s+(1m|3m|5m|15m|30m|1h|2h|4h|8h|12h|1d)\b/i);if(!t)return"15m";let r=t[1].toLowerCase();return ff.has(r)?r:null}function vf(e){let t={...gf},r=e.match(/stop\s*loss\s*(\d+(?:\.\d+)?)\s*%?/i);r&&(t.stopLossPct=Number(r[1]));let n=e.match(/take\s*profit\s*(\d+(?:\.\d+)?)\s*%?/i);n&&(t.takeProfitPct=Number(n[1]));let o=e.match(/leverage\s*(\d+(?:\.\d+)?)/i);o&&(t.maxLeverage=Number(o[1]));let s=e.match(/position\s*size\s*(\d+(?:\.\d+)?)\s*%?/i);s&&(t.positionSizePct=Number(s[1]));let a=e.match(/max\s*notional\s*(?:usd\s*)?\$?\s*(\d+(?:\.\d+)?)/i);return a&&(t.maxNotionalUsd=Number(a[1])),t}function If(e){return[/\bon\s+(?:1m|3m|5m|15m|30m|1h|2h|4h|8h|12h|1d)\b/gi,/\bstop\s*loss\s*\d+(?:\.\d+)?\s*%?/gi,/\btake\s*profit\s*\d+(?:\.\d+)?\s*%?/gi,/\bleverage\s*\d+(?:\.\d+)?/gi,/\bposition\s*size\s*\d+(?:\.\d+)?\s*%?/gi,/\bmax\s*notional\s*(?:usd\s*)?\$?\s*\d+(?:\.\d+)?/gi].some(r=>(e.match(r)??[]).length>1)}function _f(e){let t=pf("sha256").update(e,"utf8").digest("hex").slice(0,10),r=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40),o=`${r.length?r:"draft"}-${t}`.replace(/[^a-z0-9._-]/g,"").slice(0,64);return/^[a-z0-9]/.test(o)?o:`d${o}`.slice(0,64)}function Cf(e){let t=e.match(/\bema\s*(\d+)\s*cross(?:es)?\s*(above|below)\s*ema\s*(\d+)\b/i);if(!t)return null;let r=Number(t[1]),n=t[2].toLowerCase(),o=Number(t[3]);if(!(r>0)||!(o>0)||r===o)return null;let s=/\b(exit\s+on\s+reverse|reverse\s+exit)\b/i.test(e);return{kind:"ema_cross",fast:r,slow:o,direction:n,reverse:s}}function Of(e){let t=e.match(/\brsi\s*(\d+)\s*(above|below)\s*(-?\d+(?:\.\d+)?)/i);if(!t)return null;let r=Number(t[3]);return!Number.isFinite(r)||r<=0||r>=100?null:{kind:"rsi",period:Number(t[1]),op:t[2].toLowerCase(),threshold:r}}function Tf(e){let t=e.match(/\bfunding\s*rate\s*(above|below)\s*(-?\d+(?:\.\d+)?)(%?)(?=\s|,|$)/i);if(!t)return null;let r=Number(t[2]);return t[3]==="%"&&(r=r/100),{kind:"funding",op:t[1].toLowerCase(),threshold:r}}function Rf(e,t){let r=e.replace(/^(long|short)\s+[A-Z][A-Z0-9]{1,11}\s+when\s+/i,"");if(r===e)return!1;t.kind==="ema_cross"?r=r.replace(/^ema\s*\d+\s*cross(?:es)?\s*(?:above|below)\s*ema\s*\d+\b/i,""):t.kind==="rsi"?r=r.replace(/^rsi\s*\d+\s*(?:above|below)\s*\d+(?:\.\d+)?\b/i,""):r=r.replace(/^funding\s*rate\s*(?:above|below)\s*-?\d+(?:\.\d+)?%?(?=\s|,|$)/i,"");let n=[/(?:,\s*)?\bon\s+(?:1m|3m|5m|15m|30m|1h|2h|4h|8h|12h|1d)\b/gi,/(?:,\s*)?\bstop\s*loss\s*\d+(?:\.\d+)?\s*%?/gi,/(?:,\s*)?\btake\s*profit\s*\d+(?:\.\d+)?\s*%?/gi,/(?:,\s*)?\bleverage\s*\d+(?:\.\d+)?/gi,/(?:,\s*)?\bposition\s*size\s*\d+(?:\.\d+)?\s*%?/gi,/(?:,\s*)?\bmax\s*notional\s*(?:usd\s*)?\$?\s*\d+(?:\.\d+)?/gi];t.kind==="ema_cross"&&n.push(/(?:,\s*)?\b(?:exit\s+on\s+reverse|reverse\s+exit)\b/gi);for(let o of n)r=r.replace(o,"");return r.replace(/[\s,;]+/g,"")===""}function Hi(e){let t=Math.max(2,Math.floor(e/2));return{value:e,min:Math.max(2,e-t),max:Math.min(500,e+t),step:1}}function Nf({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:s,name:a,spec:i}){let c=[{id:"c",type:"input",field:"close"},{id:"emaLeft",type:"indicator",indicator:"ema",input:"c",period:{param:"ema_left_period"}},{id:"emaRight",type:"indicator",indicator:"ema",input:"c",period:{param:"ema_right_period"}},{id:"cross",type:"cross",direction:i.direction,left:"emaLeft",right:"emaRight"}],u={entryLong:null,entryShort:null,exitLong:null,exitShort:null};if(e==="long"?u.entryLong="cross":u.entryShort="cross",i.reverse){let p=i.direction==="above"?"below":"above";c.push({id:"crossRev",type:"cross",direction:p,left:"emaLeft",right:"emaRight"}),e==="long"?u.exitLong="crossRev":u.exitShort="crossRev"}return{version:1,id:s,name:a,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{ema_left_period:Hi(i.fast),ema_right_period:Hi(i.slow)},nodes:c,rules:u,risk:{...n,expiresAt:o}}}function $f({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:s,name:a,spec:i}){let c=[{id:"c",type:"input",field:"close"},{id:"rsi",type:"indicator",indicator:"rsi",input:"c",period:i.period},{id:"thr",type:"constant",value:i.threshold},{id:"sig",type:"compare",op:i.op==="above"?"gt":"lt",left:"rsi",right:"thr"}];return{version:1,id:s,name:a,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{},nodes:c,rules:{entryLong:e==="long"?"sig":null,entryShort:e==="short"?"sig":null,exitLong:null,exitShort:null},risk:{...n,expiresAt:o}}}function Pf({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:s,name:a,spec:i}){let c=[{id:"fr",type:"input",field:"fundingRate"},{id:"thr",type:"constant",value:i.threshold},{id:"sig",type:"compare",op:i.op==="above"?"gt":"lt",left:"fr",right:"thr"}];return{version:1,id:s,name:a,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{},nodes:c,rules:{entryLong:e==="long"?"sig":null,entryShort:e==="short"?"sig":null,exitLong:null,exitShort:null},risk:{...n,expiresAt:o}}}function zi(e,t={}){if(typeof e!="string")throw new ae("prompt must be a string");if(e.length>1e3)throw new ae("prompt length must be <= 1000");if(!xf(t))throw new ae("options must be a plain object");if(!Number.isInteger(t.nowMs))throw new ae("options.nowMs is required integer epoch ms");let r=t.nowMs,n=wf;if("expiresInMs"in t){if(!Number.isInteger(t.expiresInMs))throw new ae("expiresInMs must be an integer");if(n=t.expiresInMs,n<yf||n>bf)throw new ae("expiresInMs must be between 1h and 30d")}if(hf.test(e))throw new ae(`prompt appears to contain secrets and is rejected. ${vt}`);let o=Sf(e);if(!o)throw new ae(`empty prompt. ${vt}`);if(If(o))throw new ae(`duplicate interval or risk clause. ${vt}`);let s=Ef(o),a=kf(o),i=Af(o);if(!s||!a||!i)throw new ae(`could not parse side/coin/interval. ${vt}`);let c=vf(o);if(!(c.maxLeverage>0)||c.maxLeverage>50)throw new ae("leverage out of range");if(!(c.positionSizePct>0)||c.positionSizePct>100)throw new ae("position size out of range");let u=r+n,p=_f(o),l=`Draft ${a} ${s}`.slice(0,100),d=Cf(o),f=Of(o),h=Tf(o),y=[d,f,h].filter(Boolean);if(y.length!==1)throw new ae(`unsupported or ambiguous prompt. ${vt}`);if(!Rf(o,y[0]))throw new ae(`unsupported or ambiguous prompt. ${vt}`);let g,b=y[0],S={side:s,coin:a,interval:i,risk:c,expiresAt:u,id:p,name:l,spec:b};b.kind==="ema_cross"?g=Nf(S):b.kind==="rsi"?g=$f(S):g=Pf(S);let I=mo(g,{nowMs:r});if(!I.ok)throw new ae(`draft failed validation: ${I.errors.map(A=>A.message).join("; ")}`);return bo(ue(g,{nowMs:r}))}var ae,ff,mf,hf,vt,gf,yf,bf,wf,Vi=w(()=>{ot();ae=class extends Error{constructor(t){super(t),this.name="StrategyDraftError"}},ff=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),mf=new Set(["BTC","ETH","SOL","HYPE"]),hf=/\b(mnemonic|private\s*key|privkey|seed\s*phrase|seed\b|api[_-]?key|secret\s*key|wallet\s*key|passphrase)\b/i,vt="Supported grammar: (1) EMA cross: <long|short> <COIN> when EMA <n> crosses <above|below> EMA <m> [on <interval>] [, exit on reverse] [, risk knobs]; (2) RSI: <long|short> <COIN> when RSI <n> <above|below> <threshold> [on <interval>] [, risk knobs]; (3) funding: <long|short> <COIN> when funding rate <above|below> <decimal|percent%> [on <interval>] [, risk knobs]. Risk knobs: stop loss %, take profit %, leverage, position size %, max notional USD. Coins: BTC ETH SOL HYPE or uppercase token <=12 chars. Intervals: 1m 3m 5m 15m 30m 1h 2h 4h 8h 12h 1d.",gf=Object.freeze({maxLeverage:1,maxNotionalUsd:100,positionSizePct:5,stopLossPct:2,takeProfitPct:4,cooldownBars:1,maxDailyLossPct:3}),yf=36e5,bf=30*864e5,wf=864e5});import{createHash as qf}from"node:crypto";function Qi(e){let t=String(e).toLowerCase();return t==="holdout"||t==="test"||t==="oos"||t.includes("holdout")||t.includes("oos")?!0:t==="testbars"||t.endsWith("testbars")||t.startsWith("test")||t.endsWith("test")?!t.includes("backtest"):!1}function Gi(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function xo(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)xo(t);return Object.freeze(e)}for(let t of Object.keys(e))xo(e[t]);return Object.freeze(e)}function tr(e){if(Array.isArray(e))return e.map(tr);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=tr(e[r]);return t}return e}function Nr(e){return JSON.stringify(tr(e))}function Bf(e){let{min:t,max:r,step:n}=e;if(!(n>0)||t>r)return[];let o=[],s=Math.floor((r-t)/n+1e-9);for(let i=0;i<=s;i++){let c=t+i*n;if(c>r+1e-9)break;let u=Math.abs(c-Math.round(c))<1e-9?Math.round(c):Number(c.toPrecision(12));u<t-1e-9||u>r+1e-9||o.push(u)}if(o.length===0)return[];let a=o[o.length-1];if(Math.abs(a-r)>1e-9){let i=(r-t)/n;Math.abs(i-Math.round(i))<=1e-9&&o.push(r)}return o}function Uf(e,t){if(e.length===0)return[];let r=[{}];for(let n of e){let o=t[n],s=[];for(let a of r)for(let i of o)s.push({...a,[n]:i});r=s}return r.sort((n,o)=>{let s=Nr(n),a=Nr(o);return s<a?-1:s>a?1:0}),r}function wo(e,t,r,n,o){let s=0;if(e==="maxDrawdownPct"){if(s=t.maxDrawdownPct-n.maxDrawdownPct,s!==0)return s<0}else if(s=t[e]-n[e],s!==0)return s>0;let a=Nr(r),i=Nr(o);return a<i}function Yi(e,t,r={}){if(!Gi(r))throw new TypeError("options must be a plain object");for(let A of Object.keys(r))if(Qi(A))throw new TypeError(`options must not include holdout/test/oos key "${A}"`);let n=new Set(["maxTrials","objective","backtestOptions"]);for(let A of Object.keys(r))if(!n.has(A))throw new TypeError(`unknown option "${A}"`);let o=64;if("maxTrials"in r){let A=r.maxTrials;if(!Number.isInteger(A)||A<1||A>Ki)throw new TypeError(`maxTrials must be an integer 1..${Ki}`);o=A}let s=r.objective??"netPnlUsd";if(!Wi.has(s))throw new TypeError(`objective must be one of ${[...Wi].join("|")}`);let a=r.backtestOptions??{};if(!Gi(a))throw new TypeError("backtestOptions must be a plain object");for(let A of Object.keys(a))if(Qi(A))throw new TypeError(`backtestOptions must not include holdout/test/oos key "${A}"`);let i=ue(e),c=Object.keys(i.parameters).sort();if(c.length===0)throw new Error("optimizeStrategy requires at least one declared parameter");let u={},p=1;for(let A of c){let O=Bf(i.parameters[A]);if(O.length===0)throw new Error(`parameter "${A}" produces an empty grid`);u[A]=O,p*=O.length}let l=Uf(c,u);if(l.length===0)throw new Error("parameter grid is empty");let d=l.slice(0,o),f=[],h=null,y=null;for(let A of d){let O=Jt(i,A),_=We(O,t,a);y==null&&(y=_.config);let m={netPnlUsd:_.metrics.netPnlUsd,netPnlPct:_.metrics.netPnlPct,maxDrawdownPct:_.metrics.maxDrawdownPct,winRate:_.metrics.winRate,profitFactor:_.metrics.profitFactor,tradeCount:_.metrics.tradeCount,sharpe:_.metrics.sharpe,turnoverUsd:_.metrics.turnoverUsd},T={parameters:{...A},metrics:m};f.push(T),(!h||wo(s,m,A,h.metrics,h.parameters))&&(h=T)}f.sort((A,O)=>wo(s,A.metrics,A.parameters,O.metrics,O.parameters)?-1:wo(s,O.metrics,O.parameters,A.metrics,A.parameters)?1:0);let g={...h.parameters},b=Jt(i,g),S={strategyHash:xt(i),compilerHash:st,trainBarsHash:Qt(t),backtestConfig:y,objective:s,maxTrials:o,trialsRun:f.length,candidates:f,bestParameters:g,bestStrategy:b},I={id:qf("sha256").update(JSON.stringify(tr(S)),"utf8").digest("hex"),...S};return xo(tr(JSON.parse(JSON.stringify(I))))}var Ki,Wi,Xi=w(()=>{it();ot();_r();Ki=256,Wi=new Set(["netPnlUsd","profitFactor","sharpe","maxDrawdownPct"])});import Fe from"node:fs";import $r from"node:path";function Pr(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function qe(e){return e==null?e:JSON.parse(JSON.stringify(e))}function Lf(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function It(e,t="record"){if(Array.isArray(e)){e.forEach((r,n)=>It(r,`${t}[${n}]`));return}if(Pr(e))for(let[r,n]of Object.entries(e)){let o=Lf(r);if(Df.some(s=>o.includes(s)))throw new Error(`shadow-store: forbidden secret-like field at ${t}.${r}`);It(n,`${t}.${r}`)}}function Ff(e){if(typeof e!="string"||!e||!$r.isAbsolute(e))throw new Error("shadow-store: path must be an absolute path")}function Ji(e){let t;try{t=Fe.lstatSync(e)}catch(n){if(n&&n.code==="ENOENT")return;throw n}if(t.isSymbolicLink())throw new Error("shadow-store: store path must not be a symlink");if(!t.isFile())throw new Error("shadow-store: store path must be a regular file");if(t.mode&511&18)throw new Error("shadow-store: store file must not be group or world writable")}function Mf(){return{version:Eo,runners:[]}}function Zi(e,t){let r;try{r=JSON.parse(e)}catch{throw new Error("shadow-store: malformed JSON")}if(!Pr(r))throw new Error("shadow-store: malformed JSON root");if(r.version!==Eo)throw new Error(`shadow-store: unsupported version ${r.version}`);if(!Array.isArray(r.runners))throw new Error("shadow-store: runners must be an array");return It(r,$r.basename(t)),{version:Eo,runners:r.runners.map(n=>qe(n))}}function ea(e,t){It(t,"store");let r=$r.dirname(e);Fe.mkdirSync(r,{recursive:!0,mode:448});let n=$r.join(r,`.shadow-store.${process.pid}.${Date.now()}.tmp`),o=`${JSON.stringify(t)}
|
|
4
|
-
`;try{Fe.writeFileSync(n,o,{mode:384,flag:"wx"}),Fe.renameSync(n,e);try{Fe.chmodSync(e,384)}catch{}}catch(s){try{Fe.unlinkSync(n)}catch{}throw s}}function ta(e={}){let t=e.path;if(Ff(t),Ji(t),Fe.existsSync(t)?Zi(Fe.readFileSync(t,"utf8"),t):ea(t,Mf()),So.has(t))return So.get(t);let r=!1,n=[];function o(){if(r)return;let h=n.shift();if(h){r=!0;try{let y=h.fn();r=!1,h.resolve(y),o()}catch(y){r=!1,h.reject(y),o()}}}function s(h){if(!r&&n.length===0){r=!0;try{return h()}finally{r=!1,queueMicrotask(o)}}return new Promise((y,g)=>{n.push({fn:h,resolve:y,reject:g}),queueMicrotask(o)})}function a(){return Ji(t),Zi(Fe.readFileSync(t,"utf8"),t)}function i(h){ea(t,h)}function c(h){if(!Pr(h)||typeof h.id!="string"||!h.id)throw new Error("shadow-store: create requires record with string id");It(h,"record");let y=a();if(y.runners.some(b=>b.id===h.id))throw new Error(`shadow-store: runner id already exists: ${h.id}`);let g=qe(h);return y.runners.push(g),i(y),qe(g)}function u(h){let y=a().runners.find(g=>g.id===h);return y?qe(y):null}function p(){return a().runners.map(h=>qe(h))}function l(h,y){if(typeof y!="function")throw new Error("shadow-store: updater must be a function");let g=a(),b=g.runners.findIndex(A=>A.id===h);if(b<0)throw new Error(`shadow-store: runner not found: ${h}`);let S=qe(g.runners[b]),I=y(S);if(!Pr(I)||I.id!==h)throw new Error("shadow-store: updater must return record with same id");return It(I,"record"),g.runners[b]=qe(I),i(g),qe(g.runners[b])}function d(h){let y=a(),g=y.runners.findIndex(S=>S.id===h);if(g<0)throw new Error(`shadow-store: runner not found: ${h}`);let b=qe(y.runners[g]);return b.status!=="stopped"&&(b.status="stopped",y.runners[g]=b,i(y)),qe(y.runners[g])}let f={create(h){return s(()=>c(h))},get(h){return u(h)},list(){return p()},update(h,y){return s(()=>l(h,y))},stop(h){return s(()=>d(h))}};return So.set(t,f),f}var Eo,Df,So,ra=w(()=>{Eo=1,Df=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];So=new Map});import{createHash as vo}from"node:crypto";function ko(e){return e==null?e:JSON.parse(JSON.stringify(e))}function Ao(e){return Array.isArray(e)?e.map(Ao):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Ao(e[t])])):e}function oa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("shadow-runner: record must be an object");return vo("sha256").update(JSON.stringify(Ao(e))).digest("hex")}function jf(e,t,r,n,o){return vo("sha256").update(`${e}|${t}|${r}|${n}|${o}`).digest("hex")}function Hf(e,t,r,n){return vo("sha256").update(`shadow|${e}|${t}|${r}|${n??""}`).digest("hex")}function zf(e){return e==="entryLong"||e==="exitShort"?"buy":e==="entryShort"||e==="exitLong"?"sell":e}function na(e){return e==="entryLong"||e==="entryShort"}function Io({storePath:e,clock:t=Date.now}={}){if(typeof e!="string"||!e)throw new Error("shadow-runner: storePath required");let r=ta({path:e});function n({strategy:c,evidenceId:u=null}={}){let p=le(c),l=u==null?null:String(u),d=r.list().filter(b=>b.status==="running"&&b.strategyHash===p.strategyHash&&b.compilerHash===p.compilerHash&&b.evidenceId===l).sort((b,S)=>b.createdAt-S.createdAt||b.id.localeCompare(S.id))[0];if(d)return ko(d);let f=t(),h=Hf(f,p.strategyHash,p.compilerHash,l),y=r.get(h);if(y)return ko(y);let g={id:h,strategy:ko(p.strategy),strategyHash:p.strategyHash,compilerHash:p.compilerHash,evidenceId:l,status:"running",cursor:null,intendedOrders:[],fills:[],missedFills:[],markouts:[],createdAt:f,updatedAt:f,position:null,cooldownBarsRemaining:0,cooldownStartT:null,lastProcessedBarIndex:-1};return r.create(g)}function o(c){return r.get(c)}function s(){return r.list()}function a(c){return r.stop(c)}function i(c,u,{markoutHorizons:p=[1,4,12]}={}){if(!Array.isArray(u))throw new TypeError("shadow-runner: bars must be an array");return r.update(c,l=>{if(l.status!=="running")throw new Error("shadow-runner: runner is stopped");if(u.length===0)return l;let f=le(l.strategy).evaluateAll(u),h=new Map;for(let x=0;x<u.length;x++)h.set(u[x].t,x);let y=l.cursor,g=[];for(let x=0;x<u.length;x++){let N=u[x].t;(y==null||N>y)&&g.push(x)}if(g.length===0)return l;let b=new Map(l.intendedOrders.map(x=>[x.id,x])),S=new Set(l.fills.map(x=>x.orderId)),I=new Map(l.missedFills.map(x=>[x.orderId,x])),A=(x,N)=>`${x}|${N}`,O=new Map(l.markouts.map(x=>[A(x.orderId,x.horizon),x])),_=l.position?{...l.position}:null,m=Number.isInteger(l.cooldownBarsRemaining)?Math.max(0,l.cooldownBarsRemaining):0,T=Number.isFinite(l.cooldownStartT)?l.cooldownStartT:null;function j({action:x,signalBarT:N,signalIndex:L}){let K=zf(x),W=jf(l.id,l.strategyHash,N,K,x);if(b.has(W))return b.get(W);let B=L+1,H=B<u.length,ie={id:W,action:x,type:x,side:K,signalBarT:N,fillBarT:H?u[B].t:null,status:H?"open":"missed"};return b.set(W,ie),l.intendedOrders.push(ie),ie}function se(x,N,L){if(S.has(x.id))return;let K={orderId:x.id,action:na(x.action)?"entry":"exit",side:x.side,price:N.o,barT:N.t,signalBarT:x.signalBarT,barIndex:L};if(l.fills.push(K),S.add(x.id),x.status="filled",x.fillBarT=N.t,I.has(x.id)&&(I.delete(x.id),l.missedFills=l.missedFills.filter(W=>W.orderId!==x.id)),na(x.action)){_={side:x.action==="entryLong"?"long":"short",entryOrderId:x.id,entryBarT:N.t,entryPrice:N.o,entryBarIndex:L};for(let W of p){let B=A(x.id,W);if(O.has(B))continue;let H={orderId:x.id,horizon:W,entryBarT:N.t,entryPrice:N.o,side:_.side,status:"pending",close:null,barT:null};O.set(B,H),l.markouts.push(H)}}else _=null,m=Number(l.strategy?.risk?.cooldownBars)||0,T=N.t}function Te(x){if(S.has(x.id)||I.has(x.id))return;let N={orderId:x.id,action:x.action,side:x.side,signalBarT:x.signalBarT,status:"missed"};I.set(x.id,N),l.missedFills.push(N),x.status="missed"}for(let x of l.intendedOrders){if(x.status==="filled"||S.has(x.id))continue;let N=h.get(x.signalBarT);if(N==null)continue;let L=N+1;L<u.length&&(y==null||u[L].t>y)&&se(x,u[L],L)}for(let x of g){let N=u[x],L=f[x].signals,K=_,W=H=>{if(_||m>0&&(T==null||N.t>=T))return;let re=j({action:H,signalBarT:N.t,signalIndex:x}),Re=x+1;Re<u.length?se(re,u[Re],Re):Te(re)},B=H=>{if(!_||_.side==="long"&&H!=="exitLong"||_.side==="short"&&H!=="exitShort")return;let ie=j({action:H,signalBarT:N.t,signalIndex:x}),re=x+1;re<u.length?se(ie,u[re],re):Te(ie)};K?(L.exitLong&&B("exitLong"),L.exitShort&&B("exitShort")):L.entryLong&&L.entryShort||(L.entryLong&&W("entryLong"),L.entryShort&&W("entryShort")),m>0&&T!=null&&N.t>=T&&(m-=1,m===0&&(T=null)),l.cursor=N.t,l.lastProcessedBarIndex=x}for(let x of l.markouts){if(x.status!=="pending")continue;let N=l.fills.find(W=>W.orderId===x.orderId&&W.action==="entry");if(!N)continue;let L=h.get(N.barT);if(L==null)continue;let K=L+x.horizon;if(K<u.length){x.close=u[K].c,x.barT=u[K].t,x.status="filled";let W=x.entryPrice;x.markout=x.side==="long"?(x.close-W)/W:(W-x.close)/W}}return l.position=_,l.cooldownBarsRemaining=m,l.cooldownStartT=T,l.updatedAt=t(),l})}return{start:n,step:i,list:s,get:o,stop:a}}var sa=w(()=>{it();ra()});var ca={};z(ca,{runStrategyOperation:()=>Jf});import Vf from"node:os";import Kf from"node:path";function rr(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Qf(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Co(e){if(Array.isArray(e)){for(let t of e)Co(t);return}if(rr(e))for(let[t,r]of Object.entries(e)){if(Wf.some(n=>Qf(t).includes(n)))throw new Error(`strategy service: secret-like field "${t}" is forbidden`);Co(r)}}function Gf(e){if(!rr(e))throw new TypeError("strategy input must be a plain object");return Co(e),e}function Yf(e,t){let r=t.nowMs??e.nowMs??Date.now();if(!Number.isInteger(r))throw new TypeError("nowMs must be an integer epoch milliseconds");return r}async function _o(e,t,r,n){if(Array.isArray(t.bars))return t.bars;let o=so(e.venue),s=r.fetchBars??o.fetchBars;if(typeof s!="function")throw new Error(`strategy venue ${o.id} does not support history`);let a=await s({coin:e.market.coin,interval:e.market.interval,count:t.count??1500,endTime:t.endTime??n}),i=Array.isArray(a)?a:a?.bars;if(!Array.isArray(i))throw new Error("strategy history provider returned no bars");return i}function Oo(e,t){let r=e.backtestOptions??{};if(!rr(r))throw new TypeError("backtestOptions must be a plain object");return{...r,nowMs:t}}function ia(e,t,r,n,o={}){let s=e.evidenceOptions??{};if(!rr(s))throw new TypeError("evidenceOptions must be a plain object");return{...s,...o,strategy:t,bars:r,backtestOptions:Oo(e,n)}}function aa(){return Kf.join(Vf.homedir(),".oracle","strategy-shadow.json")}function Xf(e,t){return{perStrategyNotionalUsd:e.risk.maxNotionalUsd,maxLeverage:e.risk.maxLeverage,dailyLossCapUsd:e.risk.maxNotionalUsd*(e.risk.maxDailyLossPct/100),chainAllowlist:[e.venue],assetAllowlist:[e.market.coin],expiresAt:Math.min(e.risk.expiresAt,t+864e5),killSwitchRequired:!0}}async function Jf(e,t={},r={}){let n=Gf(t),o=Yf(n,r);if(e==="draft")return{strategy:zi(n.prompt,{nowMs:o})};if(e==="validate"){let s=le(n.strategy);if(s.strategy.risk.expiresAt<=o)throw new Error("strategy is expired");return{valid:!0,strategy:s.strategy,strategyHash:s.strategyHash,compilerHash:s.compilerHash,compilerVersion:s.compilerVersion,requiredSeries:s.requiredSeries}}if(e==="backtest"||e==="evidence"){let s=le(n.strategy),a=await _o(s.strategy,n,r,o);er(s,a);let i=Zn(ia(n,s.strategy,a,o));return e==="evidence"?i:{backtest:We(s.strategy,a,Oo(n,o)),evidence:i}}if(e==="optimize"){let s=le(n.strategy),a=await _o(s.strategy,n,r,o);er(s,a);let i=n.trainFraction,c=n.evidenceOptions?.trainFraction;if(i!=null&&c!=null&&i!==c)throw new TypeError("conflicting trainFraction controls are forbidden");let u=i??c??.7;if(typeof u!="number"||u<=0||u>=1)throw new TypeError("trainFraction must be in (0,1)");let p=a.slice(0,Math.floor(a.length*u)),l=n.options??{};if(!rr(l))throw new TypeError("options must be a plain object");let d=Yi(s.strategy,p,{...l,...n.maxTrials==null?{}:{maxTrials:n.maxTrials},backtestOptions:Oo(n,o)}),f=d.bestStrategy;return{strategy:f,optimization:d,evidence:Zn(ia(n,f,a,o,{trainFraction:u}))}}if(e==="shadow"){let s=Io({storePath:r.storePath??aa(),clock:()=>o}),a=n.action;if(a==="start")return await s.start({strategy:n.strategy,evidenceId:n.evidenceId??n.evidence?.id??null});if(a==="list")return await s.list();if(a==="get")return await s.get(n.id);if(a==="stop")return await s.stop(n.id);if(a==="step"){let i=await s.get(n.id);if(!i)throw new Error(`shadow runner not found: ${n.id}`);let c=await _o(i.strategy,n,r,o);return er(le(i.strategy),c),await s.step(n.id,c,n.stepOptions??{})}throw new Error(`unknown shadow action: ${a}`)}if(e==="prepare"){let s=le(n.strategy),a=so(s.strategy.venue);if(typeof n.shadowId!="string"||!n.shadowId)throw new Error("strategy prepare requires a matching shadow runner id");let c=await Io({storePath:r.storePath??aa(),clock:()=>o}).get(n.shadowId);if(!c)throw new Error("strategy prepare shadow runner not found");if(c.status!=="running")throw new Error("strategy prepare requires an active shadow runner");if(!Number.isFinite(c.cursor))throw new Error("strategy prepare requires a stepped shadow runner");if(c.strategyHash!==s.strategyHash||c.compilerHash!==s.compilerHash)throw new Error("strategy prepare shadow runner does not match strategy artifacts");if(c.evidenceId!==n.evidence?.id)throw new Error("strategy prepare shadow runner does not match evidence artifact");let u=n.caps??Xf(s.strategy,o);return a.prepareIntent({strategy:s.strategy,evidence:n.evidence,shadow:{id:c.id,stateHash:oa(c),status:c.status,cursor:c.cursor,updatedAt:c.updatedAt},caps:u,nowMs:o,env:r.env??process.env})}throw new Error(`unknown strategy operation: ${e}`)}var Wf,ua=w(()=>{_r();it();eo();Vi();Xi();sa();io();Wf=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"]});var Ea={};z(Ea,{DEFAULT_CROSS_CHAIN_SOURCES:()=>ga,DEFAULT_SAME_CHAIN_SOURCES:()=>ha,NATIVE_TOKEN:()=>To,canonicalJson:()=>ba,hashFirmQuote:()=>Sa,hashRfqIntent:()=>xa,normalizeFirmQuote:()=>No,normalizeRfqIntent:()=>om,sha256Hex:()=>nr});import{createHash as Zf}from"node:crypto";import{getAddress as ma,isAddress as Ro}from"ethers";function J(e,t="invalid"){throw new Error(`rfq: ${e} ${t}`)}function da(e,t){let r=Number(e);return(!Number.isSafeInteger(r)||r<=0)&&J(t,"must be a positive chainId"),r}function qr(e,t){let r=String(e??"").trim();return(!em.test(r)||BigInt(r)<=0n)&&J(t,"must be a positive integer string"),r}function tm(e,t){return e==null||e===""?null:qr(e,t)}function pa(e,t){let r=String(e??"").trim();return r.toLowerCase()===To.toLowerCase()?To:(Ro(r)||J(t,"must be an EVM address or native token sentinel"),ma(r))}function ya(e,t){let r=String(e??"").trim();return Ro(r)||J(t,"must be an EVM address"),ma(r)}function rm(e,t){return e==null||e===""?null:ya(e,t)}function fa(e,t,r){return e===void 0?[...r]:(Array.isArray(e)||J(t,"must be an array"),e.map(n=>String(n).trim()).filter(Boolean))}function nm(e,{nowMs:t,maxDeadlineMs:r},n){let o=Number(e);return Number.isFinite(o)||J(n,"must be a finite millisecond timestamp"),o<=t&&J(n,"expired"),o>t+r&&J(n,"exceeds maxDeadlineMs"),Math.floor(o)}function _t(e){if(Array.isArray(e))return e.map(_t);if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())e[r]!==void 0&&(t[r]=_t(e[r]));return t}return e}function ba(e){return JSON.stringify(_t(e))}function nr(e){return`0x${Zf("sha256").update(ba(e)).digest("hex")}`}function wa(e,t){let r={...e};for(let n of t)delete r[n];return r}function xa(e){return nr(wa(e,["intentHash"]))}function Sa(e){return nr(wa(e,["firmQuoteHash"]))}function om(e={},t={}){let r=Number(t.nowMs??Date.now()),n=Number(t.maxDeadlineMs??1800*1e3);(!Number.isFinite(r)||!Number.isFinite(n)||n<=0)&&J("time","is invalid");let o=da(e.fromChainId??e.fromChain,"fromChainId"),s=da(e.toChainId??e.toChain,"toChainId"),i=o===s?ha:ga,c={kind:"rfq-intent",version:1,fromChainId:o,toChainId:s,sellToken:pa(e.sellToken??e.tokenIn??e.fromToken,"sellToken"),buyToken:pa(e.buyToken??e.tokenOut??e.toToken,"buyToken"),sellAmount:qr(e.sellAmount??e.amountIn??e.fromAmount,"sellAmount"),receiver:ya(e.receiver??e.recipient??e.to,"receiver"),deadlineMs:nm(e.deadlineMs??e.deadline??e.expiresAtMs,{nowMs:r,maxDeadlineMs:n},"deadline"),minBuyAmount:tm(e.minBuyAmount??e.minOut??e.amountOutMin,"minBuyAmount"),allowedSources:fa(e.allowedSources,"allowedSources",i),allowedRouters:fa(e.allowedRouters,"allowedRouters",[]),slippageBps:Number.isFinite(Number(e.slippageBps))?Number(e.slippageBps):null,partialFill:e.partialFill===!0,metadata:e.metadata&&typeof e.metadata=="object"&&!Array.isArray(e.metadata)?_t(e.metadata):{}};return c.slippageBps!=null&&(!Number.isInteger(c.slippageBps)||c.slippageBps<0||c.slippageBps>1e4)&&J("slippageBps","must be 0 to 10000"),c.intentId=e.intentId?String(e.intentId):nr({seed:"rfq-intent",intent:c}).slice(0,34),c.intentHash=xa(c),Object.freeze(c)}function sm(e){return(!e||typeof e!="object"||Array.isArray(e))&&J("artifact","required"),e.typedDataHash!=null&&!la.test(String(e.typedDataHash))&&J("artifact.typedDataHash","must be bytes32"),e.calldataHash!=null&&!la.test(String(e.calldataHash))&&J("artifact.calldataHash","must be bytes32"),e.to!=null&&!Ro(String(e.to))&&J("artifact.to","must be an address"),e.data!=null&&!/^0x(?:[0-9a-fA-F]{2})*$/.test(String(e.data))&&J("artifact.data","must be hex"),_t(e)}function No(e,t={},r={}){(!e||e.kind!=="rfq-intent")&&J("intent","required");let n=Number(r.nowMs??Date.now()),o=Number(t.expiryMs??t.expiresAtMs??t.validUntilMs);Number.isFinite(o)||J("quote expiry","required"),o<=n&&J("quote","expired"),o>e.deadlineMs&&J("quote expiry","exceeds intent deadline");let s=String(t.source??t.provider??"").trim();s||J("source","required"),e.allowedSources.includes(s)||J("source","not allowed by intent");let a=qr(t.amountOut??t.buyAmount,"amountOut"),i=qr(t.minBuyAmount??t.minOut??a,"minBuyAmount");BigInt(i)>BigInt(a)&&J("minBuyAmount","exceeds amountOut");let c=sm(t.artifact??t.executableArtifact??t.transaction??t.typedData),u=Number(t.quotedAtMs??t.timestampMs??r.nowMs??Date.now());Number.isFinite(u)||J("quotedAtMs","must be finite");let p=rm(t.router??t.settlementRouter??c.to,"router"),l={kind:"rfq-firm-quote",provider:"rfq",surface:"rfq",version:1,quoteId:String(t.quoteId??t.id??"").trim(),source:s,intentHash:e.intentHash,fromChainId:e.fromChainId,toChainId:e.toChainId,sellToken:e.sellToken,buyToken:e.buyToken,sellAmount:e.sellAmount,receiver:e.receiver,router:p,amountOut:a,minBuyAmount:i,quotedAtMs:Math.floor(u),expiryMs:Math.floor(o),artifact:c,maker:t.maker?String(t.maker):null,metadata:t.metadata&&typeof t.metadata=="object"&&!Array.isArray(t.metadata)?_t(t.metadata):{}};return l.quoteId||(l.quoteId=nr({seed:"rfq-quote",out:l}).slice(0,34)),l.firmQuoteHash=Sa(l),Object.freeze(l)}var To,ha,ga,la,em,$o=w(()=>{To="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",ha=Object.freeze(["lifi","paraswap","0x","cow","uniswap-v3"]),ga=Object.freeze(["lifi"]),la=/^0x[0-9a-fA-F]{64}$/,em=/^\d+$/});import{readFileSync as im}from"node:fs";import{homedir as am}from"node:os";import{join as Br}from"node:path";function cm(){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=am();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Br(t,".config","oracle")).trim();return[e,Br(r,"exec.env")].filter(Boolean)}return[e,Br(t,".config","oracle","exec.env"),Br(t,".config","mad-desk","exec.env")].filter(Boolean)}function ka(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of cm())try{let s=im(o,"utf8"),a=s.match(new RegExp(`^${t}=(.*)$`,"m"))||s.match(new RegExp(`^${r}=(.*)$`,"m"));if(a&&(n=a[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}var Aa=w(()=>{});var va=w(()=>{});import{createHash as um,createHmac as lm,timingSafeEqual as yx}from"node:crypto";function qo(e){return Array.isArray(e)?`[${e.map(qo).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${qo(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function dm(e,{required:t=!1}={}){try{return ka(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Ca(e){let{signature:t,...r}=e;return r}function Oa(e,{secret:t}={}){let r=dm(t);return r?{...e,signature:lm("sha256",r).update(qo(Ca(e))).digest("hex")}:e}function pm(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 um("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function Ee(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 Oa({...Ca(e),calldataHash:pm(n)},{secret:o})}function Po(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function fm(e){let t=e==null?Ia: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,Ia)}function Me({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:o}={}){let s=Po(e,0),a=s>0?s>=25e4?5:s>=1e5?10:s>=5e4?20:s>=1e4?40:70:n?30:10,i=Math.min(60,Math.abs(Po(t,0))*2),c=Math.min(40,Math.floor(Math.max(0,Po(r,0))/5e3)*5),u=Math.max(25,Math.ceil(20+a+i+c)),p=fm(o);return{mode:"auto",requiredBps:u,selectedBps:Math.min(u,p),capBps:p,executable:u<=p}}function mm({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:o=0,quoteAgeMs:s=0,crossChain:a=!1,requestedCapBps:i,quotedAtMs:c=Date.now(),ttlMs:u=_a,secret:p}={}){let l=BigInt(r??0);if(l<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let d=Me({liquidityUsd:n,priceChange5m:o,quoteAgeMs:s,crossChain:a,requestedCapBps:i});if(!d.executable)throw new Error(`auto-slippage requires ${d.requiredBps} bps above hard/requested cap ${d.capBps}; route blocked`);let f=Number(c);if(!Number.isFinite(f))throw new Error("auto-slippage: quotedAtMs must be a finite number");let h=Math.min(3e4,Math.max(1e3,Number(u)||_a)),y=l*BigInt(1e4-d.selectedBps),g=y/10000n;if(y%10000n!==0n&&(g+=1n),g>l&&(g=l),l>0n&&g<=0n)throw new Error(`auto-slippage: quote ${l} is too small to express a ${d.selectedBps} bps floor without rounding to zero`);let b=Number((l-g)*10000n/(l===0n?1n:l));if(b>d.capBps)throw new Error(`auto-slippage: realised floor implies ${b} bps, above cap ${d.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Oa({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:l.toString(),minAmountOut:g.toString(),requiredBps:d.requiredBps,selectedBps:d.selectedBps,capBps:d.capBps,quotedAtMs:f,expiresAtMs:f+h},{secret:p})}function oe(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:o,priceChange5m:s,crossChain:a,requestedCapBps:i,quotedAtMs:c=Date.now(),ttlMs:u}={}){let p=mm({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:o,priceChange5m:s,crossChain:a,requestedCapBps:i,quotedAtMs:c,ttlMs:u});return{...e,autoSlippage:p,amountOutMinimum:p.minAmountOut}}var Ia,_a,je=w(()=>{Aa();va();Ia=100,_a=2e4});function Bo(e){let t=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:Ye}var Ye,Ur=w(()=>{Ye="0x000000000000000000000000000000000000dEaD"});import{Contract as hm,JsonRpcProvider as gm}from"ethers";function Em(e){return Sm.test(String(e||""))}async function Ta(e,{contract:t=ym,rpc:r=wm,chainId:n=bm,balanceOf:o}={}){if(!Em(e))throw new Error("invalid-address");if(o)return BigInt(await o(e));let s=new gm(r,n,{staticNetwork:!0}),a=new hm(t,xm,s);return BigInt(await a.balanceOf(e))}var ym,bm,wm,xm,Sm,Ra=w(()=>{ym="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",bm=999,wm="https://rpc.hyperliquid.xyz/evm",xm=["function balanceOf(address owner) view returns (uint256)"],Sm=/^0x[a-fA-F0-9]{40}$/});import{existsSync as km,readFileSync as Am}from"node:fs";import{homedir as vm}from"node:os";import{join as Na}from"node:path";function Cm(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call($a,t)?$a[t]:_m}function $m(e=process.env){if(e[Pa])return String(e[Pa]);let t=e.ORACLE_CONFIG_DIR||Na(vm(),".config","oracle");return Na(t,"fee-recipient")}function Pm(e=process.env){try{let t=$m(e);if(!km(t))return"";let r=Am(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function qm(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),Im)}function Bm({env:e=process.env,action:t="swap"}={}){let r=String(e[Tm]||"").trim(),n=Cm(t),o=qm(e[Om],{fallback:r?n:0}),s=Math.min(o,n),a=String(e[Rm]||Nm).trim();if(!s)return{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(r))return{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"no-recipient"};let i=Pm(e);return i&&i!==r.toLowerCase()?{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:s,recipient:r,integrator:a,action:t,applies:!0,reason:"configured"}}async function Dr({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={}}={}){let o=Bm({env:t,action:r}),s=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(s))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await Ta(s,n))>0n?{...o,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...o,holderVerificationStatus:"non-holder"}}catch{return{...o,holderVerificationStatus:"unavailable"}}}function qa(e){return e?.applies?`Oracle routing fee ${e.bps} bps (${(e.bps/100).toFixed(2)}%) to ${e.recipient}.`:e?.reason==="locals-only-holder"?"No Oracle fee (Locals Only holder).":"No Oracle fee."}function Ba(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function Ua(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var Im,_m,$a,Om,Tm,Rm,Pa,Nm,Lr=w(()=>{Ra();Im=100,_m=5,$a=Object.freeze({swap:5,bridge:5,perps:0,nft:0});Om="ORACLE_INTEGRATOR_FEE_BPS",Tm="ORACLE_INTEGRATOR_FEE_RECIPIENT",Rm="ORACLE_INTEGRATOR_ID",Pa="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",Nm="oracle"});var Lo={};z(Lo,{LIFI_API:()=>La,lifiChains:()=>Mm,lifiHealth:()=>Lm,lifiPrepare:()=>Fm,lifiQuote:()=>ct});function Do(e={}){return(e.baseUrl||process.env.LIFI_API_URL||La).replace(/\/$/,"")}function Dm(e){let t=String(e||Uo).toLowerCase();return t===Uo.toLowerCase()||t===Um}function Da(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 Lm(e={}){let t=await v(`${Do(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 ct(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:o=Uo,toToken:s,fromAmount:a,fromAddress:i=Ye}=e;if(r==null||!s||!a)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let c=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:o,toToken:s,fromAmount:String(a),fromAddress:i}),u=Me({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 Dr({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[g,b]of Object.entries(Ba(p)))c.set(g,b);let l=await v(`${Do(t)}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),d=l?.estimate?.toAmount||l?.toAmount;if(!d)return{...l,autoSlippagePolicy:u,oracleFee:p};let f=l?.transactionRequest?.to||l?.estimate?.approvalAddress||"lifi",h=oe(l,{chainId:Number(r),venue:f,amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),y=l?.estimate?.toAmountMin||l?.toAmountMin;if(y!=null&&BigInt(y)<BigInt(h.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...h,oracleFee:p}}async function Fm(e={},t={}){let r=await ct(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 s=null;if(!Dm(e.fromToken)){let a=r?.estimate?.approvalAddress||r?.approvalAddress;if(!a)throw new Error("lifi: ERC20 route missing approvalAddress");let i=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;s={token:Da(i,"approval token"),spender:Da(a,"approval spender"),amount:String(e.fromAmount)}}return Q({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:o,quote:r,autoSlippage:r.autoSlippage,requiresApproval:s,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:Ee(r.autoSlippage,{chainId:o,venue:n.to,data:n.data})}},{provider:"lifi",kind:"lifi-tx"})}async function Mm(e={}){return v(`${Do(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var La,Uo,Um,or=w(()=>{F();je();Ur();de();Lr();La="https://li.quest/v1";Uo="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Um="0x0000000000000000000000000000000000000000"});var ja={};z(ja,{PARASWAP_API:()=>Fa,paraswapHealth:()=>Hm,paraswapPrepare:()=>jm,paraswapPrice:()=>Ot,paraswapTokens:()=>Ma});function Ct(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 Ma(e={},t={}){let r=Number(e.chainId||1);return v(`${Fo(t)}/tokens/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Ot(e={},t={}){let r=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let n=new URLSearchParams({srcToken:Ct(e.srcToken,"srcToken"),destToken:Ct(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 Dr({wallet:e.userAddress||e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[i,c]of Object.entries(Ua(o)))n.set(i,c);let s=await v(`${Fo(t)}/prices?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=s?.priceRoute?.destAmount;return a?{...oe(s,{chainId:r,venue:s?.priceRoute?.contractAddress||"paraswap-quote",amountOut:a,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,quoteAgeMs:0,requestedCapBps:e.maxSlippageBps??e.slippageBps}),executionReady:!1,executionBlocker:"call prepare to bind the price route to a validated transaction",oracleFee:o}:{...s,executionReady:!1,oracleFee:o}}async function jm(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=Ct(e.userAddress,"userAddress"),o=await Ot(e,t),s=o?.priceRoute,a=String(s?.contractAddress||"").toLowerCase();if(!a)throw new Error("paraswap: price route missing contractAddress");let i={srcToken:Ct(e.srcToken,"srcToken"),destToken:Ct(e.destToken,"destToken"),srcAmount:String(s.srcAmount||e.amount),destAmount:String(o.amountOutMinimum),priceRoute:s,userAddress:n,ignoreChecks:!1,ignoreGasEstimate:!1};e.receiver&&(i.receiver=Ct(e.receiver,"receiver"));let c=await v(`${Fo(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()!==a)throw new Error("paraswap: transaction target mismatch");if(c.from&&String(c.from).toLowerCase()!==n)throw new Error("paraswap: transaction sender mismatch");return Q({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:s.tokenTransferProxy||a,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:Ee(o.autoSlippage,{chainId:r,venue:c.to,data:c.data})}},{provider:"paraswap",kind:"paraswap-tx"})}async function Hm(e={}){let t=await Ma({chainId:1},e),r=Array.isArray(t?.tokens)?t.tokens.length:Object.keys(t?.tokens||{}).length;return{ok:r>0,tokenSample:r}}var Fa,Fo,Fr=w(()=>{F();je();de();Lr();Fa="https://api.paraswap.io",Fo=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||Fa).replace(/\/$/,"")});function Mr({provider:e,defaultUrl:t,hosts:r=[],url:n,strict:o=!1}){let a=(String(n??"").trim()||String(t)).replace(/\/$/,"");if(a===String(t).replace(/\/$/,""))return{baseUrl:a,trusted:!0,host:za(t)};let i;try{i=new URL(a)}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([za(t),...r]).has(c)){let p=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return i.protocol==="http:"&&!p?{baseUrl:a,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:a,trusted:!0,host:c}}if(String(process.env[Ha]||"")==="1")return{baseUrl:a,trusted:!1,host:c};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${Ha}=1 to permit it)`);return{baseUrl:a,trusted:!1,host:c}}function za(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function jr(e,t,r){let n={...e};if(!r)return n;for(let[o,s]of Object.entries(t||{}))s&&(n[o]=s);return n}var Ha,Mo=w(()=>{Ha="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});var Ya={};z(Ya,{ZEROX_API:()=>Va,zeroxHealth:()=>zm,zeroxPrepare:()=>Vm,zeroxPrice:()=>Ga,zeroxQuote:()=>Tt});function Ka(e={}){return Mr({provider:"zerox",defaultUrl:Va,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function Wa(e={}){return Ka(e).baseUrl}function Hr(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function Qa(e={}){return jr({"0x-version":"v2",accept:"application/json"},{"0x-api-key":Hr(e)},Ka(e).trusted)}async function zm(e={}){if(!Hr(e))return{ok:!1,configured:!1,error:"ZEROX_API_KEY not set"};try{let t=await Ga({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 Ga(e={},t={}){if(!Hr(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:s,taker:a}=e;if(!n||!o||!s)throw new Error("zeroxPrice requires sellToken, buyToken, sellAmount");let i=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:o,sellAmount:String(s)});return a&&i.set("taker",a),v(`${Wa(t)}/swap/allowance-holder/price?${i}`,{headers:Qa(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function Tt(e={},t={}){if(!Hr(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:s,taker:a}=e;if(!n||!o||!s)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let i=Me({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(s),slippageBps:String(i.selectedBps)});a&&c.set("taker",a);let u=await v(`${Wa(t)}/swap/allowance-holder/quote?${c}`,{headers:Qa(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),p=u?.buyAmount||u?.grossBuyAmount;return p?oe(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 Vm(e={},t={}){if(!e.taker)throw new Error("0x: taker required for executable prepare");let r=await Tt(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),s=r?.issues?.allowance?.spender||r?.allowanceTarget;return Q({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:s,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:Ee(r.autoSlippage,{chainId:o,venue:n.to,data:n.data})}},{provider:"zerox",kind:"zerox-tx"})}var Va,zr=w(()=>{F();je();Mo();de();Va="https://api.0x.org"});var zx,Xa=w(()=>{zx=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});var ac={};z(ac,{COW_CANCEL_TYPES:()=>rc,COW_HOSTS:()=>Ho,COW_ORDER_TYPES:()=>Vr,COW_SETTLEMENT:()=>Za,COW_VAULT_RELAYER:()=>ec,cowCancelOrders:()=>n0,cowChains:()=>i0,cowHealth:()=>Ym,cowOrder:()=>ic,cowOrderStatus:()=>sc,cowOrderUid:()=>Jm,cowPrepareCancel:()=>t0,cowPrepareOrder:()=>Xm,cowQuote:()=>ut,cowSignCancel:()=>r0,cowSignOrder:()=>Zm,cowSubmitSignedOrder:()=>e0,cowVerifyOrderFill:()=>s0});import{TypedDataEncoder as Ja,getAddress as sr,isAddress as Km}from"ethers";function Kr(e,t={}){if(t.baseUrl)return t.baseUrl.replace(/\/$/,"");let r=Ho[Number(e)];if(!r)throw new Error(`cowswap: unsupported chainId ${e}`);return r}function Wm(e,t="v1",r={}){let n=Kr(e,r);return t==="v1"?n:n.replace(/\/api\/v1$/,`/api/${t}`)}function Xe(e,t){let r=String(e||"").trim();if(!Km(r))throw new Error(`cowswap: ${t} must be an address`);return sr(r).toLowerCase()}function Rt(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 nc(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 oc(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 Qm({digest:e,owner:t,validTo:r}={}){let n=nc(e,"order digest").slice(2),o=Xe(t,"owner").slice(2).toLowerCase(),s=Number(r);if(!Number.isInteger(s)||s<0||s>4294967295)throw new Error("cowswap: validTo must fit uint32");return`0x${n}${o}${s.toString(16).padStart(8,"0")}`.toLowerCase()}function zo(e){let t=Za[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:sr(t)}}function Gm(e={},t,r){let n=Xe(e.sellToken,"sellToken"),o=Xe(e.buyToken,"buyToken"),s=Xe(e.receiver||r,"receiver"),a=Number(e.validTo);if(!Number.isInteger(a)||a<=0)throw new Error("cowswap: quote.validTo required");let i=nc(e.appData||e.appDataHash||`0x${"0".repeat(64)}`,"appData");return{sellToken:n,buyToken:o,receiver:s,sellAmount:Rt(e.sellAmount,"sellAmount"),buyAmount:Rt(e.buyAmount,"buyAmount"),validTo:a,appData:i,feeAmount:Rt(e.feeAmount??"0","feeAmount"),kind:String(e.kind||"sell"),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance||"erc20"),buyTokenBalance:String(e.buyTokenBalance||"erc20")}}async function Ym(e={}){try{let t=await ut({chainId:1,sellToken:jo[1],buyToken:tc[1],sellAmountBeforeFee:"1000000000000000",from:Ye},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 ut(e={},t={}){let r=Number(e.chainId??1),n=Bo(e.from||e.owner),o=e.sellToken||jo[r],s=e.buyToken||tc[r],a=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!o||!s||a==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(o)&&(o=jo[r],!o))throw new Error("no WETH mapping for chain");let i={sellToken:o,buyToken:s,from:n,receiver:e.receiver||n,sellAmountBeforeFee:a,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},c=await v(`${Kr(r,t)}/quote`,{method:"POST",body:i,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),u=c?.quote?.buyAmount||c?.buyAmount;return u?oe(c,{chainId:r,venue:"cowswap-order",amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):c}async function Xm(e={},t={}){let r=Number(e.chainId??1),n=Xe(Bo(e.from||e.owner||e.signer),"owner"),o=await ut({...e,chainId:r,from:n,signingScheme:e.signingScheme||"eip712"},t),s=Gm(o?.quote||o,r,n),a=zo(r),i={domain:a,types:Vr,primaryType:"Order",message:s},c=Ja.hash(a,Vr,s),u=ec[r];if(!u)throw new Error(`cowswap: vault relayer not registered for chain ${r}`);return Q({provider:"cowswap",orderReady:!0,executionReady:!1,chainId:r,owner:n,signingScheme:"eip712",settlement:a.verifyingContract.toLowerCase(),vaultRelayer:sr(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:a.verifyingContract.toLowerCase(),vaultRelayer:sr(u).toLowerCase(),sellToken:s.sellToken,buyToken:s.buyToken,sellAmount:s.sellAmount,buyAmount:s.buyAmount,validTo:s.validTo,quoteId:o?.id??e.quoteId??null,typedDataHash:c,issuedAtMs:Date.now(),expiresAtMs:Math.min(s.validTo*1e3,Date.now()+2e4)},requiresApproval:{token:s.sellToken,spender:sr(u).toLowerCase(),amount:s.sellAmount}},{provider:"cowswap",kind:"cow-order"})}async function sc(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrderStatus requires uid");return v(`${Kr(r,t)}/orders/${encodeURIComponent(n)}/status`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ic(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrder requires uid");return v(`${Kr(r,t)}/orders/${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}function Jm(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||Ja.hash(zo(r),Vr,n),s=e.owner||e.from||e.signer||n.receiver;return Qm({digest:o,owner:s,validTo:n.validTo})}async function Zm(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 e0(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 t0(e={}){let t=Number(e.chainId??1),r=Xe(e.owner||e.from||e.signer,"owner"),n=(e.orderUids||e.uids||[e.uid]).filter(Boolean).map((a,i)=>oc(a,`orderUids[${i}]`));if(!n.length)throw new Error("cowswap: orderUids required");let o=zo(t);return Q({provider:"cowswap",chainId:t,owner:r,orderUids:n,signingScheme:"eip712",typedData:{domain:o,types:rc,primaryType:"OrderCancellations",message:{orderUids:n}},cancelReady:!0,executableArtifact:!0},{provider:"cowswap",kind:"cow-cancel"})}async function r0(e={},t={}){throw new Error("cowswap.cowSignCancel refused: @oracle-agent/oracle is prepare-only. Cancel-sign with the user wallet.")}async function n0(e={},t={}){throw new Error("cowswap.cowCancelOrders refused: @oracle-agent/oracle is prepare-only. Cancel from the user wallet or local operator.")}function o0(e={}){return Rt(e.buyAmount??e.executedBuyAmount??"0","trade.buyAmount")}async function s0(e={},t={}){let r=Number(e.chainId??1),n=oc(e.uid||e.orderUid),o=t.order||await ic({chainId:r,uid:n},t),s=t.status||o.status||await sc({chainId:r,uid:n},t).catch(()=>null),a=t.trades||await v(`${Wm(r,"v2",t)}/trades?orderUid=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),i=Array.isArray(a)?a:[],c=e.expectedOwner?Xe(e.expectedOwner,"expectedOwner"):null;if(c&&Xe(o.owner||i[0]?.owner||c,"owner")!==c)return{ok:!1,provider:"cowswap",chainId:r,uid:n,reason:"owner mismatch",order:o,status:s,trades:i};let u=0n;for(let d of i.filter(f=>String(f.orderUid||"").toLowerCase()===n))u+=BigInt(o0(d));u===0n&&o.executedBuyAmount!=null&&(u=BigInt(Rt(o.executedBuyAmount,"executedBuyAmount")));let p=e.minBuyAmount!=null?BigInt(Rt(e.minBuyAmount,"minBuyAmount")):0n,l=u>=p&&String(o.status||s?.status||"").toLowerCase()!=="expired";return{ok:l,provider:"cowswap",chainId:r,uid:n,status:o.status||s?.status||null,executedBuyAmount:u.toString(),minBuyAmount:e.minBuyAmount??null,trades:i,settlementTxs:[...new Set(i.map(d=>d.txHash).filter(Boolean))],order:o,orderStatus:s,reason:l?null:"insufficient fill or expired order"}}function i0(){return Object.keys(Ho).map(Number)}var Ho,Za,ec,jo,tc,Vr,rc,Wr=w(()=>{F();je();Xa();Ur();de();Ho={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"},Za=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),ec=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),jo={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},tc={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},Vr=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"}]}),rc=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function uc(e){return a0.get(Number(e))||null}function lc(e,t=process.env){let r=uc(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}var cc,a0,dc=w(()=>{cc={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}},a0=new Map(Object.values(cc).map(e=>[e.chainId,e]))});import{Interface as c0,getAddress as u0}from"ethers";function ir(e,t){try{return u0(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function d0(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=lc(e,r);return n||l0[Number(e)]||null}function f0(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!p0.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 ee(e,t,r=[],n={}){let o=String(t||"");f0(o);let s=d0(e,n);if(!s)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let i=await v(s,{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 Gr(e,t={}){let r=await ee(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function pc(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await ee(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function fc(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=ir(e.token||e.tokenAddress,"token"),o=ir(e.owner,"owner"),s=ir(e.spender,"spender"),a=Qr.encodeFunctionData("allowance",[o,s]),i=await ee(r,"eth_call",[{to:n,data:a},e.blockTag||"latest"],t),c=Qr.decodeFunctionResult("allowance",i),u=BigInt(c[0]);return{chainId:r,token:n,owner:o,spender:s,allowance:u.toString(),allowanceHex:`0x${u.toString(16)}`,blockTag:e.blockTag||"latest"}}async function mc(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=ir(e.token||e.tokenAddress,"token"),o=ir(e.account||e.owner||e.address,"account"),s=Qr.encodeFunctionData("balanceOf",[o]),a=await ee(r,"eth_call",[{to:n,data:s},e.blockTag||"latest"],t),i=Qr.decodeFunctionResult("balanceOf",a),c=BigInt(i[0]);return{chainId:r,token:n,account:o,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var Qr,l0,p0,lt=w(()=>{F();dc();Qr=new c0(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);l0={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"};p0=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/});function y0(e,t,r){let n=ke(t),o=ke(r),s=ke(e?.baseToken?.address),a=ke(e?.quoteToken?.address);return s===n&&a===o||s===o&&a===n}function b0(e){let t=Number(e?.liquidity?.usd);return Number.isFinite(t)&&t>=0?t:null}function w0(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||m0).replace(/\/$/,"")}async function Vo(e,t={}){if(!e)throw new Error("tokenAddress required");return v(`${w0(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function Yr({chainId:e,tokenA:t,tokenB:r,dexIds:n=[]}={},o={}){if(e==null||!t||!r)throw new Error("chainId, tokenA, and tokenB required");let s=ke(h0[Number(e)]||e),a=new Set(g0(n).filter(Boolean).map(ke)),i=[...new Set([t,r].map(d=>String(d)).filter(Boolean))],c=await Promise.allSettled(i.map(d=>Vo(d,{...o,baseUrl:o.dexscreenerBaseUrl,timeoutMs:o.dexscreenerTimeoutMs??Math.min(Number(o.timeoutMs??4e3),4e3)}))),u=new Set,p=[];for(let d of c)if(d.status==="fulfilled")for(let f of d.value?.pairs||d.value?.data?.pairs||[]){let h=`${ke(f?.chainId)}:${ke(f?.dexId)}:${ke(f?.pairAddress)}`;u.has(h)||(u.add(h),p.push(f))}return p.filter(d=>ke(d?.chainId)===s).filter(d=>y0(d,t,r)).filter(d=>!a.size||a.has(ke(d?.dexId))).map(d=>({pairAddress:d.pairAddress??null,dexId:d.dexId??null,chainId:d.chainId??null,liquidityUsd:b0(d),pairCreatedAt:d.pairCreatedAt??null})).filter(d=>d.liquidityUsd!=null).sort((d,f)=>f.liquidityUsd-d.liquidityUsd)[0]??null}var m0,h0,ke,g0,Xr=w(()=>{F();m0="https://api.dexscreener.com",h0=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"}),ke=e=>String(e??"").toLowerCase(),g0=e=>Array.isArray(e)?e:e==null?[]:[e]});var Ec={};z(Ec,{PANCAKE_FEE_TIERS:()=>Jr,UNI_V3_CHAINS:()=>pe,UNI_V3_FEE_TIERS:()=>yc,UNI_V3_VENUES:()=>xc,uniV3Chains:()=>I0,uniV3EthUsdc:()=>Sc,uniV3Health:()=>v0,uniV3PrepareExactIn:()=>A0,uniV3QuoteExactIn:()=>dt,uniV3QuoteExactInPath:()=>k0});import{Interface as gc,getAddress as ar,isAddress as x0}from"ethers";function Wo(e,t){let r=Number(e),n=pe[r];if(!n)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys(pe).join(", ")})`);let o=xc[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 s=String(t).toLowerCase();if(s===n.name&&n.quoter&&n.router)return{chainId:r,venue:n.name,...n};let a=o,i=a[s];if(!i){let c=[...n.quoter&&n.router?[n.name]:[],...Object.keys(a)].join(", ");throw new Error(`uniswap-v3: unknown venue "${t}" on chain ${r} (known: ${c})`)}return{chainId:r,venue:s,...n,quoter:i.quoter,router:i.router,feeTiers:i.feeTiers||null}}function Ko(e,t){let r=pe[Number(t)];if(!e||e===bc||e===wc||/^eth$/i.test(String(e)))return ar(r.weth);let n=String(e);if(/^weth$/i.test(n))return ar(r.weth);if(/^usdc$/i.test(n))return ar(r.usdc);if(!x0(n))throw new Error(`invalid token address: ${e}`);return ar(n)}function S0(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 E0(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 dt(e={},t={}){let{chainId:r,quoter:n,router:o,feeTiers:s}=Wo(e.chainId??8453,e.venue),a=Ko(e.tokenIn||"WETH",r),i=Ko(e.tokenOut||pe[r].usdc,r),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");let u=s&&s.length?s:yc,p=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[u[Math.min(2,u.length-1)]]:[...u],l=[],d=null;for(let y of p){let g=Zr.encodeFunctionData("quoteExactInputSingle",[{tokenIn:a,tokenOut:i,amountIn:c,fee:y,sqrtPriceLimitX96:0n}]);try{let b=await ee(r,"eth_call",[{to:n,data:g},"latest"],t);if(!b||b==="0x"){l.push({fee:y,ok:!1,error:"empty result"});continue}let S=Zr.decodeFunctionResult("quoteExactInputSingle",b),I={fee:y,ok:!0,amountOut:S[0].toString(),sqrtPriceX96After:S[1].toString(),initializedTicksCrossed:Number(S[2]),gasEstimate:S[3].toString()};l.push(I),(!d||BigInt(I.amountOut)>BigInt(d.amountOut))&&(d=I)}catch(b){l.push({fee:y,ok:!1,error:String(b.message||b).slice(0,160)})}}if(!d){let y=l.map(g=>`${g.fee}:${g.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${r}: ${y}`)}let f=e.liquidityUsd==null?await Yr({chainId:r,tokenA:a,tokenB:i,dexIds:S0(e.venue)},t).catch(()=>null):null,h=e.liquidityUsd??f?.liquidityUsd??null;return oe({venue:"uniswap-v3",chainId:r,chain:pe[r].name,quoter:n,tokenIn:a,tokenOut:i,amountIn:c.toString(),fee:d.fee,amountOut:d.amountOut,gasEstimate:d.gasEstimate,liquidityUsd:h,liquiditySource:f,sqrtPriceX96After:d.sqrtPriceX96After,initializedTicksCrossed:d.initializedTicksCrossed,triedFees:l,best:!0},{chainId:r,venue:o,amountOut:d.amountOut,liquidityUsd:h,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function k0(e={},t={}){let{chainId:r,quoter:n,router:o}=Wo(e.chainId??8453),s=(e.tokens||[]).map(d=>Ko(d,r)),a=(e.fees||[]).map(Number);if(s.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=E0(s,a),u=Zr.encodeFunctionData("quoteExactInput",[c,i]),p=await ee(r,"eth_call",[{to:n,data:u},"latest"],t),l=Zr.decodeFunctionResult("quoteExactInput",p);return oe({venue:"uniswap-v3",chainId:r,chain:pe[r].name,quoter:n,tokens:s,fees:a,path:c,amountIn:i.toString(),amountOut:l[0].toString(),gasEstimate:l[3].toString()},{chainId:r,venue:o,amountOut:l[0].toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Sc(e={},t={}){let r=Number(e.chainId??8453),n=e.amountIn??"1000000000000000",o=await dt({chainId:r,tokenIn:pe[r].weth,tokenOut:pe[r].usdc,amountIn:n,fee:e.fee},t),s=Number(o.amountOut)/1e6;return{...o,amountOutUsdc:s,pair:"WETH/USDC"}}async function A0(e={},t={}){let r=Number(e.chainId??8453),n=Wo(r,e.venue),o=ar(e.recipient),s=String(e.tokenIn||"WETH"),a=!e.tokenIn||s===bc||s===wc||/^eth$/i.test(s),i=await dt(e,t),c=hc.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))),l=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+u,d=hc.encodeFunctionData("multicall",[l,[c]]);return Q({provider:"uniswap-v3",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:l,quote:i,autoSlippage:i.autoSlippage,requiresApproval:a?null:{token:i.tokenIn,spender:n.router,amount:i.amountIn},transaction:{chainId:r,from:o,to:n.router,data:d,value:a?i.amountIn:"0",slippageGuard:Ee(i.autoSlippage,{chainId:r,venue:n.router,data:d})}},{provider:"uniswap-v3",kind:"univ3-swap-tx"})}async function v0(e={}){let t=Number(e.chainId??8453);try{let r=await Sc({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 I0(){return Object.entries(pe).map(([e,t])=>({chainId:Number(e),name:t.name,quoter:t.quoter,weth:t.weth,usdc:t.usdc}))}var pe,yc,Zr,hc,bc,wc,Jr,xc,en=w(()=>{lt();Xr();je();de();pe={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"}},yc=[100,500,3e3,1e4],Zr=new gc(["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)"]),hc=new gc(["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)"]),bc="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",wc="0x0000000000000000000000000000000000000000",Jr=[100,500,2500,1e4],xc={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Jr}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Jr}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Jr}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}}});var _c={};z(_c,{executeRfqCandidates:()=>vc,rankRfqQuotes:()=>Ic,requestRfqQuotes:()=>O0,sourceCandidates:()=>Ac});function cr(e,t){return Array.isArray(e?.allowedSources)&&e.allowedSources.includes(t)}function kc(e,t){return String(e?.[t]??"").trim()}function ur(e,t){return Object.freeze({source:e,run:t})}function Ac(e,t={}){if(!e||e.kind!=="rfq-intent")throw new Error("rfq: intent required");let r=t.env??process.env,n=t.providers??{},o=t.supportedUniV3Chains??pe,s=Number(e.fromChainId)===Number(e.toChainId),a=[];return cr(e,"lifi")&&a.push(ur("lifi",async()=>{let c=await(n.lifiQuote??ct)({fromChain:e.fromChainId,toChain:e.toChainId,fromToken:e.sellToken,toToken:e.buyToken,fromAmount:e.sellAmount,fromAddress:e.receiver},t),u=c?.estimate??c?.[0]?.estimate??c;return{quoteId:c?.id??c?.routeId??null,amountOut:u?.toAmount??c?.toAmount,minBuyAmount:u?.toAmountMin??c?.toAmountMin??u?.toAmount??c?.toAmount,expiryMs:Date.now()+Number(t.defaultQuoteTtlMs??2e4),artifact:{type:"lifi-route",calldataHash:c?.transactionRequest?.data?await _0(t,c.transactionRequest.data):void 0,route:c},metadata:{tool:c?.tool??c?.toolDetails?.name??null}}})),s&&(cr(e,"paraswap")&&a.push(ur("paraswap",async()=>{let c=await(n.paraswapPrice??Ot)({chainId:e.fromChainId,srcToken:e.sellToken,destToken:e.buyToken,amount:e.sellAmount,srcDecimals:t.decimalsIn,destDecimals:t.decimalsOut},t),u=c?.priceRoute??c;return{quoteId:u?.id??null,amountOut:u?.destAmount,minBuyAmount:c?.amountOutMinimum??u?.destAmount,expiryMs:Date.now()+Number(t.defaultQuoteTtlMs??2e4),artifact:{type:"paraswap-price-route",route:u},metadata:{contractAddress:u?.contractAddress??null}}})),cr(e,"0x")&&(kc(r,"ZEROX_API_KEY")||kc(r,"0X_API_KEY")||n.zeroxQuote)&&a.push(ur("0x",async()=>{let c=await(n.zeroxQuote??Tt)({chainId:e.fromChainId,sellToken:e.sellToken,buyToken:e.buyToken,sellAmount:e.sellAmount,taker:e.receiver},t);return{quoteId:c?.id??null,amountOut:c?.buyAmount??c?.grossBuyAmount,minBuyAmount:c?.minBuyAmount??c?.buyAmount,expiryMs:Date.now()+Number(t.defaultQuoteTtlMs??2e4),artifact:{type:"0x-transaction",to:c?.transaction?.to,data:c?.transaction?.data,value:c?.transaction?.value??"0"},metadata:{route:c?.route??null}}})),cr(e,"cow")&&a.push(ur("cow",async()=>{let c=await(n.cowQuote??ut)({chainId:e.fromChainId,sellToken:e.sellToken,buyToken:e.buyToken,sellAmountBeforeFee:e.sellAmount,from:e.receiver,signingScheme:"eip712"},t),u=c?.quote??c;return{quoteId:c?.id??null,amountOut:u?.buyAmount,minBuyAmount:u?.buyAmount,expiryMs:Math.min(Number(u?.validTo??0)*1e3||Date.now()+Number(t.defaultQuoteTtlMs??2e4),e.deadlineMs),artifact:{type:"cow-order",order:u},metadata:{solver:!0}}})),cr(e,"uniswap-v3")&&o[Number(e.fromChainId)]&&a.push(ur("uniswap-v3",async()=>{let c=await(n.uniV3QuoteExactIn??dt)({chainId:e.fromChainId,tokenIn:e.sellToken,tokenOut:e.buyToken,amountIn:e.sellAmount},t);return{quoteId:c?.id??null,amountOut:c?.amountOut,minBuyAmount:c?.minOut??c?.amountOutMinimum??c?.amountOut,expiryMs:Date.now()+Number(t.defaultQuoteTtlMs??2e4),artifact:{type:"uniswap-v3-quote",quoter:c?.quoter,fee:c?.fee},metadata:{onchain:!0}}}))),a}async function _0(e,t){return`0x${(await import("node:crypto")).createHash("sha256").update(String(t)).digest("hex")}`}async function C0(e,t){return Promise.race([Promise.resolve().then(e.run),new Promise((r,n)=>setTimeout(()=>n(new Error(`${e.source}: timeout`)),t))])}async function vc(e,t,r={}){let n=Number(r.timeoutMs??12e3),o=await Promise.allSettled(t.map(i=>C0(i,n))),s=[],a=[];for(let i=0;i<o.length;i++){let c=t[i],u=o[i];if(u.status==="rejected"){a.push({source:c.source,error:String(u.reason?.message||u.reason)});continue}try{s.push(No(e,{...u.value,source:c.source},r))}catch(p){a.push({source:c.source,error:String(p?.message||p)})}}return{quotes:s,failed:a}}function Ic(e=[],t={}){let r=Number(t.nowMs??Date.now()),n=e.filter(a=>Number(a.expiryMs??0)>r);n.sort((a,i)=>{let c=BigInt(i.minBuyAmount??0)-BigInt(a.minBuyAmount??0);if(c!==0n)return c>0n?1:-1;let u=BigInt(i.amountOut??0)-BigInt(a.amountOut??0);return u>0n?1:u<0n?-1:0});let o=n.map(a=>({...a,scoreBasis:"minBuyAmount"})),s=[];return o.length||s.push("no RFQ source returned a usable firm quote"),e.length!==o.length&&s.push("expired RFQ quotes were excluded from ranking"),{best:o[0]??null,quotes:o,failed:[],warnings:s}}async function O0(e,t={}){let r=Ac(e,t),{quotes:n,failed:o}=await vc(e,r,t),s=Ic(n,t);return{kind:"rfq-result",intent:e,best:s.best,quotes:s.quotes,failed:o,warnings:[...s.warnings],sourcesTried:r.length,sourcesAnswered:n.length}}var Cc=w(()=>{or();Fr();zr();Wr();en();$o()});function Oc(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,s]of(e.venues||[]).entries()){let a=`venues[${o}]`;if(!s||typeof s!="object"){t.push(`${a} must be an object`);continue}T0.test(s.address||"")||t.push(`${a}.address is not a valid 20-byte address`),/^0x0{40}$/.test(s.address||"")&&t.push(`${a}.address is the zero address -- placeholder left in place?`),s.kind||t.push(`${a}.kind is required (router|quoter|factory|...)`),s.verified?(s.verified.method||t.push(`${a}.verified.method is required`),s.verified.source||t.push(`${a}.verified.source is required`),s.verified.date||r.push(`${a}.verified.date missing -- add one so staleness is visible`)):t.push(`${a} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let n=e.capabilities||{};for(let o of Object.keys(n))Nt.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 Tc(e){let{ok:t,errors:r,warnings:n}=Oc(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
|
|
4
|
+
`;try{Fe.writeFileSync(n,o,{mode:384,flag:"wx"}),Fe.renameSync(n,e);try{Fe.chmodSync(e,384)}catch{}}catch(s){try{Fe.unlinkSync(n)}catch{}throw s}}function ta(e={}){let t=e.path;if(Ff(t),Ji(t),Fe.existsSync(t)?Zi(Fe.readFileSync(t,"utf8"),t):ea(t,Mf()),So.has(t))return So.get(t);let r=!1,n=[];function o(){if(r)return;let h=n.shift();if(h){r=!0;try{let y=h.fn();r=!1,h.resolve(y),o()}catch(y){r=!1,h.reject(y),o()}}}function s(h){if(!r&&n.length===0){r=!0;try{return h()}finally{r=!1,queueMicrotask(o)}}return new Promise((y,g)=>{n.push({fn:h,resolve:y,reject:g}),queueMicrotask(o)})}function a(){return Ji(t),Zi(Fe.readFileSync(t,"utf8"),t)}function i(h){ea(t,h)}function c(h){if(!Pr(h)||typeof h.id!="string"||!h.id)throw new Error("shadow-store: create requires record with string id");It(h,"record");let y=a();if(y.runners.some(b=>b.id===h.id))throw new Error(`shadow-store: runner id already exists: ${h.id}`);let g=qe(h);return y.runners.push(g),i(y),qe(g)}function u(h){let y=a().runners.find(g=>g.id===h);return y?qe(y):null}function p(){return a().runners.map(h=>qe(h))}function l(h,y){if(typeof y!="function")throw new Error("shadow-store: updater must be a function");let g=a(),b=g.runners.findIndex(A=>A.id===h);if(b<0)throw new Error(`shadow-store: runner not found: ${h}`);let S=qe(g.runners[b]),I=y(S);if(!Pr(I)||I.id!==h)throw new Error("shadow-store: updater must return record with same id");return It(I,"record"),g.runners[b]=qe(I),i(g),qe(g.runners[b])}function d(h){let y=a(),g=y.runners.findIndex(S=>S.id===h);if(g<0)throw new Error(`shadow-store: runner not found: ${h}`);let b=qe(y.runners[g]);return b.status!=="stopped"&&(b.status="stopped",y.runners[g]=b,i(y)),qe(y.runners[g])}let f={create(h){return s(()=>c(h))},get(h){return u(h)},list(){return p()},update(h,y){return s(()=>l(h,y))},stop(h){return s(()=>d(h))}};return So.set(t,f),f}var Eo,Df,So,ra=w(()=>{Eo=1,Df=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];So=new Map});import{createHash as vo}from"node:crypto";function ko(e){return e==null?e:JSON.parse(JSON.stringify(e))}function Ao(e){return Array.isArray(e)?e.map(Ao):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Ao(e[t])])):e}function oa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("shadow-runner: record must be an object");return vo("sha256").update(JSON.stringify(Ao(e))).digest("hex")}function jf(e,t,r,n,o){return vo("sha256").update(`${e}|${t}|${r}|${n}|${o}`).digest("hex")}function Hf(e,t,r,n){return vo("sha256").update(`shadow|${e}|${t}|${r}|${n??""}`).digest("hex")}function zf(e){return e==="entryLong"||e==="exitShort"?"buy":e==="entryShort"||e==="exitLong"?"sell":e}function na(e){return e==="entryLong"||e==="entryShort"}function Io({storePath:e,clock:t=Date.now}={}){if(typeof e!="string"||!e)throw new Error("shadow-runner: storePath required");let r=ta({path:e});function n({strategy:c,evidenceId:u=null}={}){let p=le(c),l=u==null?null:String(u),d=r.list().filter(b=>b.status==="running"&&b.strategyHash===p.strategyHash&&b.compilerHash===p.compilerHash&&b.evidenceId===l).sort((b,S)=>b.createdAt-S.createdAt||b.id.localeCompare(S.id))[0];if(d)return ko(d);let f=t(),h=Hf(f,p.strategyHash,p.compilerHash,l),y=r.get(h);if(y)return ko(y);let g={id:h,strategy:ko(p.strategy),strategyHash:p.strategyHash,compilerHash:p.compilerHash,evidenceId:l,status:"running",cursor:null,intendedOrders:[],fills:[],missedFills:[],markouts:[],createdAt:f,updatedAt:f,position:null,cooldownBarsRemaining:0,cooldownStartT:null,lastProcessedBarIndex:-1};return r.create(g)}function o(c){return r.get(c)}function s(){return r.list()}function a(c){return r.stop(c)}function i(c,u,{markoutHorizons:p=[1,4,12]}={}){if(!Array.isArray(u))throw new TypeError("shadow-runner: bars must be an array");return r.update(c,l=>{if(l.status!=="running")throw new Error("shadow-runner: runner is stopped");if(u.length===0)return l;let f=le(l.strategy).evaluateAll(u),h=new Map;for(let x=0;x<u.length;x++)h.set(u[x].t,x);let y=l.cursor,g=[];for(let x=0;x<u.length;x++){let N=u[x].t;(y==null||N>y)&&g.push(x)}if(g.length===0)return l;let b=new Map(l.intendedOrders.map(x=>[x.id,x])),S=new Set(l.fills.map(x=>x.orderId)),I=new Map(l.missedFills.map(x=>[x.orderId,x])),A=(x,N)=>`${x}|${N}`,O=new Map(l.markouts.map(x=>[A(x.orderId,x.horizon),x])),_=l.position?{...l.position}:null,m=Number.isInteger(l.cooldownBarsRemaining)?Math.max(0,l.cooldownBarsRemaining):0,T=Number.isFinite(l.cooldownStartT)?l.cooldownStartT:null;function j({action:x,signalBarT:N,signalIndex:L}){let K=zf(x),W=jf(l.id,l.strategyHash,N,K,x);if(b.has(W))return b.get(W);let B=L+1,H=B<u.length,ie={id:W,action:x,type:x,side:K,signalBarT:N,fillBarT:H?u[B].t:null,status:H?"open":"missed"};return b.set(W,ie),l.intendedOrders.push(ie),ie}function se(x,N,L){if(S.has(x.id))return;let K={orderId:x.id,action:na(x.action)?"entry":"exit",side:x.side,price:N.o,barT:N.t,signalBarT:x.signalBarT,barIndex:L};if(l.fills.push(K),S.add(x.id),x.status="filled",x.fillBarT=N.t,I.has(x.id)&&(I.delete(x.id),l.missedFills=l.missedFills.filter(W=>W.orderId!==x.id)),na(x.action)){_={side:x.action==="entryLong"?"long":"short",entryOrderId:x.id,entryBarT:N.t,entryPrice:N.o,entryBarIndex:L};for(let W of p){let B=A(x.id,W);if(O.has(B))continue;let H={orderId:x.id,horizon:W,entryBarT:N.t,entryPrice:N.o,side:_.side,status:"pending",close:null,barT:null};O.set(B,H),l.markouts.push(H)}}else _=null,m=Number(l.strategy?.risk?.cooldownBars)||0,T=N.t}function Te(x){if(S.has(x.id)||I.has(x.id))return;let N={orderId:x.id,action:x.action,side:x.side,signalBarT:x.signalBarT,status:"missed"};I.set(x.id,N),l.missedFills.push(N),x.status="missed"}for(let x of l.intendedOrders){if(x.status==="filled"||S.has(x.id))continue;let N=h.get(x.signalBarT);if(N==null)continue;let L=N+1;L<u.length&&(y==null||u[L].t>y)&&se(x,u[L],L)}for(let x of g){let N=u[x],L=f[x].signals,K=_,W=H=>{if(_||m>0&&(T==null||N.t>=T))return;let re=j({action:H,signalBarT:N.t,signalIndex:x}),Re=x+1;Re<u.length?se(re,u[Re],Re):Te(re)},B=H=>{if(!_||_.side==="long"&&H!=="exitLong"||_.side==="short"&&H!=="exitShort")return;let ie=j({action:H,signalBarT:N.t,signalIndex:x}),re=x+1;re<u.length?se(ie,u[re],re):Te(ie)};K?(L.exitLong&&B("exitLong"),L.exitShort&&B("exitShort")):L.entryLong&&L.entryShort||(L.entryLong&&W("entryLong"),L.entryShort&&W("entryShort")),m>0&&T!=null&&N.t>=T&&(m-=1,m===0&&(T=null)),l.cursor=N.t,l.lastProcessedBarIndex=x}for(let x of l.markouts){if(x.status!=="pending")continue;let N=l.fills.find(W=>W.orderId===x.orderId&&W.action==="entry");if(!N)continue;let L=h.get(N.barT);if(L==null)continue;let K=L+x.horizon;if(K<u.length){x.close=u[K].c,x.barT=u[K].t,x.status="filled";let W=x.entryPrice;x.markout=x.side==="long"?(x.close-W)/W:(W-x.close)/W}}return l.position=_,l.cooldownBarsRemaining=m,l.cooldownStartT=T,l.updatedAt=t(),l})}return{start:n,step:i,list:s,get:o,stop:a}}var sa=w(()=>{it();ra()});var ca={};z(ca,{runStrategyOperation:()=>Jf});import Vf from"node:os";import Kf from"node:path";function rr(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Qf(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Co(e){if(Array.isArray(e)){for(let t of e)Co(t);return}if(rr(e))for(let[t,r]of Object.entries(e)){if(Wf.some(n=>Qf(t).includes(n)))throw new Error(`strategy service: secret-like field "${t}" is forbidden`);Co(r)}}function Gf(e){if(!rr(e))throw new TypeError("strategy input must be a plain object");return Co(e),e}function Yf(e,t={}){if(t.nowMs!==void 0){if(!Number.isInteger(t.nowMs))throw new TypeError("nowMs must be an integer epoch milliseconds");return t.nowMs}let r=Date.now();if(e.nowMs===void 0||e.nowMs===null)return r;if(!Number.isInteger(e.nowMs))throw new TypeError("nowMs must be an integer epoch milliseconds");if(Math.abs(e.nowMs-r)>12e4)throw new Error("nowMs outside allowed wall-clock skew (120s); omit nowMs to use server time");return e.nowMs}async function _o(e,t,r,n){if(Array.isArray(t.bars))return t.bars;let o=so(e.venue),s=r.fetchBars??o.fetchBars;if(typeof s!="function")throw new Error(`strategy venue ${o.id} does not support history`);let a=await s({coin:e.market.coin,interval:e.market.interval,count:t.count??1500,endTime:t.endTime??n}),i=Array.isArray(a)?a:a?.bars;if(!Array.isArray(i))throw new Error("strategy history provider returned no bars");return i}function Oo(e,t){let r=e.backtestOptions??{};if(!rr(r))throw new TypeError("backtestOptions must be a plain object");return{...r,nowMs:t}}function ia(e,t,r,n,o={}){let s=e.evidenceOptions??{};if(!rr(s))throw new TypeError("evidenceOptions must be a plain object");return{...s,...o,strategy:t,bars:r,backtestOptions:Oo(e,n)}}function aa(){return Kf.join(Vf.homedir(),".oracle","strategy-shadow.json")}function Xf(e,t){return{perStrategyNotionalUsd:e.risk.maxNotionalUsd,maxLeverage:e.risk.maxLeverage,dailyLossCapUsd:e.risk.maxNotionalUsd*(e.risk.maxDailyLossPct/100),chainAllowlist:[e.venue],assetAllowlist:[e.market.coin],expiresAt:Math.min(e.risk.expiresAt,t+864e5),killSwitchRequired:!0}}async function Jf(e,t={},r={}){let n=Gf(t),o=Yf(n,r);if(e==="draft")return{strategy:zi(n.prompt,{nowMs:o})};if(e==="validate"){let s=le(n.strategy);if(s.strategy.risk.expiresAt<=o)throw new Error("strategy is expired");return{valid:!0,strategy:s.strategy,strategyHash:s.strategyHash,compilerHash:s.compilerHash,compilerVersion:s.compilerVersion,requiredSeries:s.requiredSeries}}if(e==="backtest"||e==="evidence"){let s=le(n.strategy),a=await _o(s.strategy,n,r,o);er(s,a);let i=Zn(ia(n,s.strategy,a,o));return e==="evidence"?i:{backtest:We(s.strategy,a,Oo(n,o)),evidence:i}}if(e==="optimize"){let s=le(n.strategy),a=await _o(s.strategy,n,r,o);er(s,a);let i=n.trainFraction,c=n.evidenceOptions?.trainFraction;if(i!=null&&c!=null&&i!==c)throw new TypeError("conflicting trainFraction controls are forbidden");let u=i??c??.7;if(typeof u!="number"||u<=0||u>=1)throw new TypeError("trainFraction must be in (0,1)");let p=a.slice(0,Math.floor(a.length*u)),l=n.options??{};if(!rr(l))throw new TypeError("options must be a plain object");let d=Yi(s.strategy,p,{...l,...n.maxTrials==null?{}:{maxTrials:n.maxTrials},backtestOptions:Oo(n,o)}),f=d.bestStrategy;return{strategy:f,optimization:d,evidence:Zn(ia(n,f,a,o,{trainFraction:u}))}}if(e==="shadow"){let s=Io({storePath:r.storePath??aa(),clock:()=>o}),a=n.action;if(a==="start")return await s.start({strategy:n.strategy,evidenceId:n.evidenceId??n.evidence?.id??null});if(a==="list")return await s.list();if(a==="get")return await s.get(n.id);if(a==="stop")return await s.stop(n.id);if(a==="step"){let i=await s.get(n.id);if(!i)throw new Error(`shadow runner not found: ${n.id}`);let c=await _o(i.strategy,n,r,o);return er(le(i.strategy),c),await s.step(n.id,c,n.stepOptions??{})}throw new Error(`unknown shadow action: ${a}`)}if(e==="prepare"){let s=le(n.strategy),a=so(s.strategy.venue);if(typeof n.shadowId!="string"||!n.shadowId)throw new Error("strategy prepare requires a matching shadow runner id");let c=await Io({storePath:r.storePath??aa(),clock:()=>o}).get(n.shadowId);if(!c)throw new Error("strategy prepare shadow runner not found");if(c.status!=="running")throw new Error("strategy prepare requires an active shadow runner");if(!Number.isFinite(c.cursor))throw new Error("strategy prepare requires a stepped shadow runner");if(c.strategyHash!==s.strategyHash||c.compilerHash!==s.compilerHash)throw new Error("strategy prepare shadow runner does not match strategy artifacts");if(c.evidenceId!==n.evidence?.id)throw new Error("strategy prepare shadow runner does not match evidence artifact");let u=n.caps??Xf(s.strategy,o);return a.prepareIntent({strategy:s.strategy,evidence:n.evidence,shadow:{id:c.id,stateHash:oa(c),status:c.status,cursor:c.cursor,updatedAt:c.updatedAt},caps:u,nowMs:o,env:r.env??process.env})}throw new Error(`unknown strategy operation: ${e}`)}var Wf,ua=w(()=>{_r();it();eo();Vi();Xi();sa();io();Wf=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"]});var Ea={};z(Ea,{DEFAULT_CROSS_CHAIN_SOURCES:()=>ga,DEFAULT_SAME_CHAIN_SOURCES:()=>ha,NATIVE_TOKEN:()=>To,canonicalJson:()=>ba,hashFirmQuote:()=>Sa,hashRfqIntent:()=>xa,normalizeFirmQuote:()=>No,normalizeRfqIntent:()=>om,sha256Hex:()=>nr});import{createHash as Zf}from"node:crypto";import{getAddress as ma,isAddress as Ro}from"ethers";function J(e,t="invalid"){throw new Error(`rfq: ${e} ${t}`)}function da(e,t){let r=Number(e);return(!Number.isSafeInteger(r)||r<=0)&&J(t,"must be a positive chainId"),r}function qr(e,t){let r=String(e??"").trim();return(!em.test(r)||BigInt(r)<=0n)&&J(t,"must be a positive integer string"),r}function tm(e,t){return e==null||e===""?null:qr(e,t)}function pa(e,t){let r=String(e??"").trim();return r.toLowerCase()===To.toLowerCase()?To:(Ro(r)||J(t,"must be an EVM address or native token sentinel"),ma(r))}function ya(e,t){let r=String(e??"").trim();return Ro(r)||J(t,"must be an EVM address"),ma(r)}function rm(e,t){return e==null||e===""?null:ya(e,t)}function fa(e,t,r){return e===void 0?[...r]:(Array.isArray(e)||J(t,"must be an array"),e.map(n=>String(n).trim()).filter(Boolean))}function nm(e,{nowMs:t,maxDeadlineMs:r},n){let o=Number(e);return Number.isFinite(o)||J(n,"must be a finite millisecond timestamp"),o<=t&&J(n,"expired"),o>t+r&&J(n,"exceeds maxDeadlineMs"),Math.floor(o)}function _t(e){if(Array.isArray(e))return e.map(_t);if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())e[r]!==void 0&&(t[r]=_t(e[r]));return t}return e}function ba(e){return JSON.stringify(_t(e))}function nr(e){return`0x${Zf("sha256").update(ba(e)).digest("hex")}`}function wa(e,t){let r={...e};for(let n of t)delete r[n];return r}function xa(e){return nr(wa(e,["intentHash"]))}function Sa(e){return nr(wa(e,["firmQuoteHash"]))}function om(e={},t={}){let r=Number(t.nowMs??Date.now()),n=Number(t.maxDeadlineMs??1800*1e3);(!Number.isFinite(r)||!Number.isFinite(n)||n<=0)&&J("time","is invalid");let o=da(e.fromChainId??e.fromChain,"fromChainId"),s=da(e.toChainId??e.toChain,"toChainId"),i=o===s?ha:ga,c={kind:"rfq-intent",version:1,fromChainId:o,toChainId:s,sellToken:pa(e.sellToken??e.tokenIn??e.fromToken,"sellToken"),buyToken:pa(e.buyToken??e.tokenOut??e.toToken,"buyToken"),sellAmount:qr(e.sellAmount??e.amountIn??e.fromAmount,"sellAmount"),receiver:ya(e.receiver??e.recipient??e.to,"receiver"),deadlineMs:nm(e.deadlineMs??e.deadline??e.expiresAtMs,{nowMs:r,maxDeadlineMs:n},"deadline"),minBuyAmount:tm(e.minBuyAmount??e.minOut??e.amountOutMin,"minBuyAmount"),allowedSources:fa(e.allowedSources,"allowedSources",i),allowedRouters:fa(e.allowedRouters,"allowedRouters",[]),slippageBps:Number.isFinite(Number(e.slippageBps))?Number(e.slippageBps):null,partialFill:e.partialFill===!0,metadata:e.metadata&&typeof e.metadata=="object"&&!Array.isArray(e.metadata)?_t(e.metadata):{}};return c.slippageBps!=null&&(!Number.isInteger(c.slippageBps)||c.slippageBps<0||c.slippageBps>1e4)&&J("slippageBps","must be 0 to 10000"),c.intentId=e.intentId?String(e.intentId):nr({seed:"rfq-intent",intent:c}).slice(0,34),c.intentHash=xa(c),Object.freeze(c)}function sm(e){return(!e||typeof e!="object"||Array.isArray(e))&&J("artifact","required"),e.typedDataHash!=null&&!la.test(String(e.typedDataHash))&&J("artifact.typedDataHash","must be bytes32"),e.calldataHash!=null&&!la.test(String(e.calldataHash))&&J("artifact.calldataHash","must be bytes32"),e.to!=null&&!Ro(String(e.to))&&J("artifact.to","must be an address"),e.data!=null&&!/^0x(?:[0-9a-fA-F]{2})*$/.test(String(e.data))&&J("artifact.data","must be hex"),_t(e)}function No(e,t={},r={}){(!e||e.kind!=="rfq-intent")&&J("intent","required");let n=Number(r.nowMs??Date.now()),o=Number(t.expiryMs??t.expiresAtMs??t.validUntilMs);Number.isFinite(o)||J("quote expiry","required"),o<=n&&J("quote","expired"),o>e.deadlineMs&&J("quote expiry","exceeds intent deadline");let s=String(t.source??t.provider??"").trim();s||J("source","required"),e.allowedSources.includes(s)||J("source","not allowed by intent");let a=qr(t.amountOut??t.buyAmount,"amountOut"),i=qr(t.minBuyAmount??t.minOut??a,"minBuyAmount");BigInt(i)>BigInt(a)&&J("minBuyAmount","exceeds amountOut");let c=sm(t.artifact??t.executableArtifact??t.transaction??t.typedData),u=Number(t.quotedAtMs??t.timestampMs??r.nowMs??Date.now());Number.isFinite(u)||J("quotedAtMs","must be finite");let p=rm(t.router??t.settlementRouter??c.to,"router"),l={kind:"rfq-firm-quote",provider:"rfq",surface:"rfq",version:1,quoteId:String(t.quoteId??t.id??"").trim(),source:s,intentHash:e.intentHash,fromChainId:e.fromChainId,toChainId:e.toChainId,sellToken:e.sellToken,buyToken:e.buyToken,sellAmount:e.sellAmount,receiver:e.receiver,router:p,amountOut:a,minBuyAmount:i,quotedAtMs:Math.floor(u),expiryMs:Math.floor(o),artifact:c,maker:t.maker?String(t.maker):null,metadata:t.metadata&&typeof t.metadata=="object"&&!Array.isArray(t.metadata)?_t(t.metadata):{}};return l.quoteId||(l.quoteId=nr({seed:"rfq-quote",out:l}).slice(0,34)),l.firmQuoteHash=Sa(l),Object.freeze(l)}var To,ha,ga,la,em,$o=w(()=>{To="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",ha=Object.freeze(["lifi","paraswap","0x","cow","uniswap-v3"]),ga=Object.freeze(["lifi"]),la=/^0x[0-9a-fA-F]{64}$/,em=/^\d+$/});import{readFileSync as im}from"node:fs";import{homedir as am}from"node:os";import{join as Br}from"node:path";function cm(){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=am();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Br(t,".config","oracle")).trim();return[e,Br(r,"exec.env")].filter(Boolean)}return[e,Br(t,".config","oracle","exec.env"),Br(t,".config","mad-desk","exec.env")].filter(Boolean)}function ka(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of cm())try{let s=im(o,"utf8"),a=s.match(new RegExp(`^${t}=(.*)$`,"m"))||s.match(new RegExp(`^${r}=(.*)$`,"m"));if(a&&(n=a[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}var Aa=w(()=>{});var va=w(()=>{});import{createHash as um,createHmac as lm,timingSafeEqual as yx}from"node:crypto";function qo(e){return Array.isArray(e)?`[${e.map(qo).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${qo(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function dm(e,{required:t=!1}={}){try{return ka(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Ca(e){let{signature:t,...r}=e;return r}function Oa(e,{secret:t}={}){let r=dm(t);return r?{...e,signature:lm("sha256",r).update(qo(Ca(e))).digest("hex")}:e}function pm(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 um("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function Ee(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 Oa({...Ca(e),calldataHash:pm(n)},{secret:o})}function Po(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function fm(e){let t=e==null?Ia: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,Ia)}function Me({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:o}={}){let s=Po(e,0),a=s>0?s>=25e4?5:s>=1e5?10:s>=5e4?20:s>=1e4?40:70:n?30:10,i=Math.min(60,Math.abs(Po(t,0))*2),c=Math.min(40,Math.floor(Math.max(0,Po(r,0))/5e3)*5),u=Math.max(25,Math.ceil(20+a+i+c)),p=fm(o);return{mode:"auto",requiredBps:u,selectedBps:Math.min(u,p),capBps:p,executable:u<=p}}function mm({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:o=0,quoteAgeMs:s=0,crossChain:a=!1,requestedCapBps:i,quotedAtMs:c=Date.now(),ttlMs:u=_a,secret:p}={}){let l=BigInt(r??0);if(l<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let d=Me({liquidityUsd:n,priceChange5m:o,quoteAgeMs:s,crossChain:a,requestedCapBps:i});if(!d.executable)throw new Error(`auto-slippage requires ${d.requiredBps} bps above hard/requested cap ${d.capBps}; route blocked`);let f=Number(c);if(!Number.isFinite(f))throw new Error("auto-slippage: quotedAtMs must be a finite number");let h=Math.min(3e4,Math.max(1e3,Number(u)||_a)),y=l*BigInt(1e4-d.selectedBps),g=y/10000n;if(y%10000n!==0n&&(g+=1n),g>l&&(g=l),l>0n&&g<=0n)throw new Error(`auto-slippage: quote ${l} is too small to express a ${d.selectedBps} bps floor without rounding to zero`);let b=Number((l-g)*10000n/(l===0n?1n:l));if(b>d.capBps)throw new Error(`auto-slippage: realised floor implies ${b} bps, above cap ${d.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Oa({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:l.toString(),minAmountOut:g.toString(),requiredBps:d.requiredBps,selectedBps:d.selectedBps,capBps:d.capBps,quotedAtMs:f,expiresAtMs:f+h},{secret:p})}function oe(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:o,priceChange5m:s,crossChain:a,requestedCapBps:i,quotedAtMs:c=Date.now(),ttlMs:u}={}){let p=mm({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:o,priceChange5m:s,crossChain:a,requestedCapBps:i,quotedAtMs:c,ttlMs:u});return{...e,autoSlippage:p,amountOutMinimum:p.minAmountOut}}var Ia,_a,je=w(()=>{Aa();va();Ia=100,_a=2e4});function Bo(e){let t=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:Ye}var Ye,Ur=w(()=>{Ye="0x000000000000000000000000000000000000dEaD"});import{Contract as hm,JsonRpcProvider as gm}from"ethers";function Em(e){return Sm.test(String(e||""))}async function Ta(e,{contract:t=ym,rpc:r=wm,chainId:n=bm,balanceOf:o}={}){if(!Em(e))throw new Error("invalid-address");if(o)return BigInt(await o(e));let s=new gm(r,n,{staticNetwork:!0}),a=new hm(t,xm,s);return BigInt(await a.balanceOf(e))}var ym,bm,wm,xm,Sm,Ra=w(()=>{ym="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",bm=999,wm="https://rpc.hyperliquid.xyz/evm",xm=["function balanceOf(address owner) view returns (uint256)"],Sm=/^0x[a-fA-F0-9]{40}$/});import{existsSync as km,readFileSync as Am}from"node:fs";import{homedir as vm}from"node:os";import{join as Na}from"node:path";function Cm(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call($a,t)?$a[t]:_m}function $m(e=process.env){if(e[Pa])return String(e[Pa]);let t=e.ORACLE_CONFIG_DIR||Na(vm(),".config","oracle");return Na(t,"fee-recipient")}function Pm(e=process.env){try{let t=$m(e);if(!km(t))return"";let r=Am(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function qm(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),Im)}function Bm({env:e=process.env,action:t="swap"}={}){let r=String(e[Tm]||"").trim(),n=Cm(t),o=qm(e[Om],{fallback:r?n:0}),s=Math.min(o,n),a=String(e[Rm]||Nm).trim();if(!s)return{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(r))return{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"no-recipient"};let i=Pm(e);return i&&i!==r.toLowerCase()?{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:s,recipient:r,integrator:a,action:t,applies:!0,reason:"configured"}}async function Dr({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={}}={}){let o=Bm({env:t,action:r}),s=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(s))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await Ta(s,n))>0n?{...o,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...o,holderVerificationStatus:"non-holder"}}catch{return{...o,holderVerificationStatus:"unavailable"}}}function qa(e){return e?.applies?`Oracle routing fee ${e.bps} bps (${(e.bps/100).toFixed(2)}%) to ${e.recipient}.`:e?.reason==="locals-only-holder"?"No Oracle fee (Locals Only holder).":"No Oracle fee."}function Ba(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function Ua(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var Im,_m,$a,Om,Tm,Rm,Pa,Nm,Lr=w(()=>{Ra();Im=100,_m=5,$a=Object.freeze({swap:5,bridge:5,perps:0,nft:0});Om="ORACLE_INTEGRATOR_FEE_BPS",Tm="ORACLE_INTEGRATOR_FEE_RECIPIENT",Rm="ORACLE_INTEGRATOR_ID",Pa="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",Nm="oracle"});var Lo={};z(Lo,{LIFI_API:()=>La,lifiChains:()=>Mm,lifiHealth:()=>Lm,lifiPrepare:()=>Fm,lifiQuote:()=>ct});function Do(e={}){return(e.baseUrl||process.env.LIFI_API_URL||La).replace(/\/$/,"")}function Dm(e){let t=String(e||Uo).toLowerCase();return t===Uo.toLowerCase()||t===Um}function Da(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 Lm(e={}){let t=await v(`${Do(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 ct(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:o=Uo,toToken:s,fromAmount:a,fromAddress:i=Ye}=e;if(r==null||!s||!a)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let c=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:o,toToken:s,fromAmount:String(a),fromAddress:i}),u=Me({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 Dr({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[g,b]of Object.entries(Ba(p)))c.set(g,b);let l=await v(`${Do(t)}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),d=l?.estimate?.toAmount||l?.toAmount;if(!d)return{...l,autoSlippagePolicy:u,oracleFee:p};let f=l?.transactionRequest?.to||l?.estimate?.approvalAddress||"lifi",h=oe(l,{chainId:Number(r),venue:f,amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),y=l?.estimate?.toAmountMin||l?.toAmountMin;if(y!=null&&BigInt(y)<BigInt(h.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...h,oracleFee:p}}async function Fm(e={},t={}){let r=await ct(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 s=null;if(!Dm(e.fromToken)){let a=r?.estimate?.approvalAddress||r?.approvalAddress;if(!a)throw new Error("lifi: ERC20 route missing approvalAddress");let i=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;s={token:Da(i,"approval token"),spender:Da(a,"approval spender"),amount:String(e.fromAmount)}}return Q({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:o,quote:r,autoSlippage:r.autoSlippage,requiresApproval:s,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:Ee(r.autoSlippage,{chainId:o,venue:n.to,data:n.data})}},{provider:"lifi",kind:"lifi-tx"})}async function Mm(e={}){return v(`${Do(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var La,Uo,Um,or=w(()=>{F();je();Ur();de();Lr();La="https://li.quest/v1";Uo="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Um="0x0000000000000000000000000000000000000000"});var ja={};z(ja,{PARASWAP_API:()=>Fa,paraswapHealth:()=>Hm,paraswapPrepare:()=>jm,paraswapPrice:()=>Ot,paraswapTokens:()=>Ma});function Ct(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 Ma(e={},t={}){let r=Number(e.chainId||1);return v(`${Fo(t)}/tokens/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Ot(e={},t={}){let r=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let n=new URLSearchParams({srcToken:Ct(e.srcToken,"srcToken"),destToken:Ct(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 Dr({wallet:e.userAddress||e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[i,c]of Object.entries(Ua(o)))n.set(i,c);let s=await v(`${Fo(t)}/prices?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=s?.priceRoute?.destAmount;return a?{...oe(s,{chainId:r,venue:s?.priceRoute?.contractAddress||"paraswap-quote",amountOut:a,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,quoteAgeMs:0,requestedCapBps:e.maxSlippageBps??e.slippageBps}),executionReady:!1,executionBlocker:"call prepare to bind the price route to a validated transaction",oracleFee:o}:{...s,executionReady:!1,oracleFee:o}}async function jm(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=Ct(e.userAddress,"userAddress"),o=await Ot(e,t),s=o?.priceRoute,a=String(s?.contractAddress||"").toLowerCase();if(!a)throw new Error("paraswap: price route missing contractAddress");let i={srcToken:Ct(e.srcToken,"srcToken"),destToken:Ct(e.destToken,"destToken"),srcAmount:String(s.srcAmount||e.amount),destAmount:String(o.amountOutMinimum),priceRoute:s,userAddress:n,ignoreChecks:!1,ignoreGasEstimate:!1};e.receiver&&(i.receiver=Ct(e.receiver,"receiver"));let c=await v(`${Fo(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()!==a)throw new Error("paraswap: transaction target mismatch");if(c.from&&String(c.from).toLowerCase()!==n)throw new Error("paraswap: transaction sender mismatch");return Q({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:s.tokenTransferProxy||a,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:Ee(o.autoSlippage,{chainId:r,venue:c.to,data:c.data})}},{provider:"paraswap",kind:"paraswap-tx"})}async function Hm(e={}){let t=await Ma({chainId:1},e),r=Array.isArray(t?.tokens)?t.tokens.length:Object.keys(t?.tokens||{}).length;return{ok:r>0,tokenSample:r}}var Fa,Fo,Fr=w(()=>{F();je();de();Lr();Fa="https://api.paraswap.io",Fo=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||Fa).replace(/\/$/,"")});function Mr({provider:e,defaultUrl:t,hosts:r=[],url:n,strict:o=!1}){let a=(String(n??"").trim()||String(t)).replace(/\/$/,"");if(a===String(t).replace(/\/$/,""))return{baseUrl:a,trusted:!0,host:za(t)};let i;try{i=new URL(a)}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([za(t),...r]).has(c)){let p=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return i.protocol==="http:"&&!p?{baseUrl:a,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:a,trusted:!0,host:c}}if(String(process.env[Ha]||"")==="1")return{baseUrl:a,trusted:!1,host:c};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${Ha}=1 to permit it)`);return{baseUrl:a,trusted:!1,host:c}}function za(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function jr(e,t,r){let n={...e};if(!r)return n;for(let[o,s]of Object.entries(t||{}))s&&(n[o]=s);return n}var Ha,Mo=w(()=>{Ha="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});var Ya={};z(Ya,{ZEROX_API:()=>Va,zeroxHealth:()=>zm,zeroxPrepare:()=>Vm,zeroxPrice:()=>Ga,zeroxQuote:()=>Tt});function Ka(e={}){return Mr({provider:"zerox",defaultUrl:Va,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function Wa(e={}){return Ka(e).baseUrl}function Hr(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function Qa(e={}){return jr({"0x-version":"v2",accept:"application/json"},{"0x-api-key":Hr(e)},Ka(e).trusted)}async function zm(e={}){if(!Hr(e))return{ok:!1,configured:!1,error:"ZEROX_API_KEY not set"};try{let t=await Ga({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 Ga(e={},t={}){if(!Hr(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:s,taker:a}=e;if(!n||!o||!s)throw new Error("zeroxPrice requires sellToken, buyToken, sellAmount");let i=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:o,sellAmount:String(s)});return a&&i.set("taker",a),v(`${Wa(t)}/swap/allowance-holder/price?${i}`,{headers:Qa(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function Tt(e={},t={}){if(!Hr(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:s,taker:a}=e;if(!n||!o||!s)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let i=Me({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(s),slippageBps:String(i.selectedBps)});a&&c.set("taker",a);let u=await v(`${Wa(t)}/swap/allowance-holder/quote?${c}`,{headers:Qa(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),p=u?.buyAmount||u?.grossBuyAmount;return p?oe(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 Vm(e={},t={}){if(!e.taker)throw new Error("0x: taker required for executable prepare");let r=await Tt(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),s=r?.issues?.allowance?.spender||r?.allowanceTarget;return Q({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:s,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:Ee(r.autoSlippage,{chainId:o,venue:n.to,data:n.data})}},{provider:"zerox",kind:"zerox-tx"})}var Va,zr=w(()=>{F();je();Mo();de();Va="https://api.0x.org"});var zx,Xa=w(()=>{zx=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});var ac={};z(ac,{COW_CANCEL_TYPES:()=>rc,COW_HOSTS:()=>Ho,COW_ORDER_TYPES:()=>Vr,COW_SETTLEMENT:()=>Za,COW_VAULT_RELAYER:()=>ec,cowCancelOrders:()=>n0,cowChains:()=>i0,cowHealth:()=>Ym,cowOrder:()=>ic,cowOrderStatus:()=>sc,cowOrderUid:()=>Jm,cowPrepareCancel:()=>t0,cowPrepareOrder:()=>Xm,cowQuote:()=>ut,cowSignCancel:()=>r0,cowSignOrder:()=>Zm,cowSubmitSignedOrder:()=>e0,cowVerifyOrderFill:()=>s0});import{TypedDataEncoder as Ja,getAddress as sr,isAddress as Km}from"ethers";function Kr(e,t={}){if(t.baseUrl)return t.baseUrl.replace(/\/$/,"");let r=Ho[Number(e)];if(!r)throw new Error(`cowswap: unsupported chainId ${e}`);return r}function Wm(e,t="v1",r={}){let n=Kr(e,r);return t==="v1"?n:n.replace(/\/api\/v1$/,`/api/${t}`)}function Xe(e,t){let r=String(e||"").trim();if(!Km(r))throw new Error(`cowswap: ${t} must be an address`);return sr(r).toLowerCase()}function Rt(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 nc(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 oc(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 Qm({digest:e,owner:t,validTo:r}={}){let n=nc(e,"order digest").slice(2),o=Xe(t,"owner").slice(2).toLowerCase(),s=Number(r);if(!Number.isInteger(s)||s<0||s>4294967295)throw new Error("cowswap: validTo must fit uint32");return`0x${n}${o}${s.toString(16).padStart(8,"0")}`.toLowerCase()}function zo(e){let t=Za[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:sr(t)}}function Gm(e={},t,r){let n=Xe(e.sellToken,"sellToken"),o=Xe(e.buyToken,"buyToken"),s=Xe(e.receiver||r,"receiver"),a=Number(e.validTo);if(!Number.isInteger(a)||a<=0)throw new Error("cowswap: quote.validTo required");let i=nc(e.appData||e.appDataHash||`0x${"0".repeat(64)}`,"appData");return{sellToken:n,buyToken:o,receiver:s,sellAmount:Rt(e.sellAmount,"sellAmount"),buyAmount:Rt(e.buyAmount,"buyAmount"),validTo:a,appData:i,feeAmount:Rt(e.feeAmount??"0","feeAmount"),kind:String(e.kind||"sell"),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance||"erc20"),buyTokenBalance:String(e.buyTokenBalance||"erc20")}}async function Ym(e={}){try{let t=await ut({chainId:1,sellToken:jo[1],buyToken:tc[1],sellAmountBeforeFee:"1000000000000000",from:Ye},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 ut(e={},t={}){let r=Number(e.chainId??1),n=Bo(e.from||e.owner),o=e.sellToken||jo[r],s=e.buyToken||tc[r],a=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!o||!s||a==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(o)&&(o=jo[r],!o))throw new Error("no WETH mapping for chain");let i={sellToken:o,buyToken:s,from:n,receiver:e.receiver||n,sellAmountBeforeFee:a,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},c=await v(`${Kr(r,t)}/quote`,{method:"POST",body:i,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),u=c?.quote?.buyAmount||c?.buyAmount;return u?oe(c,{chainId:r,venue:"cowswap-order",amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):c}async function Xm(e={},t={}){let r=Number(e.chainId??1),n=Xe(Bo(e.from||e.owner||e.signer),"owner"),o=await ut({...e,chainId:r,from:n,signingScheme:e.signingScheme||"eip712"},t),s=Gm(o?.quote||o,r,n),a=zo(r),i={domain:a,types:Vr,primaryType:"Order",message:s},c=Ja.hash(a,Vr,s),u=ec[r];if(!u)throw new Error(`cowswap: vault relayer not registered for chain ${r}`);return Q({provider:"cowswap",orderReady:!0,executionReady:!1,chainId:r,owner:n,signingScheme:"eip712",settlement:a.verifyingContract.toLowerCase(),vaultRelayer:sr(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:a.verifyingContract.toLowerCase(),vaultRelayer:sr(u).toLowerCase(),sellToken:s.sellToken,buyToken:s.buyToken,sellAmount:s.sellAmount,buyAmount:s.buyAmount,validTo:s.validTo,quoteId:o?.id??e.quoteId??null,typedDataHash:c,issuedAtMs:Date.now(),expiresAtMs:Math.min(s.validTo*1e3,Date.now()+2e4)},requiresApproval:{token:s.sellToken,spender:sr(u).toLowerCase(),amount:s.sellAmount}},{provider:"cowswap",kind:"cow-order"})}async function sc(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrderStatus requires uid");return v(`${Kr(r,t)}/orders/${encodeURIComponent(n)}/status`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ic(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrder requires uid");return v(`${Kr(r,t)}/orders/${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}function Jm(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||Ja.hash(zo(r),Vr,n),s=e.owner||e.from||e.signer||n.receiver;return Qm({digest:o,owner:s,validTo:n.validTo})}async function Zm(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 e0(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 t0(e={}){let t=Number(e.chainId??1),r=Xe(e.owner||e.from||e.signer,"owner"),n=(e.orderUids||e.uids||[e.uid]).filter(Boolean).map((a,i)=>oc(a,`orderUids[${i}]`));if(!n.length)throw new Error("cowswap: orderUids required");let o=zo(t);return Q({provider:"cowswap",chainId:t,owner:r,orderUids:n,signingScheme:"eip712",typedData:{domain:o,types:rc,primaryType:"OrderCancellations",message:{orderUids:n}},cancelReady:!0,executableArtifact:!0},{provider:"cowswap",kind:"cow-cancel"})}async function r0(e={},t={}){throw new Error("cowswap.cowSignCancel refused: @oracle-agent/oracle is prepare-only. Cancel-sign with the user wallet.")}async function n0(e={},t={}){throw new Error("cowswap.cowCancelOrders refused: @oracle-agent/oracle is prepare-only. Cancel from the user wallet or local operator.")}function o0(e={}){return Rt(e.buyAmount??e.executedBuyAmount??"0","trade.buyAmount")}async function s0(e={},t={}){let r=Number(e.chainId??1),n=oc(e.uid||e.orderUid),o=t.order||await ic({chainId:r,uid:n},t),s=t.status||o.status||await sc({chainId:r,uid:n},t).catch(()=>null),a=t.trades||await v(`${Wm(r,"v2",t)}/trades?orderUid=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),i=Array.isArray(a)?a:[],c=e.expectedOwner?Xe(e.expectedOwner,"expectedOwner"):null;if(c&&Xe(o.owner||i[0]?.owner||c,"owner")!==c)return{ok:!1,provider:"cowswap",chainId:r,uid:n,reason:"owner mismatch",order:o,status:s,trades:i};let u=0n;for(let d of i.filter(f=>String(f.orderUid||"").toLowerCase()===n))u+=BigInt(o0(d));u===0n&&o.executedBuyAmount!=null&&(u=BigInt(Rt(o.executedBuyAmount,"executedBuyAmount")));let p=e.minBuyAmount!=null?BigInt(Rt(e.minBuyAmount,"minBuyAmount")):0n,l=u>=p&&String(o.status||s?.status||"").toLowerCase()!=="expired";return{ok:l,provider:"cowswap",chainId:r,uid:n,status:o.status||s?.status||null,executedBuyAmount:u.toString(),minBuyAmount:e.minBuyAmount??null,trades:i,settlementTxs:[...new Set(i.map(d=>d.txHash).filter(Boolean))],order:o,orderStatus:s,reason:l?null:"insufficient fill or expired order"}}function i0(){return Object.keys(Ho).map(Number)}var Ho,Za,ec,jo,tc,Vr,rc,Wr=w(()=>{F();je();Xa();Ur();de();Ho={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"},Za=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),ec=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),jo={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},tc={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},Vr=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"}]}),rc=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function uc(e){return a0.get(Number(e))||null}function lc(e,t=process.env){let r=uc(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}var cc,a0,dc=w(()=>{cc={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}},a0=new Map(Object.values(cc).map(e=>[e.chainId,e]))});import{Interface as c0,getAddress as u0}from"ethers";function ir(e,t){try{return u0(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function d0(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=lc(e,r);return n||l0[Number(e)]||null}function f0(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!p0.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 ee(e,t,r=[],n={}){let o=String(t||"");f0(o);let s=d0(e,n);if(!s)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let i=await v(s,{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 Gr(e,t={}){let r=await ee(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function pc(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await ee(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function fc(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=ir(e.token||e.tokenAddress,"token"),o=ir(e.owner,"owner"),s=ir(e.spender,"spender"),a=Qr.encodeFunctionData("allowance",[o,s]),i=await ee(r,"eth_call",[{to:n,data:a},e.blockTag||"latest"],t),c=Qr.decodeFunctionResult("allowance",i),u=BigInt(c[0]);return{chainId:r,token:n,owner:o,spender:s,allowance:u.toString(),allowanceHex:`0x${u.toString(16)}`,blockTag:e.blockTag||"latest"}}async function mc(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=ir(e.token||e.tokenAddress,"token"),o=ir(e.account||e.owner||e.address,"account"),s=Qr.encodeFunctionData("balanceOf",[o]),a=await ee(r,"eth_call",[{to:n,data:s},e.blockTag||"latest"],t),i=Qr.decodeFunctionResult("balanceOf",a),c=BigInt(i[0]);return{chainId:r,token:n,account:o,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var Qr,l0,p0,lt=w(()=>{F();dc();Qr=new c0(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);l0={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"};p0=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/});function y0(e,t,r){let n=ke(t),o=ke(r),s=ke(e?.baseToken?.address),a=ke(e?.quoteToken?.address);return s===n&&a===o||s===o&&a===n}function b0(e){let t=Number(e?.liquidity?.usd);return Number.isFinite(t)&&t>=0?t:null}function w0(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||m0).replace(/\/$/,"")}async function Vo(e,t={}){if(!e)throw new Error("tokenAddress required");return v(`${w0(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function Yr({chainId:e,tokenA:t,tokenB:r,dexIds:n=[]}={},o={}){if(e==null||!t||!r)throw new Error("chainId, tokenA, and tokenB required");let s=ke(h0[Number(e)]||e),a=new Set(g0(n).filter(Boolean).map(ke)),i=[...new Set([t,r].map(d=>String(d)).filter(Boolean))],c=await Promise.allSettled(i.map(d=>Vo(d,{...o,baseUrl:o.dexscreenerBaseUrl,timeoutMs:o.dexscreenerTimeoutMs??Math.min(Number(o.timeoutMs??4e3),4e3)}))),u=new Set,p=[];for(let d of c)if(d.status==="fulfilled")for(let f of d.value?.pairs||d.value?.data?.pairs||[]){let h=`${ke(f?.chainId)}:${ke(f?.dexId)}:${ke(f?.pairAddress)}`;u.has(h)||(u.add(h),p.push(f))}return p.filter(d=>ke(d?.chainId)===s).filter(d=>y0(d,t,r)).filter(d=>!a.size||a.has(ke(d?.dexId))).map(d=>({pairAddress:d.pairAddress??null,dexId:d.dexId??null,chainId:d.chainId??null,liquidityUsd:b0(d),pairCreatedAt:d.pairCreatedAt??null})).filter(d=>d.liquidityUsd!=null).sort((d,f)=>f.liquidityUsd-d.liquidityUsd)[0]??null}var m0,h0,ke,g0,Xr=w(()=>{F();m0="https://api.dexscreener.com",h0=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"}),ke=e=>String(e??"").toLowerCase(),g0=e=>Array.isArray(e)?e:e==null?[]:[e]});var Ec={};z(Ec,{PANCAKE_FEE_TIERS:()=>Jr,UNI_V3_CHAINS:()=>pe,UNI_V3_FEE_TIERS:()=>yc,UNI_V3_VENUES:()=>xc,uniV3Chains:()=>I0,uniV3EthUsdc:()=>Sc,uniV3Health:()=>v0,uniV3PrepareExactIn:()=>A0,uniV3QuoteExactIn:()=>dt,uniV3QuoteExactInPath:()=>k0});import{Interface as gc,getAddress as ar,isAddress as x0}from"ethers";function Wo(e,t){let r=Number(e),n=pe[r];if(!n)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys(pe).join(", ")})`);let o=xc[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 s=String(t).toLowerCase();if(s===n.name&&n.quoter&&n.router)return{chainId:r,venue:n.name,...n};let a=o,i=a[s];if(!i){let c=[...n.quoter&&n.router?[n.name]:[],...Object.keys(a)].join(", ");throw new Error(`uniswap-v3: unknown venue "${t}" on chain ${r} (known: ${c})`)}return{chainId:r,venue:s,...n,quoter:i.quoter,router:i.router,feeTiers:i.feeTiers||null}}function Ko(e,t){let r=pe[Number(t)];if(!e||e===bc||e===wc||/^eth$/i.test(String(e)))return ar(r.weth);let n=String(e);if(/^weth$/i.test(n))return ar(r.weth);if(/^usdc$/i.test(n))return ar(r.usdc);if(!x0(n))throw new Error(`invalid token address: ${e}`);return ar(n)}function S0(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 E0(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 dt(e={},t={}){let{chainId:r,quoter:n,router:o,feeTiers:s}=Wo(e.chainId??8453,e.venue),a=Ko(e.tokenIn||"WETH",r),i=Ko(e.tokenOut||pe[r].usdc,r),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");let u=s&&s.length?s:yc,p=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[u[Math.min(2,u.length-1)]]:[...u],l=[],d=null;for(let y of p){let g=Zr.encodeFunctionData("quoteExactInputSingle",[{tokenIn:a,tokenOut:i,amountIn:c,fee:y,sqrtPriceLimitX96:0n}]);try{let b=await ee(r,"eth_call",[{to:n,data:g},"latest"],t);if(!b||b==="0x"){l.push({fee:y,ok:!1,error:"empty result"});continue}let S=Zr.decodeFunctionResult("quoteExactInputSingle",b),I={fee:y,ok:!0,amountOut:S[0].toString(),sqrtPriceX96After:S[1].toString(),initializedTicksCrossed:Number(S[2]),gasEstimate:S[3].toString()};l.push(I),(!d||BigInt(I.amountOut)>BigInt(d.amountOut))&&(d=I)}catch(b){l.push({fee:y,ok:!1,error:String(b.message||b).slice(0,160)})}}if(!d){let y=l.map(g=>`${g.fee}:${g.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${r}: ${y}`)}let f=e.liquidityUsd==null?await Yr({chainId:r,tokenA:a,tokenB:i,dexIds:S0(e.venue)},t).catch(()=>null):null,h=e.liquidityUsd??f?.liquidityUsd??null;return oe({venue:"uniswap-v3",chainId:r,chain:pe[r].name,quoter:n,tokenIn:a,tokenOut:i,amountIn:c.toString(),fee:d.fee,amountOut:d.amountOut,gasEstimate:d.gasEstimate,liquidityUsd:h,liquiditySource:f,sqrtPriceX96After:d.sqrtPriceX96After,initializedTicksCrossed:d.initializedTicksCrossed,triedFees:l,best:!0},{chainId:r,venue:o,amountOut:d.amountOut,liquidityUsd:h,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function k0(e={},t={}){let{chainId:r,quoter:n,router:o}=Wo(e.chainId??8453),s=(e.tokens||[]).map(d=>Ko(d,r)),a=(e.fees||[]).map(Number);if(s.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=E0(s,a),u=Zr.encodeFunctionData("quoteExactInput",[c,i]),p=await ee(r,"eth_call",[{to:n,data:u},"latest"],t),l=Zr.decodeFunctionResult("quoteExactInput",p);return oe({venue:"uniswap-v3",chainId:r,chain:pe[r].name,quoter:n,tokens:s,fees:a,path:c,amountIn:i.toString(),amountOut:l[0].toString(),gasEstimate:l[3].toString()},{chainId:r,venue:o,amountOut:l[0].toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Sc(e={},t={}){let r=Number(e.chainId??8453),n=e.amountIn??"1000000000000000",o=await dt({chainId:r,tokenIn:pe[r].weth,tokenOut:pe[r].usdc,amountIn:n,fee:e.fee},t),s=Number(o.amountOut)/1e6;return{...o,amountOutUsdc:s,pair:"WETH/USDC"}}async function A0(e={},t={}){let r=Number(e.chainId??8453),n=Wo(r,e.venue),o=ar(e.recipient),s=String(e.tokenIn||"WETH"),a=!e.tokenIn||s===bc||s===wc||/^eth$/i.test(s),i=await dt(e,t),c=hc.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))),l=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+u,d=hc.encodeFunctionData("multicall",[l,[c]]);return Q({provider:"uniswap-v3",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:l,quote:i,autoSlippage:i.autoSlippage,requiresApproval:a?null:{token:i.tokenIn,spender:n.router,amount:i.amountIn},transaction:{chainId:r,from:o,to:n.router,data:d,value:a?i.amountIn:"0",slippageGuard:Ee(i.autoSlippage,{chainId:r,venue:n.router,data:d})}},{provider:"uniswap-v3",kind:"univ3-swap-tx"})}async function v0(e={}){let t=Number(e.chainId??8453);try{let r=await Sc({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 I0(){return Object.entries(pe).map(([e,t])=>({chainId:Number(e),name:t.name,quoter:t.quoter,weth:t.weth,usdc:t.usdc}))}var pe,yc,Zr,hc,bc,wc,Jr,xc,en=w(()=>{lt();Xr();je();de();pe={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"}},yc=[100,500,3e3,1e4],Zr=new gc(["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)"]),hc=new gc(["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)"]),bc="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",wc="0x0000000000000000000000000000000000000000",Jr=[100,500,2500,1e4],xc={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Jr}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Jr}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Jr}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}}});var _c={};z(_c,{executeRfqCandidates:()=>vc,rankRfqQuotes:()=>Ic,requestRfqQuotes:()=>O0,sourceCandidates:()=>Ac});function cr(e,t){return Array.isArray(e?.allowedSources)&&e.allowedSources.includes(t)}function kc(e,t){return String(e?.[t]??"").trim()}function ur(e,t){return Object.freeze({source:e,run:t})}function Ac(e,t={}){if(!e||e.kind!=="rfq-intent")throw new Error("rfq: intent required");let r=t.env??process.env,n=t.providers??{},o=t.supportedUniV3Chains??pe,s=Number(e.fromChainId)===Number(e.toChainId),a=[];return cr(e,"lifi")&&a.push(ur("lifi",async()=>{let c=await(n.lifiQuote??ct)({fromChain:e.fromChainId,toChain:e.toChainId,fromToken:e.sellToken,toToken:e.buyToken,fromAmount:e.sellAmount,fromAddress:e.receiver},t),u=c?.estimate??c?.[0]?.estimate??c;return{quoteId:c?.id??c?.routeId??null,amountOut:u?.toAmount??c?.toAmount,minBuyAmount:u?.toAmountMin??c?.toAmountMin??u?.toAmount??c?.toAmount,expiryMs:Date.now()+Number(t.defaultQuoteTtlMs??2e4),artifact:{type:"lifi-route",calldataHash:c?.transactionRequest?.data?await _0(t,c.transactionRequest.data):void 0,route:c},metadata:{tool:c?.tool??c?.toolDetails?.name??null}}})),s&&(cr(e,"paraswap")&&a.push(ur("paraswap",async()=>{let c=await(n.paraswapPrice??Ot)({chainId:e.fromChainId,srcToken:e.sellToken,destToken:e.buyToken,amount:e.sellAmount,srcDecimals:t.decimalsIn,destDecimals:t.decimalsOut},t),u=c?.priceRoute??c;return{quoteId:u?.id??null,amountOut:u?.destAmount,minBuyAmount:c?.amountOutMinimum??u?.destAmount,expiryMs:Date.now()+Number(t.defaultQuoteTtlMs??2e4),artifact:{type:"paraswap-price-route",route:u},metadata:{contractAddress:u?.contractAddress??null}}})),cr(e,"0x")&&(kc(r,"ZEROX_API_KEY")||kc(r,"0X_API_KEY")||n.zeroxQuote)&&a.push(ur("0x",async()=>{let c=await(n.zeroxQuote??Tt)({chainId:e.fromChainId,sellToken:e.sellToken,buyToken:e.buyToken,sellAmount:e.sellAmount,taker:e.receiver},t);return{quoteId:c?.id??null,amountOut:c?.buyAmount??c?.grossBuyAmount,minBuyAmount:c?.minBuyAmount??c?.buyAmount,expiryMs:Date.now()+Number(t.defaultQuoteTtlMs??2e4),artifact:{type:"0x-transaction",to:c?.transaction?.to,data:c?.transaction?.data,value:c?.transaction?.value??"0"},metadata:{route:c?.route??null}}})),cr(e,"cow")&&a.push(ur("cow",async()=>{let c=await(n.cowQuote??ut)({chainId:e.fromChainId,sellToken:e.sellToken,buyToken:e.buyToken,sellAmountBeforeFee:e.sellAmount,from:e.receiver,signingScheme:"eip712"},t),u=c?.quote??c;return{quoteId:c?.id??null,amountOut:u?.buyAmount,minBuyAmount:u?.buyAmount,expiryMs:Math.min(Number(u?.validTo??0)*1e3||Date.now()+Number(t.defaultQuoteTtlMs??2e4),e.deadlineMs),artifact:{type:"cow-order",order:u},metadata:{solver:!0}}})),cr(e,"uniswap-v3")&&o[Number(e.fromChainId)]&&a.push(ur("uniswap-v3",async()=>{let c=await(n.uniV3QuoteExactIn??dt)({chainId:e.fromChainId,tokenIn:e.sellToken,tokenOut:e.buyToken,amountIn:e.sellAmount},t);return{quoteId:c?.id??null,amountOut:c?.amountOut,minBuyAmount:c?.minOut??c?.amountOutMinimum??c?.amountOut,expiryMs:Date.now()+Number(t.defaultQuoteTtlMs??2e4),artifact:{type:"uniswap-v3-quote",quoter:c?.quoter,fee:c?.fee},metadata:{onchain:!0}}}))),a}async function _0(e,t){return`0x${(await import("node:crypto")).createHash("sha256").update(String(t)).digest("hex")}`}async function C0(e,t){return Promise.race([Promise.resolve().then(e.run),new Promise((r,n)=>setTimeout(()=>n(new Error(`${e.source}: timeout`)),t))])}async function vc(e,t,r={}){let n=Number(r.timeoutMs??12e3),o=await Promise.allSettled(t.map(i=>C0(i,n))),s=[],a=[];for(let i=0;i<o.length;i++){let c=t[i],u=o[i];if(u.status==="rejected"){a.push({source:c.source,error:String(u.reason?.message||u.reason)});continue}try{s.push(No(e,{...u.value,source:c.source},r))}catch(p){a.push({source:c.source,error:String(p?.message||p)})}}return{quotes:s,failed:a}}function Ic(e=[],t={}){let r=Number(t.nowMs??Date.now()),n=e.filter(a=>Number(a.expiryMs??0)>r);n.sort((a,i)=>{let c=BigInt(i.minBuyAmount??0)-BigInt(a.minBuyAmount??0);if(c!==0n)return c>0n?1:-1;let u=BigInt(i.amountOut??0)-BigInt(a.amountOut??0);return u>0n?1:u<0n?-1:0});let o=n.map(a=>({...a,scoreBasis:"minBuyAmount"})),s=[];return o.length||s.push("no RFQ source returned a usable firm quote"),e.length!==o.length&&s.push("expired RFQ quotes were excluded from ranking"),{best:o[0]??null,quotes:o,failed:[],warnings:s}}async function O0(e,t={}){let r=Ac(e,t),{quotes:n,failed:o}=await vc(e,r,t),s=Ic(n,t);return{kind:"rfq-result",intent:e,best:s.best,quotes:s.quotes,failed:o,warnings:[...s.warnings],sourcesTried:r.length,sourcesAnswered:n.length}}var Cc=w(()=>{or();Fr();zr();Wr();en();$o()});function Oc(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,s]of(e.venues||[]).entries()){let a=`venues[${o}]`;if(!s||typeof s!="object"){t.push(`${a} must be an object`);continue}T0.test(s.address||"")||t.push(`${a}.address is not a valid 20-byte address`),/^0x0{40}$/.test(s.address||"")&&t.push(`${a}.address is the zero address -- placeholder left in place?`),s.kind||t.push(`${a}.kind is required (router|quoter|factory|...)`),s.verified?(s.verified.method||t.push(`${a}.verified.method is required`),s.verified.source||t.push(`${a}.verified.source is required`),s.verified.date||r.push(`${a}.verified.date missing -- add one so staleness is visible`)):t.push(`${a} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let n=e.capabilities||{};for(let o of Object.keys(n))Nt.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 Tc(e){let{ok:t,errors:r,warnings:n}=Oc(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
|
|
5
5
|
- ${r.join(`
|
|
6
6
|
- `)}`);let o=e.capabilities||{},s=Nt.filter(i=>typeof o[i]=="function"),a={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:[...s],unsupported:Nt.filter(i=>!s.includes(i))}},supports(i){return s.includes(i)}};for(let i of Nt)s.includes(i)?a[i]=async(...c)=>o[i](...c,{scanner:a}):a[i]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${i}". Supported: ${s.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(a)}function tn(e){let t=Tc(e);return $t.set(t.chainId,t),t}function R0(e){return $t.get(Number(e))||null}function N0(){return[...$t.values()]}function $0(){$t.clear()}function P0(){let e={};for(let t of $t.values())e[t.chainId]={key:t.key,name:t.name,...t.capabilities(),venueCount:t.venues.length,failClosed:t.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:$t.size,capabilities:[...Nt],chains:e}}var Nt,P,R,T0,$t,pt=w(()=>{Nt=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),P=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),R=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),T0=/^0x[0-9a-fA-F]{40}$/;$t=new Map});function Rc(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:o=null,feeUsd:s=null,oracleFeeBps:a=0,estimatedGas:i=null,liquidityUsd:c=null,error:u=null,executionReady:p=!1,meta:l={}}=e||{};if(u||r==null)return{source:t,quality:Ae.FAILED,amountOut:null,error:u||"no amountOut returned"};let d=lr(r);if(d==null||d<=0n)return{source:t,quality:Ae.FAILED,amountOut:null,error:"non-positive amountOut"};let f=Number(a);return{source:t,quality:o==null?Ae.NO_GAS:Ae.FULL,amountOut:d.toString(),minOut:lr(n)?.toString()??null,gasUsd:o,feeUsd:s,oracleFeeBps:Number.isFinite(f)&&f>0?Math.floor(f):0,estimatedGas:i==null?null:String(i),liquidityUsd:c==null?null:Number(c),executionReady:p,meta:l}}async function $c(e,t,{divisor:r=1000n}={}){let n=lr(t);if(n==null||n<=0n)return null;let o=n/r>0n?n/r:1n;if(o>=n)return null;let s,a;try{[s,a]=await Promise.all([e(o),e(n)])}catch{return null}let i=lr(s),c=lr(a);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 Pc(e,t,{maxImpactPct:r=25}={}){let n=[],o=[],s=(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)}),a=[...e.warnings??[]];return n.length&&a.push(`dropped ${n.length} route(s) on price impact: `+n.map(i=>`${i.source} (${i.impactPct}%)`).join(", ")),o.length&&a.push(`price impact NOT measured for: ${o.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:s,best:s[0]??null,impactRejected:n,impactUnmeasured:o,warnings:a}}function Qo(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:o=50}={}){let s=e.filter(b=>b.quality!==Ae.FAILED),a=e.filter(b=>b.quality===Ae.FAILED),i=t!=null&&t>0&&r!=null&&r>=0,c=s.map(b=>{let S=BigInt(b.amountOut),I=0n,A=!1,O=BigInt(b.oracleFeeBps??0),_=O>0n?S*O/10000n:0n;if(i){let j=(b.gasUsd??0)+(b.feeUsd??0);if(j>0){let se=j/t*10**r;Number.isFinite(se)&&se>=0&&(I=BigInt(Math.floor(se)),A=!0)}else b.gasUsd===0&&(A=!0)}let m=I+_,T=S>m?S-m:0n;return{...b,grossOut:S.toString(),netOut:T.toString(),costInDest:I.toString(),oracleFeeInDest:_.toString(),costAccounted:A}}),u=Number(o)>0?Number(o):0,p=c.reduce((b,S)=>BigInt(S.netOut)>b?BigInt(S.netOut):b,0n),l=b=>p>0n?Number((p-BigInt(b))*10000n/p):0,d=[],f=c.slice().sort((b,S)=>BigInt(S.netOut)>BigInt(b.netOut)?1:-1)[0]??null;c.sort((b,S)=>{let I=l(b.netOut)<=u?0:1,A=l(S.netOut)<=u?0:1;if(n&&u>0&&I!==A)return I-A;if(n&&u>0){let O=b.liquidityUsd??-1,_=S.liquidityUsd??-1;if(O!==_)return _-O}return BigInt(S.netOut)>BigInt(b.netOut)?1:-1}),n&&u>0&&f&&c[0]&&c[0].source!==f.source&&d.push(`liquidity-first: chose ${c[0].source} (liquidity $${c[0].liquidityUsd??"unknown"}) over best-price ${f.source} within ${u} bps`);let h=c.filter(b=>!b.costAccounted).map(b=>b.source);i?h.length&&d.push(`gas not reported by: ${h.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):d.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let y=null,g=null;if(c.length>=2&&c[0].costAccounted&&c[1].costAccounted){let b=BigInt(c[0].netOut),S=BigInt(c[1].netOut);S>0n&&(y=Number((b-S)*10000n/S),g=`${c[0].source} vs ${c[1].source}`)}return{best:c[0]??null,routes:c,failed:a,improvementBps:y,spreadBasis:g,rankedOn:i?"net-of-cost":"gross",warnings:d}}async function rn(e,{timeoutMs:t=12e3}={}){let r=(o,s)=>Promise.race([o,new Promise((a,i)=>setTimeout(()=>i(new Error(`${s}: timeout`)),t))]);return(await Promise.allSettled(e.map(o=>r(Promise.resolve().then(o.run),o.source)))).map((o,s)=>{let a=e[s].source;return o.status==="rejected"?Rc({source:a,error:String(o.reason?.message||o.reason)}):Rc({source:a,...o.value})})}var Ae,Nc,lr,Go=w(()=>{pt();Ae=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),Nc={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"},lr=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}}});function qc(e={}){return Mr({provider:"oneinch",defaultUrl:q0,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function B0(e={}){return qc(e).baseUrl}function Bc(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function U0(e={}){let t=Bc(e);return jr({accept:"application/json"},{Authorization:t?`Bearer ${t}`:""},qc(e).trusted)}async function Uc(e={},t={}){if(!Bc(t))throw new Error("ONEINCH_API_KEY required for 1inch");let r=Number(e.chainId??1),{src:n,dst:o,amount:s}=e;if(!n||!o||!s)throw new Error("oneinchQuote requires src, dst, amount");let a=new URLSearchParams({src:n,dst:o,amount:String(s)}),i=await v(`${B0(t)}/${r}/quote?${a}`,{headers:U0(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});return i?.dstAmount?oe(i,{chainId:r,venue:"1inch-quote",amountOut:i.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):i}var q0,Dc=w(()=>{F();je();Mo();de();q0="https://api.1inch.dev/swap/v6.0"});var Vc={};z(Vc,{UNI_V4_CHAINS:()=>He,UNI_V4_FEE_TIERS:()=>jc,computeV4PoolId:()=>zc,uniV4Chains:()=>W0,uniV4Health:()=>Q0,uniV4PrepareExactIn:()=>K0,uniV4QuoteExactIn:()=>on});import{AbiCoder as D0,Interface as Mc,getAddress as ve,isAddress as nn,keccak256 as L0}from"ethers";function Yo(e){let t=Number(e),r=He[t];if(!r)throw new Error(`uniswap-v4: unsupported chainId ${e} (supported: ${Object.keys(He).join(", ")})`);return{chainId:t,...r}}function Fc(e,t){let r=He[Number(t)];if(!e||e===Hc||e===ft||/^eth$/i.test(String(e)))return ve(r.weth);let n=String(e);if(/^weth$/i.test(n))return ve(r.weth);if(/^usdc$/i.test(n)||/^usdg$/i.test(n))return ve(r.usdc);if(!nn(n))throw new Error(`invalid token address: ${e}`);return ve(n)}function zc({currency0:e,currency1:t,fee:r,tickSpacing:n,hooks:o=ft}){let s=ve(e),a=ve(t);if(s.toLowerCase()===a.toLowerCase())throw new Error("poolKey currencies must differ");let[i,c]=s.toLowerCase()<a.toLowerCase()?[s,a]:[a,s],u=o&&nn(o)?ve(o):ft;return L0(dr.encode(["address","address","uint24","int24","address"],[i,c,Number(r),Number(n),u]))}function z0({tokenIn:e,tokenOut:t,fee:r,tickSpacing:n,hooks:o=ft}){let s=ve(e),a=ve(t),[i,c]=s.toLowerCase()<a.toLowerCase()?[s,a]:[a,s],u=s.toLowerCase()===i.toLowerCase();return{poolKey:{currency0:i,currency1:c,fee:Number(r),tickSpacing:Number(n),hooks:o&&nn(o)?ve(o):ft},zeroForOne:u}}async function on(e={},t={}){let{chainId:r,quoter:n,poolManager:o,universalRouter:s}=Yo(e.chainId??8453),a=Fc(e.tokenIn||"WETH",r),i=Fc(e.tokenOut||He[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}]:[...jc],p=e.hooks||ft,l=[],d=null;for(let y of u){let{poolKey:g,zeroForOne:b}=z0({tokenIn:a,tokenOut:i,fee:y.fee,tickSpacing:y.tickSpacing,hooks:p}),S=Lc.encodeFunctionData("quoteExactInputSingle",[{poolKey:g,zeroForOne:b,exactAmount:c,hookData:"0x"}]);try{let I=await ee(r,"eth_call",[{to:n,data:S},"latest"],t);if(!I||I==="0x"){l.push({...y,ok:!1,error:"empty result"});continue}let A=Lc.decodeFunctionResult("quoteExactInputSingle",I),O={fee:y.fee,tickSpacing:y.tickSpacing,ok:!0,amountOut:A[0].toString(),gasEstimate:A[1].toString(),poolKey:g,zeroForOne:b,poolId:zc({...g})};l.push(O),(!d||BigInt(O.amountOut)>BigInt(d.amountOut))&&(d=O)}catch(I){l.push({...y,ok:!1,error:String(I.message||I).slice(0,160)})}}if(!d){let y=l.map(g=>`${g.fee}/${g.tickSpacing}:${g.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 quote failed chain=${r}: ${y}`)}let f=e.liquidityUsd==null?await Yr({chainId:r,tokenA:a,tokenB:i,dexIds:V0},t).catch(()=>null):null,h=e.liquidityUsd??f?.liquidityUsd??null;return oe({venue:"uniswap-v4",chainId:r,chain:He[r].name,poolManager:o,quoter:n,universalRouter:s||null,tokenIn:a,tokenOut:i,amountIn:c.toString(),fee:d.fee,tickSpacing:d.tickSpacing,hooks:d.poolKey.hooks,poolId:d.poolId,zeroForOne:d.zeroForOne,amountOut:d.amountOut,gasEstimate:d.gasEstimate,liquidityUsd:h,liquiditySource:f,triedTiers:l,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&nn(e.recipient)&&e.slippageBps!=null},{chainId:r,venue:s||n,amountOut:d.amountOut,liquidityUsd:h,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function K0(e={},t={}){let r=Number(e.chainId??8453),n=Yo(r);if(!e.recipient)throw new Error("uniswap-v4 prepare requires recipient");let o=ve(e.recipient);if(e.slippageBps==null)throw new Error("uniswap-v4 prepare requires explicit slippageBps");let s=Number(e.slippageBps);if(!Number.isInteger(s)||s<0||s>=1e4)throw new Error("slippageBps must be an integer from 0 through 9999");let a=String(e.tokenIn||"");if(!a||a===Hc||a===ft||/^eth$/i.test(a))throw new Error("uniswap-v4 prepare currently requires an ERC-20 tokenIn; native input is not inferred");let i=await on(e,t);if(!n.universalRouter)throw new Error(`uniswap-v4: no Universal Router on chain ${r}`);let c=BigInt(i.amountOut)*BigInt(1e4-s)/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},l=dr.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"]]),d=dr.encode(["address","uint256"],[i.tokenIn,BigInt(i.amountIn)]),f=dr.encode(["address","uint256"],[i.tokenOut,c]),h=dr.encode(["bytes","bytes[]"],[j0,[l,d,f]]),y=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),b=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+y,S=F0.encodeFunctionData("execute",[M0,[h],b]);return Q({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:s},requiresApproval:{token:i.tokenIn,spender:H0,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:S,value:"0"}},{provider:"uniswap-v4",kind:"univ4-swap-tx"})}async function W0(){return Object.entries(He).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 Q0(e={}){let t=Yo(e.chainId??8453),r=await ee(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 dr,ft,He,jc,Lc,F0,M0,j0,H0,Hc,V0,Xo=w(()=>{lt();Xr();je();de();dr=D0.defaultAbiCoder(),ft="0x0000000000000000000000000000000000000000",He={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"}},jc=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],Lc=new Mc(["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)"]),F0=new Mc(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),M0="0x10",j0="0x060c0f",H0="0x000000000022D473030F116dDEE9F6B43aC78BA3",Hc="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";V0=["uniswap-v4","uniswapv4"]});function X0(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||G0).replace(/\/$/,"")}function J0(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||Y0).replace(/\/$/,"")}async function sn(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return v(`${X0(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Kc(e={}){return v(`${J0(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var G0,Y0,Jo=w(()=>{F();G0="https://coins.llama.fi",Y0="https://api.llama.fi"});var an={};z(an,{ACROSS_API:()=>Wc,HOP_API:()=>Qc,RELAY_API:()=>Gc,acrossHealth:()=>eh,acrossSuggestedFees:()=>Yc,hopHealth:()=>th,hopQuote:()=>Xc,relayHealth:()=>rh,relayPrepare:()=>nh,relayQuote:()=>Zo});async function eh(e={}){try{return{ok:!0,estimatedFillTimeSec:(await Yc({token:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",destinationToken:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",originChainId:1,destinationChainId:42161,amount:"1000000000000000"},e)).estimatedFillTimeSec}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function Yc(e={},t={}){let{token:r,destinationToken:n=r,originChainId:o,destinationChainId:s,amount:a}=e;if(!r||o==null||s==null||!a)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let i=new URLSearchParams({token:r,destinationToken:n,originChainId:String(o),destinationChainId:String(s),amount:String(a)}),c=(t.baseUrl||process.env.ACROSS_API_URL||Wc).replace(/\/$/,"");return v(`${c}/suggested-fees?${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function th(e={}){try{let t=await Xc({amount:"1000000000000000",token:"ETH",fromChain:"ethereum",toChain:"arbitrum",slippage:.5},e);return{ok:!0,estimatedRecieved:t.estimatedRecieved||t.estimatedReceived}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function Xc(e={},t={}){let{amount:r,token:n="ETH",fromChain:o="ethereum",toChain:s="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let a=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),i=Me({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==s,requestedCapBps:e.maxSlippageBps??e.slippageBps??a});if(!i.executable)throw new Error(`hop: route requires ${i.requiredBps} bps above cap ${i.capBps}`);let c=new URLSearchParams({amount:String(r),token:n,fromChain:o,toChain:s,slippage:String(i.selectedBps/100)}),u=(t.baseUrl||process.env.HOP_API_URL||Qc).replace(/\/$/,""),p=await v(`${u}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),l=p?.estimatedRecieved||p?.estimatedReceived;return l?oe(p,{chainId:Number(e.originChainId||e.chainId||Z0[o]||0),venue:p?.tx?.to||"hop",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==s,requestedCapBps:e.maxSlippageBps??e.slippageBps??a}):{...p,autoSlippagePolicy:i}}async function rh(e={}){try{let t=await Zo({user:Ye,originChainId:1,destinationChainId:8453,originCurrency:"0x0000000000000000000000000000000000000000",destinationCurrency:"0x0000000000000000000000000000000000000000",amount:"1000000000000000",tradeType:"EXACT_INPUT"},e);return{ok:!0,hasSteps:Array.isArray(t.steps),stepCount:t.steps?.length||0}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function Zo(e={},t={}){let{user:r=Ye,originChainId:n,destinationChainId:o,originCurrency:s="0x0000000000000000000000000000000000000000",destinationCurrency:a="0x0000000000000000000000000000000000000000",amount:i,tradeType:c="EXACT_INPUT"}=e;if(n==null||o==null||!i)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let u=Me({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!u.executable)throw new Error(`relay: route requires ${u.requiredBps} bps above cap ${u.capBps}`);let p=(t.baseUrl||process.env.RELAY_API_URL||Gc).replace(/\/$/,""),l=await v(`${p}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(o),originCurrency:s,destinationCurrency:a,amount:String(i),tradeType:c,slippageTolerance:String(u.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),d=l?.details?.currencyOut?.amount;return!d||!/^\d+$/.test(String(d))?{...l,autoSlippagePolicy:u}:oe(l,{chainId:Number(n),venue:l?.steps?.[0]?.items?.[0]?.data?.to||"relay",amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function nh(e={},t={}){let r=await Zo(e,t),n=Number(e.originChainId),o=(r.steps||[]).flatMap(i=>(i.items||[]).filter(c=>c?.data?.to&&c?.data?.data).map(c=>({stepId:i.id,...c.data})));if(!o.length)throw new Error("relay: quote returned no executable transaction items");let s=String(r?.autoSlippage?.venue||"").toLowerCase();if(o.some(i=>String(i.to).toLowerCase()!==s))throw new Error("relay: route includes a separate approval/transaction that is not yet safely bound");let a=o.map(i=>({chainId:n,from:i.from||e.user,to:i.to,data:i.data,value:i.value??"0x0",...i.gasLimit!=null||i.gas!=null?{gasLimit:i.gasLimit??i.gas}:{},slippageGuard:Ee(r.autoSlippage,{chainId:n,venue:i.to,data:i.data})}));return Q({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:r,autoSlippage:r.autoSlippage,transactions:a},{provider:"relay",kind:"relay-tx"})}var Wc,Qc,Gc,Z0,cn=w(()=>{F();je();Ur();de();Wc="https://across.to/api",Qc="https://api.hop.exchange/v1",Gc="https://api.relay.link",Z0={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453}});function un(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let o=Be(n?.amountUSD);o!=null&&(t+=o,r=!0)}return r?t:null}async function Zc(e,t={}){let r=Nc[Number(e)];if(!r)return null;try{let n=await sn([r],t);return Be(n?.coins?.[r]?.price)}catch{return null}}async function oh(e={}){try{let t=await Kc({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function sh(e,t={}){let r=Je(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...Jc[r]||[r]),n.push(...Jc[Je(e)]||[e]),n}function ih(e,t,r={}){let n=Array.isArray(e)?e:[],o=sh(t,r).map(Je).filter(Boolean);for(let s of o){let a=n.find(c=>Je(c?.slug)===s||Je(c?.name)===s),i=Be(a?.tvl);if(i!=null)return{liquidityUsd:i,protocol:a?.name??a?.slug??s}}for(let s of o){let a=n.find(c=>{let u=Je(c?.category);return!u.includes("bridge")&&!u.includes("crosschain")?!1:Je(c?.slug).includes(s)||Je(c?.name).includes(s)}),i=Be(a?.tvl);if(i!=null)return{liquidityUsd:i,protocol:a?.name??a?.slug??s}}return null}function es({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,slippageBps:s,decimalsIn:a,decimalsOut:i,nativePriceUsd:c=null,destDecimalsPromise:u=null,opts:p={}}){let l=[];return l.push({source:"lifi",run:async()=>{let d=await ct({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n},p),f=d?.estimate??d?.[0]?.estimate;return{amountOut:f?.toAmount,minOut:f?.toAmountMin,gasUsd:un(f?.gasCosts),feeUsd:un(f?.feeCosts),oracleFeeBps:d?.oracleFee?.applies?d.oracleFee.bps:0,meta:{tool:d?.tool??d?.toolDetails?.name,oracleFee:d?.oracleFee??null}}}}),a!=null&&l.push({source:"paraswap",run:async()=>{let d=i??(await Promise.resolve(u))?.decimals;if(d==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let f=await Ot({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:a,destDecimals:d},p),h=f?.priceRoute;return{amountOut:h?.destAmount,gasUsd:Be(h?.gasCostUSD),oracleFeeBps:f?.oracleFee?.applies?f.oracleFee.bps:0,meta:{bestRoute:h?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange,oracleFee:f?.oracleFee??null}}}}),process.env.ZEROX_API_KEY&&l.push({source:"0x",run:async()=>{let d=await Tt({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:o},p),f=null,h=d?.totalNetworkFee,y=await Promise.resolve(c);return h!=null&&y&&(f=Number(h)/1e18*y),{amountOut:d?.buyAmount,minOut:d?.minBuyAmount,gasUsd:f,meta:{source:d?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&l.push({source:"1inch",run:async()=>{let d=await Uc({chainId:e,src:t,dst:r,amount:n},p),f=null;return d?.gas!=null&&c&&(f=null),{amountOut:d?.dstAmount,gasUsd:f,meta:{gasUnits:d?.gas}}}}),l.push({source:"cow",run:async()=>{let d=await ut({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:o},p),f=d?.quote??d,h=f?.feeAmount;return{amountOut:f?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:h,settlement:"solver-executed"}}}}),pe[Number(e)]&&l.push({source:"uniswap-v3",run:async()=>{let d=await dt({chainId:e,tokenIn:t,tokenOut:r,amountIn:n},p);return{amountOut:d?.amountOut,minOut:d?.minOut??d?.amountOutMinimum??null,gasUsd:null,liquidityUsd:d?.liquidityUsd??null,meta:{onchain:!0,fee:d?.fee,gasUnits:d?.gasEstimate,quoter:d?.quoter}}}}),He[Number(e)]&&l.push({source:"uniswap-v4",run:async()=>{let d=await on({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o,slippageBps:s},p);return{amountOut:d?.amountOut,minOut:d?.minOut??d?.amountOutMinimum??null,gasUsd:null,liquidityUsd:d?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:d?.fee,tickSpacing:d?.tickSpacing,poolId:d?.poolId,hooks:d?.hooks,gasUnits:d?.gasEstimate,quoter:d?.quoter,poolManager:d?.poolManager,prepareReady:d?.prepareReady===!0,executionReady:!1}}}}),l}function eu({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:s,opts:a={}}){let i=[],c=null,u=async(p,l={})=>(c||=oh(a),ih(await c,p,l));return i.push({source:"lifi",run:async()=>{let p=await ct({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:o},a),l=p?.estimate??p?.[0]?.estimate,d={tool:p?.tool??p?.toolDetails?.name,durationSeconds:Be(l?.executionDuration)},f=await u("lifi",d);return{amountOut:l?.toAmount,minOut:l?.toAmountMin,gasUsd:un(l?.gasCosts),feeUsd:un(l?.feeCosts),oracleFeeBps:p?.oracleFee?.applies?p.oracleFee.bps:0,liquidityUsd:f?.liquidityUsd??null,meta:{...d,liquidityProtocol:f?.protocol,oracleFee:p?.oracleFee??null}}}}),i.push({source:"relay",run:async()=>{let{relayQuote:p}=await Promise.resolve().then(()=>(cn(),an)),d=(await p({user:s,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(o)},a))?.details,f={durationSeconds:Be(d?.timeEstimate),rate:d?.rate},h=await u("relay",f);return{amountOut:d?.currencyOut?.amount,minOut:d?.currencyOut?.minimumAmount,gasUsd:Be(d?.totalImpact?.usd)!=null?Math.abs(Be(d.totalImpact.usd)):null,liquidityUsd:h?.liquidityUsd??null,meta:{...f,liquidityProtocol:h?.protocol}}}}),i.push({source:"across",run:async()=>{let{acrossSuggestedFees:p}=await Promise.resolve().then(()=>(cn(),an)),l=await p({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(o)},a),d=l?.totalRelayFee?.total,f=null;if(d!=null)try{let y=BigInt(String(o))-BigInt(String(d));y>0n&&(f=y.toString())}catch{}let h=await u("across");return{amountOut:f,gasUsd:null,liquidityUsd:h?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:Be(l?.estimatedFillTimeSec),limits:l?.limits?{min:l.limits.minDeposit,max:l.limits.maxDeposit}:void 0,liquidityProtocol:h?.protocol}}}}),i}var Be,Je,Jc,tu=w(()=>{or();Fr();zr();Dc();Wr();en();Xo();Jo();Go();Be=e=>{let t=Number(e);return Number.isFinite(t)?t:null};Je=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),Jc=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"]})});var nu={};z(nu,{QUALITY:()=>Ae,bestBridgeRoute:()=>pr,bestSwapRoute:()=>Pt,formatComparisonNote:()=>ln});async function ru(e,t,r){let n=ah[Number(e)];if(!n)return{priceUsd:null,decimals:null};let o=`${n}:${t}`;try{let a=(await sn([o],r))?.coins?.[o],i=Number(a?.price),c=Number(a?.decimals);return{priceUsd:Number.isFinite(i)?i:null,decimals:Number.isFinite(c)?c:null}}catch{return{priceUsd:null,decimals:null}}}async function Pt(e,t={}){let{chainId:r,tokenIn:n,tokenOut:o,amountIn:s}=e;if(r==null||!n||!o||s==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let a=Zc(r,t),i=ru(r,o,t),c=es({...e,nativePriceUsd:a,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:t}),[u,p]=await Promise.all([rn(c,{timeoutMs:t.timeoutMs??12e3}),i]);a.catch(()=>{});let l=Qo(u,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50}),d=t.maxImpactPct===void 0?25:t.maxImpactPct;if(d!=null&&l.best){let f=l.best.source,y=await $c(async g=>{let b=es({...e,amountIn:g.toString(),nativePriceUsd:a,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:t}).filter(I=>I.source===f);return b.length?(await rn(b,{timeoutMs:t.timeoutMs??12e3}))?.[0]?.amountOut??null:null},s);if(y){let g=Pc(l,{[f]:y},{maxImpactPct:d});return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(s),...g,sourcesTried:c.length,sourcesAnswered:u.filter(b=>b.quality!==Ae.FAILED).length,note:ln(g,c.length),priceImpact:{[f]:Number(y.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(s),...l,sourcesTried:c.length,sourcesAnswered:u.filter(f=>f.quality!==Ae.FAILED).length,note:ln(l,c.length)}}async function pr(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:o,tokenOut:s,amountIn:a}=e;if(r==null||n==null||!o||!s||a==null)throw new Error("bestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(r)===Number(n))throw new Error("bestBridgeRoute is for cross-chain; use bestSwapRoute for same-chain");let i=ru(n,s,t),c=eu({...e,opts:t}),[u,p]=await Promise.all([rn(c,{timeoutMs:t.timeoutMs??15e3}),i]),l=Qo(u,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50}),d=l.routes.map(f=>({source:f.source,seconds:f.meta?.durationSeconds??null})).filter(f=>f.seconds!=null);return{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:o,tokenOut:s,amountIn:String(a),...l,durations:d,sourcesTried:c.length,sourcesAnswered:u.filter(f=>f.quality!==Ae.FAILED).length,note:ln(l,c.length)}}function ch(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${qa(t)}`:""}function ln(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=ch(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,s=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 a=s>=.01?`${s.toFixed(2)}%`:`${o.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${a} better than the runner-up (${e.spreadBasis})`+n}return`best of ${r} routes, ranked on ${e.rankedOn}. No spread quoted: the top routes report cost differently, so the margin is not comparable.`+n}var ah,qt=w(()=>{Go();tu();Lr();Jo();ah={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"}});var ou={};z(ou,{ARTIFACT:()=>ze,prepareBestRoute:()=>fh,supportedPreparers:()=>lh});function lh(){return Object.keys(dn)}async function fh(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(!ph.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(dh.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 Pt(e,t);if(!n.best){let g=n.impactRejected??[];return{ok:!1,reason:g.length?g[0].reason:"no source returned a usable route",priceImpactBlocked:g.length>0,impactRejected:g,comparison:n}}let o=e.source||n.best.source,s=n.routes.find(g=>g.source===o);if(!s)return{ok:!1,reason:`source "${o}" did not return a usable route`,comparison:n};let a=dn[o];if(!a){let g=n.routes.find(b=>dn[b.source]&&b.source!==o);return{ok:!1,reason:`${o} won the comparison but has no prepare path in this build. `+(g?`Next preparable route is ${g.source}; pass source:"${g.source}" to use it.`:"No route in this comparison can be prepared."),comparison:n,winner:o}}let i;try{i=await a(e,t)}catch(g){let b=typeof g?.body=="string"?g.body:g?.body?JSON.stringify(g.body):"",S=[String(g?.message||g),b].filter(Boolean).join(" :: "),I=/allowance/i.test(S),A=!I&&/not enough|insufficient|balance/i.test(S),O,_;I?(_="approval-required-first",O=`${o} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${S}`):A?(_="taker-not-funded",O=`${o} refused to build the transaction: ${S}. This venue verifies the taker holds the input token. Quoting works for any address; preparing needs the real funded wallet.`):(_="provider-error",O=`${o} prepare failed: ${S}`);let m=n.routes.find(T=>dn[T.source]&&T.source!==o);return{ok:!1,reason:O,failureKind:_,...m?{alternative:m.source}:{},comparison:n}}let c=e.driftToleranceBps??uh,u=null,p=null;if(i.amountOut!=null&&s.grossOut!=null)try{let g=BigInt(s.grossOut),b=BigInt(i.amountOut);g>0n&&(u=Number((b-g)*10000n/g),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 l=n.routes.filter(g=>g.source!==o).map(g=>({source:g.source,netOut:g.netOut,gasUsd:g.gasUsd})),f=n.routes.map(g=>({source:g.source,liquidityUsd:g.liquidityUsd??null})).reduce((g,b)=>Math.max(g,b.liquidityUsd??0),0)||null,h=s.liquidityUsd??null,y=h!=null&&f>0?Math.round(h/f*100):null;return Q({ok:!0,chosen:{source:o,wasWinner:o===n.best.source,netOut:s.netOut,grossOut:s.grossOut,gasUsd:s.gasUsd,liquidityUsd:s.liquidityUsd??null},liquidity:{chosenUsd:h,maxUsd:f,sharePct:y},priceImpact:n.priceImpact??null,impactUnmeasured:n.impactUnmeasured??[],...i,unsigned:!0,signedBy:"user-wallet",destination:i.artifactKind===ze.TRANSACTION?i.transaction?.to??null:i.settlement??null,driftBps:u,warnings:[...p?[p]:[],...n.warnings||[],...i.artifactKind===ze.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:l,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"})}var ze,uh,dn,dh,ph,su=w(()=>{qt();de();ze=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),uh=100,dn={"uniswap-v3":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},s)=>{let{uniV3PrepareExactIn:a}=await Promise.resolve().then(()=>(en(),Ec)),i=await a({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o},s);return{artifactKind:ze.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:s,fee:a,tickSpacing:i,hooks:c},u)=>{let{uniV4PrepareExactIn:p}=await Promise.resolve().then(()=>(Xo(),Vc)),l=await p({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o,slippageBps:s,fee:a,tickSpacing:i,hooks:c},u);return{artifactKind:ze.TRANSACTION,transaction:l.transaction,requiresApproval:l.requiresApproval,amountOut:l.quote?.amountOut??null,minOut:l.quote?.amountOutMinimum??null,prepareReady:!0,executionReady:!1}},lifi:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},s)=>{let{lifiPrepare:a}=await Promise.resolve().then(()=>(or(),Lo)),i=await a({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n,fromAddress:o},s);return{artifactKind:ze.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:s,decimalsOut:a},i)=>{let{paraswapPrepare:c}=await Promise.resolve().then(()=>(Fr(),ja)),u=await c({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:s,destDecimals:a,userAddress:o,side:"SELL"},i);return{artifactKind:ze.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},s)=>{let{zeroxPrepare:a}=await Promise.resolve().then(()=>(zr(),Ya)),i=await a({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:o},s);return{artifactKind:ze.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},s)=>{let{cowPrepareOrder:a}=await Promise.resolve().then(()=>(Wr(),ac)),i=await a({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:o},s);return{artifactKind:ze.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"}}};dh=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),ph=/^0x[0-9a-fA-F]{40}$/});var iu={};z(iu,{prepareBestBridgeRoute:()=>bh,supportedBridgePreparers:()=>yh});function yh(){return Object.keys(pn)}async function bh(e,t={}){let{taker:r,fromChainId:n,toChainId:o}=e;if(!r)throw new Error("prepareBestBridgeRoute requires taker: bridge transactions are built FOR an address, and the quote-only placeholder must never end up in one");if(!mh.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(hh.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. Bridging to it would send funds to an address nobody controls, on a chain where you cannot undo it.`);let s=await pr(e,t);if(!s.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:s};let a=e.source||s.best.source,i=s.routes.find(g=>g.source===a);if(!i)return{ok:!1,reason:`source "${a}" returned no usable route`,comparison:s};let c=pn[a];if(!c){let g=s.routes.find(b=>pn[b.source]&&b.source!==a);return{ok:!1,reason:`${a} won the comparison but has no bridge prepare path in this build. `+(g?`Next preparable route is ${g.source}; pass source:"${g.source}".`:"No route in this comparison can be prepared."),failureKind:"no-prepare-path",...g?{alternative:g.source}:{},winner:a,comparison:s}}let u;try{u=await c(e,t)}catch(g){let b=typeof g?.body=="string"?g.body:g?.body?JSON.stringify(g.body):"",S=[String(g?.message||g),b].filter(Boolean).join(" :: "),I=/allowance/i.test(S),A=!I&&/not enough|insufficient|balance/i.test(S),O=s.routes.find(_=>pn[_.source]&&_.source!==a);return{ok:!1,reason:I?`${a} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${S}`:A?`${a} refused to build: ${S}. Quoting works for any address; preparing needs the real funded wallet on chain ${n}.`:`${a} bridge prepare failed: ${S}`,failureKind:I?"approval-required-first":A?"taker-not-funded":"provider-error",...O?{alternative:O.source}:{},comparison:s}}let p=u.transactions||[];if(!p.length)return{ok:!1,reason:`${a} returned no executable transaction for this route`,failureKind:"provider-error",comparison:s};let l=p.filter(g=>g.chainId!=null&&Number(g.chainId)!==Number(n));if(l.length)return{ok:!1,reason:`${a} returned a transaction for chain ${l[0].chainId} but the origin chain is ${n}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:s};let d=e.driftToleranceBps??gh,f=null,h=null;if(u.amountOut!=null&&i.grossOut!=null)try{let g=BigInt(i.grossOut),b=BigInt(u.amountOut);g>0n&&(f=Number((b-g)*10000n/g),f<-d&&(h=`route moved ${(f/100).toFixed(2)}% against you since the comparison (tolerance ${(d/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let y=[...h?[h]:[],...s.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${o}. Expect ~${u.durationSeconds!=null?`${u.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];return p.length>1&&y.push(`This route needs ${p.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`),Q({ok:!0,chosen:{source:a,wasWinner:a===s.best.source,netOut:i.netOut,grossOut:i.grossOut,gasUsd:i.gasUsd},artifactKind:"unsigned-transaction-sequence",fromChainId:Number(n),toChainId:Number(o),transactionCount:p.length,transactions:p,requiresApproval:u.requiresApproval??null,minOut:u.minOut??null,durationSeconds:u.durationSeconds??null,destination:p[0]?.to??null,unsigned:!0,signedBy:"user-wallet",driftBps:f,warnings:y,runnersUp:s.routes.filter(g=>g.source!==a).map(g=>({source:g.source,netOut:g.netOut,gasUsd:g.gasUsd})),comparison:{rankedOn:s.rankedOn,sourcesAnswered:s.sourcesAnswered,sourcesTried:s.sourcesTried,improvementBps:s.improvementBps},note:`UNSIGNED. ${p.length} transaction(s) on chain ${n}, crediting chain ${o}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge"})}var mh,hh,gh,pn,au=w(()=>{qt();de();mh=/^0x[0-9a-fA-F]{40}$/,hh=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),gh=100,pn={relay:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:s},a)=>{let{relayPrepare:i}=await Promise.resolve().then(()=>(cn(),an)),c=await i({user:s,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(o)},a);return{transactions:c.transactions||[],amountOut:c.quote?.details?.currencyOut?.amount??null,minOut:c.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:c.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:s,isHolder:a},i)=>{let{lifiPrepare:c}=await Promise.resolve().then(()=>(or(),Lo)),u=await c({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:o,fromAddress:s,isHolder:a,feeAction:"bridge"},i);return{transactions:u.transaction?[u.transaction]:[],requiresApproval:u.requiresApproval??null,amountOut:u.quote?.estimate?.toAmount??null,minOut:u.quote?.estimate?.toAmountMin??null,durationSeconds:u.quote?.estimate?.executionDuration??null}}}});var lu={};z(lu,{buildTwapSchedule:()=>uu,normalizeTwapParams:()=>cu,prepareTwapChunk:()=>Ah,simulateTwap:()=>vh});function cu(e={}){let t=Math.max(wh,Math.min(xh,Number(e.splits)||Eh)),r=Math.max(.1,Number(e.windowHours)||kh),n=Math.max(Sh,r*3600),o=BigInt(e.amount)/BigInt(t),s=Math.floor(n/t),a=Number(e.slippageBps)||100;if(!e.chainId)throw new Error("twap requires chainId");if(!e.tokenIn||!e.tokenOut)throw new Error("twap requires tokenIn and tokenOut");if(!e.taker)throw new Error("twap requires taker address");if(BigInt(e.amount)<=0n)throw new Error("twap amount must be positive");return{chainId:Number(e.chainId),tokenIn:String(e.tokenIn),tokenOut:String(e.tokenOut),amount:String(e.amount),splits:t,chunkSize:String(o),windowHours:r,windowSec:n,intervalSec:s,taker:String(e.taker),slippageBps:a,status:"planned",createdAt:new Date().toISOString()}}function uu(e){let t=cu(e),r=Math.floor(Date.now()/1e3),n=[];for(let o=0;o<t.splits;o++)n.push({splitIndex:o+1,executeAfter:new Date((r+o*t.intervalSec)*1e3).toISOString(),chunkSize:t.chunkSize});return{params:t,schedule:n}}async function Ah(e,t,{chainId:r,tokenIn:n,tokenOut:o,chunkSize:s,taker:a,slippageBps:i}=e.params){if(t<1||t>e.params.splits)throw new Error(`splitIndex ${t} out of range 1-${e.params.splits}`);let c=await Pt({chainId:r,tokenIn:n,tokenOut:o,amountIn:s,taker:a}),u=Q(c.transaction??c.tx,{chainId:r,taker:a,tokenIn:n,tokenOut:o,amountIn:s,slippageBps:i,kind:"twap",splitIndex:t,totalSplits:e.params.splits});return{splitIndex:t,chunkSize:s,quote:{amountOut:c.amountOut??c.quote?.amountOut,source:c.source??c.venue,priceImpact:c.priceImpact},...u}}async function vh(e,{quoteFn:t=Pt}={}){let r=uu(e),n=[],o=0n,s="unknown";for(let i=0;i<r.params.splits;i++)try{let c=await t({chainId:r.params.chainId,tokenIn:r.params.tokenIn,tokenOut:r.params.tokenOut,amountIn:r.params.chunkSize,taker:r.params.taker}),u=BigInt(c.amountOut??c.quote?.amountOut??"0");o+=u,s=c.source??c.venue??s,n.push({splitIndex:i+1,amountOut:String(u),source:c.source??c.venue})}catch(c){n.push({splitIndex:i+1,error:String(c.message||c).slice(0,200)})}let a=o>0n?(Number(o)/Number(BigInt(r.params.amount))).toFixed(6):null;return{params:r.params,schedule:r.schedule,totalOut:String(o),averagePrice:a,bestSource:s,chunks:n,simulatedAt:new Date().toISOString()}}var wh,xh,Sh,Eh,kh,du=w(()=>{qt();de();wh=2,xh=100,Sh=60,Eh=10,kh=6});async function mu({srcChainId:e,srcChainTokenIn:t,srcChainTokenInAmount:r,dstChainId:n,dstChainTokenOut:o,slippage:s=100,affiliateFeePercent:a="0"}={}){if(!e||!n||!t||!o||!r)return{error:"debridge quote requires srcChainId, dstChainId, srcChainTokenIn, dstChainTokenOut, srcChainTokenInAmount"};if(!pu.has(Number(e))||!pu.has(Number(n)))return{error:`debridge: unsupported chain pair ${e} -> ${n}`};try{let i={srcChainId:String(e),srcChainTokenIn:t,srcChainTokenInAmount:String(r),dstChainId:String(n),dstChainTokenOut:o,slippage:s,affiliateFeePercent:a},c=await v(`${fu}/dln/order/quote`,{method:"POST",body:JSON.stringify(i),headers:{"content-type":"application/json"}});return c.error?{error:String(c.error)}:{estimation:c.estimation??{},order:c.order??{},fixFee:c.fixFee??"0"}}catch(i){return{error:String(i.message||i).slice(0,200)}}}async function hu(){try{return{ok:!0,chainCount:(await v(`${fu}/supported-chains-info`))?.chains?.length??0}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var fu,pu,gu=w(()=>{F();de();fu="https://dln.debridge.finance/v1.0",pu=new Set([1,10,56,137,8453,42161,43114,59144,534352,7777777,324,5e3,1101,81457])});async function bu({active:e=!0}={}){let t=Date.now();if(Bt.size&&t-yu<Ih)return[...Bt.values()];try{let r=await v(`${ts}/exchange/currencies?active=${e?"true":"false"}`);Bt.clear();for(let n of r??[])Bt.set(String(n.ticker).toLowerCase(),n);return yu=t,r??[]}catch(r){return Bt.size?[...Bt.values()]:{error:String(r.message||r).slice(0,200)}}}async function _h(e,t){if(!e||!t)return{error:"changenow minAmount requires fromTicker and toTicker"};try{return{minAmount:(await v(`${ts}/exchange/min-amount/${encodeURIComponent(e)}_${encodeURIComponent(t)}`))?.minAmount??"0"}}catch(r){return{error:String(r.message||r).slice(0,200)}}}async function Ch(e,t,r,{flow:n="standard"}={}){if(!e||!t||!r)return{error:"changenow estimate requires fromTicker, toTicker, fromAmount"};try{let o=new URLSearchParams({fromCurrency:String(e).toLowerCase(),toCurrency:String(t).toLowerCase(),fromAmount:String(r),flow:n}),s=await v(`${ts}/exchange/estimated-amount?${o}`);return{fromAmount:s?.fromAmount,toAmount:s?.toAmount,rate:s?.rate,flow:s?.flow??n}}catch(o){return{error:String(o.message||o).slice(0,200)}}}async function wu({fromTicker:e,toTicker:t,fromAmount:r,flow:n}={}){if(!e||!t)return{error:"changenow quote requires fromTicker and toTicker"};let o=await _h(e,t);if(o.error)return o;let s=r??o.minAmount,a=await Ch(e,t,s,{flow:n});if(a.error)return a;let i=await bu(),c=i.find(p=>String(p?.ticker).toLowerCase()===String(e).toLowerCase()),u=i.find(p=>String(p?.ticker).toLowerCase()===String(t).toLowerCase());return{provider:"changenow",fromTicker:e,toTicker:t,fromAmount:s,toAmount:a.toAmount,estimatedRate:a.rate,minAmount:o.minAmount,flow:a.flow,networkFee:c?.networkFee??null,kycRequired:c?.kycRequired??u?.kycRequired??!1,riskDisclosure:"ChangeNOW is a centralized swap service. Funds are sent to a ChangeNOW deposit address. Not self-custodial during the swap window."}}async function xu(){try{let e=await bu();return e?.error?{ok:!1,error:e.error}:{ok:!0,currencyCount:Array.isArray(e)?e.length:0}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var ts,Bt,yu,Ih,Su=w(()=>{F();ts="https://api.changenow.io/v2",Bt=new Map,yu=0,Ih=6e5});async function Eu({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:o,fromAddress:s,slippage:a=1}={}){if(!e||!t||!r||!n||!o||!s)return{error:"squid quote requires fromChain, toChain, fromToken, toToken, fromAmount, fromAddress"};try{let i={fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:String(o),fromAddress:s,slippage:a},c=await v(`${Oh}/route`,{method:"POST",body:JSON.stringify(i),headers:{"content-type":"application/json"}});return{route:c?.route??{},toAmount:c?.route?.estimate?.toAmount,fee:c?.route?.estimate?.feeCosts}}catch(i){return{error:String(i.message||i).slice(0,200)}}}var Oh,ku=w(()=>{F();Oh="https://api.squidrouter.com/v1"});async function Au({srcChainId:e,dstChainId:t,token:r,amount:n,dstGasForCall:o=0,minAmountOut:s="0"}={}){if(!e||!t||!r||!n)return{error:"stargate quote requires srcChainId, dstChainId, token, amount"};try{let a=new URLSearchParams({srcChainId:String(e),dstChainId:String(t),token:r,amount:String(n),dstGasForCall:String(o),minAmountOut:String(s)}),i=await v(`${Th}/quote?${a}`);return{amountOut:i?.amountOut,fee:i?.fee,estimatedTime:i?.estimatedTime}}catch(a){return{error:String(a.message||a).slice(0,200)}}}var Th,vu=w(()=>{F();Th="https://api.stargate.finance"});async function Iu({fromAsset:e,toAsset:t,amount:r,destination:n}={}){if(!e||!t||!r)return{error:"thorchain quote requires fromAsset, toAsset, amount"};try{let o=new URLSearchParams({from_asset:e,to_asset:t,amount:String(r),destination:n||""}),s=await v(`${Rh}/quote/swap?${o}`);return{expectedAmountOut:s?.expected_amount_out,fees:s?.fees,slippageBps:s?.slippage_bps,inboundAddress:s?.inbound_address,memo:s?.memo,estimatedTime:s?.total_swap_seconds?`${Math.round(s.total_swap_seconds/60)} min`:"unknown"}}catch(o){return{error:String(o.message||o).slice(0,200)}}}var Rh,_u=w(()=>{F();Rh="https://midgard.ninerealms.com/v2"});async function Cu({fromChainId:e,toChainId:t,fromToken:r,toToken:n,fromAmount:o,userAddress:s}={}){if(!e||!t||!r||!n||!o||!s)return{error:"bungee quote requires fromChainId, toChainId, fromToken, toToken, fromAmount, userAddress"};try{let a=new URLSearchParams({fromChainId:String(e),toChainId:String(t),fromTokenAddress:r,toTokenAddress:n,fromAmount:String(o),userAddress:s,sort:"output",singleTxOnly:"false"}),i=await v(`${Nh}/quote?${a}`);return{amountOut:i?.result?.toAmount,feeUsd:i?.result?.totalGasFeesInUsd,route:i?.result?.route,estimatedTime:i?.result?.serviceTime?`${i.result.serviceTime}s`:"unknown"}}catch(a){return{error:String(a.message||a).slice(0,200)}}}var Nh,Ou=w(()=>{F();Nh="https://api.socket.tech/v2"});async function Tu({originDomain:e,destinationDomain:t,originToken:r,destinationToken:n,amount:o}={}){if(!e||!t||!r||!n||!o)return{error:"connext quote requires originDomain, destinationDomain, originToken, destinationToken, amount"};try{let s={originDomain:String(e),destinationDomain:String(t),originToken:r,destinationToken:n,amount:String(o)},a=await v(`${$h}/estimate`,{method:"POST",body:JSON.stringify(s),headers:{"content-type":"application/json"}});return{amountOut:a?.amountOut,fee:a?.fee,estimatedTime:a?.estimatedTransferTime}}catch(s){return{error:String(s.message||s).slice(0,200)}}}var $h,Ru=w(()=>{F();$h="https://api.connext.network"});async function Nu({fromChain:e,toChain:t,token:r,amount:n}={}){if(!e||!t||!r||!n)return{error:"wormhole quote requires fromChain, toChain, token, amount"};try{let o=new URLSearchParams({fromChain:String(e),toChain:String(t),token:r,amount:String(n)}),s=await v(`${Ph}/quote?${o}`);return{amountOut:s?.amountOut,fee:s?.fee,estimatedTime:s?.estimatedTime}}catch(o){return{error:String(o.message||o).slice(0,200)}}}var Ph,$u=w(()=>{F();Ph="https://api.portalbridge.com/v1"});function qh(e,t){return`0x${ns.getAmountsOut}`+be(e)+be(64)+be(t.length)+t.map(fr).join("")}function Bh(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 s=128+o*64;if(t.length<s+64)return null;n.push(BigInt(`0x${t.slice(s,s+64)}`))}return n}function rs(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}function Uh(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>os)throw new Error(`slippageBps ${r} exceeds the ${os} 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 Pu(e){let{chainId:t,wrappedNative:r}=e;async function n(o,s,a,i){let c=await ee(t,"eth_call",[{to:o,data:qh(s,a)},"latest"],i);return Bh(c?.result??c)}return{async quote({tokenIn:o,tokenOut:s,amountIn:a,path:i},c={}){let u=rs(c.scanner);if(!u)return{chainId:t,evidence:P.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let p=i||[o,s];if(p.some(d=>!/^0x[0-9a-fA-F]{40}$/.test(d||"")))throw new Error("quote requires valid 20-byte addresses");let l=await n(u,a,p,c);return l?{chainId:t,router:u,path:p,amountIn:String(a),amountOut:l[l.length-1].toString(),hops:p.length-1,evidence:P.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:p,evidence:P.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:s,base:a},i={}){let c=rs(i.scanner),u=a||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:R.UNKNOWN,evidence:P.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:R.UNKNOWN,evidence:P.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,s,[u,o],i);if(!p)return{chainId:t,token:o,verdict:R.FAIL,evidence:P.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let l=p[p.length-1];if(l===0n)return{chainId:t,token:o,verdict:R.FAIL,evidence:P.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let d=await n(c,l,[o,u],i);if(!d)return{chainId:t,token:o,verdict:R.FAIL,evidence:P.LIVE,leg:"sell",bought:l.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=d[d.length-1],h=Number(f*10000n/BigInt(s)),y=R.PASS,g="round trip completes with expected fee/impact loss";return h<5e3?(y=R.FAIL,g=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(y=R.CAUTION,g=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:u,router:c,verdict:y,reason:g,amountIn:String(s),bought:l.toString(),returned:f.toString(),retentionBps:h,evidence:P.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:s,amountIn:a,recipient:i,slippageBps:c=50,deadlineSeconds:u=900,path:p},l={}){let d=l.scanner,f=rs(d);if(!f)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,s],y=await this.quote({tokenIn:o,tokenOut:s,amountIn:a,path:h},l);if(y.evidence!==P.LIVE)throw new Error(`cannot prepare without a live quote (${y.evidence}: ${y.reason??"no reason given"})`);let g=Uh(y.amountOut,c);if(g<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=BigInt(Math.floor(Date.now()/1e3)+Number(u)),S=r&&h[0].toLowerCase()===r.toLowerCase()&&l.useNative,I=S?`0x${ns.swapExactETHForTokens}`+be(g)+be(128)+fr(i)+be(b)+be(h.length)+h.map(fr).join(""):`0x${ns.swapExactTokensForTokens}`+be(a)+be(g)+be(160)+fr(i)+be(b)+be(h.length)+h.map(fr).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:I,value:S?`0x${BigInt(a).toString(16)}`:"0x0"},guard:{quotedOut:y.amountOut,minOut:g.toString(),slippageBps:c,maxSlippageBps:os,deadline:b.toString()},requires:S?[]:[{step:"approve",token:h[0],spender:f,amount:String(a)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var ns,be,fr,os,qu=w(()=>{lt();pt();ns={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},be=e=>BigInt(e).toString(16).padStart(64,"0"),fr=e=>e.slice(2).toLowerCase().padStart(64,"0");os=100});function Lh(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>is)throw new Error(`slippageBps ${r} exceeds the ${is} 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 ss(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function Du(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:s,tokenIn:a,tokenOut:i,amountIn:c,fee:u},p){let l=`0x${Bu.quoteExactInputSingle}`+mr(a)+mr(i)+mt(c)+mt(u)+mt(0),d=await ee(t,"eth_call",[{to:s,data:l},"latest"],p).catch(()=>null),f=d?.result??d;if(!f||f==="0x"||f.length<66)return null;let h=BigInt(`0x${f.slice(2,66)}`);return h>0n?h:null}async function o({quoter:s,tokenIn:a,tokenOut:i,amountIn:c},u){let p=[],l=null;for(let d of Dh){let f=await n({quoter:s,tokenIn:a,tokenOut:i,amountIn:c,fee:d},u);p.push({fee:d,amountOut:f?f.toString():null}),f&&(!l||f>l.amountOut)&&(l={fee:d,amountOut:f})}return{best:l,tried:p}}return{async quote({tokenIn:s,tokenOut:a,amountIn:i},c={}){let u=ss(c.scanner,"quoter");if(!u)return{chainId:t,evidence:P.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let d of[s,a])if(!Uu.test(d||""))throw new Error("quote requires valid 20-byte addresses");let{best:p,tried:l}=await o({quoter:u,tokenIn:s,tokenOut:a,amountIn:i},c);return p?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:s,tokenOut:a,amountIn:String(i),amountOut:p.amountOut.toString(),fee:p.fee,triedFeeTiers:l,evidence:P.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:s,tokenOut:a,triedFeeTiers:l,evidence:P.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:s,amountIn:a,base:i},c={}){let u=ss(c.scanner,"quoter"),p=i||r;if(p&&String(s).toLowerCase()===String(p).toLowerCase())return{chainId:t,token:s,verdict:R.UNKNOWN,evidence:P.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:s,verdict:R.UNKNOWN,evidence:P.UNAVAILABLE,reason:u?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let l=await o({quoter:u,tokenIn:p,tokenOut:s,amountIn:a},c);if(!l.best)return{chainId:t,token:s,verdict:R.FAIL,evidence:P.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let d=await o({quoter:u,tokenIn:s,tokenOut:p,amountIn:l.best.amountOut},c);if(!d.best)return{chainId:t,token:s,verdict:R.FAIL,evidence:P.LIVE,leg:"sell",bought:l.best.amountOut.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=d.best.amountOut,h=Number(f*10000n/BigInt(a)),y=R.PASS,g="round trip completes with expected fee/impact loss";return h<5e3?(y=R.FAIL,g=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(y=R.CAUTION,g=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:p,verdict:y,reason:g,amountIn:String(a),bought:l.best.amountOut.toString(),returned:f.toString(),retentionBps:h,buyFee:l.best.fee,sellFee:d.best.fee,evidence:P.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:a,amountIn:i,recipient:c,slippageBps:u=50,fee:p},l={}){let d=ss(l.scanner,"router");if(!d)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(!Uu.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:s,tokenOut:a,amountIn:i},l);if(f.evidence!==P.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let h=p??f.fee,y=Lh(f.amountOut,u);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let g=`0x${Bu.exactInputSingle}`+mr(s)+mr(a)+mt(h)+mr(c)+mt(i)+mt(y)+mt(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:d,data:g,value:"0x0"},guard:{quotedOut:f.amountOut,minOut:y.toString(),slippageBps:u,maxSlippageBps:is,fee:h},requires:[{step:"approve",token:s,spender:d,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 Dh,Bu,mt,mr,Uu,is,Lu=w(()=>{lt();pt();Dh=[100,500,3e3,1e4],Bu={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},mt=e=>BigInt(e).toString(16).padStart(64,"0"),mr=e=>e.slice(2).toLowerCase().padStart(64,"0"),Uu=/^0x[0-9a-fA-F]{40}$/,is=100});function Fu(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function Mu(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),s=Buffer.from(o,"hex").toString("utf8").replace(/\0+$/,"");if(s)return s}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function Fh(e){let{chainId:t}=e;async function r(n,o,s){return ee(t,"eth_call",[{to:n,data:o},"latest"],s)}return{async blockNumber(n={}){let o=await Gr(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:P.LIVE}},async nativeBalance(n,o={}){let s=await pc(t,n,o);return{chainId:t,address:n,wei:s?.wei??s?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:P.LIVE}},async tokenBalance({token:n,owner:o},s={}){let a=await mc({chainId:t,token:n,owner:o},s);return{chainId:t,token:n,owner:o,raw:a?.balance??a,evidence:P.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:P.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[s,a,i,c]=await Promise.all([r(n,fn.decimals,o).catch(()=>null),r(n,fn.symbol,o).catch(()=>null),r(n,fn.name,o).catch(()=>null),r(n,fn.totalSupply,o).catch(()=>null)]),u=Fu(s?.result??s),p=u!==null||a?.result||i?.result;return{chainId:t,address:n,decimals:u===null?null:Number(u),symbol:Mu(a?.result??a),name:Mu(i?.result??i),totalSupply:(Fu(c?.result??c)??null)?.toString()??null,evidence:p?P.LIVE:P.UNKNOWN,warning:p?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(n,o={}){let s=e.dexscreenerSlug;if(!s)return{chainId:t,token:n,pools:[],evidence:P.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let a=await Vo(n,o).catch(()=>null),c=(a?.pairs||a?.data?.pairs||[]).filter(u=>String(u.chainId).toLowerCase()===String(s).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?P.LIVE:P.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:o,address:s,topics:a,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 l=n;l<=o;l+=i){let d=Math.min(l+i-1,o);p.push([l,d])}for(let[l,d]of p){let f={fromBlock:`0x${l.toString(16)}`,toBlock:`0x${d.toString(16)}`};s&&(f.address=s),a&&(f.topics=a);let h=await ee(t,"eth_getLogs",[f],c).catch(y=>({error:String(y?.message||y)}));if(h?.error)return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!1,failedAt:[l,d],error:h.error,evidence:P.UNKNOWN};for(let y of h?.result??h??[])u.push(y)}return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!0,chunks:p.length,evidence:P.LIVE}},async scoreRisk(n,o={}){let s=[],a=R.PASS,i=p=>{let l={[R.PASS]:0,[R.CAUTION]:1,[R.UNKNOWN]:2,[R.FAIL]:3};l[p]>l[a]&&(a=p)},c=await this.resolveToken(n,o);c.evidence!==P.LIVE?(s.push({check:"erc20-metadata",result:R.UNKNOWN,detail:c.warning}),i(R.UNKNOWN)):s.push({check:"erc20-metadata",result:R.PASS,detail:`${c.symbol} / ${c.decimals}d`});let u=await this.resolvePools(n,o);if(u.evidence===P.UNAVAILABLE)s.push({check:"liquidity",result:R.UNKNOWN,detail:u.reason}),i(R.UNKNOWN);else if(!u.pools.length)s.push({check:"liquidity",result:R.FAIL,detail:"no pool with liquidity found"}),i(R.FAIL);else{let p=u.pools[0],l=p.liquidityUsd??0;l<5e3?(s.push({check:"liquidity",result:R.CAUTION,detail:`top pool only $${l}`}),i(R.CAUTION)):s.push({check:"liquidity",result:R.PASS,detail:`$${l} on ${p.dex}`}),p.createdAt&&Date.now()-p.createdAt<24*3600*1e3&&(s.push({check:"age",result:R.CAUTION,detail:"pool under 24h old"}),i(R.CAUTION))}if(typeof this.sellSimulation=="function"){let p=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(l=>({verdict:R.UNKNOWN,reason:String(l?.message||l)}));s.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 s.push({check:"sellability",result:R.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(R.UNKNOWN);return{chainId:t,token:n,verdict:a,checks:s,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function as(e){let r={...Fh(e)},n=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,Du({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,Pu({chainId:e.chainId,wrappedNative:e.wrappedNative}));let o={};for(let[s,a]of Object.entries(r))o[s]=a.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 fn,ju=w(()=>{lt();Xr();pt();qu();Lu();fn={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"}});function Hu(){return hr.map(e=>tn(as(e)))}function zu(e){return tn(as(e))}var hr,cs=w(()=>{ju();pt();hr=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}}]}])});import{Interface as Yu,getAddress as Mh,id as Xu}from"ethers";function Ut(e){return e?.cache===!1?!1:!e?.fetchImpl||e.cache===!0}function ds(e,t,r){let n=e.get(t);return n?Date.now()-n.at>r?(e.delete(t),null):n:null}function mn(e,t,r,n){for(e.delete(t),e.set(t,{at:Date.now(),value:r});e.size>n;){let o=e.keys().next();if(o.done)break;e.delete(o.value)}}function og(e,t){try{return Mh(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function sg(e){return`0x${e.slice(2).toLowerCase().padStart(64,"0")}`}function Gu(e){return`0x${String(e).slice(-40).toLowerCase()}`}function ig({unlimited:e,spenderLabel:t,lastActivityAt:r}){if(e)return"unlimited";if(!t)return"unknown-spender";if(r){let n=Date.parse(r);if(Number.isFinite(n)&&Date.now()-n>Jh)return"stale"}return"scoped"}function ag(e,t,r){if(r)return"UNLIMITED";if(t==null)return e.toString();let n=10n**BigInt(t),o=e/n,s=e%n;if(s===0n)return o.toLocaleString("en-US");let a=s.toString().padStart(t,"0").replace(/0+$/,"").slice(0,6);return`${o.toLocaleString("en-US")}${a?`.${a}`:""}`}async function cg(e,t,r,n){let o=`${e}:${t}`,s=n?.get(o);if(s)return s;if(Ut(r)){let i=ds(Wu,o,Zh);if(i)return i.value}let a=(async()=>{let i=async l=>{try{let d=Vu.encodeFunctionData(l,[]),f=await ee(e,"eth_call",[{to:t,data:d},"latest"],r);return!f||f==="0x"?null:Vu.decodeFunctionResult(l,f)[0]}catch{return null}},[c,u]=await Promise.all([i("decimals"),i("symbol")]),p={decimals:c==null?null:Number(c),symbol:u==null?null:String(u).slice(0,24)};return Ut(r)&&mn(Wu,o,p,rg),p})();return n?.set(o,a),a}async function ug(e,t,r){let n=Math.min(Math.max(Number(r.lookbackBlocks)||Hh,1),zh),o=await Gr(e,r);if(!Number.isFinite(o))throw new Error("chain head unavailable");let s=Math.max(0,o-n),a=await ee(e,"eth_getLogs",[{fromBlock:`0x${s.toString(16)}`,toBlock:"latest",topics:[jh,sg(t)]}],r);if(!Array.isArray(a))throw new Error("log scan returned no array");let i=new Map;for(let c of a){let u=String(c?.address||"").toLowerCase(),p=c?.topics?.[2];!u||!p||i.set(`${u}:${Gu(p)}`,{token:u,spender:Gu(p)})}return{pairs:[...i.values()],fromBlock:s,toBlock:o}}function lg(e){return(Gh[e]||[]).flatMap(r=>Kh.map(n=>({token:r.address,spender:n.address,symbol:r.symbol,decimals:r.decimals})))}async function dg(e,t,r={}){let n=[],o="direct-probe",s=null,a=lg(e),i=ls(e),c=Ut(r)&&ds(us,e,eg)?.value===!1;if(a.length===0&&i.length===0&&c)return{scan:{chainId:e,status:"unconfigured",method:o,error:"no Approval log access and no candidate token or collection set for this chain"},approvals:[]};try{let u=await ug(e,t,r);n=u.pairs,o="log-scan",s={fromBlock:u.fromBlock,toBlock:u.toBlock},Ut(r)&&mn(us,e,!0,64)}catch{if(Ut(r)&&mn(us,e,!1,64),n=a,n.length===0&&i.length===0)return{scan:{chainId:e,status:"unconfigured",method:o,error:"no Approval log access and no candidate token or collection set for this chain"},approvals:[]}}try{let u=new Map,l=(await Ir(n,r.concurrency||4,async f=>{try{let h=await fc({chainId:e,token:f.token,owner:t,spender:f.spender},r),y=BigInt(h.allowance);if(y<=0n)return null;let g=f.symbol?{symbol:f.symbol,decimals:f.decimals??null}:await cg(e,f.token,r,u),b=y>=Xh,S=Vh[f.spender]||null;return{id:`${e}:${f.token}:${f.spender}`,chainId:e,standard:"erc20",token:f.token,tokenSymbol:g.symbol,decimals:g.decimals,spender:f.spender,spenderLabel:S,allowance:y.toString(),allowanceDisplay:ag(y,g.decimals,b),unlimited:b,lastActivityAt:null,risk:ig({unlimited:b,spenderLabel:S,lastActivityAt:null})}}catch{return null}})).filter(Boolean),d=await fg(e,t,r);return{scan:{chainId:e,status:"ok",method:o,pairsProbed:n.length,collectionsProbed:ls(e).length,...s||{}},approvals:[...l,...d]}}catch(u){return{scan:{chainId:e,status:"unavailable",method:o,error:String(u?.message||u).slice(0,200)},approvals:[]}}}async function pg(e,t,r,n,o){try{let s=Ku.encodeFunctionData("isApprovedForAll",[r,n]),a=await ee(e,"eth_call",[{to:t,data:s},"latest"],o);return!a||a==="0x"?null:!!Ku.decodeFunctionResult("isApprovedForAll",a)[0]}catch{return null}}function ls(e){return(Qh[e]||[]).flatMap(r=>Wh.map(n=>({collection:r.address,collectionName:r.name,operator:n.address,operatorLabel:n.label})))}async function fg(e,t,r){let n=ls(e);return n.length===0?[]:(await Ir(n,r.concurrency||4,async s=>await pg(e,s.collection,t,s.operator,r)!==!0?null:{id:`${e}:${s.collection}:${s.operator}:all`,chainId:e,standard:"erc721",token:s.collection,tokenSymbol:s.collectionName,decimals:null,spender:s.operator,spenderLabel:s.operatorLabel,allowance:null,allowanceDisplay:"ALL ITEMS",unlimited:!0,lastActivityAt:null,risk:"operator-all"})).filter(Boolean)}async function Ju(e={},t={}){let r=og(e.owner||e.address,"owner"),n=new Map(hr.map(f=>[f.chainId,f])),o=Array.isArray(e.chainIds)&&e.chainIds.length?[...new Set(e.chainIds.map(Number))].filter(f=>n.has(f)):[...n.keys()],s=`${r}:${[...o].sort((f,h)=>f-h).join(",")}:${e.lookbackBlocks??""}`,a=Ut(t)&&!e.refresh;if(a){let f=ds(Qu,s,tg);if(f)return{...f.value,cached:!0,cachedAgeMs:Date.now()-f.at}}let i=await Ir(o,e.concurrency||3,f=>dg(f,r,{...t,lookbackBlocks:e.lookbackBlocks})),c=i.flatMap(f=>f.approvals),u=i.map(f=>f.scan),p=u.find(f=>f.method==="log-scan"&&f.toBlock),l=u.some(f=>f.method==="direct-probe"&&f.status==="ok"),d={provider:"approvals",operation:"scan",readOnly:!0,queriedAt:new Date().toISOString(),owner:r,scannedRange:p?`last ${p.toBlock-p.fromBlock} blocks`:l?"known routers, live allowance probe":null,approvals:c,scans:u,warnings:["Approval discovery is scoped. Log scanning is used where the endpoint permits it; otherwise a curated router set is probed directly. An empty result means nothing was found in that scope, not that the wallet is safe.","NFT operator approval (setApprovalForAll) is checked against a curated collection and marketplace set on supported chains only. A collection outside that set is not checked."]};return a&&mn(Qu,s,d,ng),{...d,cached:!1,cachedAgeMs:0}}var Vu,Ku,jh,jE,Hh,zh,Vh,Kh,Wh,Qh,Gh,Yh,Xh,Jh,Zh,eg,tg,rg,ng,Wu,us,Qu,Zu=w(()=>{cs();F();lt();Vu=new Yu(["function decimals() view returns (uint8)","function symbol() view returns (string)"]),Ku=new Yu(["function isApprovedForAll(address owner, address operator) view returns (bool)","function name() view returns (string)"]),jh=Xu("Approval(address,address,uint256)"),jE=Xu("ApprovalForAll(address,address,bool)"),Hh=1e4,zh=2e5,Vh=Object.freeze({"0x1111111254eeb25477b68fb85ed929f73a960582":"1inch v5 Router","0x111111125421ca6dc452d289314280a0f8842a65":"1inch v6 Router","0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45":"Uniswap Universal Router","0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad":"Uniswap Universal Router","0x000000000022d473030f116ddee9f6b43ac78ba3":"Permit2","0xe592427a0aece92de3edee1f18e0157c05861564":"Uniswap v3 Router","0x7a250d5630b4cf539739df2c5dacb4c659f2488d":"Uniswap v2 Router","0xdef1c0ded9bec7f1a1670819833240f027b25eff":"0x Exchange Proxy","0x2626664c2603336e57b271c5c0b26f421741e481":"Uniswap SwapRouter02 (Base)","0x6131b5fae19ea4f9d964eac0408e4408b66337b5":"KyberSwap Meta Aggregator","0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC (token contract)"}),Kh=Object.freeze([{address:"0x000000000022d473030f116ddee9f6b43ac78ba3",label:"Permit2"},{address:"0x1111111254eeb25477b68fb85ed929f73a960582",label:"1inch v5 Router"},{address:"0x111111125421ca6dc452d289314280a0f8842a65",label:"1inch v6 Router"},{address:"0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45",label:"Uniswap Universal Router"},{address:"0xe592427a0aece92de3edee1f18e0157c05861564",label:"Uniswap v3 Router"},{address:"0x7a250d5630b4cf539739df2c5dacb4c659f2488d",label:"Uniswap v2 Router"},{address:"0xdef1c0ded9bec7f1a1670819833240f027b25eff",label:"0x Exchange Proxy"},{address:"0x2626664c2603336e57b271c5c0b26f421741e481",label:"Uniswap SwapRouter02"}]),Wh=Object.freeze([{address:"0x1e0049783f008a0085193e00003d00cd54003c71",label:"OpenSea Seaport Conduit"},{address:"0x00000000000000adc04c56bf30ac9d3c0aaf14dc",label:"Seaport 1.5"},{address:"0x0000000000000068f116a894984e2db1123eb395",label:"Seaport 1.6"},{address:"0x00000000000001ad428e4906ae43d8f9852d0dd6",label:"Seaport 1.4"},{address:"0x000000000000ad05ccc4f10045630fb830b95127",label:"Blur Marketplace"},{address:"0x00000000000000000000000000000000000000a5",label:"Blur Execution Delegate"},{address:"0xf42aa99f011a1fa7cda90e5e98b277e306bca83e",label:"Rarible Transfer Proxy"},{address:"0x000000000022d473030f116ddee9f6b43ac78ba3",label:"Permit2"}]),Qh=Object.freeze({1:[{address:"0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d",name:"Bored Ape Yacht Club"},{address:"0x60e4d786628fea6478f785a6d7e704777c86a7c6",name:"Mutant Ape Yacht Club"},{address:"0xed5af388653567af2f388e6224dc7c4b3241c544",name:"Azuki"},{address:"0x8a90cab2b38dba80c64b7734e58ee1db38b8992e",name:"Doodles"},{address:"0x49cf6f5d44e70224e2e23fdcdd2c053f30ada28b",name:"CloneX"},{address:"0x23581767a106ae21c074b2276d25e5c3e136a68b",name:"Moonbirds"}]}),Gh=Object.freeze({1:[{address:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",symbol:"USDC",decimals:6},{address:"0xdac17f958d2ee523a2206206994597c13d831ec7",symbol:"USDT",decimals:6},{address:"0x6b175474e89094c44da98b954eedeac495271d0f",symbol:"DAI",decimals:18},{address:"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",symbol:"WETH",decimals:18},{address:"0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",symbol:"WBTC",decimals:8}],8453:[{address:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",symbol:"USDC",decimals:6},{address:"0x4200000000000000000000000000000000000006",symbol:"WETH",decimals:18}],42161:[{address:"0xaf88d065e77c8cc2239327c5edb3a432268e5831",symbol:"USDC",decimals:6},{address:"0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9",symbol:"USDT",decimals:6},{address:"0x82af49447d8a07e3bd95bd0d56f35241523fbab1",symbol:"WETH",decimals:18}],10:[{address:"0x0b2c639c533813f4aa9d7837caf62653d097ff85",symbol:"USDC",decimals:6},{address:"0x4200000000000000000000000000000000000006",symbol:"WETH",decimals:18}],137:[{address:"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359",symbol:"USDC",decimals:6},{address:"0xc2132d05d31c914a87c6611c10748aeb04b58e8f",symbol:"USDT",decimals:6}]}),Yh=(1n<<256n)-1n,Xh=Yh/2n,Jh=4320*60*60*1e3,Zh=360*60*1e3,eg=600*1e3,tg=45*1e3,rg=512,ng=128,Wu=new Map,us=new Map,Qu=new Map});var rl={};z(rl,{aggregateBridgeQuotes:()=>el,bridgeAggregatorHealth:()=>hg,checkRevokeNeeded:()=>tl,scanBridgeRoutes:()=>mg});async function el(e={}){let{fromChainId:t,toChainId:r,tokenIn:n,tokenOut:o,amount:s,taker:a,fromSymbol:i="?",toSymbol:c="?",fromDecimals:u=18,toDecimals:p=18}=e,l=[],d=[],f=mu({srcChainId:t,srcChainTokenIn:n,srcChainTokenInAmount:s,dstChainId:r,dstChainTokenOut:o}).then(m=>m.error?(d.push(`debridge: ${m.error}`),null):{provider:"debridge",amountOut:m.estimation?.dstChainTokenOut?.amount??m.estimation?.toAmount,feeUsd:m.estimation?.fixFee??m.fixFee,estimatedTime:m.estimation?.execution?.estimatedTransferTime?`${m.estimation.execution.estimatedTransferTime}s`:"unknown",preparable:!0,raw:m}).catch(m=>(d.push(`debridge: ${m.message}`),null)),h=pr({fromChainId:t,toChainId:r,tokenIn:n,tokenOut:o,amountIn:s,taker:a}).then(m=>!m||m.error?(d.push(`lifi: ${m?.error??"no route"}`),null):{provider:"lifi-relay",amountOut:m.amountOut??m.quote?.amountOut,feeUsd:m.feeUsd??m.totalFee,estimatedTime:m.estimatedTime??m.duration??"unknown",preparable:!!m.transaction,raw:m}).catch(m=>(d.push(`lifi: ${m.message}`),null)),y=Eu({fromChain:t,toChain:r,fromToken:n,toToken:o,fromAmount:s,fromAddress:a}).then(m=>m.error?(d.push(`squid: ${m.error}`),null):{provider:"squid",amountOut:m.toAmount,feeUsd:Array.isArray(m.fee)?m.fee.reduce((T,j)=>T+(Number(j.amountUsd)||0),0):null,estimatedTime:"30s - 3min",preparable:!1,raw:m}).catch(m=>(d.push(`squid: ${m.message}`),null)),g=Au({srcChainId:t,dstChainId:r,token:n,amount:s}).then(m=>m.error?(d.push(`stargate: ${m.error}`),null):{provider:"stargate",amountOut:m.amountOut,feeUsd:m.fee,estimatedTime:m.estimatedTime||"1-5 min",preparable:!1,raw:m}).catch(m=>(d.push(`stargate: ${m.message}`),null)),b=Iu({fromAsset:i,toAsset:c,amount:s,destination:a}).then(m=>m.error?(d.push(`thorchain: ${m.error}`),null):{provider:"thorchain",amountOut:m.expectedAmountOut,feeUsd:m.fees?.total,estimatedTime:m.estimatedTime||"10-30 min",preparable:!1,raw:m}).catch(m=>(d.push(`thorchain: ${m.message}`),null)),S=(async()=>{if(!i||!c||i==="?"||c==="?")return d.push("changenow: ticker symbols required, skipping"),null;try{let m=await wu({fromTicker:i,toTicker:c,fromAmount:s});return m.error?(d.push(`changenow: ${m.error}`),null):{provider:"changenow",amountOut:m.toAmount,feeUsd:m.networkFee,estimatedTime:m.flow==="standard"?"5-30 min":"instant",preparable:!1,kycRequired:m.kycRequired,raw:m}}catch(m){return d.push(`changenow: ${m.message}`),null}})(),I=Cu({fromChainId:t,toChainId:r,fromToken:n,toToken:o,fromAmount:s,userAddress:a}).then(m=>m.error?(d.push(`bungee: ${m.error}`),null):{provider:"bungee",amountOut:m.amountOut,feeUsd:m.feeUsd,estimatedTime:m.estimatedTime,preparable:!1,raw:m}).catch(m=>(d.push(`bungee: ${m.message}`),null)),A=Tu({originDomain:t,destinationDomain:r,originToken:n,destinationToken:o,amount:s}).then(m=>m.error?(d.push(`connext: ${m.error}`),null):{provider:"connext",amountOut:m.amountOut,feeUsd:m.fee,estimatedTime:m.estimatedTime||"5-20 min",preparable:!1,raw:m}).catch(m=>(d.push(`connext: ${m.message}`),null)),O=Nu({fromChain:t,toChain:r,token:n,amount:s}).then(m=>m.error?(d.push(`wormhole: ${m.error}`),null):{provider:"wormhole",amountOut:m.amountOut,feeUsd:m.fee,estimatedTime:m.estimatedTime||"5-15 min",preparable:!1,raw:m}).catch(m=>(d.push(`wormhole: ${m.message}`),null)),_=await Promise.allSettled([f,h,y,g,b,I,A,O,S]);for(let m of _)m.status==="fulfilled"&&m.value&&l.push(m.value);return l.sort((m,T)=>{let j=Number(m.amountOut??0),se=Number(T.amountOut??0);return j!==se?se-j:m.preparable&&!T.preparable?-1:!m.preparable&&T.preparable?1:0}),{providers:l.map(m=>m.provider),bestRoute:l[0]?.provider??"none",winner:l[0]??null,runnersUp:l.slice(1),errors:d.length?d:null}}async function tl({chainId:e,taker:t,tokenIn:r}={}){if(!e||!t)return{needsRevoke:!1,note:"no wallet to check"};try{let o=(await Ju({chainIds:[e],address:t})).approvals;if(!o?.length)return{needsRevoke:!1,note:"no active approvals found"};let s=r?o.find(a=>String(a.token).toLowerCase()===String(r).toLowerCase()):null;return s&&BigInt(s.allowance??"0")>0n?{needsRevoke:!0,spender:s.spender,amount:s.allowance,symbol:s.symbol??"?",decimals:s.decimals??18,note:`approval found for ${s.spender}, revoke before bridging`}:{needsRevoke:!1,note:`no active approval for this token (${o.length} total approvals on chain)`}}catch(n){return{needsRevoke:!1,note:`revoke check unavailable: ${String(n.message||n).slice(0,100)}`}}}async function mg(e={}){let[t,r]=await Promise.all([el(e),tl({chainId:e.fromChainId,taker:e.taker,tokenIn:e.tokenIn})]),n=t.winner??{};return{kind:"bridge",fromChainId:e.fromChainId,toChainId:e.toChainId,fromSymbol:e.fromSymbol,toSymbol:e.toSymbol,amount:e.amount,fromDecimals:e.fromDecimals??18,toDecimals:e.toDecimals??18,bestRoute:n.provider??"none",amountOut:n.amountOut,feeUsd:n.feeUsd,estimatedTime:n.estimatedTime,preparable:n.preparable?"yes":"no (manual send)",providers:t.providers,runnersUp:t.runnersUp,revokeCheck:r,errors:t.errors,confidence:t.providers.length>=2?.85:t.providers.length===1?.6:.1}}async function hg(){let[e,t]=await Promise.all([hu().catch(r=>({ok:!1,error:r.message})),xu().catch(r=>({ok:!1,error:r.message}))]);return{debridge:e,changenow:t,lifi:{ok:!0,note:"integrated via router"}}}var mk,nl=w(()=>{qt();gu();Su();ku();vu();_u();Ou();Ru();$u();Zu();mk=Object.freeze(["debridge","lifi-relay","squid","stargate","thorchain","bungee","connext","wormhole","changenow"])});var ol={};z(ol,{DYDX_API:()=>hn,dydxHealth:()=>bg,dydxMarkets:()=>gg,dydxOrderbook:()=>yg});async function gg(e=50){try{return((await v(`${hn}/v4/perpetualMarkets?limit=${e}`))?.markets||[]).map(r=>({ticker:r?.ticker,oraclePrice:r?.oraclePrice,indexPrice:r?.indexPrice,nextFundingRate:r?.nextFundingRate?`${(Number(r.nextFundingRate)*100).toFixed(4)}%`:null,openInterest:r?.openInterest,volume24h:r?.volume24H}))}catch(t){return{error:String(t.message||t).slice(0,200)}}}async function yg(e){try{let t=await v(`${hn}/v4/orderbooks/perpetualMarket/${e}`);return{bids:t?.bids?.slice(0,5),asks:t?.asks?.slice(0,5)}}catch(t){return{error:String(t.message||t).slice(0,200)}}}async function bg(){try{return{ok:!0,serverTime:(await v(`${hn}/v4/time`))?.iso}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var hn,sl=w(()=>{F();hn="https://api.dydx.exchange"});var al={};z(al,{DRIFT_API:()=>il,driftHealth:()=>xg,driftMarkets:()=>wg});async function wg(){try{return((await v(`${il}/v2/markets`))?.markets||[]).map(t=>({symbol:t?.symbol||t?.marketIndex,oraclePrice:t?.amm?.oraclePrice,markPrice:t?.amm?.markPrice,fundingRate:t?.amm?.lastFundingRate?`${(Number(t.amm.lastFundingRate)*100).toFixed(4)}%`:null,openInterest:{long:t?.amm?.longFunding,short:t?.amm?.shortFunding},volume24h:t?.amm?.quoteAssetVolume}))}catch(e){return{error:String(e.message||e).slice(0,200)}}}async function xg(){try{return{ok:!0,note:"Drift v2 perps on Solana \u2014 public reads via dlob.drift.trade"}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var il,cl=w(()=>{F();il="https://dlob.drift.trade"});var ul={};z(ul,{VERTEX_API:()=>gn,vertexHealth:()=>kg,vertexMarkets:()=>Sg,vertexOrderbook:()=>Eg});async function Sg(){try{return((await v(`${gn}/query`,{method:"POST",body:JSON.stringify({all_markets:{}}),headers:{"content-type":"application/json"}}))?.data?.all_markets||[]).map(t=>({market:t?.market,type:t?.type,oraclePrice:t?.oracle_price_x18?(Number(BigInt(t.oracle_price_x18))/1e18).toFixed(4):null,minSize:t?.min_size,productId:t?.product_id}))}catch(e){return{error:String(e.message||e).slice(0,200)}}}async function Eg(e){try{let r=(await v(`${gn}/query`,{method:"POST",body:JSON.stringify({market_liquidity:{product_id:Number(e),depth:5}}),headers:{"content-type":"application/json"}}))?.data?.market_liquidity;return{bids:r?.bids||[],asks:r?.asks||[]}}catch(t){return{error:String(t.message||t).slice(0,200)}}}async function kg(){try{return{ok:!0,status:(await v(`${gn}/status`))?.status||"unknown"}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var gn,ll=w(()=>{F();gn="https://gateway.prod.vertexprotocol.com/v2"});var dl={};z(dl,{pancakeHealth:()=>Ig,pancakeQuote:()=>vg});async function vg({chainId:e=56,tokenIn:t,tokenOut:r,amountIn:n,fee:o=500}={}){if(!t||!r||!n)return{error:"pancake quote requires tokenIn, tokenOut, amountIn"};try{let s={tokenIn:String(t).toLowerCase(),tokenOut:String(r).toLowerCase(),amountIn:String(n),fee:String(o)},a=await v(`${Ag}/quote`,{method:"POST",body:JSON.stringify(s),headers:{"content-type":"application/json"}});return{amountOut:a?.amountOut,route:a?.route}}catch(s){return{error:String(s.message||s).slice(0,200)}}}async function Ig(){try{return{ok:!0,chains:["bsc (56)","ethereum (1)","arbitrum (42161)","base (8453)","opbnb (204)","zksync (324)","linea (59144)"]}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var Ag,pl=w(()=>{F();Ag="https://api.thegraph.com/subgraphs/name/pancakeswap/exchange-v3-bsc"});var ml={};z(ml,{sushiHealth:()=>Og,sushiQuote:()=>Cg});async function Cg({chainId:e=1,tokenIn:t,tokenOut:r,amountIn:n,fee:o=500}={}){if(!t||!r||!n)return{error:"sushi quote requires tokenIn, tokenOut, amountIn"};try{let s=`{ quote(tokenIn:"${t}",tokenOut:"${r}",amountIn:"${n}",fee:${o}) { amountOut route } }`,a=await v(`${_g(e)}/quote?query=${encodeURIComponent(s)}`);return{amountOut:a?.data?.quote?.amountOut,route:a?.data?.quote?.route}}catch(s){return{error:String(s.message||s).slice(0,200)}}}async function Og(){try{return{ok:!0,chains:Object.keys(fl).length+" chains"}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var _g,fl,hl=w(()=>{F();_g=e=>`https://api.thegraph.com/subgraphs/name/sushi-v3/v3-${fl[e]||"ethereum"}`,fl={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",59144:"linea",534352:"scroll",324:"zksync-era",250:"fantom",2222:"kava",1088:"metis",1284:"moonbeam",1285:"moonriver",288:"boba",1101:"polygon-zkevm",5e3:"mantle",81457:"blast"}});var gl={};z(gl,{raydiumHealth:()=>Ng,raydiumQuote:()=>Rg});async function Rg({inputMint:e,outputMint:t,amount:r,slippageBps:n=50}={}){if(!e||!t||!r)return{error:"raydium quote requires inputMint, outputMint, amount"};try{let o=new URLSearchParams({inputMint:e,outputMint:t,amount:String(r),slippageBps:String(n),onlyDirectRoutes:"true"}),s=await v(`${Tg}/quote?${o}`),a=(s?.routePlan||[]).filter(i=>i?.swapInfo?.label?.toLowerCase().includes("raydium"));return{amountOut:s?.outAmount,priceImpactPct:s?.priceImpactPct,raydiumRoutes:a.length,allRoutes:s?.routePlan?.length||0}}catch(o){return{error:String(o.message||o).slice(0,200)}}}async function Ng(){try{return{ok:!0,note:"Raydium routes through Jupiter aggregator on Solana"}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var Tg,yl=w(()=>{F();Tg="https://quote-api.jup.ag/v6"});var bl={};z(bl,{AEVO_API:()=>ps,aevoHealth:()=>Pg,aevoMarkets:()=>$g});async function $g(){try{return(await v(`${ps}/markets`)||[]).map(t=>({instrument:t?.instrument_name,type:t?.instrument_type,markPrice:t?.mark_price,indexPrice:t?.index_price,fundingRate:t?.funding_rate?`${(Number(t.funding_rate)*100).toFixed(4)}%`:null,openInterest:t?.open_interest,volume24h:t?.volume_24h}))}catch(e){return{error:String(e.message||e).slice(0,200)}}}async function Pg(){try{return{ok:(await v(`${ps}/ping`))?.status==="ok"}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var ps,wl=w(()=>{F();ps="https://api.aevo.xyz"});var xl={};z(xl,{compoundHealth:()=>Ug,compoundMarkets:()=>Bg});async function Bg(){try{return((await v(`${qg}/ctoken`))?.cToken||[]).map(t=>({symbol:t?.symbol,underlying:t?.underlying_symbol,supplyApy:t?.supply_rate?.value?`${(Number(t.supply_rate.value)*100).toFixed(2)}%`:null,borrowApy:t?.borrow_rate?.value?`${(Number(t.borrow_rate.value)*100).toFixed(2)}%`:null,totalSupply:t?.total_supply?.value,totalBorrow:t?.total_borrows?.value,collateralFactor:t?.collateral_factor?.value?`${(Number(t.collateral_factor.value)*100).toFixed(0)}%`:null}))}catch(e){return{error:String(e.message||e).slice(0,200)}}}async function Ug(){try{return{ok:!0,note:"Compound v2 \u2014 Ethereum mainnet lending"}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var qg,Sl=w(()=>{F();qg="https://api.compound.finance/api/v2"});var El={};z(El,{yearnHealth:()=>Fg,yearnVaults:()=>Lg});async function Lg(){try{return(await v(`${Dg}/vaults/all`)||[]).map(t=>({name:t?.name,symbol:t?.symbol,apy:t?.apy?.net_apy?`${(Number(t.apy.net_apy)*100).toFixed(2)}%`:null,tvl:t?.tvl?.tvl_deposited,chain:t?.chainId,type:t?.type||"v2"}))}catch(e){return{error:String(e.message||e).slice(0,200)}}}async function Fg(){try{return{ok:!0,note:"Yearn \u2014 yield aggregator across Ethereum, Arbitrum, Optimism, Fantom"}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var Dg,kl=w(()=>{F();Dg="https://api.yearn.fi/v1"});var Al={};z(Al,{convexHealth:()=>Hg,convexPools:()=>jg});async function jg(){try{return(await v(`${Mg}/pools`)||[]).map(t=>({name:t?.curvePool?.name||t?.name,curveApy:t?.curvePool?.apy?`${(Number(t.curvePool.apy)*100).toFixed(2)}%`:null,convexApy:t?.apy?`${(Number(t.apy)*100).toFixed(2)}%`:null,tvl:t?.tvl,boosted:t?.boosted||!1}))}catch(e){return{error:String(e.message||e).slice(0,200)}}}async function Hg(){try{return{ok:!0,note:"Convex \u2014 CRV/CVX yield optimizer on Ethereum"}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}var Mg,vl=w(()=>{F();Mg="https://api.convexfinance.com/api"});function ht(e){if(!Number.isSafeInteger(e)||e<0||e>1e3)throw new RangeError("scale must be a safe integer from 0 through 1000")}function Ue(e,t){if(typeof e!="bigint")throw new TypeError("mantissa must be a bigint");return ht(t),Object.freeze({mantissa:e,scale:t})}function Ze(e,t="value"){if(e===null||typeof e!="object")throw new TypeError(`${t} must be a fixed point value`);if(typeof e.mantissa!="bigint")throw new TypeError(`${t}.mantissa must be a bigint`);ht(e.scale)}function yn(e){return ht(e),10n**BigInt(e)}function $(e){if(typeof e!="string"||!/^[+-]?\d+(?:\.\d+)?$/.test(e))throw new TypeError("value must be a plain decimal string");let t=e.startsWith("-"),r=e[0]==="-"||e[0]==="+"?e.slice(1):e,[n,o=""]=r.split("."),s=`${n}${o}`,a=BigInt(s)*(t?-1n:1n);return Ue(a,o.length)}function fe(e,t){if(ht(t),typeof e=="bigint")return Ue(e,t);if(typeof e!="string"||!/^[+-]?\d+$/.test(e))throw new TypeError("value must be an integer string or bigint");return Ue(BigInt(e),t)}function Ie(e){Ze(e);let t=e.mantissa<0n,r=(t?-e.mantissa:e.mantissa).toString();if(e.scale===0)return`${t?"-":""}${r}`;let n=r.padStart(e.scale+1,"0"),o=n.length-e.scale;return`${t?"-":""}${n.slice(0,o)}.${n.slice(o)}`}function gr(e,t){return Ze(e),ht(t),t===e.scale?Ue(e.mantissa,e.scale):t>e.scale?Ue(e.mantissa*yn(t-e.scale),t):Ue(e.mantissa/yn(e.scale-t),t)}function fs(e,t){Ze(e,"left"),Ze(t,"right");let r=Math.max(e.scale,t.scale);return[gr(e,r),gr(t,r),r]}function et(e,t){let[r,n,o]=fs(e,t);return Ue(r.mantissa+n.mantissa,o)}function yr(e,t){let[r,n,o]=fs(e,t);return Ue(r.mantissa-n.mantissa,o)}function he(e,t){Ze(e,"left"),Ze(t,"right");let r=e.scale+t.scale;return ht(r),Ue(e.mantissa*t.mantissa,r)}function _e(e,t,r=Math.max(e?.scale??0,t?.scale??0)){if(Ze(e,"left"),Ze(t,"right"),ht(r),t.mantissa===0n)throw new RangeError("division by zero");let n=e.mantissa*yn(t.scale+r),o=t.mantissa*yn(e.scale);return Ue(n/o,r)}function tt(e,t){let[r,n]=fs(e,t);return r.mantissa<n.mantissa?-1:r.mantissa>n.mantissa?1:0}var vk,we=w(()=>{vk=Object.freeze({mantissa:10000n,scale:0})});import{existsSync as _l,readFileSync as zg}from"node:fs";import{dirname as Il,join as ms}from"node:path";import{fileURLToPath as Vg}from"node:url";function Kg(e){let t=Il(Vg(e));for(let r=0;r<8;r+=1){let n=ms(t,"package.json");if(_l(n))try{let s=JSON.parse(zg(n,"utf8"));if(s&&typeof s.version=="string")return t}catch{}let o=Il(t);if(o===t)break;t=o}throw new Error(`oracle: could not resolve package root from ${e}`)}function Cl(e,t){let r=Kg(t),n=ms(r,"dist","assets",e);return _l(n)?n:ms(r,e)}var Ol=w(()=>{});import{readFileSync as Wg,existsSync as Qg}from"node:fs";import{fileURLToPath as Gg}from"node:url";import{dirname as Yg,join as Rl}from"node:path";function Jg(){try{let e=Cl("equities-fixtures",import.meta.url);if(e&&Qg(e))return e}catch{}return Xg}function ey(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function D(e,t){throw new TypeError(`Fixture fixtures/${e}: ${t}`)}function te(e,t,r){ey(e)||D(t,`${r} must be an object`)}function M(e,t,r){(typeof e!="string"||e.length===0)&&D(t,`${r} must be a nonempty string`)}function De(e,t,r){Number.isSafeInteger(e)||D(t,`${r} must be a safe integer`)}function rt(e,t,r){te(e,t,r);for(let[n,o]of Object.entries(e))M(n,t,`${r} key`),te(o,t,`${r}.${n}`)}function ty(e,t){te(e,t,"root"),De(e.capturedAt,t,"capturedAt"),te(e.venues,t,"venues");let r=[["hyperliquid_hip3","dexs"],["arcus","markets"],["arcus_spot","pairs"],["rh_uniswap","pools"],["rh_chainlink_oracles","assets"]];for(let[n,o]of r){let s=e.venues[n];te(s,t,`venues.${n}`),M(s.type,t,`venues.${n}.type`),M(s.chain,t,`venues.${n}.chain`),M(s.tier,t,`venues.${n}.tier`),rt(s[o],t,`venues.${n}.${o}`)}for(let[n,o]of Object.entries(e.venues.hyperliquid_hip3.dexs))rt(o,t,`venues.hyperliquid_hip3.dexs.${n}`)}function ry(e,t){rt(e,t,"root"),Object.keys(e).length===0&&D(t,"root must not be empty");for(let[r,n]of Object.entries(e))Array.isArray(n.venues)||D(t,`${r}.venues must be an array`),n.venues.forEach((o,s)=>M(o,t,`${r}.venues[${s}]`))}function ny(e,t){te(e,t,"root");for(let r of["chainId","block","oracleScaleExp","usdgDecimals","equityDecimals"])De(e[r],t,r);M(e.usdg,t,"usdg"),rt(e.assets,t,"assets");for(let[r,n]of Object.entries(e.assets))M(n.oracle,t,`assets.${r}.oracle`),M(n.token,t,`assets.${r}.token`),(typeof n.rawPrice!="string"||!/^\d+$/.test(n.rawPrice))&&D(t,`assets.${r}.rawPrice must be an integer string`),(typeof n.usd!="number"||!Number.isFinite(n.usd)||n.usd<0)&&D(t,`assets.${r}.usd must be a nonnegative finite source number`)}function oy(e,t){te(e,t,"root");for(let n of["holidayDayIndex","names","dates"])Array.isArray(e[n])||D(t,`${n} must be an array`);let r=e.holidayDayIndex.length;(e.names.length!==r||e.dates.length!==r)&&D(t,"holidayDayIndex, names, and dates must have equal lengths"),e.holidayDayIndex.forEach((n,o)=>De(n,t,`holidayDayIndex[${o}]`)),e.names.forEach((n,o)=>M(n,t,`names[${o}]`)),e.dates.forEach((n,o)=>{(typeof n!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(n))&&D(t,`dates[${o}] must use YYYY-MM-DD`)})}function sy(e,t){te(e,t,"root"),(!Array.isArray(e.dstTransitions)||e.dstTransitions.length===0)&&D(t,"dstTransitions must be a nonempty array");let r=new Set;e.dstTransitions.forEach((n,o)=>{te(n,t,`dstTransitions[${o}]`);for(let s of["year","startUtc","endUtc"])De(n[s],t,`dstTransitions[${o}].${s}`);n.startUtc>=n.endUtc&&D(t,`dstTransitions[${o}] startUtc must be before endUtc`),r.has(n.year)&&D(t,`dstTransitions contains duplicate year ${n.year}`),r.add(n.year)})}function iy(e,t){rt(e,t,"root"),Object.keys(e).length===0&&D(t,"root must not be empty");for(let[r,n]of Object.entries(e)){for(let o of["addr","quote","quoteAddr","dex","pair"])M(n[o],t,`${r}.${o}`);(typeof n.liq!="number"||!Number.isFinite(n.liq)||n.liq<0)&&D(t,`${r}.liq must be a nonnegative finite source number`)}}function ay(e,t){te(e,t,"root"),De(e.capturedAt,t,"capturedAt"),De(e.block,t,"block"),De(e.chainId,t,"chainId"),M(e.gasPriceWei,t,"gasPriceWei"),M(e.stateView,t,"stateView"),rt(e.pools,t,"pools"),Object.keys(e.pools).length===0&&D(t,"pools must not be empty");for(let[r,n]of Object.entries(e.pools)){for(let o of["pair","version","quote","token","sqrtPriceX96"])M(n[o],t,`pools.${r}.${o}`);n.version!=="v3"&&n.version!=="v4"&&D(t,`pools.${r}.version must be v3 or v4`),typeof n.quoteIsToken0!="boolean"&&D(t,`pools.${r}.quoteIsToken0 must be a boolean`),(!/^[0-9]+$/.test(n.sqrtPriceX96)||BigInt(n.sqrtPriceX96)<=0n)&&D(t,`pools.${r}.sqrtPriceX96 must be a positive integer string`)}}function cy(e,t){te(e,t,"root"),De(e.capturedAt,t,"capturedAt"),M(e.source,t,"source"),te(e.books,t,"books"),Object.keys(e.books).length===0&&D(t,"books must not be empty");for(let[r,n]of Object.entries(e.books)){te(n,t,`books.${r}`),(!Array.isArray(n.bids)||!Array.isArray(n.asks))&&D(t,`books.${r} must have bids and asks arrays`);for(let[o,s]of n.bids.entries())te(s,t,`books.${r}.bids[${o}]`),M(s.px,t,`books.${r}.bids[${o}].px`),M(s.sz,t,`books.${r}.bids[${o}].sz`);for(let[o,s]of n.asks.entries())te(s,t,`books.${r}.asks[${o}]`),M(s.px,t,`books.${r}.asks[${o}].px`),M(s.sz,t,`books.${r}.asks[${o}].sz`)}}function uy(e,t){te(e,t,"root"),De(e.capturedAt,t,"capturedAt"),M(e.source,t,"source"),M(e.chain,t,"chain"),rt(e.tokens,t,"tokens"),te(e.pairs,t,"pairs"),Object.keys(e.tokens).length===0&&D(t,"tokens must not be empty");for(let[r,n]of Object.entries(e.tokens)){M(n.symbolRaw,t,`tokens.${r}.symbolRaw`),M(n.mint,t,`tokens.${r}.mint`),Object.hasOwn(e.pairs,r)||D(t,`pairs.${r} is required for token ${r}`),(!Array.isArray(e.pairs[r])||e.pairs[r].length===0)&&D(t,`pairs.${r} must be a nonempty array`);for(let[o,s]of e.pairs[r].entries())te(s,t,`pairs.${r}[${o}]`),M(s.pairAddress,t,`pairs.${r}[${o}].pairAddress`),M(s.dexId,t,`pairs.${r}[${o}].dexId`),(typeof s.priceUsd!="number"||!Number.isFinite(s.priceUsd)||s.priceUsd<=0)&&D(t,`pairs.${r}[${o}].priceUsd must be a positive finite number`),(typeof s.liquidityUsd!="number"||!Number.isFinite(s.liquidityUsd)||s.liquidityUsd<0)&&D(t,`pairs.${r}[${o}].liquidityUsd must be a nonnegative finite number`)}}function ly(e,t){te(e,t,"root"),De(e.capturedAt,t,"capturedAt"),M(e.source,t,"source"),M(e.chain,t,"chain"),e.chain!=="ton"&&D(t,'chain must be "ton"'),rt(e.tokens,t,"tokens"),te(e.pairs,t,"pairs"),Object.keys(e.tokens).length===0&&D(t,"tokens must not be empty");for(let[r,n]of Object.entries(e.tokens)){M(n.symbolRaw,t,`tokens.${r}.symbolRaw`),M(n.mint,t,`tokens.${r}.mint`),Object.hasOwn(e.pairs,r)||D(t,`pairs.${r} is required for token ${r}`),(!Array.isArray(e.pairs[r])||e.pairs[r].length===0)&&D(t,`pairs.${r} must be a nonempty array`);for(let[o,s]of e.pairs[r].entries())te(s,t,`pairs.${r}[${o}]`),M(s.pairAddress,t,`pairs.${r}[${o}].pairAddress`),M(s.dexId,t,`pairs.${r}[${o}].dexId`),(typeof s.priceUsd!="number"||!Number.isFinite(s.priceUsd)||s.priceUsd<=0)&&D(t,`pairs.${r}[${o}].priceUsd must be a positive finite number`),(typeof s.liquidityUsd!="number"||!Number.isFinite(s.liquidityUsd)||s.liquidityUsd<0)&&D(t,`pairs.${r}[${o}].liquidityUsd must be a nonnegative finite number`)}}function py(e,t){let r=Nl[t],n=Rl(e,r),o;try{o=Wg(n,"utf8")}catch(a){throw a?.code==="ENOENT"?new Error(`Fixture fixtures/${r} is missing at ${n}`):new Error(`Fixture fixtures/${r} could not be read: ${a.message}`)}let s;try{s=JSON.parse(o)}catch(a){throw new SyntaxError(`Fixture fixtures/${r} contains invalid JSON: ${a.message}`)}return dy[t](s,r),s}function $l(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))$l(t)}return e}function hs({fixtureDir:e=Zg}={}){if(typeof e!="string"||e.length===0)throw new TypeError("fixtureDir must be a nonempty path string");let t={};for(let r of Object.keys(Nl))t[r]=py(e,r);return $l(t)}function Ve(){return Tl??=hs(),Tl}function ge(){return Ve().venues}function Pl(){return Ve().universe}function ql(){return Ve().oracles}function Bl(){return Ve().nyseHolidays}function Ul(){return Ve().dstTransitions}function bn(){return Ve().rhPoolState}function Dl(){return Ve().solanaXstocks}function Ll(){return Ve().tonXstocks}function Fl(){return Ve().hip3L2Books}var Xg,Zg,Nl,dy,Tl,Ce=w(()=>{Ol();Xg=Rl(Yg(Gg(import.meta.url)),"fixtures");Zg=Jg(),Nl=Object.freeze({venues:"venues.json",universe:"universe.json",oracles:"oracles.json",nyseHolidays:"nyse_holidays.json",dstTransitions:"dst_transitions.json",equityDexPools:"equity_dex_pools.json",rhPoolState:"rh_pool_state.json",solanaXstocks:"solana_xstocks.json",tonXstocks:"ton_xstocks.json",hip3L2Books:"hip3_l2books.json"});dy=Object.freeze({venues:ty,universe:ry,oracles:ny,nyseHolidays:oy,dstTransitions:sy,equityDexPools:iy,rhPoolState:ay,solanaXstocks:uy,tonXstocks:ly,hip3L2Books:cy})});function hy(){let e=Ul().dstTransitions.map(n=>({year:n.year,startMs:n.startUtc*ys,endMs:n.endUtc*ys}));e.sort((n,o)=>n.startMs-o.startMs);let t=e[0].year,r=e[e.length-1].year;return Object.freeze({rows:Object.freeze(e),firstYear:t,lastYear:r,coverageStartMs:Date.UTC(t,0,1),coverageEndMs:Date.UTC(r+1,0,1)})}function Ql(){return jl??=hy(),jl}function gy(){return gs===void 0&&(gs=new Set(Bl().holidayDayIndex)),gs}function Gl(e,t){if(!Number.isSafeInteger(e))throw new TypeError(`${t}: epochMs must be a safe integer number of milliseconds`)}function yy(e,t){let{coverageStartMs:r,coverageEndMs:n,firstYear:o,lastYear:s}=Ql();if(e<r||e>=n)throw new RangeError(`${t}: ${new Date(e).toISOString()} is outside DST fixture coverage (${o} through ${s}). Refusing to assume a UTC offset.`)}function by(e){for(let t of Ql().rows)if(e>=t.startMs&&e<t.endMs)return!0;return!1}function wy(e){return by(e)?my:fy}function xy(e){let t=e+wy(e),r=Math.floor(t/Ml),n=t-r*Ml,o=new Date(t);return{dayIndex:r,minuteOfDay:Math.floor(n/Hl),msIntoDay:n,weekday:o.getUTCDay()}}function Sy({dayIndex:e,weekday:t}){return t===0||t===6?!1:!gy().has(e)}function Ey(e){return e<zl?"dark":e<Vl?"extended":e<Kl?"core":e<Wl?"extended":"dark"}function br(e){Gl(e,"sessionState"),yy(e,"sessionState");let t=xy(e);return Sy(t)?Ey(t.minuteOfDay):"dark"}function ws(e){return Gl(e,"isDark"),br(e)==="dark"}var ys,Hl,bs,Ml,fy,my,zl,Vl,Kl,Wl,Uk,Dk,jl,gs,wn=w(()=>{Ce();ys=1e3,Hl=60*ys,bs=60*Hl,Ml=24*bs,fy=-5*bs,my=-4*bs,zl=240,Vl=570,Kl=960,Wl=1200,Uk=Object.freeze([zl,Vl,Kl,Wl]),Dk=Object.freeze(["core","extended","dark"])});function Sn(e,t){e.push(Object.freeze({venue:t.venue,symbol:t.symbol??null,reason:t.reason,evidence:t.evidence??null}))}function vy(e){let t=e.raw?.vol24h;return!!(t===0||t===0||typeof t=="number"&&Number.isFinite(t)&&t<=0)}function Iy(e){return!e.bid||!e.ask?!1:tt(e.bid,e.ask)>0}function Yl(e,t,r){return Number.isSafeInteger(e.capturedAt)?t-e.capturedAt>r:!1}function En(e,t={}){if(!Array.isArray(e))throw new TypeError("quotes must be an array");let r=t.nowMs??Date.now(),n=t.quoteFreshnessMs??ky,o=t.oracleFreshnessMs??Ay,s=t.includeDormant===!0,a=[],i=[];for(let c of e){if(vy(c)){s?a.push(Object.freeze({...c,staleData:!0})):Sn(i,{venue:c.venue,symbol:c.symbolRaw??c.symbol,reason:xn.DORMANT_VENUE,evidence:{vol24h:c.raw?.vol24h??null}});continue}if(Iy(c)){Sn(i,{venue:c.venue,symbol:c.symbolRaw??c.symbol,reason:xn.CROSSED_BOOK,evidence:{bid:c.bid?String(c.bid.mantissa)+"e-"+c.bid.scale:null,ask:c.ask?String(c.ask.mantissa)+"e-"+c.ask.scale:null}});continue}if(Yl(c,r,n)){Sn(i,{venue:c.venue,symbol:c.symbolRaw??c.symbol,reason:xn.STALE_QUOTE,evidence:{capturedAt:c.capturedAt,nowMs:r,ageMs:r-c.capturedAt,freshnessMs:n}});continue}if(c.tier==="read-only"&&c.raw?.oracleRaw!==void 0){let u=br(r),p=u==="core"?o:o*2;if(Yl(c,r,p)){Sn(i,{venue:c.venue,symbol:c.symbolRaw??c.symbol,reason:xn.STALE_ORACLE,evidence:{capturedAt:c.capturedAt,nowMs:r,session:u}});continue}}a.push(c)}return{survivors:a,excluded:i}}var xn,ky,Ay,xs=w(()=>{we();wn();xn=Object.freeze({DORMANT_VENUE:"dormant-venue",CROSSED_BOOK:"crossed-book",STALE_QUOTE:"stale-quote",STALE_ORACLE:"stale-oracle"}),ky=12e4,Ay=6e5});function _y(e){if(typeof e!="number"||!Number.isFinite(e))throw new TypeError("value must be a finite number");let t=String(e);if(!t.includes("e")&&!t.includes("E"))return t;let[r,n]=t.split(/[eE]/),o=Number(n),s=r.startsWith("-"),a=s?r.slice(1):r,[i,c=""]=a.split("."),u=`${i}${c}`,p=i.length+o,l;return p<=0?l=`0.${"0".repeat(-p)}${u}`:p>=u.length?l=`${u}${"0".repeat(p-u.length)}`:l=`${u.slice(0,p)}.${u.slice(p)}`,`${s?"-":""}${l}`}function ce(e){return e==null?null:typeof e=="string"?$(e):typeof e!="number"||!Number.isFinite(e)?null:$(_y(e))}function Oe(e,t){let r=ce(e);if(r===null)throw new TypeError(`${t} must be a finite source number`);return r}var gt=w(()=>{we()});function G(e,t){throw new TypeError(`${e} ${t}`)}function Zl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yt(e,t){Zl(e)||G(t,"must be an object")}function ed(e,t,r){Object.hasOwn(e,t)||G(`${r}.${t}`,"is required")}function Dt(e,t){(typeof e!="string"||e.length===0)&&G(t,"must be a nonempty string")}function wr(e,t,r){t.has(e)||G(r,`must be one of ${[...t].join(", ")}`)}function Es(e,t){(!Number.isSafeInteger(e)||e<0)&&G(t,"must be a nonnegative safe integer")}function Ss(e,t,r=!1){e===null&&r||(Zl(e)||G(t,"must be a fixed point value"),typeof e.mantissa!="bigint"&&G(`${t}.mantissa`,"must be a bigint"),(!Number.isSafeInteger(e.scale)||e.scale<0)&&G(`${t}.scale`,"must be a nonnegative safe integer"))}function kn(e,t,r=!1){e===null&&r||yt(e,t)}function Jl(e,t){yt(e,t),Dt(e.venue,`${t}.venue`),Dt(e.reason,`${t}.reason`),Py.test(e.reason)||G(`${t}.reason`,"must be a machine readable lower case code"),Object.hasOwn(e,"symbol")&&e.symbol!==null&&Dt(e.symbol,`${t}.symbol`)}function me(e){yt(e,"quote");for(let r of["venue","chain","instrument","tier","symbolRaw","symbol","side","requestedSize",...Xl,"costAccounted","capturedAt","blockOrSeq","raw"])ed(e,r,"quote");Dt(e.venue,"quote.venue"),!(typeof e.chain=="string"&&e.chain.length>0)&&!(Number.isSafeInteger(e.chain)&&e.chain>=0)&&G("quote.chain","must be a nonempty string or nonnegative chain id"),wr(e.instrument,Cy,"quote.instrument"),wr(e.tier,Oy,"quote.tier"),Dt(e.symbolRaw,"quote.symbolRaw"),Dt(e.symbol,"quote.symbol"),wr(e.side,Ty,"quote.side"),Ss(e.requestedSize,"quote.requestedSize"),e.requestedSize.mantissa<0n&&G("quote.requestedSize","must not be negative");let t=0;for(let r of $y)Object.hasOwn(e,r)&&(Ss(e[r],`quote.${r}`),t+=1);t===0&&G("quote","must contain at least one of bid, ask, mid, mark");for(let r of Xl)Ss(e[r],`quote.${r}`,!0);if(typeof e.costAccounted!="boolean"&&G("quote.costAccounted","must be a boolean"),e.costAccounted){for(let r of["fees","gasEstimate","priceImpact"])e[r]===null&&G(`quote.${r}`,"cannot be unknown when costAccounted is true");e.instrument==="perp"&&e.fundingHourly===null&&G("quote.fundingHourly","cannot be unknown when costAccounted is true for a perp")}return e.instrument==="spot"&&e.fundingHourly!==null&&G("quote.fundingHourly","must be null for a spot quote"),Es(e.capturedAt,"quote.capturedAt"),e.blockOrSeq!==null&&!(typeof e.blockOrSeq=="string"&&e.blockOrSeq.length>0)&&!(Number.isSafeInteger(e.blockOrSeq)&&e.blockOrSeq>=0)&&G("quote.blockOrSeq","must be null, a nonempty string, or a nonnegative safe integer"),yt(e.raw,"quote.raw"),e}function An(e){yt(e,"rankResult");for(let t of["rankedOn","ranked","winner","runnersUp","improvementBps","sourcesAnswered","sourcesTried","failed","excluded","darkWindow","instrumentMix","bestPreparable"])ed(e,t,"rankResult");return wr(e.rankedOn,Ry,"rankResult.rankedOn"),Array.isArray(e.ranked)||G("rankResult.ranked","must be an array"),e.ranked.forEach((t,r)=>kn(t,`rankResult.ranked[${r}]`)),kn(e.winner,"rankResult.winner",!0),e.ranked.length===0&&e.winner!==null&&G("rankResult.winner","must be null when ranked is empty"),e.ranked.length>0&&e.winner===null&&G("rankResult.winner","must be present when ranked is not empty"),Array.isArray(e.runnersUp)||G("rankResult.runnersUp","must be an array"),e.runnersUp.forEach((t,r)=>kn(t,`rankResult.runnersUp[${r}]`)),e.improvementBps!==null&&!(typeof e.improvementBps=="number"&&Number.isFinite(e.improvementBps))&&G("rankResult.improvementBps","must be a finite number or null"),Es(e.sourcesAnswered,"rankResult.sourcesAnswered"),Es(e.sourcesTried,"rankResult.sourcesTried"),e.sourcesAnswered>e.sourcesTried&&G("rankResult.sourcesAnswered","must not exceed sourcesTried"),Array.isArray(e.failed)||G("rankResult.failed","must be an array"),e.failed.forEach((t,r)=>Jl(t,`failed[${r}]`)),Array.isArray(e.excluded)||G("rankResult.excluded","must be an array"),e.excluded.forEach((t,r)=>Jl(t,`excluded[${r}]`)),e.darkWindow!==null&&yt(e.darkWindow,"rankResult.darkWindow"),wr(e.instrumentMix,Ny,"rankResult.instrumentMix"),kn(e.bestPreparable,"rankResult.bestPreparable",!0),Object.hasOwn(e,"carry")&&e.carry!==null&&yt(e.carry,"rankResult.carry"),e}var Cy,Oy,Ty,Ry,Ny,$y,Xl,Py,Ke=w(()=>{Cy=new Set(["spot","perp"]),Oy=new Set(["read-only","quote-only","prepare","intent"]),Ty=new Set(["buy","sell"]),Ry=new Set(["net-of-cost","gross"]),Ny=new Set(["homogeneous","heterogeneous"]),$y=["bid","ask","mid","mark"],Xl=["fees","gasEstimate","priceImpact","fundingHourly"],Py=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/});function td(){return ge().venues.arcus}function Dy(){return Object.keys(td().markets).sort()}function Ly({symbol:e,side:t="buy",sizeUsd:r=null}={}){if(typeof e!="string"||e.length===0)return null;let n=e.endsWith("-USD")?e.slice(0,-4):e,o=td().markets[n];if(!o)return null;let s=Oe(o.mark,`${n}.mark`),a=ce(o.oracle),i=ce(o.fundingHourly),c=r===null?$("0"):r,u={venue:qy,chain:By,instrument:"perp",tier:Uy,symbolRaw:e,symbol:n,side:t,requestedSize:c,mark:s,fees:null,gasEstimate:null,priceImpact:null,fundingHourly:i,costAccounted:!1,capturedAt:ge().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.arcus",oraclePrice:o.oracle,vol24h:o.vol24h,oi:o.oi,fundingAnnPct:o.fundingAnnPct,category:o.category,isOutsideRth:o.isOutsideRth===!0,rth:o.rth,darkWindowFundingHourly:vn,initialMarginFraction:o.initialMarginFraction??null,offHoursInitialMarginFraction:o.offHoursInitialMarginFraction??null,reasonCostUnknown:"fees, gas, and impact at size not captured for Arcus perps"}};return a!==null&&(u.raw.oracleFixed=a),me(u)}function In({side:e="buy",sizeUsd:t=null}={}){return Dy().map(r=>Ly({symbol:r,side:e,sizeUsd:t})).filter(r=>r!==null)}var qy,By,Uy,vn,ks=w(()=>{Ce();gt();we();Ke();qy="arcus_perp",By="robinhood-4663",Uy="quote-only",vn="0.00000480324074074"});function As(e,t,r=8){if(e==null)throw new TypeError("hourlyFundingRate is required");if(!Number.isFinite(t)||t<0)throw new RangeError("horizonHours must be a nonnegative finite number");if(t===0)return $("0");let n=$(String(t)),o=fe(10000n,0);return he(he(e,n),o)}function nd(e,t,r={}){if(e.instrument!=="perp")return{model:"current-funding-held-constant",horizonHours:t,carryBps:$("0"),carryBpsDisplay:"0",confidence:"estimate",note:"spot has no funding carry"};let n=r.nowMs??Date.now(),o=r.applyDarkWindowLock===!0,s=e.fundingHourly;if(o&&s!==null){let i=Fy(n,t),c=t-i,u=$(vn),p=As(s,c),l=As(u,i),d=Math.max(p.scale,l.scale),f={mantissa:p.mantissa*10n**BigInt(d-p.scale)+l.mantissa*10n**BigInt(d-l.scale),scale:d};return{model:"current-funding-held-constant",horizonHours:t,carryBps:f,carryBpsDisplay:Ie(f),confidence:"estimate",darkHours:i,litHours:c,darkWindowRate:vn,compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}if(s===null)return{model:"current-funding-held-constant",horizonHours:t,carryBps:null,carryBpsDisplay:null,confidence:"estimate",note:"funding rate unknown"};let a=As(s,t);return{model:"current-funding-held-constant",horizonHours:t,carryBps:a,carryBpsDisplay:Ie(a),confidence:"estimate",compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}function Fy(e,t){if(t<=0)return 0;let r=0,n=Math.floor(t);for(let o=0;o<n;o+=1)ws(e+o*rd)&&(r+=1);return t>n&&ws(e+n*rd)&&(r+=t-n),r}var rd,tA,od=w(()=>{we();ks();wn();rd=36e5,tA=24*365});function My(e){return e.mid??e.mark??e.ask??e.bid??null}function jy(e){let t=My(e);if(t===null)return null;let r=e.costAccounted===!0,n=$("0");e.fees!==null?n=et(n,e.fees):r=!1,e.priceImpact!==null?n=et(n,e.priceImpact):e.requestedSize&&e.requestedSize.mantissa>0n&&(r=!1),e.gasEstimate===null?r=!1:n=et(n,e.gasEstimate);let o;if(e.fees!==null&&tt(e.fees,$("1"))<0&&tt(e.fees,$("0"))>=0){let s=et($("1"),e.fees);o=he(t,s),e.priceImpact!==null&&(o=et(o,he(t,e.priceImpact)))}else o=et(t,n);return{net:o,costAccounted:r,px:t}}function Hy(e,t,r=null){return{venue:e.venue,chain:e.chain,instrument:e.instrument,tier:e.tier,symbol:e.symbol,symbolRaw:e.symbolRaw,side:e.side,price:t.px,net:t.net,costAccounted:t.costAccounted,fundingHourly:e.fundingHourly,carry:r,quote:e}}function zy(e,t){if(!e||!t||!e.costAccounted||!t.costAccounted||e.instrument!==t.instrument||e.net.mantissa===0n)return null;let r=yr(t.net,e.net);return _e(he(r,fe(10000n,0)),t.net,4)}function _n(e,t={}){if(!Array.isArray(e))throw new TypeError("quotes must be an array");let r=t.nowMs??e[0]?.capturedAt??Date.now(),n=e.length,o=e,s=[];if(!t.skipLiveness){let m=En(e,{nowMs:r});o=m.survivors,s=m.excluded}let a=e.length,i=[],c=t.horizonHours,u=Number.isFinite(c)&&c>0,p=[];for(let m of o){let T=jy(m);if(T===null)continue;let j=null;if(u&&m.instrument==="perp"&&(j=nd(m,c,{nowMs:r}),j.carryBps!==null)){let se=et($("1"),_e(j.carryBps,fe(10000n,0),12));T.net=he(T.net,se),T.costAccounted=!1}p.push(Hy(m,T,j))}let l=p,d="homogeneous";if(u)d="heterogeneous",l=p;else{let m=p.filter(j=>j.instrument==="spot"),T=p.filter(j=>j.instrument==="perp");m.length>0&&T.length>0?(l=m.length>=T.length?m:T,d="homogeneous"):(l=p,d="homogeneous")}l.sort((m,T)=>{let j=tt(m.net,T.net);return j!==0?j:m.venue<T.venue?-1:m.venue>T.venue?1:0});let f=l[0]??null,h=l.slice(1),y=l,g="gross";f&&f.costAccounted&&(h.length===0||h[0].costAccounted)&&(g="net-of-cost");let b=h.length===0?null:zy(f,h[0]),S=p.find(m=>m.tier==="prepare")??null,I=br(r),A=I==="core"?null:{session:I,warning:I==="dark"?"market is dark; marks are not real price discovery":"extended session; thinner books and higher staleness risk"},O=null;u&&(O=Vy(p));let _={rankedOn:g,ranked:y,winner:f,runnersUp:h,improvementBps:b===null?null:Number(Ie(b)),sourcesAnswered:a,sourcesTried:n,failed:i,excluded:s,darkWindow:A,instrumentMix:d,bestPreparable:S,carry:f?.carry??null,breakEvenHorizonHours:O};return An(_)}function Vy(e){let t=e.filter(s=>s.instrument==="spot").sort((s,a)=>tt(s.net,a.net))[0],r=e.filter(s=>s.instrument==="perp").sort((s,a)=>tt(s.net,a.net))[0];if(!t||!r||r.fundingHourly===null)return null;let n=yr(t.net,r.net);if(n.mantissa===0n)return 0;let o=he(r.fundingHourly,r.price);if(o.mantissa===0n)return null;try{let s=_e(n,o,4),a=Number(Ie(s));return!Number.isFinite(a)||a<0?null:a}catch{return null}}var vs=w(()=>{xs();od();wn();we();Ke()});function Is(){return bn()}function Xy(e){return{mantissa:e*e*10n**BigInt(Lt)/Gy,scale:Lt}}function Jy(e){let t=Xy(BigInt(e.sqrtPriceX96)),r=e.quote==="USDG"?6:18,n=18;if(e.quoteIsToken0){let o=_e(he(t,fe(10n**BigInt(r),0)),fe(10n**BigInt(n),0),Lt);return o.mantissa===0n?null:_e($("1"),o,Lt)}return _e(he(t,fe(10n**BigInt(n),0)),fe(10n**BigInt(r),0),Lt)}function Zy(e){let t=ql(),r=t.assets[e];return r?fe(r.rawPrice,t.oracleScaleExp):null}function eb(e,t){if(e===null||t===null||e.mantissa<=0n||t.mantissa<=0n)return null;let r={...e};return _e(t,tb(r,t),Lt)}function tb(e,t){let r=Math.max(e.scale,t.scale);return{mantissa:gr(e,r).mantissa+gr(t,r).mantissa,scale:r}}function rb(e){let t=Is(),r=Yy[e];return r?{wei:BigInt(t.gasPriceWei)*r,units:r,native:"ETH"}:null}function _s(){return Object.keys(Is().pools).sort()}function Ft({symbol:e,side:t="buy",sizeUsd:r=null}={}){if(typeof e!="string"||e.length===0)throw new TypeError("symbol must be a nonempty string");let n=Is(),o=n.pools[e];if(!o)return null;let s=Jy(o);if(s===null)return null;let a=ce(o.liqUsd),i=r===null?$("0"):r,c=o.feePpm===null||o.feePpm===void 0?null:_e(fe(BigInt(o.feePpm),0),fe(1000000n,0),8),u=i.mantissa===0n?$("0"):eb(a,i),p=rb(o.version),f={venue:Ky,chain:Wy,instrument:"spot",tier:Qy,symbolRaw:e,symbol:e,side:t,requestedSize:i,mid:s,fees:c,gasEstimate:null,priceImpact:u,fundingHourly:null,costAccounted:!1,capturedAt:n.capturedAt*1e3,blockOrSeq:n.block,raw:{fixture:"fixtures/rh_pool_state.json",pair:o.pair,version:o.version,sqrtPriceX96:o.sqrtPriceX96,quote:o.quote,quoteIsToken0:o.quoteIsToken0,liqUsd:o.liqUsd,gasNativeWei:p===null?null:p.wei.toString(),gasUnits:p===null?null:p.units.toString(),impactModel:"constant-product-estimate",notes:["price read live from chain 4663",o.version==="v4"?"v4 fee may be dynamic via hook and was not captured":"v3 fee tier is the pool static fee","gas known in native wei only, no ETH price captured to denominate it"]}},h=Zy(e);return h!==null&&(f.referencePrice=h,f.referenceBasisBps=Ie(_e(he(yr(s,h),fe(10000n,0)),h,4))),me(f)}function sd({side:e="buy",sizeUsd:t=null}={}){return _s().map(r=>Ft({symbol:r,side:e,sizeUsd:t})).filter(r=>r!==null)}var Ky,Wy,Qy,Gy,Lt,Yy,Cs=w(()=>{Ce();gt();we();Ke();Ky="rh_uniswap",Wy=4663,Qy="prepare",Gy=1n<<192n,Lt=18,Yy=Object.freeze({v3:180000n,v4:240000n})});function Cn(e={}){let{symbol:t,side:r="buy",sizeUsd:n=null,recipient:o,nowMs:s=Date.now()}=e;if(typeof t!="string"||!t)throw new TypeError("symbol is required");if(typeof o!="string"||!/^0x[0-9a-fA-F]{40}$/.test(o))throw new TypeError("recipient must be a 0x-prefixed 20 byte address");let a=Ft({symbol:t,side:r,sizeUsd:n});if(a===null)throw new Error(`no RH Uniswap pool for ${t}`);if(a.tier!=="prepare")throw new Error(`route tier is ${a.tier}, only prepare tier can be prepared`);let i=s-a.capturedAt;if(i>id)throw new Error(`quote is stale (${i}ms old, bound ${id}ms); re-quote before preparing`);let u=bn().pools[t],p=u.version==="v4"?ob:nb,l=p,d=r==="buy"?u.quoteAddr:u.token;return Object.freeze({artifactKind:"unsigned-tx",chainId:4663,to:p,data:"0x",value:"0",requiresApproval:{spender:l,token:d,amount:null},requiresWalletSignature:!0,backendSigner:!1,unsigned:!0,houseSigned:!1,quoteRef:{venue:a.venue,symbol:a.symbol,symbolRaw:a.symbolRaw,capturedAt:a.capturedAt,blockOrSeq:a.blockOrSeq,mid:a.mid,version:u.version,pair:u.pair},quoteAgeMs:i,recipient:o,side:r,notes:["prepare-only: user wallet must sign","calldata encoding is deferred; this artifact is the bound intent",u.version==="v4"?"V4 route via PoolManager":"V3 route via SwapRouter (address not yet pinned)"]})}var id,nb,ob,Os=w(()=>{Cs();Ce();id=12e4,nb="0x0000000000000000000000000000000000000000",ob="0x84b75b19A3cdf8E2F56d0507d22D442847B2053C"});function xr(){return ge().venues.hyperliquid_hip3}function ad(){return Object.keys(xr().dexs).sort()}function cb(){let e=[];for(let[t,r]of Object.entries(xr().dexs))for(let n of Object.keys(r))e.push(`${t}:${n}`);return e.sort()}function ub(e){if(typeof e!="string"||e.length===0)return[];let t=e.indexOf(":");if(t>0){let n=e.slice(0,t),o=e.slice(t+1),s=xr().dexs[n]?.[o];return s?[{dex:n,ticker:o,market:s}]:[]}let r=[];for(let[n,o]of Object.entries(xr().dexs))Object.hasOwn(o,e)&&r.push({dex:n,ticker:e,market:o[e]});return r}function lb(e,t){try{return Fl().books[`${e}:${t}`]??null}catch{return null}}function db(e,t,r){if(!e||r===null||r.mantissa<=0n)return null;let n=t==="buy"?e.asks:e.bids;if(!n||n.length===0)return null;let o=Number(Ie(r));if(!Number.isFinite(o)||o<=0)return null;let s=0,a=0,i=0;for(let c of n){let u=Number(c.px),p=Number(c.sz);if(!(u>0)||!(p>0))continue;let l=u*p,d=Math.min(o,l),f=d/u;if(s+=d,a+=f,o-=d,i+=1,o<=1e-9)break}return a<=0?null:{vwap:s/a,filledUsd:s,unfilledUsd:Math.max(0,o),levelsUsed:i}}function pb(e,t,r,n){let o=db(e,t,r);if(!o)return{impact:null,depth:null};let s=Number(Ie(n));if(!(s>0))return{impact:null,depth:o};let a=t==="buy"?(o.vwap-s)/s:(s-o.vwap)/s,i=Math.max(0,a);return{impact:ce(Number(i.toPrecision(12))),depth:{...o,impactFraction:i,fullyFilled:o.unfilledUsd<=1e-6}}}function cd({dex:e,ticker:t,market:r,side:n,size:o}){let s=Oe(r.mark,`${e}:${t}.mark`),a=ce(r.fundingHourly),i=ce(r.vol24h),c=ce(r.oi),u=o===null?$("0"):o,p=lb(e,t),l=null,d=null,f="fees and gas not captured";if(u.mantissa>0n)if(p){let g=pb(p,n,u,s);l=g.impact,d=g.depth,d?.fullyFilled?f="impact measured from l2Book; fees and gas still not captured":f="book walked but size exceeds visible depth; fees and gas not captured"}else f="no order book depth wired for this coin; fees and gas not captured";else p?f="zero size; fees and gas not captured":f="no order book depth wired for this coin; fees and gas not captured";let y={venue:sb,chain:ib,instrument:"perp",tier:ab,symbolRaw:`${e}:${t}`,symbol:t,side:n,requestedSize:u,mark:s,fees:null,gasEstimate:null,priceImpact:l,fundingHourly:a,costAccounted:!1,capturedAt:ge().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.hyperliquid_hip3",dex:e,ticker:t,vol24h:r.vol24h,oi:r.oi,fundingAnnPct:r.fundingAnnPct,maxLev:r.maxLev,reasonCostUnknown:f,hasL2Book:p!==null,l2BookFixture:p?"fixtures/hip3_l2books.json":null,depth:d}};return i!==null&&(y.raw.vol24hFixed=i),c!==null&&(y.raw.oiFixed=c),p?.bids?.[0]&&p?.asks?.[0]&&(y.bid=$(String(p.bids[0].px)),y.ask=$(String(p.asks[0].px))),me(y)}function ud({symbol:e,side:t="buy",sizeUsd:r=null}={}){let n=ub(e);return n.length===0||n.length>1?null:cd({...n[0],side:t,size:r})}function On({side:e="buy",sizeUsd:t=null,ticker:r=null}={}){let n=[];for(let o of cb()){let[s,a]=o.split(":");if(r!==null&&a!==r)continue;let i=xr().dexs[s][a];n.push(cd({dex:s,ticker:a,market:i,side:e,size:t}))}return n}var sb,ib,ab,ld=w(()=>{Ce();gt();we();Ke();sb="hyperliquid_hip3",ib="hyperliquid",ab="quote-only"});function dd(){return ge().venues.arcus_spot}function gb(){return Object.keys(dd().pairs).sort()}function yb({symbol:e,side:t="buy",sizeUsd:r=null}={}){if(typeof e!="string"||e.length===0)return null;let n=dd().pairs[e];if(!n)return null;let o=n.bid===void 0||n.bid===null?null:Oe(n.bid,`${e}.bid`),s=n.ask===void 0||n.ask===null?null:Oe(n.ask,`${e}.ask`),a=ce(n.last),i=null;if(o!==null&&s!==null){i={mantissa:o.mantissa+s.mantissa,scale:o.scale===s.scale?o.scale+1:Math.max(o.scale,s.scale)+1};let l=Math.max(o.scale,s.scale),d=o.scale===l?o.mantissa:o.mantissa*10n**BigInt(l-o.scale),f=s.scale===l?s.mantissa:s.mantissa*10n**BigInt(l-s.scale);i={mantissa:d+f,scale:l+1},i={mantissa:(d+f)/2n,scale:l}}else a!==null&&(i=a);if(o===null&&s===null&&i===null)return null;let c=r===null?$("0"):r,u=$("0"),p={venue:fb,chain:mb,instrument:"spot",tier:hb,symbolRaw:e,symbol:e,side:t,requestedSize:c,fees:u,gasEstimate:null,priceImpact:null,fundingHourly:null,costAccounted:!1,capturedAt:ge().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.arcus_spot",last:n.last,bid:n.bid,ask:n.ask,vol24h:n.vol24h,feeKnownZero:!0,reasonCostUnknown:"gas and impact at size not captured; fee is a known zero"}};return o!==null&&(p.bid=o),s!==null&&(p.ask=s),i!==null&&(p.mid=i),me(p)}function Tn({side:e="buy",sizeUsd:t=null}={}){return gb().map(r=>yb({symbol:r,side:e,sizeUsd:t})).filter(r=>r!==null)}var fb,mb,hb,pd=w(()=>{Ce();gt();we();Ke();fb="arcus_spot",mb="robinhood-4663",hb="quote-only"});function Rn(){return Dl()}function Ts(){return Object.keys(Rn().tokens).sort()}function Sb(e){let t=Rn().pairs[e];return!t||t.length===0?null:[...t].sort((r,n)=>(n.liquidityUsd??0)-(r.liquidityUsd??0))[0]}function Eb(e,t){if(e===null||t===null)return null;if(e.mantissa<=0n||t.mantissa<=0n)return $("0");let r=Math.max(e.scale,t.scale),n=e.scale===r?e.mantissa:e.mantissa*10n**BigInt(r-e.scale),o=t.scale===r?t.mantissa:t.mantissa*10n**BigInt(r-t.scale),s=o*10n**6n,a=n+o;return{mantissa:s/a,scale:6}}function Rs({symbol:e,side:t="buy",sizeUsd:r=null}={}){if(typeof e!="string"||e.length===0)return null;let n=e,o=e,s=Rn().tokens;if(Object.hasOwn(s,e))n=e,o=s[e].symbolRaw;else if(e.endsWith("x")||e.endsWith("X")){let h=e.slice(0,-1).toUpperCase();if(Object.hasOwn(s,h))n=h,o=s[h].symbolRaw;else return null}else return null;let a=s[n],i=Sb(n);if(!a||!i)return null;let c=Oe(i.priceUsd,`${n}.priceUsd`),u=ce(i.liquidityUsd),p=r===null?$("0"):r,l=p.mantissa===0n?$("0"):Eb(u,p),d=!1;p.mantissa===0n&&(i.liquidityUsd??0)>=fd&&(d=!1);let f={venue:bb,chain:wb,instrument:"spot",tier:xb,symbolRaw:o,symbol:n,side:t,requestedSize:p,mid:c,fees:null,gasEstimate:null,priceImpact:l,fundingHourly:null,costAccounted:d,capturedAt:Rn().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/solana_xstocks.json",mint:a.mint,pairAddress:i.pairAddress,dexId:i.dexId,quote:i.quote,liquidityUsd:i.liquidityUsd,volume24h:i.volume24h,priceUsd:i.priceUsd,source:"dexscreener",approximate:!0,reasonCostUnknown:"DexScreener liquidity.usd is a third-party float; fees and SOL gas not captured; impact is modeled",thin:(i.liquidityUsd??0)<fd}};return me(f)}function md({side:e="buy",sizeUsd:t=null}={}){return Ts().map(r=>Rs({symbol:r,side:e,sizeUsd:t})).filter(r=>r!==null)}var bb,wb,xb,fd,hd=w(()=>{Ce();gt();we();Ke();bb="solana_xstocks",wb="solana",xb="quote-only",fd=25e3});function Nn(){return Ll()}function Ns(){return Object.keys(Nn().tokens).sort()}function Cb(e){let t=Nn().pairs[e];return!t||t.length===0?null:[...t].sort((r,n)=>(n.liquidityUsd??0)-(r.liquidityUsd??0))[0]}function Ob(e,t){if(e===null||t===null)return null;if(e.mantissa<=0n||t.mantissa<=0n)return $("0");let r=Math.max(e.scale,t.scale),n=e.scale===r?e.mantissa:e.mantissa*10n**BigInt(r-e.scale),o=t.scale===r?t.mantissa:t.mantissa*10n**BigInt(r-t.scale),s=o*10n**6n,a=n+o;return{mantissa:s/a,scale:6}}function $s({symbol:e,side:t="buy",sizeUsd:r=null}={}){if(typeof e!="string"||e.length===0)return null;let n=e,o=e,s=Nn().tokens;if(Object.hasOwn(s,e))n=e,o=s[e].symbolRaw;else if(e.endsWith("x")||e.endsWith("X")){let h=e.slice(0,-1).toUpperCase();if(Object.hasOwn(s,h))n=h,o=s[h].symbolRaw;else return null}else{let h=e.toUpperCase();if(Object.hasOwn(s,h))n=h,o=s[h].symbolRaw;else return null}let a=s[n],i=Cb(n);if(!a||!i)return null;let c=Oe(i.priceUsd,`${n}.priceUsd`),u=ce(i.liquidityUsd),p=r===null?$("0"):r,l=p.mantissa===0n?$("0"):Ob(u,p),f={venue:kb,chain:Ab,instrument:"spot",tier:vb,symbolRaw:o,symbol:n,side:t,requestedSize:p,mid:c,fees:null,gasEstimate:null,priceImpact:l,fundingHourly:null,costAccounted:!1,capturedAt:Nn().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/ton_xstocks.json",mint:a.mint,pairAddress:i.pairAddress,dexId:i.dexId,quote:i.quote,liquidityUsd:i.liquidityUsd,volume24h:i.volume24h,priceUsd:i.priceUsd,source:"dexscreener",approximate:!0,reasonCostUnknown:"DexScreener liquidity.usd is a third-party float; fees and TON gas not captured; impact is modeled; TON books are thin",thin:(i.liquidityUsd??0)<Ib,impactSizeFractionHint:_b}};return me(f)}function gd({side:e="buy",sizeUsd:t=null}={}){return Ns().map(r=>$s({symbol:r,side:e,sizeUsd:t})).filter(r=>r!==null)}var kb,Ab,vb,Ib,_b,yd=w(()=>{Ce();gt();we();Ke();kb="ton_stonfi",Ab="ton",vb="quote-only",Ib=25e3,_b=.01});var $n={};z($n,{bestEquityRoute:()=>Tb,collectEquityQuotes:()=>wd,equityVenues:()=>Rb,getUniverse:()=>Pl,getVenues:()=>ge,loadFixtures:()=>hs,prepareEquity:()=>Cn,prepareEquityRoute:()=>Nb,rankEquityQuotes:()=>_n,toJsonSafe:()=>$b,validateQuote:()=>me,validateRankResult:()=>An});function Ps(e){return e==null||e===""?null:typeof e=="object"&&e&&typeof e.mantissa=="bigint"?e:$(String(e))}function wd(e,{sizeUsd:t=null}={}){if(typeof e!="string"||!e.trim())throw new TypeError("ticker is required");let r=e.trim().toUpperCase(),n=Ps(t),o=[],s=ud({symbol:`xyz:${r}`,sizeUsd:n});if(s)o.push(s);else for(let u of On({ticker:r,sizeUsd:n}))o.push(u);for(let u of In({sizeUsd:n}))u.symbol===r&&o.push(u);for(let u of Tn({sizeUsd:n}))u.symbol===r&&o.push(u);let a=Ft({symbol:r,sizeUsd:n});a&&o.push(a);let i=Rs({symbol:r,sizeUsd:n});i&&o.push(i);let c=$s({symbol:r,sizeUsd:n});return c&&o.push(c),o}function Tb(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase();if(!t)throw new Error("bestEquityRoute requires ticker");let r=Ps(e.sizeUsd??e.size??null),n=wd(t,{sizeUsd:r});if(n.length===0)return{ticker:t,rankedOn:"gross",ranked:[],winner:null,runnersUp:[],improvementBps:null,sourcesAnswered:0,sourcesTried:0,failed:[],excluded:[],bestPreparable:null,instrumentMix:"homogeneous",note:"no venue answered for this ticker in the pinned fixture capture"};let o=n[0].capturedAt,s=String(o).length<=10?o*1e3:o,a=e.nowMs==null,i=e.nowMs??o+1e3,c=Math.max(0,Date.now()-s),u=_n(n,{nowMs:i,horizonHours:e.horizonHours!=null?Number(e.horizonHours):void 0,skipLiveness:e.skipLiveness===!0});return{ticker:t,...u,dataSource:a?"fixture":"caller-clock",capturedAt:s,ageMs:c,stale:c>bd}}function Rb(){let e=[{venue:"hyperliquid_hip3",tier:"quote-only",chain:"hyperliquid",n:On().length},{venue:"arcus_perp",tier:"quote-only",chain:"robinhood-4663",n:In().length},{venue:"arcus_spot",tier:"quote-only",chain:"robinhood-4663",n:Tn().length},{venue:"rh_uniswap",tier:"prepare",chain:4663,n:_s().length},{venue:"solana_xstocks",tier:"quote-only",chain:"solana",n:Ts().length},{venue:"ton_stonfi",tier:"quote-only",chain:"ton",n:Ns().length}],t=[...On(),...In(),...Tn(),...sd(),...md(),...gd()],r=(t[0]?.capturedAt??Date.now())+1e3,{survivors:n,excluded:o}=En(t,{nowMs:r});return{inventory:e,hip3Dexs:ad(),liveness:{survivors:n.length,excluded:o.length,byReason:o.reduce((s,a)=>(s[a.reason]=(s[a.reason]??0)+1,s),{})},capturedAt:ge().capturedAt,custody:"prepare-only",note:"quote-only venues are ranked for discovery; only rh_uniswap is preparable in v1"}}function Nb(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase(),r=e.recipient||e.taker;if(!t)throw new Error("prepareEquityRoute requires ticker");if(!r)throw new Error("prepareEquityRoute requires recipient (signing wallet)");let n=Ps(e.sizeUsd??e.size??null),o=Ft({symbol:t,sizeUsd:n});if(!o)return{ok:!1,failureKind:"no-prepare-path",ticker:t,note:"no RH Uniswap prepare-tier route for this ticker in fixtures"};try{let s=String(o.capturedAt).length<=10?o.capturedAt*1e3:o.capturedAt,a=e.nowMs!=null,i=a?Number(e.nowMs):Date.now(),c=Math.max(0,Date.now()-s),u=Cn({symbol:t,sizeUsd:n,recipient:r,nowMs:i});return{ok:!0,ticker:t,artifact:u,bestPreparableVenue:"rh_uniswap",dataSource:a?"caller-clock":"live-clock",capturedAt:s,ageMs:c,stale:c>bd}}catch(s){return{ok:!1,failureKind:"prepare-refused",ticker:t,error:String(s.message||s)}}}function $b(e){return JSON.parse(JSON.stringify(e,(t,r)=>typeof r=="bigint"?r.toString():r))}var bd,Pn=w(()=>{we();vs();Os();xs();ld();pd();ks();Cs();hd();yd();Ce();vs();Os();Ke();Ce();bd=3600*1e3});var qn={};z(qn,{CHAIN_CONFIGS:()=>hr,EVIDENCE:()=>P,RISK:()=>R,SCANNER_CAPABILITIES:()=>Nt,__clearScanners:()=>$0,createScanner:()=>Tc,getScanner:()=>R0,listScanners:()=>N0,registerBuiltinScanners:()=>Hu,registerCustomChain:()=>zu,registerScanner:()=>tn,scannerCoverage:()=>P0,validateScanner:()=>Oc});var Bn=w(()=>{pt();cs()});import xd from"node:fs";import jt from"node:process";import{fileURLToPath as Pb}from"node:url";import{homedir as jn}from"node:os";import{join as Hn}from"node:path";var Hs=process.env.ORACLE_PUBLIC_DESKTOP==="1",zn=Hs?process.env.ORACLE_CONFIG_DIR||Hn(jn(),".config","oracle"):Hn(jn(),".config","oracle"),Vb=Hs?zn:Hn(jn(),".config","mad-desk");function Vt(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}import Kt from"node:fs";import Wt from"node:path";var Vs=/^0x[0-9a-fA-F]{40}$/,Rd=new Set(["privatekey","private_key","secret","seed","mnemonic","passphrase","signature","keystore"]),Nd=["privatekey","privkey","secretkey","secret","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","signature","wif","xprv","xpriv","apikey","bearer","credential"],$d=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/,/\b(?:[a-z]{3,8}\s+){11,}[a-z]{3,8}\b/i],Pd=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/;function qd(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Bd(e,t){let r=qd(e);if(Rd.has(String(e).toLowerCase())||Nd.some(n=>r.includes(n)))throw new Error(`address-book: ${t} is forbidden; the book stores labels, never key material`)}function Ud(e,t){if(typeof e=="string"&&($d.some(r=>r.test(e))||Pd.test(e)))throw new Error(`address-book: ${t} looks like key material; the book stores labels, never key material`)}function Ks(){let e=Vt("ORACLE_ADDRESS_BOOK","MAD_ADDRESS_BOOK","");if(e)return Wt.resolve(e);let t=Vt("ORACLE_CONFIG_DIR","MAD_CONFIG_DIR",zn);return Wt.join(t,"address-book.json")}function Vn(e,t="field"){if(Array.isArray(e)){e.forEach((r,n)=>Vn(r,`${t}[${n}]`));return}if(!e||typeof e!="object"){Ud(e,t);return}for(let[r,n]of Object.entries(e))Bd(r,r),Vn(n,r)}function Kn(e){let t=String(e||"").trim();if(!Vs.test(t))throw new Error("address-book: address must be 0x + 40 hex characters");return t.toLowerCase()}function bt(e,t){return e==null||e===""?null:String(e).slice(0,t)}function zs(){return{version:1,updatedAt:null,entries:[]}}function Ws(e){return{address:String(e.address).toLowerCase(),label:bt(e.label,80)||"unknown",who:bt(e.who,120),role:bt(e.role,40),chainIds:Array.isArray(e.chainIds)?e.chainIds.map(Number).filter(Number.isFinite):[],notes:bt(e.notes,500),source:bt(e.source,80),firstSeenAt:e.firstSeenAt||null,lastSeenAt:e.lastSeenAt||null}}function vr(){try{let e=JSON.parse(Kt.readFileSync(Ks(),"utf8"));if(!e||typeof e!="object")return zs();let t=Array.isArray(e.entries)?e.entries:[];return{version:1,updatedAt:e.updatedAt||null,entries:t.filter(r=>r&&typeof r=="object"&&Vs.test(String(r.address||""))).map(Ws)}}catch{return zs()}}function Qs(e){let t=Ks();Kt.mkdirSync(Wt.dirname(t),{recursive:!0,mode:448});let r={...e,version:1,updatedAt:new Date().toISOString()},n=Wt.join(Wt.dirname(t),`.address-book.${process.pid}.tmp`);Kt.writeFileSync(n,`${JSON.stringify(r,null,2)}
|
|
7
7
|
`,{mode:384}),Kt.renameSync(n,t);try{Kt.chmodSync(t,384)}catch{}return r}function Gs(e={}){let t=vr(),r=t.entries;if(e.role&&(r=r.filter(n=>n.role===String(e.role))),e.who){let n=String(e.who).toLowerCase();r=r.filter(o=>(o.who||"").toLowerCase().includes(n)||(o.label||"").toLowerCase().includes(n))}if(e.q){let n=String(e.q).toLowerCase();r=r.filter(o=>o.address.includes(n)||(o.label||"").toLowerCase().includes(n)||(o.who||"").toLowerCase().includes(n)||(o.notes||"").toLowerCase().includes(n))}return{updatedAt:t.updatedAt,count:r.length,entries:r}}function Ys(e){let t=Kn(e),r=vr().entries.filter(n=>n.address===t);return{address:t,found:r.length>0,entries:r}}function Xs(e={}){Vn(e);let t=Kn(e.address),r=bt(e.label??e.role,80)||"wallet",n=new Date().toISOString(),o=vr(),s=o.entries.findIndex(u=>u.address===t&&u.label===r),a=Ws({address:t,label:r,who:e.who,role:e.role,chainIds:e.chainIds,notes:e.notes,source:e.source||"agent",firstSeenAt:s>=0&&o.entries[s].firstSeenAt||n,lastSeenAt:n});s>=0?o.entries[s]=a:o.entries.push(a);let i=u=>u==="agent"?0:u==="owner"?1:2;o.entries.sort((u,p)=>i(u.role)-i(p.role)||u.label.localeCompare(p.label)||u.address.localeCompare(p.address));let c=Qs(o);return{ok:!0,entry:a,count:c.entries.length}}function Js(e,t=null){let r=Kn(e),n=vr(),o=n.entries.length;return n.entries=n.entries.filter(s=>s.address!==r?!0:t==null?!1:s.label!==String(t)),Qs(n),{ok:!0,removed:o-n.entries.length,count:n.entries.length}}var qs=Vt("ORACLE_DATA_URL","MAD_DESK_URL","http://127.0.0.1:8787").replace(/\/$/,""),qb=[{name:"data_catalog",description:"List every read-plane provider the desk exposes (id, venue, chainIds, ops). Use this to discover what public APIs are available before calling data_call. Read-only.",inputSchema:{type:"object",properties:{}}},{name:"data_health",description:"Health of every read-plane provider (which public APIs are up / configured). Read-only.",inputSchema:{type:"object",properties:{}}},{name:"data_call",description:"Generic escape hatch: call any provider/op from the catalog. provider+op are required; args is a free-form object matching that op. Read-only. Use data_catalog first to see valid provider/op pairs.",inputSchema:{type:"object",required:["provider","op"],properties:{provider:{type:"string",description:"provider id, e.g. defillama, dexscreener, lifi, evm-rpc"},op:{type:"string",description:"op name for that provider, e.g. protocols, search, quote"},args:{type:"object",description:"op arguments (free-form)"}}}},{name:"llama_protocols",description:"DeFiLlama: full protocol list with TVL, chain(s), category, 1d/7d change. The primary cross-chain protocol scanner. Read-only. Large payload \u2014 filter client-side.",inputSchema:{type:"object",properties:{}}},{name:"llama_prices",description:"DeFiLlama current prices for coins keyed 'chain:address' or 'coingecko:id' (comma-joined or array). Read-only.",inputSchema:{type:"object",required:["coins"],properties:{coins:{type:"string",description:"comma-joined coin keys, e.g. 'ethereum:0x...,coingecko:bitcoin'"}}}},{name:"dex_search",description:"DexScreener search across all chains by symbol/name/address. Returns matching pairs with price, liquidity, volume, chain. Read-only.",inputSchema:{type:"object",required:["q"],properties:{q:{type:"string",description:"query: symbol, name, or token address"}}}},{name:"dex_token",description:"DexScreener pairs for a specific token address (any chain). Price, liquidity, volume, pair addresses. Read-only.",inputSchema:{type:"object",required:["address"],properties:{address:{type:"string"}}}},{name:"lifi_quote",description:"LI.FI cross-chain / DEX aggregator quote (no key). Best route + expected out for a swap or bridge. Read-only.",inputSchema:{type:"object",required:["fromChain","toChain","fromToken","toToken","fromAmount"],properties:{fromChain:{type:"number"},toChain:{type:"number"},fromToken:{type:"string"},toToken:{type:"string"},fromAmount:{type:"string",description:"raw integer amount (wei-scale)"},fromAddress:{type:"string",description:"optional; defaults to operator wallet"}}}},{name:"portfolio_balance",description:"Read-only balance aggregation across every configured EVM chain plus Solana, Bitcoin, and Hyperliquid. Reports native assets, supported token/collectible reads, failed or missing providers, unverified assets, timestamps, and known priced value without pretending it is a complete total. Public addresses only; never signs or broadcasts.",inputSchema:{type:"object",properties:{addresses:{type:"object",description:"Optional public wallet addresses by family. Omit configured families to use ORACLE_*_ADDRESS defaults.",properties:{evm:{type:"string"},solana:{type:"string"},bitcoin:{type:"string"},hyperliquid:{type:"string"}}},evmChainIds:{type:"array",items:{type:"number"},description:"Optional EVM chain subset. Default is every configured EVM chain."},includeTokens:{type:"boolean",description:"Include supported token reads. Default true."},includeCollectibles:{type:"boolean",description:"Include supported collectible reads. Default true."},includePrices:{type:"boolean",description:"Fetch current DeFiLlama native prices. Default true."}}}},{name:"portfolio_snapshot",description:"Query the current multichain balance and NFT inventory, then append one compact profile-local observation for historical tracking. Stores public-address fingerprint, coverage, breakdown, and known priced value only; no keys, signatures, executable payloads, or raw NFT metadata. Returns the live balance, NFT result, and recorded snapshot.",inputSchema:{type:"object",properties:{addresses:{type:"object",properties:{evm:{type:"string"},solana:{type:"string"},bitcoin:{type:"string"},hyperliquid:{type:"string"}}},evmChainIds:{type:"array",items:{type:"number"}},includeTokens:{type:"boolean"},includeCollectibles:{type:"boolean"},includePrices:{type:"boolean"},includeNfts:{type:"boolean",description:"Include provider-estimated NFT value. Default true."}}}},{name:"portfolio_history",description:"Read profile-local portfolio observations in a time range. Unknown or unavailable values remain null and are never converted to zero. Defaults to the configured public-address portfolio fingerprint.",inputSchema:{type:"object",properties:{addresses:{type:"object",properties:{evm:{type:"string"},solana:{type:"string"},bitcoin:{type:"string"},hyperliquid:{type:"string"}}},portfolioId:{type:"string"},allPortfolios:{type:"boolean",description:"Return observations for every public-address fingerprint in this profile."},since:{type:"string",description:"Inclusive ISO 8601 lower bound."},until:{type:"string",description:"Inclusive ISO 8601 upper bound."},limit:{type:"number",description:"1-1000, default 100."},order:{type:"string",enum:["asc","desc"]}}}},{name:"portfolio_value_graph",description:"Render a static SVG line graph from profile-local portfolio snapshots. Plots known priced value only, labels incomplete coverage, includes provider-estimated NFT values when recorded, and omits unavailable observations instead of plotting fake zeroes.",inputSchema:{type:"object",properties:{addresses:{type:"object",properties:{evm:{type:"string"},solana:{type:"string"},bitcoin:{type:"string"},hyperliquid:{type:"string"}}},portfolioId:{type:"string"},allPortfolios:{type:"boolean"},since:{type:"string"},until:{type:"string"},limit:{type:"number",description:"Historical observations to consider, max 1000."},maxPoints:{type:"number",description:"Rendered point cap, 2-500, default 200."}}}},{name:"evm_simulate_transaction",description:"Simulate an EVM transaction BEFORE signing: catches reverts via eth_call at pending state, decodes the reason (Error(string), Panic codes, or the raw selector for custom errors), and returns a buffered gas estimate usable as gasLimit. Also flags calls that return boolean false without reverting (some ERC-20s signal failure that way). An unreachable node returns 'unavailable', never 'would fail'. A pass reflects current chain state and is not a guarantee the transaction lands.",inputSchema:{type:"object",properties:{chainId:{type:"number"},tx:{type:"object",description:"{ from, to, data, value } \u2014 value in wei.",properties:{from:{type:"string"},to:{type:"string"},data:{type:"string"},value:{type:"string"}},required:["to"]},estimateGas:{type:"boolean",description:"Default true."},gasBufferPercent:{type:"number",description:"Headroom over the estimate. Default 20."}},required:["chainId","tx"]}},{name:"nft_mint_prepare",description:"Prepare an UNSIGNED EVM NFT mint. Discovers the collection's mint entrypoint from deployed bytecode (ERC-721 does not standardize minting), encodes calldata, prices a competitive EIP-1559 bid from fee-history percentiles, enforces gas-war caps, and reports contract risk. Returns wallet-signable calldata \u2014 never signs or broadcasts. Supply gasLimit plus maxTotalGasWei to enforce the caps; without them the artifact is returned with a loud warning.",inputSchema:{type:"object",properties:{contract:{type:"string",description:"NFT contract address."},chainId:{type:"number"},minter:{type:"string",description:"Address that will sign and receive."},quantity:{type:"number",description:"How many to mint. Default 1."},urgency:{type:"string",enum:["normal","fast","war"],description:"Bid aggressiveness. Default war."},signature:{type:"string",description:"Force a specific mint signature when several exist."},gasLimit:{type:"number"},valueWei:{type:"string",description:"Mint price in wei."},maxTotalGasWei:{type:"string",description:"Hard total gas cap."},maxFeePerGasWei:{type:"string"},maxPriorityFeePerGasWei:{type:"string"}},required:["contract","chainId","minter"]}},{name:"nft_mint_gas_price",description:"Price a competitive EIP-1559 bid for a contested transaction using eth_feeHistory reward percentiles (p50 normal / p75 fast / p90 war). maxFeePerGas is a refundable ceiling; the tip is the real spend. Reports viable:false when a cap would put the bid below the observed market rather than silently clamping to a losing number.",inputSchema:{type:"object",properties:{chainId:{type:"number"},urgency:{type:"string",enum:["normal","fast","war"]},gasLimit:{type:"number"},maxFeePerGasWei:{type:"string"},maxPriorityFeePerGasWei:{type:"string"},maxTotalGasWei:{type:"string"}},required:["chainId"]}},{name:"nft_mint_trigger",description:"Create a mint-open trigger. DEFAULTS TO alert_only: Oracle watches, notifies, and prepares a signable artifact. Firing unattended requires ALL of: actionMode set to the exact string 'execute', ORACLE_AUTONOMOUS_TRADING=1, and a bounded grant naming this exact contract/chain with maxTotalGasWei, maxValueWei, and an expiry under 24h. Any missing or mismatched bound silently downgrades to alert_only and says so. Even an armed trigger produces an unsigned artifact.",inputSchema:{type:"object",properties:{contract:{type:"string"},chainId:{type:"number"},minter:{type:"string"},quantity:{type:"number"},urgency:{type:"string",enum:["normal","fast","war"]},actionMode:{type:"string",enum:["alert_only","execute"],description:"Default alert_only. Only the exact string 'execute' can arm, and only with a grant."},grant:{type:"object",description:"Required for execute: { contract, chainId, maxTotalGasWei, maxValueWei, expiresAt }."}},required:["contract","chainId"]}},{name:"contract_risk_scan",description:"Check what powers a contract's deployer still holds before you interact with it: mint, blacklist, pause, fee changes, and upgradeability (EIP-1967, legacy zeppelinos, EIP-1822 proxies). Complements a sell simulation \u2014 that proves a token is sellable NOW, this asks whether someone can change that afterwards. Read-only eth_getCode/eth_getStorageAt; never returns 'safe', only 'unknown-risk', 'elevated', or 'high', because absence of a selector is not proof of safety.",inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (0x, 40 hex)."},chainId:{type:"number",description:"EVM chain id."}},required:["address","chainId"]}},{name:"nft_inventory",description:"Read all discoverable NFTs for configured EVM, Solana, and Bitcoin addresses. Returns normalized assets, image URLs, estimated values, per-chain partial failures, flagged/NSFW items separated from visible items, listing coverage, and explicit unsupported chains. Read-only.",inputSchema:{type:"object",properties:{addresses:{type:"object",properties:{evm:{type:"string"},solana:{type:"string"},bitcoin:{type:"string"}}},chains:{type:"array",items:{type:"string"},description:"Optional chain slug subset."},pageSize:{type:"number",description:"OpenSea items per page, max 200."},maxPages:{type:"number",description:"Maximum pages per chain, max 25."},bitcoinLimit:{type:"number"},includePnl:{type:"boolean",description:"Include OpenSea-indexed account PnL when available. Default true."},costBasis:{type:"object",description:"Optional user-supplied assetKey -> {costUsd,feesUsd,acquiredAt,source}. Missing basis stays unavailable, never zero."}}}},{name:"nft_gallery",description:"Generate one static NFT contact-sheet image page from wallet inventory or supplied normalized items. External metadata is never rendered as HTML; only allowlisted JPEG/PNG/WebP bytes are embedded and unsafe or missing media becomes a placeholder.",inputSchema:{type:"object",properties:{addresses:{type:"object",properties:{evm:{type:"string"},solana:{type:"string"},bitcoin:{type:"string"}}},chains:{type:"array",items:{type:"string"}},items:{type:"array",items:{type:"object"},description:"Optional normalized inventory items. Omit to scan configured wallets."},page:{type:"number",description:"1-based gallery page."},pageSize:{type:"number",description:"1-12 items per page."}}}},{name:"nft_pnl",description:"NFT PnL with explicit methodology. Returns OpenSea-indexed account-level PnL where available plus per-item unrealized estimates only when both user-supplied acquisition cost and provider estimated current value exist. Missing history is unavailable, never zero.",inputSchema:{type:"object",properties:{addresses:{type:"object",properties:{evm:{type:"string"},solana:{type:"string"},bitcoin:{type:"string"}}},chains:{type:"array",items:{type:"string"}},costBasis:{type:"object"}}}},{name:"nft_prepare_list",description:"Prepare an NFT listing for OpenSea EVM, Magic Eden Solana, or Satflow Bitcoin after explicit user review. Requires userConfirmed=true plus asset, marketplace, price, currency where applicable, and future expiry. Magic Eden Solana also requires confirmation exactly: list <tokenMint> on magiceden-sol for <priceSol> SOL until <expiry>. Returns approval/signing actions, an unsigned Solana transaction, or an unsigned Bitcoin PSBT. Never signs, submits, or broadcasts.",inputSchema:{type:"object",required:["marketplace","userConfirmed"],properties:{marketplace:{type:"string",enum:["opensea","magiceden","magiceden-sol","satflow"]},userConfirmed:{type:"boolean"},chain:{type:"string"},seller:{type:"string"},contract:{type:"string"},tokenId:{type:"string"},quantity:{type:"number"},priceAmount:{type:"string"},currency:{type:"string"},endTime:{type:"string"},useCreatorFee:{type:"boolean"},taker:{type:"string"},tokenMint:{type:"string"},tokenATA:{type:"string"},auctionHouse:{type:"string"},priceSol:{type:"string"},expiry:{description:"Future ISO 8601 timestamp or Unix seconds. Magic Eden Solana listings require finite future expiry; no-expiry is refused."},confirmation:{type:"string",description:"Required for Magic Eden Solana listings. Exact phrase: list <tokenMint> on magiceden-sol for <priceSol> SOL until <expiry>."},inscriptionId:{type:"string"},runesOutput:{type:"string"},ordAddress:{type:"string"},receiveAddress:{type:"string"},priceSats:{type:"string"},tapKey:{type:"string"},collectionSlug:{type:"string"}}}},{name:"rpc_balance",description:"Native token balance of an address on a chain via public RPC. Read-only. Omit address to read the operator wallet.",inputSchema:{type:"object",required:["chainId"],properties:{chainId:{type:"number"},address:{type:"string"}}}},{name:"rpc_block",description:"Latest block number on a chain via public RPC. Read-only.",inputSchema:{type:"object",required:["chainId"],properties:{chainId:{type:"number"}}}},{name:"solana_balance",description:"Solana mainnet SOL balance for a base58 public key. Read-only; no signing or broadcast.",inputSchema:{type:"object",required:["address"],properties:{address:{type:"string"},commitment:{type:"string"}}}},{name:"solana_token_accounts",description:"Solana SPL token accounts for an owner, optionally filtered by mint. Read-only.",inputSchema:{type:"object",required:["owner"],properties:{owner:{type:"string"},mint:{type:"string"},commitment:{type:"string"}}}},{name:"solana_simulate",description:"Simulate a base64 Solana transaction through RPC. Read-only; never signs or broadcasts.",inputSchema:{type:"object",required:["transaction"],properties:{transaction:{type:"string"},sigVerify:{type:"boolean"},replaceRecentBlockhash:{type:"boolean"}}}},{name:"jupiter_venues",description:"Jupiter Solana venue map, optionally verified on-chain against executable BPF loader ownership. Read-only.",inputSchema:{type:"object",properties:{verify:{type:"boolean"},rpc:{type:"string"}}}},{name:"jupiter_quote",description:"Jupiter Solana Swap API quote with a hard <=100 bps slippage cap. Read-only.",inputSchema:{type:"object",required:["inputMint","outputMint","amount"],properties:{inputMint:{type:"string"},outputMint:{type:"string"},amount:{type:"string"},slippageBps:{type:"number"}}}},{name:"jupiter_prepare",description:"Prepare an unsigned Jupiter swap transaction for the user's Solana wallet to sign. No local signer, no broadcast.",inputSchema:{type:"object",required:["userPublicKey"],properties:{userPublicKey:{type:"string"},quoteResponse:{type:"object"},inputMint:{type:"string"},outputMint:{type:"string"},amount:{type:"string"},slippageBps:{type:"number"}}}},{name:"btc_health",description:"Bitcoin L1 Esplora health + tip height (mempool.space by default). No Core RPC, no keys. Read-only.",inputSchema:{type:"object",properties:{}}},{name:"btc_fees",description:"Recommended Bitcoin fee rates (sats/vB). Read-only.",inputSchema:{type:"object",properties:{}}},{name:"btc_balance",description:"Bitcoin address balance in sats via Esplora. Read-only.",inputSchema:{type:"object",required:["address"],properties:{address:{type:"string",description:"bc1\u2026/1\u2026/3\u2026 address"}}}},{name:"btc_utxos",description:"UTXOs for a Bitcoin address via Esplora. Read-only.",inputSchema:{type:"object",required:["address"],properties:{address:{type:"string"}}}},{name:"btc_tx",description:"Lookup a Bitcoin transaction by txid via Esplora. Read-only.",inputSchema:{type:"object",required:["txid"],properties:{txid:{type:"string"}}}},{name:"btc_meta_health",description:"Ordinals/runes indexer health. Reports whether BTC_META_API_URL / vendor API keys are configured. Read-only.",inputSchema:{type:"object",properties:{}}},{name:"btc_rune_balance",description:"Rune balances for a Bitcoin address (requires configured indexer + optional API key). Read-only.",inputSchema:{type:"object",required:["address"],properties:{address:{type:"string"}}}},{name:"btc_inscriptions",description:"Inscriptions controlled by an address. REQUIRES a keyed indexer (ordinals.com has no address index). Returns unknownNotEmpty:true when unconfigured \u2014 that means UNKNOWN, never 'wallet holds none'. Protect these UTXOs from fee spends.",inputSchema:{type:"object",required:["address"],properties:{address:{type:"string"},limit:{type:"number"}}}},{name:"btc_inscription_info",description:"Inscription metadata by inscription id (content type/length, height, sat, fee). KEYLESS via ordinals.com recursive. Read-only.",inputSchema:{type:"object",required:["inscriptionId"],properties:{inscriptionId:{type:"string",description:"<64-hex-txid>i<index>"}}}},{name:"btc_inscription_children",description:"Child inscriptions of a parent (collections). KEYLESS via ordinals.com recursive. Read-only.",inputSchema:{type:"object",required:["inscriptionId"],properties:{inscriptionId:{type:"string",description:"<64-hex-txid>i<index>"},page:{type:"number"}}}},{name:"btc_ord_block_info",description:"Ord node block info / indexer tip. KEYLESS. Use to confirm the ordinals indexer is at the same tip as Esplora before trusting metaprotocol reads.",inputSchema:{type:"object",properties:{height:{type:"number",description:"omit for current tip"}}}},{name:"satflow_health",description:"Satflow marketplace health (primary BTC ordinals/runes market after Magic Eden BTC sunset). Needs SATFLOW_API_KEY. Read-only.",inputSchema:{type:"object",properties:{}}},{name:"satflow_floors",description:"Satflow collection floor prices. type=ordinals|runes. Read-only.",inputSchema:{type:"object",properties:{type:{type:"string",description:"ordinals or runes"},ids:{type:"string",description:"optional comma-separated collection ids"}}}},{name:"satflow_wallet",description:"Satflow wallet contents (ordinals/runes) for an address. Read-only.",inputSchema:{type:"object",required:["address"],properties:{address:{type:"string"},type:{type:"string"},limit:{type:"number"}}}},{name:"satflow_item",description:"Satflow item detail for an inscription id (listing + bids + meta). Read-only.",inputSchema:{type:"object",required:["inscriptionId"],properties:{inscriptionId:{type:"string"}}}},{name:"satflow_floor_listings",description:"Satflow floor listings for collection id(s). Read-only.",inputSchema:{type:"object",required:["collectionIds"],properties:{collectionIds:{type:"string"},limit:{type:"number"}}}},{name:"scanner_coverage",description:"Which chains the on-chain scanner supports and which capabilities each one has (blockNumber, nativeBalance, tokenBalance, resolveToken, resolvePools, scanBlocks, scoreRisk, quote, sellSimulation, prepareUnsignedTx). Read-only.",inputSchema:{type:"object",properties:{}}},{name:"scan_token",description:"Resolve a token on an EVM chain: metadata, its pools, and a risk score. Works on chains no indexer covers because it reads the chain directly. Read-only.",inputSchema:{type:"object",properties:{chainId:{type:"number",description:"EVM chain id, e.g. 4663 for Robinhood Chain"},token:{type:"string",description:"token contract address"}},required:["chainId","token"]}},{name:"wallet_balances",description:"Native balance for an address on an EVM chain, plus one token balance when a token address is supplied. Read-only; never signs.",inputSchema:{type:"object",properties:{chainId:{type:"number"},address:{type:"string",description:"wallet address to inspect"},token:{type:"string",description:"optional token contract for a token balance"}},required:["chainId","address"]}},{name:"address_book_remember",description:"Remember a wallet address with a label. Call this whenever someone states their address or an agent/counterparty wallet is discovered, so it survives the conversation. Stores labels only \u2014 never private keys, seeds, or passphrases.",inputSchema:{type:"object",required:["address","label"],properties:{address:{type:"string",description:"0x address"},label:{type:"string",description:"short name, e.g. research-agent"},who:{type:"string",description:"person or entity the wallet belongs to"},role:{type:"string",description:"agent | owner | person | counterparty | venue"},chainIds:{type:"array",items:{type:"number"}},notes:{type:"string"}}}},{name:"address_book_list",description:"List remembered wallets (owner, agent, people, counterparties). Read-only. Check this before sending or bridging to a person.",inputSchema:{type:"object",properties:{q:{type:"string",description:"search across label, who, address, notes"},role:{type:"string"},who:{type:"string"}}}},{name:"address_book_lookup",description:"Look up one 0x address in the durable address book. Read-only.",inputSchema:{type:"object",required:["address"],properties:{address:{type:"string"}}}},{name:"address_book_forget",description:"Remove a remembered address, optionally only one label for it.",inputSchema:{type:"object",required:["address"],properties:{address:{type:"string"},label:{type:"string"}}}},{name:"rfq_quote",description:"Create a cross-chain RFQ intent and fan it out to reviewed solver or venue sources. Returns firm quote objects with intentHash, firmQuoteHash, expiry, min receive, and unsigned executable artifacts. Never signs or broadcasts.",inputSchema:{type:"object",required:["fromChainId","toChainId","sellToken","buyToken","sellAmount","receiver","deadlineMs"],properties:{fromChainId:{type:"number"},toChainId:{type:"number"},sellToken:{type:"string"},buyToken:{type:"string"},sellAmount:{type:"string"},receiver:{type:"string"},deadlineMs:{type:"number"},minBuyAmount:{type:"string"},allowedSources:{type:"array",items:{type:"string"}},allowedRouters:{type:"array",items:{type:"string"}},slippageBps:{type:"number"},decimalsIn:{type:"number"},decimalsOut:{type:"number"}}}},{name:"best_swap_route",description:"Compare swap routes across every available aggregator and rank by NET output (after gas and fees), not headline quote. Returns the winner plus all runners-up so the ranking can be checked rather than trusted.",inputSchema:{type:"object",properties:{chainId:{type:"number",description:"EVM chain id, e.g. 8453 for Base"},tokenIn:{type:"string",description:"sell token address"},tokenOut:{type:"string",description:"buy token address"},amountIn:{type:"string",description:"raw units of tokenIn (wei-scale)"},taker:{type:"string",description:"address used for quoting only; nothing is signed"},decimalsIn:{type:"number"},decimalsOut:{type:"number"}},required:["chainId","tokenIn","tokenOut","amountIn"]}},{name:"best_bridge_route",description:"Compare cross-chain bridge routes and rank by NET output. Also reports each route's expected duration, which is NOT folded into the score -- a route that saves $2 but takes 30 minutes is a trade-off for the caller to make.",inputSchema:{type:"object",properties:{fromChainId:{type:"number"},toChainId:{type:"number"},tokenIn:{type:"string",description:"token on the origin chain"},tokenOut:{type:"string",description:"token on the destination chain"},amountIn:{type:"string",description:"raw units of tokenIn"},taker:{type:"string",description:"address used for quoting only"},decimalsOut:{type:"number"}},required:["fromChainId","toChainId","tokenIn","tokenOut","amountIn"]}},{name:"prepare_best_route",description:"Compare routes, then build the SIGNABLE artifact for the winner. Returns an unsigned transaction (LI.FI/ParaSwap/0x) or EIP-712 typed data for an off-chain order (CoW) -- the artifactKind field says which, and they require different wallet actions. Re-quotes before preparing and reports drift against the comparison. Never signs or broadcasts.",inputSchema:{type:"object",properties:{chainId:{type:"number"},tokenIn:{type:"string"},tokenOut:{type:"string"},amountIn:{type:"string",description:"raw units of tokenIn"},taker:{type:"string",description:"the REAL wallet that will sign. Placeholder/burn addresses are rejected: quoting is anonymous, preparing is not."},decimalsIn:{type:"number"},decimalsOut:{type:"number"},source:{type:"string",description:"force a specific source instead of the winner (flagged in the result)"},driftToleranceBps:{type:"number",description:"default 100"}},required:["chainId","tokenIn","tokenOut","amountIn","taker"]}},{name:"prepare_best_bridge_route",description:"Compare cross-chain bridge routes, then build the signable transaction sequence for the winner. Returns a LIST of unsigned transactions -- some routes need an approval and a deposit signed in order, and signing only the first leaves funds approved but not bridged. Reports the destination chain and expected credit time. Bridging is not atomic. Never signs or broadcasts.",inputSchema:{type:"object",properties:{fromChainId:{type:"number"},toChainId:{type:"number"},tokenIn:{type:"string",description:"token on the origin chain"},tokenOut:{type:"string",description:"token on the destination chain"},amountIn:{type:"string",description:"raw units of tokenIn"},taker:{type:"string",description:"the REAL wallet that will sign; placeholders rejected"},source:{type:"string",description:"force a source instead of the winner"},driftToleranceBps:{type:"number",description:"default 100"}},required:["fromChainId","toChainId","tokenIn","tokenOut","amountIn","taker"]}},{name:"equity_venues",description:"Inventory of on-chain equities venues (HIP-3 builder DEXes, Arcus perps/spot on Robinhood 4663, RH Uniswap prepare tier, Solana xStocks, TON ston.fi) with tiers and a liveness snapshot. Offline fixtures by default. Read-only / prepare-only.",inputSchema:{type:"object",properties:{}}},{name:"equity_quote",description:"Cross-chain best-execution comparison for a tokenized equity ticker (NVDA, SPY, TSLA, ...). Ranks HIP-3, Arcus, RH Uniswap, Solana xStocks, and TON. Returns winner + runners-up + bestPreparable (only rh_uniswap is preparable in v1). rankedOn is usually gross because fees/gas are unmeasured - say so. Never signs.",inputSchema:{type:"object",required:["ticker"],properties:{ticker:{type:"string",description:"equity ticker, e.g. NVDA, SPY, TSLA"},sizeUsd:{type:"string",description:"optional notional USD size for impact model"},horizonHours:{type:"number",description:"optional holding horizon; enables funding-adjusted spot-vs-perp ranking"}}}},{name:"equity_prepare",description:"Prepare an UNSIGNED Robinhood-chain Uniswap artifact for a tokenized equity. Only the prepare-tier venue (rh_uniswap / chain 4663). Requires the real wallet as recipient. requiresWalletSignature=true, backendSigner=false. Never signs or broadcasts.",inputSchema:{type:"object",required:["ticker","recipient"],properties:{ticker:{type:"string"},recipient:{type:"string",description:"the REAL 0x wallet that will sign; placeholders rejected"},sizeUsd:{type:"string",description:"optional notional USD size"}}}},{name:"strategy_draft",description:"Draft a deterministic Hyperliquid strategy DSL from supported plain-English EMA, RSI, or funding rules. Fails closed on unsupported ambiguity. Never signs or broadcasts.",inputSchema:{type:"object",required:["prompt"],properties:{prompt:{type:"string"},nowMs:{type:"number"}}}},{name:"strategy_validate",description:"Strictly compile and hash a Hyperliquid strategy DSL. No network or execution.",inputSchema:{type:"object",required:["strategy"],properties:{strategy:{type:"object"},nowMs:{type:"number"}}}},{name:"strategy_backtest",description:"Backtest a deterministic strategy with fees, builder fees, slippage, funding, latency, stops, take profit, and liquidation. Uses supplied bars or keyless Hyperliquid history.",inputSchema:{type:"object",required:["strategy"],properties:{strategy:{type:"object"},bars:{type:"array",items:{type:"object"}},count:{type:"number"},backtestOptions:{type:"object"}}}},{name:"strategy_optimize",description:"Run bounded deterministic parameter search on training bars, then separately evaluate out-of-sample evidence. Never uses holdout data during optimization.",inputSchema:{type:"object",required:["strategy"],properties:{strategy:{type:"object"},bars:{type:"array",items:{type:"object"}},count:{type:"number"},maxTrials:{type:"number"}}}},{name:"strategy_evidence",description:"Produce separate train, holdout, and walk-forward evidence with overfitting flags and a fail, paper-only, or live-eligible status. Live eligibility never arms execution.",inputSchema:{type:"object",required:["strategy"],properties:{strategy:{type:"object"},bars:{type:"array",items:{type:"object"}},count:{type:"number"}}}},{name:"strategy_shadow_start",description:"Start a durable local shadow runner that records intended orders and theoretical fills only. Never signs or broadcasts.",inputSchema:{type:"object",required:["strategy"],properties:{strategy:{type:"object"},evidenceId:{type:"string"}}}},{name:"strategy_shadow_list",description:"List durable local shadow runners. Read-only and secret-free.",inputSchema:{type:"object",properties:{}}},{name:"strategy_shadow_status",description:"Inspect one durable local shadow runner. Read-only and secret-free.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"strategy_shadow_step",description:"Advance one durable shadow runner over supplied or keyless historical bars. Never signs or broadcasts.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"},bars:{type:"array",items:{type:"object"}},count:{type:"number"}}}},{name:"strategy_shadow_stop",description:"Stop one durable local shadow runner. Does not submit or cancel exchange orders.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"strategy_prepare_live",description:"Create an integrity-bound prepare-only handoff after live-eligible evidence, HMAC-authenticated when local attestation is configured. All execution flags stay false. A separate local operator must revalidate, arm, sign, and broadcast.",inputSchema:{type:"object",required:["strategy","evidence","shadowId"],properties:{strategy:{type:"object"},evidence:{type:"object"},shadowId:{type:"string"},caps:{type:"object"},nowMs:{type:"number"}}}},{name:"twap_simulate",description:"Simulate a TWAP (time-weighted average price) DCA order. Splits a large order into equal-sized chunks over a configurable window, quotes every chunk at current prices, and returns the schedule + estimated average price. Read-only. Never signs or broadcasts. Use before committing to a TWAP.",inputSchema:{type:"object",required:["chainId","tokenIn","tokenOut","amount","taker"],properties:{chainId:{type:"number"},tokenIn:{type:"string"},tokenOut:{type:"string"},amount:{type:"string",description:"raw base units of tokenIn"},taker:{type:"string",description:"the REAL wallet that will sign"},splits:{type:"number",description:"number of chunks (default 10, max 100)"},windowHours:{type:"number",description:"total window in hours (default 6)"},slippageBps:{type:"number",description:"slippage cap in bps (default 100)"}}}},{name:"bridge_aggregator_scan",description:"Scan ALL cross-chain bridge routes: deBridge DLN + LI.FI/Relay + ChangeNOW. Ranks every route by net output, checks for existing token approvals that should be revoked before bridging, and returns the winner + runners-up. Read-only. Never signs or broadcasts. ChangeNOW requires ticker symbols.",inputSchema:{type:"object",required:["fromChainId","toChainId","tokenIn","tokenOut","amount","taker"],properties:{fromChainId:{type:"number"},toChainId:{type:"number"},tokenIn:{type:"string"},tokenOut:{type:"string"},amount:{type:"string",description:"raw base units of tokenIn"},taker:{type:"string"},fromSymbol:{type:"string",description:"ticker for ChangeNOW (e.g. ETH, USDC)"},toSymbol:{type:"string",description:"ticker for ChangeNOW"},fromDecimals:{type:"number",description:"default 18"},toDecimals:{type:"number",description:"default 18"}}}},{name:"perps_markets",description:"Scan perps markets across dYdX (standalone chain), Drift (Solana), and Vertex (Arbitrum). Returns ticker, oracle price, funding rate, open interest, and 24h volume. Read-only. Never signs.",inputSchema:{type:"object",properties:{venue:{type:"string",description:"dydx, drift, or vertex (default: all)"}}}},{name:"dex_quote",description:"Quote a swap across PancakeSwap (BSC+), SushiSwap (30+ chains), or Raydium (Solana via Jupiter). Specify the DEX and chain. Read-only.",inputSchema:{type:"object",required:["dex","chainId","tokenIn","tokenOut","amountIn"],properties:{dex:{type:"string",description:"pancakeswap, sushiswap, or raydium"},chainId:{type:"number"},tokenIn:{type:"string"},tokenOut:{type:"string"},amountIn:{type:"string",description:"raw base units"}}}},{name:"options_markets",description:"Scan on-chain options markets (calls/puts). Currently Aevo. Returns instruments, mark prices, funding, open interest. Read-only.",inputSchema:{type:"object",properties:{}}},{name:"lending_markets",description:"Scan lending protocol markets across Compound ($2B+ TVL). Returns supply/borrow APYs, total supply, collateral factors. Read-only.",inputSchema:{type:"object",properties:{}}},{name:"yield_vaults",description:"Scan yield aggregator vaults across Yearn + Convex. Returns vault APYs, TVLs, boosted status. Read-only.",inputSchema:{type:"object",properties:{}}}],Sd=String(jt.env.ORACLE_DEFAULT_ADDRESS||jt.env.MAD_OPERATOR_ADDRESS||"").trim(),Bb={llama_protocols:()=>({provider:"defillama",op:"protocols",args:{}}),llama_prices:e=>({provider:"defillama",op:"prices",args:{coins:e.coins}}),dex_search:e=>({provider:"dexscreener",op:"search",args:{q:e.q}}),dex_token:e=>({provider:"dexscreener",op:"token",args:{address:e.address}}),lifi_quote:e=>({provider:"lifi",op:"quote",args:{fromChain:e.fromChain,toChain:e.toChain,fromToken:e.fromToken,toToken:e.toToken,fromAmount:e.fromAmount,fromAddress:e.fromAddress||Sd||void 0}}),portfolio_balance:e=>({provider:"portfolio",op:"balances",args:{addresses:e.addresses,evmChainIds:e.evmChainIds,includeTokens:e.includeTokens,includeCollectibles:e.includeCollectibles,includePrices:e.includePrices}}),portfolio_snapshot:e=>({provider:"portfolio",op:"snapshot",args:e}),portfolio_history:e=>({provider:"portfolio",op:"history",args:e}),portfolio_value_graph:e=>({provider:"portfolio",op:"valueGraph",args:e}),nft_inventory:e=>({provider:"nft-portfolio",op:"inventory",args:e}),nft_gallery:e=>({provider:"nft-portfolio",op:"gallery",args:e}),nft_pnl:e=>({provider:"nft-portfolio",op:"pnl",args:e}),nft_prepare_list:e=>({provider:"nft-portfolio",op:"prepareList",args:e}),contract_risk_scan:e=>({provider:"contract-risk",op:"scan",args:e}),nft_mint_prepare:e=>({provider:"nft-mint",op:"prepare",args:e}),nft_mint_gas_price:e=>({provider:"nft-mint",op:"priceGas",args:e}),nft_mint_trigger:e=>({provider:"nft-mint",op:"createTrigger",args:e}),evm_simulate_transaction:e=>({provider:"evm-simulate",op:"simulate",args:e}),rpc_balance:e=>{let t=e.address||Sd;if(!t)throw new Error("address required (set ORACLE_DEFAULT_ADDRESS to supply a default)");return{provider:"evm-rpc",op:"getBalance",args:{chainId:e.chainId,address:t}}},rpc_block:e=>({provider:"evm-rpc",op:"blockNumber",args:{chainId:e.chainId}}),solana_balance:e=>({provider:"solana-rpc",op:"getBalance",args:{address:e.address,commitment:e.commitment}}),solana_token_accounts:e=>({provider:"solana-rpc",op:"tokenAccounts",args:{owner:e.owner,mint:e.mint,commitment:e.commitment}}),solana_simulate:e=>({provider:"solana-rpc",op:"simulate",args:{transaction:e.transaction,sigVerify:e.sigVerify,replaceRecentBlockhash:e.replaceRecentBlockhash}}),jupiter_venues:e=>({provider:"jupiter",op:"venues",args:{verify:e.verify,rpc:e.rpc}}),jupiter_quote:e=>({provider:"jupiter",op:"quote",args:{inputMint:e.inputMint,outputMint:e.outputMint,amount:e.amount,slippageBps:e.slippageBps}}),jupiter_prepare:e=>({provider:"jupiter",op:"prepare",args:{userPublicKey:e.userPublicKey,quoteResponse:e.quoteResponse,inputMint:e.inputMint,outputMint:e.outputMint,amount:e.amount,slippageBps:e.slippageBps}}),btc_health:()=>({provider:"bitcoin-esplora",op:"health",args:{}}),btc_fees:()=>({provider:"bitcoin-esplora",op:"fees",args:{}}),btc_balance:e=>({provider:"bitcoin-esplora",op:"address",args:{address:e.address}}),btc_utxos:e=>({provider:"bitcoin-esplora",op:"utxos",args:{address:e.address}}),btc_tx:e=>({provider:"bitcoin-esplora",op:"tx",args:{txid:e.txid}}),btc_meta_health:()=>({provider:"bitcoin-meta",op:"health",args:{}}),btc_rune_balance:e=>({provider:"bitcoin-meta",op:"runeBalances",args:{address:e.address}}),btc_inscriptions:e=>({provider:"bitcoin-meta",op:"inscriptions",args:{address:e.address,limit:e.limit}}),btc_inscription_info:e=>({provider:"bitcoin-meta",op:"inscriptionInfo",args:{inscriptionId:e.inscriptionId}}),btc_inscription_children:e=>({provider:"bitcoin-meta",op:"inscriptionChildren",args:{inscriptionId:e.inscriptionId,page:e.page}}),btc_ord_block_info:e=>({provider:"bitcoin-meta",op:"ordBlockInfo",args:{height:e.height}}),satflow_health:()=>({provider:"satflow",op:"health",args:{}}),satflow_floors:e=>({provider:"satflow",op:"collectionFloors",args:{type:e.type,ids:e.ids}}),satflow_wallet:e=>({provider:"satflow",op:"walletContents",args:{address:e.address,type:e.type,limit:e.limit}}),satflow_item:e=>({provider:"satflow",op:"item",args:{inscriptionId:e.inscriptionId||e.id}}),satflow_floor_listings:e=>({provider:"satflow",op:"floorListings",args:{collectionIds:e.collectionIds||e.ids,limit:e.limit}})};function Mt(e){jt.stdout.write(`${JSON.stringify(e)}
|