@oracle-agent/oracle 0.22.11 → 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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{realpathSync as xt}from"node:fs";import{fileURLToPath as br}from"node:url";var $r=Object.freeze({mantissa:10000n,scale:0});function P(e){if(!Number.isSafeInteger(e)||e<0||e>1e3)throw new RangeError("scale must be a safe integer from 0 through 1000")}function T(e,t){if(typeof e!="bigint")throw new TypeError("mantissa must be a bigint");return P(t),Object.freeze({mantissa:e,scale:t})}function N(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`);P(e.scale)}function Y(e){return P(e),10n**BigInt(e)}function f(e){if(typeof e!="string"||!/^[+-]?\d+(?:\.\d+)?$/.test(e))throw new TypeError("value must be a plain decimal string");let t=e.startsWith("-"),n=e[0]==="-"||e[0]==="+"?e.slice(1):e,[r,s=""]=n.split("."),o=`${r}${s}`,i=BigInt(o)*(t?-1n:1n);return T(i,s.length)}function $(e,t){if(P(t),typeof e=="bigint")return T(e,t);if(typeof e!="string"||!/^[+-]?\d+$/.test(e))throw new TypeError("value must be an integer string or bigint");return T(BigInt(e),t)}function S(e){N(e);let t=e.mantissa<0n,n=(t?-e.mantissa:e.mantissa).toString();if(e.scale===0)return`${t?"-":""}${n}`;let r=n.padStart(e.scale+1,"0"),s=r.length-e.scale;return`${t?"-":""}${r.slice(0,s)}.${r.slice(s)}`}function W(e,t){return N(e),P(t),t===e.scale?T(e.mantissa,e.scale):t>e.scale?T(e.mantissa*Y(t-e.scale),t):T(e.mantissa/Y(e.scale-t),t)}function ce(e,t){N(e,"left"),N(t,"right");let n=Math.max(e.scale,t.scale);return[W(e,n),W(t,n),n]}function D(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa+r.mantissa,s)}function Q(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa-r.mantissa,s)}function E(e,t){N(e,"left"),N(t,"right");let n=e.scale+t.scale;return P(n),T(e.mantissa*t.mantissa,n)}function R(e,t,n=Math.max(e?.scale??0,t?.scale??0)){if(N(e,"left"),N(t,"right"),P(n),t.mantissa===0n)throw new RangeError("division by zero");let r=e.mantissa*Y(t.scale+n),s=t.mantissa*Y(e.scale);return T(r/s,n)}function M(e,t){let[n,r]=ce(e,t);return n.mantissa<r.mantissa?-1:n.mantissa>r.mantissa?1:0}import{readFileSync as Rt,existsSync as It}from"node:fs";import{fileURLToPath as Tt}from"node:url";import{dirname as _t,join as Me}from"node:path";import{existsSync as _e,readFileSync as vt}from"node:fs";import{dirname as Te,join as le}from"node:path";import{fileURLToPath as qt}from"node:url";function Ot(e){let t=Te(qt(e));for(let n=0;n<8;n+=1){let r=le(t,"package.json");if(_e(r))try{let o=JSON.parse(vt(r,"utf8"));if(o&&typeof o.version=="string")return t}catch{}let s=Te(t);if(s===t)break;t=s}throw new Error(`oracle: could not resolve package root from ${e}`)}function Ne(e,t){let n=Ot(t),r=le(n,"dist","assets",e);return _e(r)?r:le(n,e)}var Nt=Me(_t(Tt(import.meta.url)),"fixtures");function Dt(){try{let e=Ne("equities-fixtures",import.meta.url);if(e&&It(e))return e}catch{}return Nt}var Mt=Dt();var Ue=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"});function Ut(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function d(e,t){throw new TypeError(`Fixture fixtures/${e}: ${t}`)}function k(e,t,n){Ut(e)||d(t,`${n} must be an object`)}function m(e,t,n){(typeof e!="string"||e.length===0)&&d(t,`${n} must be a nonempty string`)}function _(e,t,n){Number.isSafeInteger(e)||d(t,`${n} must be a safe integer`)}function U(e,t,n){k(e,t,n);for(let[r,s]of Object.entries(e))m(r,t,`${n} key`),k(s,t,`${n}.${r}`)}function jt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),k(e.venues,t,"venues");let n=[["hyperliquid_hip3","dexs"],["arcus","markets"],["arcus_spot","pairs"],["rh_uniswap","pools"],["rh_chainlink_oracles","assets"]];for(let[r,s]of n){let o=e.venues[r];k(o,t,`venues.${r}`),m(o.type,t,`venues.${r}.type`),m(o.chain,t,`venues.${r}.chain`),m(o.tier,t,`venues.${r}.tier`),U(o[s],t,`venues.${r}.${s}`)}for(let[r,s]of Object.entries(e.venues.hyperliquid_hip3.dexs))U(s,t,`venues.hyperliquid_hip3.dexs.${r}`)}function Ft(e,t){U(e,t,"root"),Object.keys(e).length===0&&d(t,"root must not be empty");for(let[n,r]of Object.entries(e))Array.isArray(r.venues)||d(t,`${n}.venues must be an array`),r.venues.forEach((s,o)=>m(s,t,`${n}.venues[${o}]`))}function Pt(e,t){k(e,t,"root");for(let n of["chainId","block","oracleScaleExp","usdgDecimals","equityDecimals"])_(e[n],t,n);m(e.usdg,t,"usdg"),U(e.assets,t,"assets");for(let[n,r]of Object.entries(e.assets))m(r.oracle,t,`assets.${n}.oracle`),m(r.token,t,`assets.${n}.token`),(typeof r.rawPrice!="string"||!/^\d+$/.test(r.rawPrice))&&d(t,`assets.${n}.rawPrice must be an integer string`),(typeof r.usd!="number"||!Number.isFinite(r.usd)||r.usd<0)&&d(t,`assets.${n}.usd must be a nonnegative finite source number`)}function Bt(e,t){k(e,t,"root");for(let r of["holidayDayIndex","names","dates"])Array.isArray(e[r])||d(t,`${r} must be an array`);let n=e.holidayDayIndex.length;(e.names.length!==n||e.dates.length!==n)&&d(t,"holidayDayIndex, names, and dates must have equal lengths"),e.holidayDayIndex.forEach((r,s)=>_(r,t,`holidayDayIndex[${s}]`)),e.names.forEach((r,s)=>m(r,t,`names[${s}]`)),e.dates.forEach((r,s)=>{(typeof r!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(r))&&d(t,`dates[${s}] must use YYYY-MM-DD`)})}function Ct(e,t){k(e,t,"root"),(!Array.isArray(e.dstTransitions)||e.dstTransitions.length===0)&&d(t,"dstTransitions must be a nonempty array");let n=new Set;e.dstTransitions.forEach((r,s)=>{k(r,t,`dstTransitions[${s}]`);for(let o of["year","startUtc","endUtc"])_(r[o],t,`dstTransitions[${s}].${o}`);r.startUtc>=r.endUtc&&d(t,`dstTransitions[${s}] startUtc must be before endUtc`),n.has(r.year)&&d(t,`dstTransitions contains duplicate year ${r.year}`),n.add(r.year)})}function Ht(e,t){U(e,t,"root"),Object.keys(e).length===0&&d(t,"root must not be empty");for(let[n,r]of Object.entries(e)){for(let s of["addr","quote","quoteAddr","dex","pair"])m(r[s],t,`${n}.${s}`);(typeof r.liq!="number"||!Number.isFinite(r.liq)||r.liq<0)&&d(t,`${n}.liq must be a nonnegative finite source number`)}}function zt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),_(e.block,t,"block"),_(e.chainId,t,"chainId"),m(e.gasPriceWei,t,"gasPriceWei"),m(e.stateView,t,"stateView"),U(e.pools,t,"pools"),Object.keys(e.pools).length===0&&d(t,"pools must not be empty");for(let[n,r]of Object.entries(e.pools)){for(let s of["pair","version","quote","token","sqrtPriceX96"])m(r[s],t,`pools.${n}.${s}`);r.version!=="v3"&&r.version!=="v4"&&d(t,`pools.${n}.version must be v3 or v4`),typeof r.quoteIsToken0!="boolean"&&d(t,`pools.${n}.quoteIsToken0 must be a boolean`),(!/^[0-9]+$/.test(r.sqrtPriceX96)||BigInt(r.sqrtPriceX96)<=0n)&&d(t,`pools.${n}.sqrtPriceX96 must be a positive integer string`)}}function Lt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),k(e.books,t,"books"),Object.keys(e.books).length===0&&d(t,"books must not be empty");for(let[n,r]of Object.entries(e.books)){k(r,t,`books.${n}`),(!Array.isArray(r.bids)||!Array.isArray(r.asks))&&d(t,`books.${n} must have bids and asks arrays`);for(let[s,o]of r.bids.entries())k(o,t,`books.${n}.bids[${s}]`),m(o.px,t,`books.${n}.bids[${s}].px`),m(o.sz,t,`books.${n}.bids[${s}].sz`);for(let[s,o]of r.asks.entries())k(o,t,`books.${n}.asks[${s}]`),m(o.px,t,`books.${n}.asks[${s}].px`),m(o.sz,t,`books.${n}.asks[${s}].sz`)}}function Wt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),U(e.tokens,t,"tokens"),k(e.pairs,t,"pairs"),Object.keys(e.tokens).length===0&&d(t,"tokens must not be empty");for(let[n,r]of Object.entries(e.tokens)){m(r.symbolRaw,t,`tokens.${n}.symbolRaw`),m(r.mint,t,`tokens.${n}.mint`),Object.hasOwn(e.pairs,n)||d(t,`pairs.${n} is required for token ${n}`),(!Array.isArray(e.pairs[n])||e.pairs[n].length===0)&&d(t,`pairs.${n} must be a nonempty array`);for(let[s,o]of e.pairs[n].entries())k(o,t,`pairs.${n}[${s}]`),m(o.pairAddress,t,`pairs.${n}[${s}].pairAddress`),m(o.dexId,t,`pairs.${n}[${s}].dexId`),(typeof o.priceUsd!="number"||!Number.isFinite(o.priceUsd)||o.priceUsd<=0)&&d(t,`pairs.${n}[${s}].priceUsd must be a positive finite number`),(typeof o.liquidityUsd!="number"||!Number.isFinite(o.liquidityUsd)||o.liquidityUsd<0)&&d(t,`pairs.${n}[${s}].liquidityUsd must be a nonnegative finite number`)}}function Qt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),e.chain!=="ton"&&d(t,'chain must be "ton"'),U(e.tokens,t,"tokens"),k(e.pairs,t,"pairs"),Object.keys(e.tokens).length===0&&d(t,"tokens must not be empty");for(let[n,r]of Object.entries(e.tokens)){m(r.symbolRaw,t,`tokens.${n}.symbolRaw`),m(r.mint,t,`tokens.${n}.mint`),Object.hasOwn(e.pairs,n)||d(t,`pairs.${n} is required for token ${n}`),(!Array.isArray(e.pairs[n])||e.pairs[n].length===0)&&d(t,`pairs.${n} must be a nonempty array`);for(let[s,o]of e.pairs[n].entries())k(o,t,`pairs.${n}[${s}]`),m(o.pairAddress,t,`pairs.${n}[${s}].pairAddress`),m(o.dexId,t,`pairs.${n}[${s}].dexId`),(typeof o.priceUsd!="number"||!Number.isFinite(o.priceUsd)||o.priceUsd<=0)&&d(t,`pairs.${n}[${s}].priceUsd must be a positive finite number`),(typeof o.liquidityUsd!="number"||!Number.isFinite(o.liquidityUsd)||o.liquidityUsd<0)&&d(t,`pairs.${n}[${s}].liquidityUsd must be a nonnegative finite number`)}}var Xt=Object.freeze({venues:jt,universe:Ft,oracles:Pt,nyseHolidays:Bt,dstTransitions:Ct,equityDexPools:Ht,rhPoolState:zt,solanaXstocks:Wt,tonXstocks:Qt,hip3L2Books:Lt});function Vt(e,t){let n=Ue[t],r=Me(e,n),s;try{s=Rt(r,"utf8")}catch(i){throw i?.code==="ENOENT"?new Error(`Fixture fixtures/${n} is missing at ${r}`):new Error(`Fixture fixtures/${n} could not be read: ${i.message}`)}let o;try{o=JSON.parse(s)}catch(i){throw new SyntaxError(`Fixture fixtures/${n} contains invalid JSON: ${i.message}`)}return Xt[t](o,n),o}function je(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))je(t)}return e}function Fe({fixtureDir:e=Mt}={}){if(typeof e!="string"||e.length===0)throw new TypeError("fixtureDir must be a nonempty path string");let t={};for(let n of Object.keys(Ue))t[n]=Vt(e,n);return je(t)}var De;function j(){return De??=Fe(),De}function q(){return j().venues}function Pe(){return j().oracles}function Be(){return j().nyseHolidays}function Ce(){return j().dstTransitions}function J(){return j().rhPoolState}function He(){return j().solanaXstocks}function ze(){return j().tonXstocks}function Le(){return j().hip3L2Books}var pe=1e3,Xe=60*pe,de=60*Xe,We=24*de,Kt=-5*de,Yt=-4*de,Ve=240,Ke=570,Ye=960,Je=1200,Mr=Object.freeze([Ve,Ke,Ye,Je]),Ur=Object.freeze(["core","extended","dark"]),Qe,fe;function Jt(){let e=Ce().dstTransitions.map(r=>({year:r.year,startMs:r.startUtc*pe,endMs:r.endUtc*pe}));e.sort((r,s)=>r.startMs-s.startMs);let t=e[0].year,n=e[e.length-1].year;return Object.freeze({rows:Object.freeze(e),firstYear:t,lastYear:n,coverageStartMs:Date.UTC(t,0,1),coverageEndMs:Date.UTC(n+1,0,1)})}function Ge(){return Qe??=Jt(),Qe}function Gt(){return fe===void 0&&(fe=new Set(Be().holidayDayIndex)),fe}function Ze(e,t){if(!Number.isSafeInteger(e))throw new TypeError(`${t}: epochMs must be a safe integer number of milliseconds`)}function Zt(e,t){let{coverageStartMs:n,coverageEndMs:r,firstYear:s,lastYear:o}=Ge();if(e<n||e>=r)throw new RangeError(`${t}: ${new Date(e).toISOString()} is outside DST fixture coverage (${s} through ${o}). Refusing to assume a UTC offset.`)}function en(e){for(let t of Ge().rows)if(e>=t.startMs&&e<t.endMs)return!0;return!1}function tn(e){return en(e)?Yt:Kt}function nn(e){let t=e+tn(e),n=Math.floor(t/We),r=t-n*We,s=new Date(t);return{dayIndex:n,minuteOfDay:Math.floor(r/Xe),msIntoDay:r,weekday:s.getUTCDay()}}function rn({dayIndex:e,weekday:t}){return t===0||t===6?!1:!Gt().has(e)}function sn(e){return e<Ve?"dark":e<Ke?"extended":e<Ye?"core":e<Je?"extended":"dark"}function X(e){Ze(e,"sessionState"),Zt(e,"sessionState");let t=nn(e);return rn(t)?sn(t.minuteOfDay):"dark"}function me(e){return Ze(e,"isDark"),X(e)==="dark"}var G=Object.freeze({DORMANT_VENUE:"dormant-venue",CROSSED_BOOK:"crossed-book",STALE_QUOTE:"stale-quote",STALE_ORACLE:"stale-oracle"}),on=12e4,un=6e5;function Z(e,t){e.push(Object.freeze({venue:t.venue,symbol:t.symbol??null,reason:t.reason,evidence:t.evidence??null}))}function an(e){let t=e.raw?.vol24h;return!!(t===0||t===0||typeof t=="number"&&Number.isFinite(t)&&t<=0)}function cn(e){return!e.bid||!e.ask?!1:M(e.bid,e.ask)>0}function et(e,t,n){return Number.isSafeInteger(e.capturedAt)?t-e.capturedAt>n:!1}function ee(e,t={}){if(!Array.isArray(e))throw new TypeError("quotes must be an array");let n=t.nowMs??Date.now(),r=t.quoteFreshnessMs??on,s=t.oracleFreshnessMs??un,o=t.includeDormant===!0,i=[],u=[];for(let a of e){if(an(a)){o?i.push(Object.freeze({...a,staleData:!0})):Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.DORMANT_VENUE,evidence:{vol24h:a.raw?.vol24h??null}});continue}if(cn(a)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.CROSSED_BOOK,evidence:{bid:a.bid?String(a.bid.mantissa)+"e-"+a.bid.scale:null,ask:a.ask?String(a.ask.mantissa)+"e-"+a.ask.scale:null}});continue}if(et(a,n,r)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.STALE_QUOTE,evidence:{capturedAt:a.capturedAt,nowMs:n,ageMs:n-a.capturedAt,freshnessMs:r}});continue}if(a.tier==="read-only"&&a.raw?.oracleRaw!==void 0){let l=X(n),c=l==="core"?s:s*2;if(et(a,n,c)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.STALE_ORACLE,evidence:{capturedAt:a.capturedAt,nowMs:n,session:l}});continue}}i.push(a)}return{survivors:i,excluded:u}}function ln(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[n,r]=t.split(/[eE]/),s=Number(r),o=n.startsWith("-"),i=o?n.slice(1):n,[u,a=""]=i.split("."),l=`${u}${a}`,c=u.length+s,p;return c<=0?p=`0.${"0".repeat(-c)}${l}`:c>=l.length?p=`${l}${"0".repeat(c-l.length)}`:p=`${l.slice(0,c)}.${l.slice(c)}`,`${o?"-":""}${p}`}function w(e){return e==null?null:typeof e=="string"?f(e):typeof e!="number"||!Number.isFinite(e)?null:f(ln(e))}function I(e,t){let n=w(e);if(n===null)throw new TypeError(`${t} must be a finite source number`);return n}var fn=new Set(["spot","perp"]),pn=new Set(["read-only","quote-only","prepare","intent"]),dn=new Set(["buy","sell"]),mn=new Set(["net-of-cost","gross"]),bn=new Set(["homogeneous","heterogeneous"]),yn=["bid","ask","mid","mark"],tt=["fees","gasEstimate","priceImpact","fundingHourly"],hn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function h(e,t){throw new TypeError(`${e} ${t}`)}function rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function B(e,t){rt(e)||h(t,"must be an object")}function st(e,t,n){Object.hasOwn(e,t)||h(`${n}.${t}`,"is required")}function C(e,t){(typeof e!="string"||e.length===0)&&h(t,"must be a nonempty string")}function V(e,t,n){t.has(e)||h(n,`must be one of ${[...t].join(", ")}`)}function ye(e,t){(!Number.isSafeInteger(e)||e<0)&&h(t,"must be a nonnegative safe integer")}function be(e,t,n=!1){e===null&&n||(rt(e)||h(t,"must be a fixed point value"),typeof e.mantissa!="bigint"&&h(`${t}.mantissa`,"must be a bigint"),(!Number.isSafeInteger(e.scale)||e.scale<0)&&h(`${t}.scale`,"must be a nonnegative safe integer"))}function te(e,t,n=!1){e===null&&n||B(e,t)}function nt(e,t){B(e,t),C(e.venue,`${t}.venue`),C(e.reason,`${t}.reason`),hn.test(e.reason)||h(`${t}.reason`,"must be a machine readable lower case code"),Object.hasOwn(e,"symbol")&&e.symbol!==null&&C(e.symbol,`${t}.symbol`)}function v(e){B(e,"quote");for(let n of["venue","chain","instrument","tier","symbolRaw","symbol","side","requestedSize",...tt,"costAccounted","capturedAt","blockOrSeq","raw"])st(e,n,"quote");C(e.venue,"quote.venue"),!(typeof e.chain=="string"&&e.chain.length>0)&&!(Number.isSafeInteger(e.chain)&&e.chain>=0)&&h("quote.chain","must be a nonempty string or nonnegative chain id"),V(e.instrument,fn,"quote.instrument"),V(e.tier,pn,"quote.tier"),C(e.symbolRaw,"quote.symbolRaw"),C(e.symbol,"quote.symbol"),V(e.side,dn,"quote.side"),be(e.requestedSize,"quote.requestedSize"),e.requestedSize.mantissa<0n&&h("quote.requestedSize","must not be negative");let t=0;for(let n of yn)Object.hasOwn(e,n)&&(be(e[n],`quote.${n}`),t+=1);t===0&&h("quote","must contain at least one of bid, ask, mid, mark");for(let n of tt)be(e[n],`quote.${n}`,!0);if(typeof e.costAccounted!="boolean"&&h("quote.costAccounted","must be a boolean"),e.costAccounted){for(let n of["fees","gasEstimate","priceImpact"])e[n]===null&&h(`quote.${n}`,"cannot be unknown when costAccounted is true");e.instrument==="perp"&&e.fundingHourly===null&&h("quote.fundingHourly","cannot be unknown when costAccounted is true for a perp")}return e.instrument==="spot"&&e.fundingHourly!==null&&h("quote.fundingHourly","must be null for a spot quote"),ye(e.capturedAt,"quote.capturedAt"),e.blockOrSeq!==null&&!(typeof e.blockOrSeq=="string"&&e.blockOrSeq.length>0)&&!(Number.isSafeInteger(e.blockOrSeq)&&e.blockOrSeq>=0)&&h("quote.blockOrSeq","must be null, a nonempty string, or a nonnegative safe integer"),B(e.raw,"quote.raw"),e}function he(e){B(e,"rankResult");for(let t of["rankedOn","ranked","winner","runnersUp","improvementBps","sourcesAnswered","sourcesTried","failed","excluded","darkWindow","instrumentMix","bestPreparable"])st(e,t,"rankResult");return V(e.rankedOn,mn,"rankResult.rankedOn"),Array.isArray(e.ranked)||h("rankResult.ranked","must be an array"),e.ranked.forEach((t,n)=>te(t,`rankResult.ranked[${n}]`)),te(e.winner,"rankResult.winner",!0),e.ranked.length===0&&e.winner!==null&&h("rankResult.winner","must be null when ranked is empty"),e.ranked.length>0&&e.winner===null&&h("rankResult.winner","must be present when ranked is not empty"),Array.isArray(e.runnersUp)||h("rankResult.runnersUp","must be an array"),e.runnersUp.forEach((t,n)=>te(t,`rankResult.runnersUp[${n}]`)),e.improvementBps!==null&&!(typeof e.improvementBps=="number"&&Number.isFinite(e.improvementBps))&&h("rankResult.improvementBps","must be a finite number or null"),ye(e.sourcesAnswered,"rankResult.sourcesAnswered"),ye(e.sourcesTried,"rankResult.sourcesTried"),e.sourcesAnswered>e.sourcesTried&&h("rankResult.sourcesAnswered","must not exceed sourcesTried"),Array.isArray(e.failed)||h("rankResult.failed","must be an array"),e.failed.forEach((t,n)=>nt(t,`failed[${n}]`)),Array.isArray(e.excluded)||h("rankResult.excluded","must be an array"),e.excluded.forEach((t,n)=>nt(t,`excluded[${n}]`)),e.darkWindow!==null&&B(e.darkWindow,"rankResult.darkWindow"),V(e.instrumentMix,bn,"rankResult.instrumentMix"),te(e.bestPreparable,"rankResult.bestPreparable",!0),Object.hasOwn(e,"carry")&&e.carry!==null&&B(e.carry,"rankResult.carry"),e}var gn="arcus_perp",kn="robinhood-4663",xn="quote-only",ne="0.00000480324074074";function ot(){return q().venues.arcus}function wn(){return Object.keys(ot().markets).sort()}function Sn({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e.endsWith("-USD")?e.slice(0,-4):e,s=ot().markets[r];if(!s)return null;let o=I(s.mark,`${r}.mark`),i=w(s.oracle),u=w(s.fundingHourly),a=n===null?f("0"):n,l={venue:gn,chain:kn,instrument:"perp",tier:xn,symbolRaw:e,symbol:r,side:t,requestedSize:a,mark:o,fees:null,gasEstimate:null,priceImpact:null,fundingHourly:u,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.arcus",oraclePrice:s.oracle,vol24h:s.vol24h,oi:s.oi,fundingAnnPct:s.fundingAnnPct,category:s.category,isOutsideRth:s.isOutsideRth===!0,rth:s.rth,darkWindowFundingHourly:ne,initialMarginFraction:s.initialMarginFraction??null,offHoursInitialMarginFraction:s.offHoursInitialMarginFraction??null,reasonCostUnknown:"fees, gas, and impact at size not captured for Arcus perps"}};return i!==null&&(l.raw.oracleFixed=i),v(l)}function re({side:e="buy",sizeUsd:t=null}={}){return wn().map(n=>Sn({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var it=36e5,Zr=24*365;function ge(e,t,n=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 f("0");let r=f(String(t)),s=$(10000n,0);return E(E(e,r),s)}function ut(e,t,n={}){if(e.instrument!=="perp")return{model:"current-funding-held-constant",horizonHours:t,carryBps:f("0"),carryBpsDisplay:"0",confidence:"estimate",note:"spot has no funding carry"};let r=n.nowMs??Date.now(),s=n.applyDarkWindowLock===!0,o=e.fundingHourly;if(s&&o!==null){let u=$n(r,t),a=t-u,l=f(ne),c=ge(o,a),p=ge(l,u),y=Math.max(c.scale,p.scale),b={mantissa:c.mantissa*10n**BigInt(y-c.scale)+p.mantissa*10n**BigInt(y-p.scale),scale:y};return{model:"current-funding-held-constant",horizonHours:t,carryBps:b,carryBpsDisplay:S(b),confidence:"estimate",darkHours:u,litHours:a,darkWindowRate:ne,compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}if(o===null)return{model:"current-funding-held-constant",horizonHours:t,carryBps:null,carryBpsDisplay:null,confidence:"estimate",note:"funding rate unknown"};let i=ge(o,t);return{model:"current-funding-held-constant",horizonHours:t,carryBps:i,carryBpsDisplay:S(i),confidence:"estimate",compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}function $n(e,t){if(t<=0)return 0;let n=0,r=Math.floor(t);for(let s=0;s<r;s+=1)me(e+s*it)&&(n+=1);return t>r&&me(e+r*it)&&(n+=t-r),n}function An(e){return e.mid??e.mark??e.ask??e.bid??null}function En(e){let t=An(e);if(t===null)return null;let n=e.costAccounted===!0,r=f("0");e.fees!==null?r=D(r,e.fees):n=!1,e.priceImpact!==null?r=D(r,e.priceImpact):e.requestedSize&&e.requestedSize.mantissa>0n&&(n=!1),e.gasEstimate===null?n=!1:r=D(r,e.gasEstimate);let s;if(e.fees!==null&&M(e.fees,f("1"))<0&&M(e.fees,f("0"))>=0){let o=D(f("1"),e.fees);s=E(t,o),e.priceImpact!==null&&(s=D(s,E(t,e.priceImpact)))}else s=D(t,r);return{net:s,costAccounted:n,px:t}}function vn(e,t,n=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:n,quote:e}}function qn(e,t){if(!e||!t||!e.costAccounted||!t.costAccounted||e.instrument!==t.instrument||e.net.mantissa===0n)return null;let n=Q(t.net,e.net);return R(E(n,$(10000n,0)),t.net,4)}function ke(e,t={}){if(!Array.isArray(e))throw new TypeError("quotes must be an array");let n=t.nowMs??e[0]?.capturedAt??Date.now(),r=e.length,s=e,o=[];if(!t.skipLiveness){let x=ee(e,{nowMs:n});s=x.survivors,o=x.excluded}let i=e.length,u=[],a=t.horizonHours,l=Number.isFinite(a)&&a>0,c=[];for(let x of s){let A=En(x);if(A===null)continue;let O=null;if(l&&x.instrument==="perp"&&(O=ut(x,a,{nowMs:n}),O.carryBps!==null)){let Et=D(f("1"),R(O.carryBps,$(10000n,0),12));A.net=E(A.net,Et),A.costAccounted=!1}c.push(vn(x,A,O))}let p=c,y="homogeneous";if(l)y="heterogeneous",p=c;else{let x=c.filter(O=>O.instrument==="spot"),A=c.filter(O=>O.instrument==="perp");x.length>0&&A.length>0?(p=x.length>=A.length?x:A,y="homogeneous"):(p=c,y="homogeneous")}p.sort((x,A)=>{let O=M(x.net,A.net);return O!==0?O:x.venue<A.venue?-1:x.venue>A.venue?1:0});let b=p[0]??null,g=p.slice(1),F=p,L="gross";b&&b.costAccounted&&(g.length===0||g[0].costAccounted)&&(L="net-of-cost");let Re=g.length===0?null:qn(b,g[0]),St=c.find(x=>x.tier==="prepare")??null,ae=X(n),$t=ae==="core"?null:{session:ae,warning:ae==="dark"?"market is dark; marks are not real price discovery":"extended session; thinner books and higher staleness risk"},Ie=null;l&&(Ie=On(c));let At={rankedOn:L,ranked:F,winner:b,runnersUp:g,improvementBps:Re===null?null:Number(S(Re)),sourcesAnswered:i,sourcesTried:r,failed:u,excluded:o,darkWindow:$t,instrumentMix:y,bestPreparable:St,carry:b?.carry??null,breakEvenHorizonHours:Ie};return he(At)}function On(e){let t=e.filter(o=>o.instrument==="spot").sort((o,i)=>M(o.net,i.net))[0],n=e.filter(o=>o.instrument==="perp").sort((o,i)=>M(o.net,i.net))[0];if(!t||!n||n.fundingHourly===null)return null;let r=Q(t.net,n.net);if(r.mantissa===0n)return 0;let s=E(n.fundingHourly,n.price);if(s.mantissa===0n)return null;try{let o=R(r,s,4),i=Number(S(o));return!Number.isFinite(i)||i<0?null:i}catch{return null}}var Rn="rh_uniswap",In=4663,Tn="prepare",_n=1n<<192n,H=18,Nn=Object.freeze({v3:180000n,v4:240000n});function xe(){return J()}function Dn(e){return{mantissa:e*e*10n**BigInt(H)/_n,scale:H}}function Mn(e){let t=Dn(BigInt(e.sqrtPriceX96)),n=e.quote==="USDG"?6:18,r=18;if(e.quoteIsToken0){let s=R(E(t,$(10n**BigInt(n),0)),$(10n**BigInt(r),0),H);return s.mantissa===0n?null:R(f("1"),s,H)}return R(E(t,$(10n**BigInt(r),0)),$(10n**BigInt(n),0),H)}function Un(e){let t=Pe(),n=t.assets[e];return n?$(n.rawPrice,t.oracleScaleExp):null}function jn(e,t){if(e===null||t===null||e.mantissa<=0n||t.mantissa<=0n)return null;let n={...e};return R(t,Fn(n,t),H)}function Fn(e,t){let n=Math.max(e.scale,t.scale);return{mantissa:W(e,n).mantissa+W(t,n).mantissa,scale:n}}function Pn(e){let t=xe(),n=Nn[e];return n?{wei:BigInt(t.gasPriceWei)*n,units:n,native:"ETH"}:null}function we(){return Object.keys(xe().pools).sort()}function z({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)throw new TypeError("symbol must be a nonempty string");let r=xe(),s=r.pools[e];if(!s)return null;let o=Mn(s);if(o===null)return null;let i=w(s.liqUsd),u=n===null?f("0"):n,a=s.feePpm===null||s.feePpm===void 0?null:R($(BigInt(s.feePpm),0),$(1000000n,0),8),l=u.mantissa===0n?f("0"):jn(i,u),c=Pn(s.version),b={venue:Rn,chain:In,instrument:"spot",tier:Tn,symbolRaw:e,symbol:e,side:t,requestedSize:u,mid:o,fees:a,gasEstimate:null,priceImpact:l,fundingHourly:null,costAccounted:!1,capturedAt:r.capturedAt*1e3,blockOrSeq:r.block,raw:{fixture:"fixtures/rh_pool_state.json",pair:s.pair,version:s.version,sqrtPriceX96:s.sqrtPriceX96,quote:s.quote,quoteIsToken0:s.quoteIsToken0,liqUsd:s.liqUsd,gasNativeWei:c===null?null:c.wei.toString(),gasUnits:c===null?null:c.units.toString(),impactModel:"constant-product-estimate",notes:["price read live from chain 4663",s.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"]}},g=Un(e);return g!==null&&(b.referencePrice=g,b.referenceBasisBps=S(R(E(Q(o,g),$(10000n,0)),g,4))),v(b)}function at({side:e="buy",sizeUsd:t=null}={}){return we().map(n=>z({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ct=12e4,Bn="0x0000000000000000000000000000000000000000",Cn="0x84b75b19A3cdf8E2F56d0507d22D442847B2053C";function Se(e={}){let{symbol:t,side:n="buy",sizeUsd:r=null,recipient:s,nowMs:o=Date.now()}=e;if(typeof t!="string"||!t)throw new TypeError("symbol is required");if(typeof s!="string"||!/^0x[0-9a-fA-F]{40}$/.test(s))throw new TypeError("recipient must be a 0x-prefixed 20 byte address");let i=z({symbol:t,side:n,sizeUsd:r});if(i===null)throw new Error(`no RH Uniswap pool for ${t}`);if(i.tier!=="prepare")throw new Error(`route tier is ${i.tier}, only prepare tier can be prepared`);let u=o-i.capturedAt;if(u>ct)throw new Error(`quote is stale (${u}ms old, bound ${ct}ms); re-quote before preparing`);let l=J().pools[t],c=l.version==="v4"?Cn:Bn,p=c,y=n==="buy"?l.quoteAddr:l.token;return Object.freeze({artifactKind:"unsigned-tx",chainId:4663,to:c,data:"0x",value:"0",requiresApproval:{spender:p,token:y,amount:null},requiresWalletSignature:!0,backendSigner:!1,unsigned:!0,houseSigned:!1,quoteRef:{venue:i.venue,symbol:i.symbol,symbolRaw:i.symbolRaw,capturedAt:i.capturedAt,blockOrSeq:i.blockOrSeq,mid:i.mid,version:l.version,pair:l.pair},quoteAgeMs:u,recipient:s,side:n,notes:["prepare-only: user wallet must sign","calldata encoding is deferred; this artifact is the bound intent",l.version==="v4"?"V4 route via PoolManager":"V3 route via SwapRouter (address not yet pinned)"]})}var Hn="hyperliquid_hip3",zn="hyperliquid",Ln="quote-only";function K(){return q().venues.hyperliquid_hip3}function lt(){return Object.keys(K().dexs).sort()}function Wn(){let e=[];for(let[t,n]of Object.entries(K().dexs))for(let r of Object.keys(n))e.push(`${t}:${r}`);return e.sort()}function Qn(e){if(typeof e!="string"||e.length===0)return[];let t=e.indexOf(":");if(t>0){let r=e.slice(0,t),s=e.slice(t+1),o=K().dexs[r]?.[s];return o?[{dex:r,ticker:s,market:o}]:[]}let n=[];for(let[r,s]of Object.entries(K().dexs))Object.hasOwn(s,e)&&n.push({dex:r,ticker:e,market:s[e]});return n}function Xn(e,t){try{return Le().books[`${e}:${t}`]??null}catch{return null}}function Vn(e,t,n){if(!e||n===null||n.mantissa<=0n)return null;let r=t==="buy"?e.asks:e.bids;if(!r||r.length===0)return null;let s=Number(S(n));if(!Number.isFinite(s)||s<=0)return null;let o=0,i=0,u=0;for(let a of r){let l=Number(a.px),c=Number(a.sz);if(!(l>0)||!(c>0))continue;let p=l*c,y=Math.min(s,p),b=y/l;if(o+=y,i+=b,s-=y,u+=1,s<=1e-9)break}return i<=0?null:{vwap:o/i,filledUsd:o,unfilledUsd:Math.max(0,s),levelsUsed:u}}function Kn(e,t,n,r){let s=Vn(e,t,n);if(!s)return{impact:null,depth:null};let o=Number(S(r));if(!(o>0))return{impact:null,depth:s};let i=t==="buy"?(s.vwap-o)/o:(o-s.vwap)/o,u=Math.max(0,i);return{impact:w(Number(u.toPrecision(12))),depth:{...s,impactFraction:u,fullyFilled:s.unfilledUsd<=1e-6}}}function ft({dex:e,ticker:t,market:n,side:r,size:s}){let o=I(n.mark,`${e}:${t}.mark`),i=w(n.fundingHourly),u=w(n.vol24h),a=w(n.oi),l=s===null?f("0"):s,c=Xn(e,t),p=null,y=null,b="fees and gas not captured";if(l.mantissa>0n)if(c){let L=Kn(c,r,l,o);p=L.impact,y=L.depth,y?.fullyFilled?b="impact measured from l2Book; fees and gas still not captured":b="book walked but size exceeds visible depth; fees and gas not captured"}else b="no order book depth wired for this coin; fees and gas not captured";else c?b="zero size; fees and gas not captured":b="no order book depth wired for this coin; fees and gas not captured";let F={venue:Hn,chain:zn,instrument:"perp",tier:Ln,symbolRaw:`${e}:${t}`,symbol:t,side:r,requestedSize:l,mark:o,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:i,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.hyperliquid_hip3",dex:e,ticker:t,vol24h:n.vol24h,oi:n.oi,fundingAnnPct:n.fundingAnnPct,maxLev:n.maxLev,reasonCostUnknown:b,hasL2Book:c!==null,l2BookFixture:c?"fixtures/hip3_l2books.json":null,depth:y}};return u!==null&&(F.raw.vol24hFixed=u),a!==null&&(F.raw.oiFixed=a),c?.bids?.[0]&&c?.asks?.[0]&&(F.bid=f(String(c.bids[0].px)),F.ask=f(String(c.asks[0].px))),v(F)}function pt({symbol:e,side:t="buy",sizeUsd:n=null}={}){let r=Qn(e);return r.length===0||r.length>1?null:ft({...r[0],side:t,size:n})}function se({side:e="buy",sizeUsd:t=null,ticker:n=null}={}){let r=[];for(let s of Wn()){let[o,i]=s.split(":");if(n!==null&&i!==n)continue;let u=K().dexs[o][i];r.push(ft({dex:o,ticker:i,market:u,side:e,size:t}))}return r}var Yn="arcus_spot",Jn="robinhood-4663",Gn="quote-only";function dt(){return q().venues.arcus_spot}function Zn(){return Object.keys(dt().pairs).sort()}function er({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=dt().pairs[e];if(!r)return null;let s=r.bid===void 0||r.bid===null?null:I(r.bid,`${e}.bid`),o=r.ask===void 0||r.ask===null?null:I(r.ask,`${e}.ask`),i=w(r.last),u=null;if(s!==null&&o!==null){u={mantissa:s.mantissa+o.mantissa,scale:s.scale===o.scale?s.scale+1:Math.max(s.scale,o.scale)+1};let p=Math.max(s.scale,o.scale),y=s.scale===p?s.mantissa:s.mantissa*10n**BigInt(p-s.scale),b=o.scale===p?o.mantissa:o.mantissa*10n**BigInt(p-o.scale);u={mantissa:y+b,scale:p+1},u={mantissa:(y+b)/2n,scale:p}}else i!==null&&(u=i);if(s===null&&o===null&&u===null)return null;let a=n===null?f("0"):n,l=f("0"),c={venue:Yn,chain:Jn,instrument:"spot",tier:Gn,symbolRaw:e,symbol:e,side:t,requestedSize:a,fees:l,gasEstimate:null,priceImpact:null,fundingHourly:null,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.arcus_spot",last:r.last,bid:r.bid,ask:r.ask,vol24h:r.vol24h,feeKnownZero:!0,reasonCostUnknown:"gas and impact at size not captured; fee is a known zero"}};return s!==null&&(c.bid=s),o!==null&&(c.ask=o),u!==null&&(c.mid=u),v(c)}function oe({side:e="buy",sizeUsd:t=null}={}){return Zn().map(n=>er({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var tr="solana_xstocks",nr="solana",rr="quote-only",mt=25e3;function ie(){return He()}function $e(){return Object.keys(ie().tokens).sort()}function sr(e){let t=ie().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function or(e,t){if(e===null||t===null)return null;if(e.mantissa<=0n||t.mantissa<=0n)return f("0");let n=Math.max(e.scale,t.scale),r=e.scale===n?e.mantissa:e.mantissa*10n**BigInt(n-e.scale),s=t.scale===n?t.mantissa:t.mantissa*10n**BigInt(n-t.scale),o=s*10n**6n,i=r+s;return{mantissa:o/i,scale:6}}function Ae({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e,s=e,o=ie().tokens;if(Object.hasOwn(o,e))r=e,s=o[e].symbolRaw;else if(e.endsWith("x")||e.endsWith("X")){let g=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}else return null;let i=o[r],u=sr(r);if(!i||!u)return null;let a=I(u.priceUsd,`${r}.priceUsd`),l=w(u.liquidityUsd),c=n===null?f("0"):n,p=c.mantissa===0n?f("0"):or(l,c),y=!1;c.mantissa===0n&&(u.liquidityUsd??0)>=mt&&(y=!1);let b={venue:tr,chain:nr,instrument:"spot",tier:rr,symbolRaw:s,symbol:r,side:t,requestedSize:c,mid:a,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:null,costAccounted:y,capturedAt:ie().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/solana_xstocks.json",mint:i.mint,pairAddress:u.pairAddress,dexId:u.dexId,quote:u.quote,liquidityUsd:u.liquidityUsd,volume24h:u.volume24h,priceUsd:u.priceUsd,source:"dexscreener",approximate:!0,reasonCostUnknown:"DexScreener liquidity.usd is a third-party float; fees and SOL gas not captured; impact is modeled",thin:(u.liquidityUsd??0)<mt}};return v(b)}function bt({side:e="buy",sizeUsd:t=null}={}){return $e().map(n=>Ae({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ir="ton_stonfi",ur="ton",ar="quote-only",cr=25e3,lr=.01;function ue(){return ze()}function Ee(){return Object.keys(ue().tokens).sort()}function fr(e){let t=ue().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function pr(e,t){if(e===null||t===null)return null;if(e.mantissa<=0n||t.mantissa<=0n)return f("0");let n=Math.max(e.scale,t.scale),r=e.scale===n?e.mantissa:e.mantissa*10n**BigInt(n-e.scale),s=t.scale===n?t.mantissa:t.mantissa*10n**BigInt(n-t.scale),o=s*10n**6n,i=r+s;return{mantissa:o/i,scale:6}}function ve({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e,s=e,o=ue().tokens;if(Object.hasOwn(o,e))r=e,s=o[e].symbolRaw;else if(e.endsWith("x")||e.endsWith("X")){let g=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}else{let g=e.toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}let i=o[r],u=fr(r);if(!i||!u)return null;let a=I(u.priceUsd,`${r}.priceUsd`),l=w(u.liquidityUsd),c=n===null?f("0"):n,p=c.mantissa===0n?f("0"):pr(l,c),b={venue:ir,chain:ur,instrument:"spot",tier:ar,symbolRaw:s,symbol:r,side:t,requestedSize:c,mid:a,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:null,costAccounted:!1,capturedAt:ue().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/ton_xstocks.json",mint:i.mint,pairAddress:u.pairAddress,dexId:u.dexId,quote:u.quote,liquidityUsd:u.liquidityUsd,volume24h:u.volume24h,priceUsd:u.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:(u.liquidityUsd??0)<cr,impactSizeFractionHint:lr}};return v(b)}function yt({side:e="buy",sizeUsd:t=null}={}){return Ee().map(n=>ve({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var dr=3600*1e3;function qe(e){return e==null||e===""?null:typeof e=="object"&&e&&typeof e.mantissa=="bigint"?e:f(String(e))}function mr(e,{sizeUsd:t=null}={}){if(typeof e!="string"||!e.trim())throw new TypeError("ticker is required");let n=e.trim().toUpperCase(),r=qe(t),s=[],o=pt({symbol:`xyz:${n}`,sizeUsd:r});if(o)s.push(o);else for(let l of se({ticker:n,sizeUsd:r}))s.push(l);for(let l of re({sizeUsd:r}))l.symbol===n&&s.push(l);for(let l of oe({sizeUsd:r}))l.symbol===n&&s.push(l);let i=z({symbol:n,sizeUsd:r});i&&s.push(i);let u=Ae({symbol:n,sizeUsd:r});u&&s.push(u);let a=ve({symbol:n,sizeUsd:r});return a&&s.push(a),s}function ht(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase();if(!t)throw new Error("bestEquityRoute requires ticker");let n=qe(e.sizeUsd??e.size??null),r=mr(t,{sizeUsd:n});if(r.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 s=r[0].capturedAt,o=String(s).length<=10?s*1e3:s,i=e.nowMs==null,u=e.nowMs??s+1e3,a=Math.max(0,Date.now()-o),l=ke(r,{nowMs:u,horizonHours:e.horizonHours!=null?Number(e.horizonHours):void 0,skipLiveness:e.skipLiveness===!0});return{ticker:t,...l,dataSource:i?"fixture":"caller-clock",capturedAt:o,ageMs:a,stale:a>dr}}function gt(){let e=[{venue:"hyperliquid_hip3",tier:"quote-only",chain:"hyperliquid",n:se().length},{venue:"arcus_perp",tier:"quote-only",chain:"robinhood-4663",n:re().length},{venue:"arcus_spot",tier:"quote-only",chain:"robinhood-4663",n:oe().length},{venue:"rh_uniswap",tier:"prepare",chain:4663,n:we().length},{venue:"solana_xstocks",tier:"quote-only",chain:"solana",n:$e().length},{venue:"ton_stonfi",tier:"quote-only",chain:"ton",n:Ee().length}],t=[...se(),...re(),...oe(),...at(),...bt(),...yt()],n=(t[0]?.capturedAt??Date.now())+1e3,{survivors:r,excluded:s}=ee(t,{nowMs:n});return{inventory:e,hip3Dexs:lt(),liveness:{survivors:r.length,excluded:s.length,byReason:s.reduce((o,i)=>(o[i.reason]=(o[i.reason]??0)+1,o),{})},capturedAt:q().capturedAt,custody:"prepare-only",note:"quote-only venues are ranked for discovery; only rh_uniswap is preparable in v1"}}function kt(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase(),n=e.recipient||e.taker;if(!t)throw new Error("prepareEquityRoute requires ticker");if(!n)throw new Error("prepareEquityRoute requires recipient (signing wallet)");let r=qe(e.sizeUsd??e.size??null),s=z({symbol:t,sizeUsd:r});if(!s)return{ok:!1,failureKind:"no-prepare-path",ticker:t,note:"no RH Uniswap prepare-tier route for this ticker in fixtures"};try{let o=Se({symbol:t,sizeUsd:r,recipient:n,nowMs:e.nowMs??s.capturedAt+1e3});return{ok:!0,ticker:t,artifact:o,bestPreparableVenue:"rh_uniswap"}}catch(o){return{ok:!1,failureKind:"prepare-refused",ticker:t,error:String(o.message||o)}}}function Oe(e){return JSON.parse(JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n))}function wt(){return`oracle equities <command>
2
+ import{realpathSync as wt}from"node:fs";import{fileURLToPath as br}from"node:url";var $r=Object.freeze({mantissa:10000n,scale:0});function P(e){if(!Number.isSafeInteger(e)||e<0||e>1e3)throw new RangeError("scale must be a safe integer from 0 through 1000")}function T(e,t){if(typeof e!="bigint")throw new TypeError("mantissa must be a bigint");return P(t),Object.freeze({mantissa:e,scale:t})}function N(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`);P(e.scale)}function Y(e){return P(e),10n**BigInt(e)}function f(e){if(typeof e!="string"||!/^[+-]?\d+(?:\.\d+)?$/.test(e))throw new TypeError("value must be a plain decimal string");let t=e.startsWith("-"),n=e[0]==="-"||e[0]==="+"?e.slice(1):e,[r,s=""]=n.split("."),o=`${r}${s}`,i=BigInt(o)*(t?-1n:1n);return T(i,s.length)}function $(e,t){if(P(t),typeof e=="bigint")return T(e,t);if(typeof e!="string"||!/^[+-]?\d+$/.test(e))throw new TypeError("value must be an integer string or bigint");return T(BigInt(e),t)}function S(e){N(e);let t=e.mantissa<0n,n=(t?-e.mantissa:e.mantissa).toString();if(e.scale===0)return`${t?"-":""}${n}`;let r=n.padStart(e.scale+1,"0"),s=r.length-e.scale;return`${t?"-":""}${r.slice(0,s)}.${r.slice(s)}`}function W(e,t){return N(e),P(t),t===e.scale?T(e.mantissa,e.scale):t>e.scale?T(e.mantissa*Y(t-e.scale),t):T(e.mantissa/Y(e.scale-t),t)}function ce(e,t){N(e,"left"),N(t,"right");let n=Math.max(e.scale,t.scale);return[W(e,n),W(t,n),n]}function D(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa+r.mantissa,s)}function Q(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa-r.mantissa,s)}function E(e,t){N(e,"left"),N(t,"right");let n=e.scale+t.scale;return P(n),T(e.mantissa*t.mantissa,n)}function R(e,t,n=Math.max(e?.scale??0,t?.scale??0)){if(N(e,"left"),N(t,"right"),P(n),t.mantissa===0n)throw new RangeError("division by zero");let r=e.mantissa*Y(t.scale+n),s=t.mantissa*Y(e.scale);return T(r/s,n)}function M(e,t){let[n,r]=ce(e,t);return n.mantissa<r.mantissa?-1:n.mantissa>r.mantissa?1:0}import{readFileSync as It,existsSync as Tt}from"node:fs";import{fileURLToPath as _t}from"node:url";import{dirname as Nt,join as Me}from"node:path";import{existsSync as _e,readFileSync as qt}from"node:fs";import{dirname as Te,join as le}from"node:path";import{fileURLToPath as Ot}from"node:url";function Rt(e){let t=Te(Ot(e));for(let n=0;n<8;n+=1){let r=le(t,"package.json");if(_e(r))try{let o=JSON.parse(qt(r,"utf8"));if(o&&typeof o.version=="string")return t}catch{}let s=Te(t);if(s===t)break;t=s}throw new Error(`oracle: could not resolve package root from ${e}`)}function Ne(e,t){let n=Rt(t),r=le(n,"dist","assets",e);return _e(r)?r:le(n,e)}var Dt=Me(Nt(_t(import.meta.url)),"fixtures");function Mt(){try{let e=Ne("equities-fixtures",import.meta.url);if(e&&Tt(e))return e}catch{}return Dt}var Ut=Mt();var Ue=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"});function jt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function d(e,t){throw new TypeError(`Fixture fixtures/${e}: ${t}`)}function k(e,t,n){jt(e)||d(t,`${n} must be an object`)}function m(e,t,n){(typeof e!="string"||e.length===0)&&d(t,`${n} must be a nonempty string`)}function _(e,t,n){Number.isSafeInteger(e)||d(t,`${n} must be a safe integer`)}function U(e,t,n){k(e,t,n);for(let[r,s]of Object.entries(e))m(r,t,`${n} key`),k(s,t,`${n}.${r}`)}function Ft(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),k(e.venues,t,"venues");let n=[["hyperliquid_hip3","dexs"],["arcus","markets"],["arcus_spot","pairs"],["rh_uniswap","pools"],["rh_chainlink_oracles","assets"]];for(let[r,s]of n){let o=e.venues[r];k(o,t,`venues.${r}`),m(o.type,t,`venues.${r}.type`),m(o.chain,t,`venues.${r}.chain`),m(o.tier,t,`venues.${r}.tier`),U(o[s],t,`venues.${r}.${s}`)}for(let[r,s]of Object.entries(e.venues.hyperliquid_hip3.dexs))U(s,t,`venues.hyperliquid_hip3.dexs.${r}`)}function Pt(e,t){U(e,t,"root"),Object.keys(e).length===0&&d(t,"root must not be empty");for(let[n,r]of Object.entries(e))Array.isArray(r.venues)||d(t,`${n}.venues must be an array`),r.venues.forEach((s,o)=>m(s,t,`${n}.venues[${o}]`))}function Bt(e,t){k(e,t,"root");for(let n of["chainId","block","oracleScaleExp","usdgDecimals","equityDecimals"])_(e[n],t,n);m(e.usdg,t,"usdg"),U(e.assets,t,"assets");for(let[n,r]of Object.entries(e.assets))m(r.oracle,t,`assets.${n}.oracle`),m(r.token,t,`assets.${n}.token`),(typeof r.rawPrice!="string"||!/^\d+$/.test(r.rawPrice))&&d(t,`assets.${n}.rawPrice must be an integer string`),(typeof r.usd!="number"||!Number.isFinite(r.usd)||r.usd<0)&&d(t,`assets.${n}.usd must be a nonnegative finite source number`)}function Ct(e,t){k(e,t,"root");for(let r of["holidayDayIndex","names","dates"])Array.isArray(e[r])||d(t,`${r} must be an array`);let n=e.holidayDayIndex.length;(e.names.length!==n||e.dates.length!==n)&&d(t,"holidayDayIndex, names, and dates must have equal lengths"),e.holidayDayIndex.forEach((r,s)=>_(r,t,`holidayDayIndex[${s}]`)),e.names.forEach((r,s)=>m(r,t,`names[${s}]`)),e.dates.forEach((r,s)=>{(typeof r!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(r))&&d(t,`dates[${s}] must use YYYY-MM-DD`)})}function Ht(e,t){k(e,t,"root"),(!Array.isArray(e.dstTransitions)||e.dstTransitions.length===0)&&d(t,"dstTransitions must be a nonempty array");let n=new Set;e.dstTransitions.forEach((r,s)=>{k(r,t,`dstTransitions[${s}]`);for(let o of["year","startUtc","endUtc"])_(r[o],t,`dstTransitions[${s}].${o}`);r.startUtc>=r.endUtc&&d(t,`dstTransitions[${s}] startUtc must be before endUtc`),n.has(r.year)&&d(t,`dstTransitions contains duplicate year ${r.year}`),n.add(r.year)})}function zt(e,t){U(e,t,"root"),Object.keys(e).length===0&&d(t,"root must not be empty");for(let[n,r]of Object.entries(e)){for(let s of["addr","quote","quoteAddr","dex","pair"])m(r[s],t,`${n}.${s}`);(typeof r.liq!="number"||!Number.isFinite(r.liq)||r.liq<0)&&d(t,`${n}.liq must be a nonnegative finite source number`)}}function Lt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),_(e.block,t,"block"),_(e.chainId,t,"chainId"),m(e.gasPriceWei,t,"gasPriceWei"),m(e.stateView,t,"stateView"),U(e.pools,t,"pools"),Object.keys(e.pools).length===0&&d(t,"pools must not be empty");for(let[n,r]of Object.entries(e.pools)){for(let s of["pair","version","quote","token","sqrtPriceX96"])m(r[s],t,`pools.${n}.${s}`);r.version!=="v3"&&r.version!=="v4"&&d(t,`pools.${n}.version must be v3 or v4`),typeof r.quoteIsToken0!="boolean"&&d(t,`pools.${n}.quoteIsToken0 must be a boolean`),(!/^[0-9]+$/.test(r.sqrtPriceX96)||BigInt(r.sqrtPriceX96)<=0n)&&d(t,`pools.${n}.sqrtPriceX96 must be a positive integer string`)}}function Wt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),k(e.books,t,"books"),Object.keys(e.books).length===0&&d(t,"books must not be empty");for(let[n,r]of Object.entries(e.books)){k(r,t,`books.${n}`),(!Array.isArray(r.bids)||!Array.isArray(r.asks))&&d(t,`books.${n} must have bids and asks arrays`);for(let[s,o]of r.bids.entries())k(o,t,`books.${n}.bids[${s}]`),m(o.px,t,`books.${n}.bids[${s}].px`),m(o.sz,t,`books.${n}.bids[${s}].sz`);for(let[s,o]of r.asks.entries())k(o,t,`books.${n}.asks[${s}]`),m(o.px,t,`books.${n}.asks[${s}].px`),m(o.sz,t,`books.${n}.asks[${s}].sz`)}}function Qt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),U(e.tokens,t,"tokens"),k(e.pairs,t,"pairs"),Object.keys(e.tokens).length===0&&d(t,"tokens must not be empty");for(let[n,r]of Object.entries(e.tokens)){m(r.symbolRaw,t,`tokens.${n}.symbolRaw`),m(r.mint,t,`tokens.${n}.mint`),Object.hasOwn(e.pairs,n)||d(t,`pairs.${n} is required for token ${n}`),(!Array.isArray(e.pairs[n])||e.pairs[n].length===0)&&d(t,`pairs.${n} must be a nonempty array`);for(let[s,o]of e.pairs[n].entries())k(o,t,`pairs.${n}[${s}]`),m(o.pairAddress,t,`pairs.${n}[${s}].pairAddress`),m(o.dexId,t,`pairs.${n}[${s}].dexId`),(typeof o.priceUsd!="number"||!Number.isFinite(o.priceUsd)||o.priceUsd<=0)&&d(t,`pairs.${n}[${s}].priceUsd must be a positive finite number`),(typeof o.liquidityUsd!="number"||!Number.isFinite(o.liquidityUsd)||o.liquidityUsd<0)&&d(t,`pairs.${n}[${s}].liquidityUsd must be a nonnegative finite number`)}}function Xt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),e.chain!=="ton"&&d(t,'chain must be "ton"'),U(e.tokens,t,"tokens"),k(e.pairs,t,"pairs"),Object.keys(e.tokens).length===0&&d(t,"tokens must not be empty");for(let[n,r]of Object.entries(e.tokens)){m(r.symbolRaw,t,`tokens.${n}.symbolRaw`),m(r.mint,t,`tokens.${n}.mint`),Object.hasOwn(e.pairs,n)||d(t,`pairs.${n} is required for token ${n}`),(!Array.isArray(e.pairs[n])||e.pairs[n].length===0)&&d(t,`pairs.${n} must be a nonempty array`);for(let[s,o]of e.pairs[n].entries())k(o,t,`pairs.${n}[${s}]`),m(o.pairAddress,t,`pairs.${n}[${s}].pairAddress`),m(o.dexId,t,`pairs.${n}[${s}].dexId`),(typeof o.priceUsd!="number"||!Number.isFinite(o.priceUsd)||o.priceUsd<=0)&&d(t,`pairs.${n}[${s}].priceUsd must be a positive finite number`),(typeof o.liquidityUsd!="number"||!Number.isFinite(o.liquidityUsd)||o.liquidityUsd<0)&&d(t,`pairs.${n}[${s}].liquidityUsd must be a nonnegative finite number`)}}var Vt=Object.freeze({venues:Ft,universe:Pt,oracles:Bt,nyseHolidays:Ct,dstTransitions:Ht,equityDexPools:zt,rhPoolState:Lt,solanaXstocks:Qt,tonXstocks:Xt,hip3L2Books:Wt});function Kt(e,t){let n=Ue[t],r=Me(e,n),s;try{s=It(r,"utf8")}catch(i){throw i?.code==="ENOENT"?new Error(`Fixture fixtures/${n} is missing at ${r}`):new Error(`Fixture fixtures/${n} could not be read: ${i.message}`)}let o;try{o=JSON.parse(s)}catch(i){throw new SyntaxError(`Fixture fixtures/${n} contains invalid JSON: ${i.message}`)}return Vt[t](o,n),o}function je(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))je(t)}return e}function Fe({fixtureDir:e=Ut}={}){if(typeof e!="string"||e.length===0)throw new TypeError("fixtureDir must be a nonempty path string");let t={};for(let n of Object.keys(Ue))t[n]=Kt(e,n);return je(t)}var De;function j(){return De??=Fe(),De}function q(){return j().venues}function Pe(){return j().oracles}function Be(){return j().nyseHolidays}function Ce(){return j().dstTransitions}function J(){return j().rhPoolState}function He(){return j().solanaXstocks}function ze(){return j().tonXstocks}function Le(){return j().hip3L2Books}var pe=1e3,Xe=60*pe,de=60*Xe,We=24*de,Yt=-5*de,Jt=-4*de,Ve=240,Ke=570,Ye=960,Je=1200,Mr=Object.freeze([Ve,Ke,Ye,Je]),Ur=Object.freeze(["core","extended","dark"]),Qe,fe;function Gt(){let e=Ce().dstTransitions.map(r=>({year:r.year,startMs:r.startUtc*pe,endMs:r.endUtc*pe}));e.sort((r,s)=>r.startMs-s.startMs);let t=e[0].year,n=e[e.length-1].year;return Object.freeze({rows:Object.freeze(e),firstYear:t,lastYear:n,coverageStartMs:Date.UTC(t,0,1),coverageEndMs:Date.UTC(n+1,0,1)})}function Ge(){return Qe??=Gt(),Qe}function Zt(){return fe===void 0&&(fe=new Set(Be().holidayDayIndex)),fe}function Ze(e,t){if(!Number.isSafeInteger(e))throw new TypeError(`${t}: epochMs must be a safe integer number of milliseconds`)}function en(e,t){let{coverageStartMs:n,coverageEndMs:r,firstYear:s,lastYear:o}=Ge();if(e<n||e>=r)throw new RangeError(`${t}: ${new Date(e).toISOString()} is outside DST fixture coverage (${s} through ${o}). Refusing to assume a UTC offset.`)}function tn(e){for(let t of Ge().rows)if(e>=t.startMs&&e<t.endMs)return!0;return!1}function nn(e){return tn(e)?Jt:Yt}function rn(e){let t=e+nn(e),n=Math.floor(t/We),r=t-n*We,s=new Date(t);return{dayIndex:n,minuteOfDay:Math.floor(r/Xe),msIntoDay:r,weekday:s.getUTCDay()}}function sn({dayIndex:e,weekday:t}){return t===0||t===6?!1:!Zt().has(e)}function on(e){return e<Ve?"dark":e<Ke?"extended":e<Ye?"core":e<Je?"extended":"dark"}function X(e){Ze(e,"sessionState"),en(e,"sessionState");let t=rn(e);return sn(t)?on(t.minuteOfDay):"dark"}function me(e){return Ze(e,"isDark"),X(e)==="dark"}var G=Object.freeze({DORMANT_VENUE:"dormant-venue",CROSSED_BOOK:"crossed-book",STALE_QUOTE:"stale-quote",STALE_ORACLE:"stale-oracle"}),un=12e4,an=6e5;function Z(e,t){e.push(Object.freeze({venue:t.venue,symbol:t.symbol??null,reason:t.reason,evidence:t.evidence??null}))}function cn(e){let t=e.raw?.vol24h;return!!(t===0||t===0||typeof t=="number"&&Number.isFinite(t)&&t<=0)}function ln(e){return!e.bid||!e.ask?!1:M(e.bid,e.ask)>0}function et(e,t,n){return Number.isSafeInteger(e.capturedAt)?t-e.capturedAt>n:!1}function ee(e,t={}){if(!Array.isArray(e))throw new TypeError("quotes must be an array");let n=t.nowMs??Date.now(),r=t.quoteFreshnessMs??un,s=t.oracleFreshnessMs??an,o=t.includeDormant===!0,i=[],u=[];for(let a of e){if(cn(a)){o?i.push(Object.freeze({...a,staleData:!0})):Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.DORMANT_VENUE,evidence:{vol24h:a.raw?.vol24h??null}});continue}if(ln(a)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.CROSSED_BOOK,evidence:{bid:a.bid?String(a.bid.mantissa)+"e-"+a.bid.scale:null,ask:a.ask?String(a.ask.mantissa)+"e-"+a.ask.scale:null}});continue}if(et(a,n,r)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.STALE_QUOTE,evidence:{capturedAt:a.capturedAt,nowMs:n,ageMs:n-a.capturedAt,freshnessMs:r}});continue}if(a.tier==="read-only"&&a.raw?.oracleRaw!==void 0){let l=X(n),c=l==="core"?s:s*2;if(et(a,n,c)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.STALE_ORACLE,evidence:{capturedAt:a.capturedAt,nowMs:n,session:l}});continue}}i.push(a)}return{survivors:i,excluded:u}}function fn(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[n,r]=t.split(/[eE]/),s=Number(r),o=n.startsWith("-"),i=o?n.slice(1):n,[u,a=""]=i.split("."),l=`${u}${a}`,c=u.length+s,p;return c<=0?p=`0.${"0".repeat(-c)}${l}`:c>=l.length?p=`${l}${"0".repeat(c-l.length)}`:p=`${l.slice(0,c)}.${l.slice(c)}`,`${o?"-":""}${p}`}function w(e){return e==null?null:typeof e=="string"?f(e):typeof e!="number"||!Number.isFinite(e)?null:f(fn(e))}function I(e,t){let n=w(e);if(n===null)throw new TypeError(`${t} must be a finite source number`);return n}var pn=new Set(["spot","perp"]),dn=new Set(["read-only","quote-only","prepare","intent"]),mn=new Set(["buy","sell"]),bn=new Set(["net-of-cost","gross"]),yn=new Set(["homogeneous","heterogeneous"]),hn=["bid","ask","mid","mark"],tt=["fees","gasEstimate","priceImpact","fundingHourly"],gn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function h(e,t){throw new TypeError(`${e} ${t}`)}function rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function B(e,t){rt(e)||h(t,"must be an object")}function st(e,t,n){Object.hasOwn(e,t)||h(`${n}.${t}`,"is required")}function C(e,t){(typeof e!="string"||e.length===0)&&h(t,"must be a nonempty string")}function V(e,t,n){t.has(e)||h(n,`must be one of ${[...t].join(", ")}`)}function ye(e,t){(!Number.isSafeInteger(e)||e<0)&&h(t,"must be a nonnegative safe integer")}function be(e,t,n=!1){e===null&&n||(rt(e)||h(t,"must be a fixed point value"),typeof e.mantissa!="bigint"&&h(`${t}.mantissa`,"must be a bigint"),(!Number.isSafeInteger(e.scale)||e.scale<0)&&h(`${t}.scale`,"must be a nonnegative safe integer"))}function te(e,t,n=!1){e===null&&n||B(e,t)}function nt(e,t){B(e,t),C(e.venue,`${t}.venue`),C(e.reason,`${t}.reason`),gn.test(e.reason)||h(`${t}.reason`,"must be a machine readable lower case code"),Object.hasOwn(e,"symbol")&&e.symbol!==null&&C(e.symbol,`${t}.symbol`)}function v(e){B(e,"quote");for(let n of["venue","chain","instrument","tier","symbolRaw","symbol","side","requestedSize",...tt,"costAccounted","capturedAt","blockOrSeq","raw"])st(e,n,"quote");C(e.venue,"quote.venue"),!(typeof e.chain=="string"&&e.chain.length>0)&&!(Number.isSafeInteger(e.chain)&&e.chain>=0)&&h("quote.chain","must be a nonempty string or nonnegative chain id"),V(e.instrument,pn,"quote.instrument"),V(e.tier,dn,"quote.tier"),C(e.symbolRaw,"quote.symbolRaw"),C(e.symbol,"quote.symbol"),V(e.side,mn,"quote.side"),be(e.requestedSize,"quote.requestedSize"),e.requestedSize.mantissa<0n&&h("quote.requestedSize","must not be negative");let t=0;for(let n of hn)Object.hasOwn(e,n)&&(be(e[n],`quote.${n}`),t+=1);t===0&&h("quote","must contain at least one of bid, ask, mid, mark");for(let n of tt)be(e[n],`quote.${n}`,!0);if(typeof e.costAccounted!="boolean"&&h("quote.costAccounted","must be a boolean"),e.costAccounted){for(let n of["fees","gasEstimate","priceImpact"])e[n]===null&&h(`quote.${n}`,"cannot be unknown when costAccounted is true");e.instrument==="perp"&&e.fundingHourly===null&&h("quote.fundingHourly","cannot be unknown when costAccounted is true for a perp")}return e.instrument==="spot"&&e.fundingHourly!==null&&h("quote.fundingHourly","must be null for a spot quote"),ye(e.capturedAt,"quote.capturedAt"),e.blockOrSeq!==null&&!(typeof e.blockOrSeq=="string"&&e.blockOrSeq.length>0)&&!(Number.isSafeInteger(e.blockOrSeq)&&e.blockOrSeq>=0)&&h("quote.blockOrSeq","must be null, a nonempty string, or a nonnegative safe integer"),B(e.raw,"quote.raw"),e}function he(e){B(e,"rankResult");for(let t of["rankedOn","ranked","winner","runnersUp","improvementBps","sourcesAnswered","sourcesTried","failed","excluded","darkWindow","instrumentMix","bestPreparable"])st(e,t,"rankResult");return V(e.rankedOn,bn,"rankResult.rankedOn"),Array.isArray(e.ranked)||h("rankResult.ranked","must be an array"),e.ranked.forEach((t,n)=>te(t,`rankResult.ranked[${n}]`)),te(e.winner,"rankResult.winner",!0),e.ranked.length===0&&e.winner!==null&&h("rankResult.winner","must be null when ranked is empty"),e.ranked.length>0&&e.winner===null&&h("rankResult.winner","must be present when ranked is not empty"),Array.isArray(e.runnersUp)||h("rankResult.runnersUp","must be an array"),e.runnersUp.forEach((t,n)=>te(t,`rankResult.runnersUp[${n}]`)),e.improvementBps!==null&&!(typeof e.improvementBps=="number"&&Number.isFinite(e.improvementBps))&&h("rankResult.improvementBps","must be a finite number or null"),ye(e.sourcesAnswered,"rankResult.sourcesAnswered"),ye(e.sourcesTried,"rankResult.sourcesTried"),e.sourcesAnswered>e.sourcesTried&&h("rankResult.sourcesAnswered","must not exceed sourcesTried"),Array.isArray(e.failed)||h("rankResult.failed","must be an array"),e.failed.forEach((t,n)=>nt(t,`failed[${n}]`)),Array.isArray(e.excluded)||h("rankResult.excluded","must be an array"),e.excluded.forEach((t,n)=>nt(t,`excluded[${n}]`)),e.darkWindow!==null&&B(e.darkWindow,"rankResult.darkWindow"),V(e.instrumentMix,yn,"rankResult.instrumentMix"),te(e.bestPreparable,"rankResult.bestPreparable",!0),Object.hasOwn(e,"carry")&&e.carry!==null&&B(e.carry,"rankResult.carry"),e}var kn="arcus_perp",xn="robinhood-4663",wn="quote-only",ne="0.00000480324074074";function ot(){return q().venues.arcus}function Sn(){return Object.keys(ot().markets).sort()}function $n({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e.endsWith("-USD")?e.slice(0,-4):e,s=ot().markets[r];if(!s)return null;let o=I(s.mark,`${r}.mark`),i=w(s.oracle),u=w(s.fundingHourly),a=n===null?f("0"):n,l={venue:kn,chain:xn,instrument:"perp",tier:wn,symbolRaw:e,symbol:r,side:t,requestedSize:a,mark:o,fees:null,gasEstimate:null,priceImpact:null,fundingHourly:u,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.arcus",oraclePrice:s.oracle,vol24h:s.vol24h,oi:s.oi,fundingAnnPct:s.fundingAnnPct,category:s.category,isOutsideRth:s.isOutsideRth===!0,rth:s.rth,darkWindowFundingHourly:ne,initialMarginFraction:s.initialMarginFraction??null,offHoursInitialMarginFraction:s.offHoursInitialMarginFraction??null,reasonCostUnknown:"fees, gas, and impact at size not captured for Arcus perps"}};return i!==null&&(l.raw.oracleFixed=i),v(l)}function re({side:e="buy",sizeUsd:t=null}={}){return Sn().map(n=>$n({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var it=36e5,Zr=24*365;function ge(e,t,n=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 f("0");let r=f(String(t)),s=$(10000n,0);return E(E(e,r),s)}function ut(e,t,n={}){if(e.instrument!=="perp")return{model:"current-funding-held-constant",horizonHours:t,carryBps:f("0"),carryBpsDisplay:"0",confidence:"estimate",note:"spot has no funding carry"};let r=n.nowMs??Date.now(),s=n.applyDarkWindowLock===!0,o=e.fundingHourly;if(s&&o!==null){let u=An(r,t),a=t-u,l=f(ne),c=ge(o,a),p=ge(l,u),y=Math.max(c.scale,p.scale),b={mantissa:c.mantissa*10n**BigInt(y-c.scale)+p.mantissa*10n**BigInt(y-p.scale),scale:y};return{model:"current-funding-held-constant",horizonHours:t,carryBps:b,carryBpsDisplay:S(b),confidence:"estimate",darkHours:u,litHours:a,darkWindowRate:ne,compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}if(o===null)return{model:"current-funding-held-constant",horizonHours:t,carryBps:null,carryBpsDisplay:null,confidence:"estimate",note:"funding rate unknown"};let i=ge(o,t);return{model:"current-funding-held-constant",horizonHours:t,carryBps:i,carryBpsDisplay:S(i),confidence:"estimate",compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}function An(e,t){if(t<=0)return 0;let n=0,r=Math.floor(t);for(let s=0;s<r;s+=1)me(e+s*it)&&(n+=1);return t>r&&me(e+r*it)&&(n+=t-r),n}function En(e){return e.mid??e.mark??e.ask??e.bid??null}function vn(e){let t=En(e);if(t===null)return null;let n=e.costAccounted===!0,r=f("0");e.fees!==null?r=D(r,e.fees):n=!1,e.priceImpact!==null?r=D(r,e.priceImpact):e.requestedSize&&e.requestedSize.mantissa>0n&&(n=!1),e.gasEstimate===null?n=!1:r=D(r,e.gasEstimate);let s;if(e.fees!==null&&M(e.fees,f("1"))<0&&M(e.fees,f("0"))>=0){let o=D(f("1"),e.fees);s=E(t,o),e.priceImpact!==null&&(s=D(s,E(t,e.priceImpact)))}else s=D(t,r);return{net:s,costAccounted:n,px:t}}function qn(e,t,n=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:n,quote:e}}function On(e,t){if(!e||!t||!e.costAccounted||!t.costAccounted||e.instrument!==t.instrument||e.net.mantissa===0n)return null;let n=Q(t.net,e.net);return R(E(n,$(10000n,0)),t.net,4)}function ke(e,t={}){if(!Array.isArray(e))throw new TypeError("quotes must be an array");let n=t.nowMs??e[0]?.capturedAt??Date.now(),r=e.length,s=e,o=[];if(!t.skipLiveness){let x=ee(e,{nowMs:n});s=x.survivors,o=x.excluded}let i=e.length,u=[],a=t.horizonHours,l=Number.isFinite(a)&&a>0,c=[];for(let x of s){let A=vn(x);if(A===null)continue;let O=null;if(l&&x.instrument==="perp"&&(O=ut(x,a,{nowMs:n}),O.carryBps!==null)){let vt=D(f("1"),R(O.carryBps,$(10000n,0),12));A.net=E(A.net,vt),A.costAccounted=!1}c.push(qn(x,A,O))}let p=c,y="homogeneous";if(l)y="heterogeneous",p=c;else{let x=c.filter(O=>O.instrument==="spot"),A=c.filter(O=>O.instrument==="perp");x.length>0&&A.length>0?(p=x.length>=A.length?x:A,y="homogeneous"):(p=c,y="homogeneous")}p.sort((x,A)=>{let O=M(x.net,A.net);return O!==0?O:x.venue<A.venue?-1:x.venue>A.venue?1:0});let b=p[0]??null,g=p.slice(1),F=p,L="gross";b&&b.costAccounted&&(g.length===0||g[0].costAccounted)&&(L="net-of-cost");let Re=g.length===0?null:On(b,g[0]),$t=c.find(x=>x.tier==="prepare")??null,ae=X(n),At=ae==="core"?null:{session:ae,warning:ae==="dark"?"market is dark; marks are not real price discovery":"extended session; thinner books and higher staleness risk"},Ie=null;l&&(Ie=Rn(c));let Et={rankedOn:L,ranked:F,winner:b,runnersUp:g,improvementBps:Re===null?null:Number(S(Re)),sourcesAnswered:i,sourcesTried:r,failed:u,excluded:o,darkWindow:At,instrumentMix:y,bestPreparable:$t,carry:b?.carry??null,breakEvenHorizonHours:Ie};return he(Et)}function Rn(e){let t=e.filter(o=>o.instrument==="spot").sort((o,i)=>M(o.net,i.net))[0],n=e.filter(o=>o.instrument==="perp").sort((o,i)=>M(o.net,i.net))[0];if(!t||!n||n.fundingHourly===null)return null;let r=Q(t.net,n.net);if(r.mantissa===0n)return 0;let s=E(n.fundingHourly,n.price);if(s.mantissa===0n)return null;try{let o=R(r,s,4),i=Number(S(o));return!Number.isFinite(i)||i<0?null:i}catch{return null}}var In="rh_uniswap",Tn=4663,_n="prepare",Nn=1n<<192n,H=18,Dn=Object.freeze({v3:180000n,v4:240000n});function xe(){return J()}function Mn(e){return{mantissa:e*e*10n**BigInt(H)/Nn,scale:H}}function Un(e){let t=Mn(BigInt(e.sqrtPriceX96)),n=e.quote==="USDG"?6:18,r=18;if(e.quoteIsToken0){let s=R(E(t,$(10n**BigInt(n),0)),$(10n**BigInt(r),0),H);return s.mantissa===0n?null:R(f("1"),s,H)}return R(E(t,$(10n**BigInt(r),0)),$(10n**BigInt(n),0),H)}function jn(e){let t=Pe(),n=t.assets[e];return n?$(n.rawPrice,t.oracleScaleExp):null}function Fn(e,t){if(e===null||t===null||e.mantissa<=0n||t.mantissa<=0n)return null;let n={...e};return R(t,Pn(n,t),H)}function Pn(e,t){let n=Math.max(e.scale,t.scale);return{mantissa:W(e,n).mantissa+W(t,n).mantissa,scale:n}}function Bn(e){let t=xe(),n=Dn[e];return n?{wei:BigInt(t.gasPriceWei)*n,units:n,native:"ETH"}:null}function we(){return Object.keys(xe().pools).sort()}function z({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)throw new TypeError("symbol must be a nonempty string");let r=xe(),s=r.pools[e];if(!s)return null;let o=Un(s);if(o===null)return null;let i=w(s.liqUsd),u=n===null?f("0"):n,a=s.feePpm===null||s.feePpm===void 0?null:R($(BigInt(s.feePpm),0),$(1000000n,0),8),l=u.mantissa===0n?f("0"):Fn(i,u),c=Bn(s.version),b={venue:In,chain:Tn,instrument:"spot",tier:_n,symbolRaw:e,symbol:e,side:t,requestedSize:u,mid:o,fees:a,gasEstimate:null,priceImpact:l,fundingHourly:null,costAccounted:!1,capturedAt:r.capturedAt*1e3,blockOrSeq:r.block,raw:{fixture:"fixtures/rh_pool_state.json",pair:s.pair,version:s.version,sqrtPriceX96:s.sqrtPriceX96,quote:s.quote,quoteIsToken0:s.quoteIsToken0,liqUsd:s.liqUsd,gasNativeWei:c===null?null:c.wei.toString(),gasUnits:c===null?null:c.units.toString(),impactModel:"constant-product-estimate",notes:["price read live from chain 4663",s.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"]}},g=jn(e);return g!==null&&(b.referencePrice=g,b.referenceBasisBps=S(R(E(Q(o,g),$(10000n,0)),g,4))),v(b)}function at({side:e="buy",sizeUsd:t=null}={}){return we().map(n=>z({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ct=12e4,Cn="0x0000000000000000000000000000000000000000",Hn="0x84b75b19A3cdf8E2F56d0507d22D442847B2053C";function Se(e={}){let{symbol:t,side:n="buy",sizeUsd:r=null,recipient:s,nowMs:o=Date.now()}=e;if(typeof t!="string"||!t)throw new TypeError("symbol is required");if(typeof s!="string"||!/^0x[0-9a-fA-F]{40}$/.test(s))throw new TypeError("recipient must be a 0x-prefixed 20 byte address");let i=z({symbol:t,side:n,sizeUsd:r});if(i===null)throw new Error(`no RH Uniswap pool for ${t}`);if(i.tier!=="prepare")throw new Error(`route tier is ${i.tier}, only prepare tier can be prepared`);let u=o-i.capturedAt;if(u>ct)throw new Error(`quote is stale (${u}ms old, bound ${ct}ms); re-quote before preparing`);let l=J().pools[t],c=l.version==="v4"?Hn:Cn,p=c,y=n==="buy"?l.quoteAddr:l.token;return Object.freeze({artifactKind:"unsigned-tx",chainId:4663,to:c,data:"0x",value:"0",requiresApproval:{spender:p,token:y,amount:null},requiresWalletSignature:!0,backendSigner:!1,unsigned:!0,houseSigned:!1,quoteRef:{venue:i.venue,symbol:i.symbol,symbolRaw:i.symbolRaw,capturedAt:i.capturedAt,blockOrSeq:i.blockOrSeq,mid:i.mid,version:l.version,pair:l.pair},quoteAgeMs:u,recipient:s,side:n,notes:["prepare-only: user wallet must sign","calldata encoding is deferred; this artifact is the bound intent",l.version==="v4"?"V4 route via PoolManager":"V3 route via SwapRouter (address not yet pinned)"]})}var zn="hyperliquid_hip3",Ln="hyperliquid",Wn="quote-only";function K(){return q().venues.hyperliquid_hip3}function lt(){return Object.keys(K().dexs).sort()}function Qn(){let e=[];for(let[t,n]of Object.entries(K().dexs))for(let r of Object.keys(n))e.push(`${t}:${r}`);return e.sort()}function Xn(e){if(typeof e!="string"||e.length===0)return[];let t=e.indexOf(":");if(t>0){let r=e.slice(0,t),s=e.slice(t+1),o=K().dexs[r]?.[s];return o?[{dex:r,ticker:s,market:o}]:[]}let n=[];for(let[r,s]of Object.entries(K().dexs))Object.hasOwn(s,e)&&n.push({dex:r,ticker:e,market:s[e]});return n}function Vn(e,t){try{return Le().books[`${e}:${t}`]??null}catch{return null}}function Kn(e,t,n){if(!e||n===null||n.mantissa<=0n)return null;let r=t==="buy"?e.asks:e.bids;if(!r||r.length===0)return null;let s=Number(S(n));if(!Number.isFinite(s)||s<=0)return null;let o=0,i=0,u=0;for(let a of r){let l=Number(a.px),c=Number(a.sz);if(!(l>0)||!(c>0))continue;let p=l*c,y=Math.min(s,p),b=y/l;if(o+=y,i+=b,s-=y,u+=1,s<=1e-9)break}return i<=0?null:{vwap:o/i,filledUsd:o,unfilledUsd:Math.max(0,s),levelsUsed:u}}function Yn(e,t,n,r){let s=Kn(e,t,n);if(!s)return{impact:null,depth:null};let o=Number(S(r));if(!(o>0))return{impact:null,depth:s};let i=t==="buy"?(s.vwap-o)/o:(o-s.vwap)/o,u=Math.max(0,i);return{impact:w(Number(u.toPrecision(12))),depth:{...s,impactFraction:u,fullyFilled:s.unfilledUsd<=1e-6}}}function ft({dex:e,ticker:t,market:n,side:r,size:s}){let o=I(n.mark,`${e}:${t}.mark`),i=w(n.fundingHourly),u=w(n.vol24h),a=w(n.oi),l=s===null?f("0"):s,c=Vn(e,t),p=null,y=null,b="fees and gas not captured";if(l.mantissa>0n)if(c){let L=Yn(c,r,l,o);p=L.impact,y=L.depth,y?.fullyFilled?b="impact measured from l2Book; fees and gas still not captured":b="book walked but size exceeds visible depth; fees and gas not captured"}else b="no order book depth wired for this coin; fees and gas not captured";else c?b="zero size; fees and gas not captured":b="no order book depth wired for this coin; fees and gas not captured";let F={venue:zn,chain:Ln,instrument:"perp",tier:Wn,symbolRaw:`${e}:${t}`,symbol:t,side:r,requestedSize:l,mark:o,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:i,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.hyperliquid_hip3",dex:e,ticker:t,vol24h:n.vol24h,oi:n.oi,fundingAnnPct:n.fundingAnnPct,maxLev:n.maxLev,reasonCostUnknown:b,hasL2Book:c!==null,l2BookFixture:c?"fixtures/hip3_l2books.json":null,depth:y}};return u!==null&&(F.raw.vol24hFixed=u),a!==null&&(F.raw.oiFixed=a),c?.bids?.[0]&&c?.asks?.[0]&&(F.bid=f(String(c.bids[0].px)),F.ask=f(String(c.asks[0].px))),v(F)}function pt({symbol:e,side:t="buy",sizeUsd:n=null}={}){let r=Xn(e);return r.length===0||r.length>1?null:ft({...r[0],side:t,size:n})}function se({side:e="buy",sizeUsd:t=null,ticker:n=null}={}){let r=[];for(let s of Qn()){let[o,i]=s.split(":");if(n!==null&&i!==n)continue;let u=K().dexs[o][i];r.push(ft({dex:o,ticker:i,market:u,side:e,size:t}))}return r}var Jn="arcus_spot",Gn="robinhood-4663",Zn="quote-only";function dt(){return q().venues.arcus_spot}function er(){return Object.keys(dt().pairs).sort()}function tr({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=dt().pairs[e];if(!r)return null;let s=r.bid===void 0||r.bid===null?null:I(r.bid,`${e}.bid`),o=r.ask===void 0||r.ask===null?null:I(r.ask,`${e}.ask`),i=w(r.last),u=null;if(s!==null&&o!==null){u={mantissa:s.mantissa+o.mantissa,scale:s.scale===o.scale?s.scale+1:Math.max(s.scale,o.scale)+1};let p=Math.max(s.scale,o.scale),y=s.scale===p?s.mantissa:s.mantissa*10n**BigInt(p-s.scale),b=o.scale===p?o.mantissa:o.mantissa*10n**BigInt(p-o.scale);u={mantissa:y+b,scale:p+1},u={mantissa:(y+b)/2n,scale:p}}else i!==null&&(u=i);if(s===null&&o===null&&u===null)return null;let a=n===null?f("0"):n,l=f("0"),c={venue:Jn,chain:Gn,instrument:"spot",tier:Zn,symbolRaw:e,symbol:e,side:t,requestedSize:a,fees:l,gasEstimate:null,priceImpact:null,fundingHourly:null,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.arcus_spot",last:r.last,bid:r.bid,ask:r.ask,vol24h:r.vol24h,feeKnownZero:!0,reasonCostUnknown:"gas and impact at size not captured; fee is a known zero"}};return s!==null&&(c.bid=s),o!==null&&(c.ask=o),u!==null&&(c.mid=u),v(c)}function oe({side:e="buy",sizeUsd:t=null}={}){return er().map(n=>tr({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var nr="solana_xstocks",rr="solana",sr="quote-only",mt=25e3;function ie(){return He()}function $e(){return Object.keys(ie().tokens).sort()}function or(e){let t=ie().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function ir(e,t){if(e===null||t===null)return null;if(e.mantissa<=0n||t.mantissa<=0n)return f("0");let n=Math.max(e.scale,t.scale),r=e.scale===n?e.mantissa:e.mantissa*10n**BigInt(n-e.scale),s=t.scale===n?t.mantissa:t.mantissa*10n**BigInt(n-t.scale),o=s*10n**6n,i=r+s;return{mantissa:o/i,scale:6}}function Ae({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e,s=e,o=ie().tokens;if(Object.hasOwn(o,e))r=e,s=o[e].symbolRaw;else if(e.endsWith("x")||e.endsWith("X")){let g=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}else return null;let i=o[r],u=or(r);if(!i||!u)return null;let a=I(u.priceUsd,`${r}.priceUsd`),l=w(u.liquidityUsd),c=n===null?f("0"):n,p=c.mantissa===0n?f("0"):ir(l,c),y=!1;c.mantissa===0n&&(u.liquidityUsd??0)>=mt&&(y=!1);let b={venue:nr,chain:rr,instrument:"spot",tier:sr,symbolRaw:s,symbol:r,side:t,requestedSize:c,mid:a,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:null,costAccounted:y,capturedAt:ie().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/solana_xstocks.json",mint:i.mint,pairAddress:u.pairAddress,dexId:u.dexId,quote:u.quote,liquidityUsd:u.liquidityUsd,volume24h:u.volume24h,priceUsd:u.priceUsd,source:"dexscreener",approximate:!0,reasonCostUnknown:"DexScreener liquidity.usd is a third-party float; fees and SOL gas not captured; impact is modeled",thin:(u.liquidityUsd??0)<mt}};return v(b)}function bt({side:e="buy",sizeUsd:t=null}={}){return $e().map(n=>Ae({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ur="ton_stonfi",ar="ton",cr="quote-only",lr=25e3,fr=.01;function ue(){return ze()}function Ee(){return Object.keys(ue().tokens).sort()}function pr(e){let t=ue().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function dr(e,t){if(e===null||t===null)return null;if(e.mantissa<=0n||t.mantissa<=0n)return f("0");let n=Math.max(e.scale,t.scale),r=e.scale===n?e.mantissa:e.mantissa*10n**BigInt(n-e.scale),s=t.scale===n?t.mantissa:t.mantissa*10n**BigInt(n-t.scale),o=s*10n**6n,i=r+s;return{mantissa:o/i,scale:6}}function ve({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e,s=e,o=ue().tokens;if(Object.hasOwn(o,e))r=e,s=o[e].symbolRaw;else if(e.endsWith("x")||e.endsWith("X")){let g=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}else{let g=e.toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}let i=o[r],u=pr(r);if(!i||!u)return null;let a=I(u.priceUsd,`${r}.priceUsd`),l=w(u.liquidityUsd),c=n===null?f("0"):n,p=c.mantissa===0n?f("0"):dr(l,c),b={venue:ur,chain:ar,instrument:"spot",tier:cr,symbolRaw:s,symbol:r,side:t,requestedSize:c,mid:a,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:null,costAccounted:!1,capturedAt:ue().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/ton_xstocks.json",mint:i.mint,pairAddress:u.pairAddress,dexId:u.dexId,quote:u.quote,liquidityUsd:u.liquidityUsd,volume24h:u.volume24h,priceUsd:u.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:(u.liquidityUsd??0)<lr,impactSizeFractionHint:fr}};return v(b)}function yt({side:e="buy",sizeUsd:t=null}={}){return Ee().map(n=>ve({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ht=3600*1e3;function qe(e){return e==null||e===""?null:typeof e=="object"&&e&&typeof e.mantissa=="bigint"?e:f(String(e))}function mr(e,{sizeUsd:t=null}={}){if(typeof e!="string"||!e.trim())throw new TypeError("ticker is required");let n=e.trim().toUpperCase(),r=qe(t),s=[],o=pt({symbol:`xyz:${n}`,sizeUsd:r});if(o)s.push(o);else for(let l of se({ticker:n,sizeUsd:r}))s.push(l);for(let l of re({sizeUsd:r}))l.symbol===n&&s.push(l);for(let l of oe({sizeUsd:r}))l.symbol===n&&s.push(l);let i=z({symbol:n,sizeUsd:r});i&&s.push(i);let u=Ae({symbol:n,sizeUsd:r});u&&s.push(u);let a=ve({symbol:n,sizeUsd:r});return a&&s.push(a),s}function gt(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase();if(!t)throw new Error("bestEquityRoute requires ticker");let n=qe(e.sizeUsd??e.size??null),r=mr(t,{sizeUsd:n});if(r.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 s=r[0].capturedAt,o=String(s).length<=10?s*1e3:s,i=e.nowMs==null,u=e.nowMs??s+1e3,a=Math.max(0,Date.now()-o),l=ke(r,{nowMs:u,horizonHours:e.horizonHours!=null?Number(e.horizonHours):void 0,skipLiveness:e.skipLiveness===!0});return{ticker:t,...l,dataSource:i?"fixture":"caller-clock",capturedAt:o,ageMs:a,stale:a>ht}}function kt(){let e=[{venue:"hyperliquid_hip3",tier:"quote-only",chain:"hyperliquid",n:se().length},{venue:"arcus_perp",tier:"quote-only",chain:"robinhood-4663",n:re().length},{venue:"arcus_spot",tier:"quote-only",chain:"robinhood-4663",n:oe().length},{venue:"rh_uniswap",tier:"prepare",chain:4663,n:we().length},{venue:"solana_xstocks",tier:"quote-only",chain:"solana",n:$e().length},{venue:"ton_stonfi",tier:"quote-only",chain:"ton",n:Ee().length}],t=[...se(),...re(),...oe(),...at(),...bt(),...yt()],n=(t[0]?.capturedAt??Date.now())+1e3,{survivors:r,excluded:s}=ee(t,{nowMs:n});return{inventory:e,hip3Dexs:lt(),liveness:{survivors:r.length,excluded:s.length,byReason:s.reduce((o,i)=>(o[i.reason]=(o[i.reason]??0)+1,o),{})},capturedAt:q().capturedAt,custody:"prepare-only",note:"quote-only venues are ranked for discovery; only rh_uniswap is preparable in v1"}}function xt(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase(),n=e.recipient||e.taker;if(!t)throw new Error("prepareEquityRoute requires ticker");if(!n)throw new Error("prepareEquityRoute requires recipient (signing wallet)");let r=qe(e.sizeUsd??e.size??null),s=z({symbol:t,sizeUsd:r});if(!s)return{ok:!1,failureKind:"no-prepare-path",ticker:t,note:"no RH Uniswap prepare-tier route for this ticker in fixtures"};try{let o=String(s.capturedAt).length<=10?s.capturedAt*1e3:s.capturedAt,i=e.nowMs!=null,u=i?Number(e.nowMs):Date.now(),a=Math.max(0,Date.now()-o),l=Se({symbol:t,sizeUsd:r,recipient:n,nowMs:u});return{ok:!0,ticker:t,artifact:l,bestPreparableVenue:"rh_uniswap",dataSource:i?"caller-clock":"live-clock",capturedAt:o,ageMs:a,stale:a>ht}}catch(o){return{ok:!1,failureKind:"prepare-refused",ticker:t,error:String(o.message||o)}}}function Oe(e){return JSON.parse(JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n))}function St(){return`oracle equities <command>
3
3
 
4
4
  Commands:
5
5
  venues inventory + tiers + liveness snapshot
@@ -12,9 +12,9 @@ Options:
12
12
  --json machine readable output
13
13
  --fixtures offline mode (default in v1)
14
14
  `}function yr(e){let t={_:[]};for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--json")t.json=!0;else if(r==="--fixtures")t.fixtures=!0;else if(r==="--size")t.size=e[++n];else if(r==="--horizon")t.horizon=e[++n];else if(r==="--recipient")t.recipient=e[++n];else{if(r.startsWith("--"))throw new Error(`unknown flag ${r}`);t._.push(r)}}return t}function hr(e){let t=[];if(t.push(`oracle equities quote ${e.ticker}`),e.darkWindow&&t.push(`WARNING: ${e.darkWindow.warning} (session=${e.darkWindow.session})`),e.stale){let n=Math.floor(e.ageMs/36e5),r=n>=24?`${Math.floor(n/24)}d ${n%24}h`:`${n}h`;t.push(`WARNING: prices are a pinned ${e.dataSource} capture ${r} old \u2014 not live quotes`)}t.push(`rankedOn=${e.rankedOn} mix=${e.instrumentMix}`),t.push(`sources answered/tried=${e.sourcesAnswered}/${e.sourcesTried} excluded=${e.excluded?.length??0} failed=${e.failed?.length??0}`),e.winner?t.push(`WINNER ${e.winner.venue} ${e.winner.instrument} tier=${e.winner.tier} net=${S(e.winner.net)} costAccounted=${e.winner.costAccounted}`):t.push("WINNER (none)");for(let n of(e.runnersUp||[]).slice(0,5))t.push(` runner ${n.venue} ${n.instrument} tier=${n.tier} net=${S(n.net)} costAccounted=${n.costAccounted}`);if(e.improvementBps!==null&&e.improvementBps!==void 0?t.push(`improvementBps=${e.improvementBps}`):t.push("improvementBps=null (no honest same-class costed comparison)"),e.bestPreparable?t.push(`bestPreparable ${e.bestPreparable.venue} net=${S(e.bestPreparable.net)}`):t.push("bestPreparable (none)"),e.excluded?.length){let n={};for(let r of e.excluded)n[r.reason]=(n[r.reason]??0)+1;t.push(`excluded: ${JSON.stringify(n)}`)}return t.join(`
15
- `)}function gr(e){let t=gt();return e.json?JSON.stringify(t,null,2):["oracle equities venues",...t.inventory.map(n=>` ${n.venue.padEnd(22)} tier=${n.tier.padEnd(11)} chain=${String(n.chain).padEnd(16)} n=${n.n}`),`liveness survivors=${t.liveness.survivors} excluded=${t.liveness.excluded} ${JSON.stringify(t.liveness.byReason)}`].join(`
16
- `)}function kr(e){let t=e._[1];if(!t)throw new Error("usage: quote <TICKER>");let n=ht({ticker:t,sizeUsd:e.size,horizonHours:e.horizon});return e.json?JSON.stringify(Oe(n),null,2):hr(n)}function xr(e){let t=e._[1];if(!t)throw new Error("usage: prepare <TICKER> --recipient 0x...");if(!e.recipient)throw new Error("--recipient is required");let n=kt({ticker:t,sizeUsd:e.size,recipient:e.recipient});if(e.json)return JSON.stringify(Oe(n),null,2);if(!n.ok)return`prepare ${t.toUpperCase()} FAILED (${n.failureKind}): ${n.error||n.note}`;let r=n.artifact;return[`prepare ${t.toUpperCase()}`,` chainId=${r.chainId} to=${r.to}`,` requiresWalletSignature=${r.requiresWalletSignature} backendSigner=${r.backendSigner}`,` approval spender=${r.requiresApproval?.spender} token=${r.requiresApproval?.token}`,` quoteAgeMs=${r.quoteAgeMs}`,...(r.notes||[]).map(s=>` note: ${s}`)].join(`
17
- `)}function wr(e=process.argv.slice(2)){if(e.length===0||e[0]==="-h"||e[0]==="--help")return process.stdout.write(wt()),0;let t=yr(e),n=t._[0],r;if(n==="venues")r=gr(t);else if(n==="quote")r=kr(t);else if(n==="prepare")r=xr(t);else throw new Error(`unknown command ${n}
18
- ${wt()}`);return process.stdout.write(r+`
19
- `),0}function Sr(){if(!process.argv[1])return!1;try{return xt(br(import.meta.url))===xt(process.argv[1])}catch{return!1}}if(Sr())try{process.exit(wr())}catch(e){process.stderr.write(String(e.message||e)+`
15
+ `)}function gr(e){let t=kt();return e.json?JSON.stringify(t,null,2):["oracle equities venues",...t.inventory.map(n=>` ${n.venue.padEnd(22)} tier=${n.tier.padEnd(11)} chain=${String(n.chain).padEnd(16)} n=${n.n}`),`liveness survivors=${t.liveness.survivors} excluded=${t.liveness.excluded} ${JSON.stringify(t.liveness.byReason)}`].join(`
16
+ `)}function kr(e){let t=e._[1];if(!t)throw new Error("usage: quote <TICKER>");let n=gt({ticker:t,sizeUsd:e.size,horizonHours:e.horizon});return e.json?JSON.stringify(Oe(n),null,2):hr(n)}function xr(e){let t=e._[1];if(!t)throw new Error("usage: prepare <TICKER> --recipient 0x...");if(!e.recipient)throw new Error("--recipient is required");let n=xt({ticker:t,sizeUsd:e.size,recipient:e.recipient});if(e.json)return JSON.stringify(Oe(n),null,2);if(!n.ok)return`prepare ${t.toUpperCase()} FAILED (${n.failureKind}): ${n.error||n.note}`;let r=n.artifact;return[`prepare ${t.toUpperCase()}`,` chainId=${r.chainId} to=${r.to}`,` requiresWalletSignature=${r.requiresWalletSignature} backendSigner=${r.backendSigner}`,` approval spender=${r.requiresApproval?.spender} token=${r.requiresApproval?.token}`,` quoteAgeMs=${r.quoteAgeMs}`,...(r.notes||[]).map(s=>` note: ${s}`)].join(`
17
+ `)}function wr(e=process.argv.slice(2)){if(e.length===0||e[0]==="-h"||e[0]==="--help")return process.stdout.write(St()),0;let t=yr(e),n=t._[0],r;if(n==="venues")r=gr(t);else if(n==="quote")r=kr(t);else if(n==="prepare")r=xr(t);else throw new Error(`unknown command ${n}
18
+ ${St()}`);return process.stdout.write(r+`
19
+ `),0}function Sr(){if(!process.argv[1])return!1;try{return wt(br(import.meta.url))===wt(process.argv[1])}catch{return!1}}if(Sr())try{process.exit(wr())}catch(e){process.stderr.write(String(e.message||e)+`
20
20
  `),process.exit(1)}export{wr as main};