@oracle-agent/oracle 0.22.11 → 0.22.12

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 +1 @@
1
- var lr=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 D(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 K(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 S(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 q(e){D(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 Q(e,t){return D(e),P(t),t===e.scale?T(e.mantissa,e.scale):t>e.scale?T(e.mantissa*K(t-e.scale),t):T(e.mantissa/K(e.scale-t),t)}function ce(e,t){D(e,"left"),D(t,"right");let n=Math.max(e.scale,t.scale);return[Q(e,n),Q(t,n),n]}function M(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa+r.mantissa,s)}function X(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa-r.mantissa,s)}function E(e,t){D(e,"left"),D(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(D(e,"left"),D(t,"right"),P(n),t.mantissa===0n)throw new RangeError("division by zero");let r=e.mantissa*K(t.scale+n),s=t.mantissa*K(e.scale);return T(r/s,n)}function U(e,t){let[n,r]=ce(e,t);return n.mantissa<r.mantissa?-1:n.mantissa>r.mantissa?1:0}import{readFileSync as At,existsSync as Et}from"node:fs";import{fileURLToPath as vt}from"node:url";import{dirname as $t,join as De}from"node:path";import{existsSync as Te,readFileSync as xt}from"node:fs";import{dirname as Ie,join as le}from"node:path";import{fileURLToPath as wt}from"node:url";function St(e){let t=Ie(wt(e));for(let n=0;n<8;n+=1){let r=le(t,"package.json");if(Te(r))try{let o=JSON.parse(xt(r,"utf8"));if(o&&typeof o.version=="string")return t}catch{}let s=Ie(t);if(s===t)break;t=s}throw new Error(`oracle: could not resolve package root from ${e}`)}function _e(e,t){let n=St(t),r=le(n,"dist","assets",e);return Te(r)?r:le(n,e)}var Ot=De($t(vt(import.meta.url)),"fixtures");function qt(){try{let e=_e("equities-fixtures",import.meta.url);if(e&&Et(e))return e}catch{}return Ot}var Rt=qt();var Me=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 It(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){It(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 j(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 Tt(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`),j(o[s],t,`venues.${r}.${s}`)}for(let[r,s]of Object.entries(e.venues.hyperliquid_hip3.dexs))j(s,t,`venues.hyperliquid_hip3.dexs.${r}`)}function _t(e,t){j(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 Nt(e,t){k(e,t,"root");for(let n of["chainId","block","oracleScaleExp","usdgDecimals","equityDecimals"])_(e[n],t,n);m(e.usdg,t,"usdg"),j(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 Dt(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 Mt(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 Ut(e,t){j(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 jt(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"),j(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 Ft(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 Pt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),j(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 Bt(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"'),j(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 Ct=Object.freeze({venues:Tt,universe:_t,oracles:Nt,nyseHolidays:Dt,dstTransitions:Mt,equityDexPools:Ut,rhPoolState:jt,solanaXstocks:Pt,tonXstocks:Bt,hip3L2Books:Ft});function Ht(e,t){let n=Me[t],r=De(e,n),s;try{s=At(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 Ct[t](o,n),o}function Ue(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Ue(t)}return e}function je({fixtureDir:e=Rt}={}){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(Me))t[n]=Ht(e,n);return Ue(t)}var Ne;function N(){return Ne??=je(),Ne}function $(){return N().venues}function Lt(){return N().universe}function Fe(){return N().oracles}function Pe(){return N().nyseHolidays}function Be(){return N().dstTransitions}function J(){return N().rhPoolState}function Ce(){return N().solanaXstocks}function He(){return N().tonXstocks}function Le(){return N().hip3L2Books}var pe=1e3,Xe=60*pe,de=60*Xe,ze=24*de,zt=-5*de,Qt=-4*de,We=240,Ve=570,Ye=960,Ke=1200,Sr=Object.freeze([We,Ve,Ye,Ke]),Ar=Object.freeze(["core","extended","dark"]),Qe,fe;function Xt(){let e=Be().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 Je(){return Qe??=Xt(),Qe}function Wt(){return fe===void 0&&(fe=new Set(Pe().holidayDayIndex)),fe}function Ge(e,t){if(!Number.isSafeInteger(e))throw new TypeError(`${t}: epochMs must be a safe integer number of milliseconds`)}function Vt(e,t){let{coverageStartMs:n,coverageEndMs:r,firstYear:s,lastYear:o}=Je();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 Yt(e){for(let t of Je().rows)if(e>=t.startMs&&e<t.endMs)return!0;return!1}function Kt(e){return Yt(e)?Qt:zt}function Jt(e){let t=e+Kt(e),n=Math.floor(t/ze),r=t-n*ze,s=new Date(t);return{dayIndex:n,minuteOfDay:Math.floor(r/Xe),msIntoDay:r,weekday:s.getUTCDay()}}function Gt({dayIndex:e,weekday:t}){return t===0||t===6?!1:!Wt().has(e)}function Zt(e){return e<We?"dark":e<Ve?"extended":e<Ye?"core":e<Ke?"extended":"dark"}function W(e){Ge(e,"sessionState"),Vt(e,"sessionState");let t=Jt(e);return Gt(t)?Zt(t.minuteOfDay):"dark"}function me(e){return Ge(e,"isDark"),W(e)==="dark"}var G=Object.freeze({DORMANT_VENUE:"dormant-venue",CROSSED_BOOK:"crossed-book",STALE_QUOTE:"stale-quote",STALE_ORACLE:"stale-oracle"}),en=12e4,tn=6e5;function Z(e,t){e.push(Object.freeze({venue:t.venue,symbol:t.symbol??null,reason:t.reason,evidence:t.evidence??null}))}function nn(e){let t=e.raw?.vol24h;return!!(t===0||t===0||typeof t=="number"&&Number.isFinite(t)&&t<=0)}function rn(e){return!e.bid||!e.ask?!1:U(e.bid,e.ask)>0}function Ze(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??en,s=t.oracleFreshnessMs??tn,o=t.includeDormant===!0,i=[],u=[];for(let a of e){if(nn(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(rn(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(Ze(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=W(n),c=l==="core"?s:s*2;if(Ze(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 sn(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(sn(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 on=new Set(["spot","perp"]),un=new Set(["read-only","quote-only","prepare","intent"]),an=new Set(["buy","sell"]),cn=new Set(["net-of-cost","gross"]),ln=new Set(["homogeneous","heterogeneous"]),fn=["bid","ask","mid","mark"],et=["fees","gasEstimate","priceImpact","fundingHourly"],pn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function g(e,t){throw new TypeError(`${e} ${t}`)}function nt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function B(e,t){nt(e)||g(t,"must be an object")}function rt(e,t,n){Object.hasOwn(e,t)||g(`${n}.${t}`,"is required")}function C(e,t){(typeof e!="string"||e.length===0)&&g(t,"must be a nonempty string")}function V(e,t,n){t.has(e)||g(n,`must be one of ${[...t].join(", ")}`)}function ye(e,t){(!Number.isSafeInteger(e)||e<0)&&g(t,"must be a nonnegative safe integer")}function be(e,t,n=!1){e===null&&n||(nt(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 te(e,t,n=!1){e===null&&n||B(e,t)}function tt(e,t){B(e,t),C(e.venue,`${t}.venue`),C(e.reason,`${t}.reason`),pn.test(e.reason)||g(`${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",...et,"costAccounted","capturedAt","blockOrSeq","raw"])rt(e,n,"quote");C(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"),V(e.instrument,on,"quote.instrument"),V(e.tier,un,"quote.tier"),C(e.symbolRaw,"quote.symbolRaw"),C(e.symbol,"quote.symbol"),V(e.side,an,"quote.side"),be(e.requestedSize,"quote.requestedSize"),e.requestedSize.mantissa<0n&&g("quote.requestedSize","must not be negative");let t=0;for(let n of fn)Object.hasOwn(e,n)&&(be(e[n],`quote.${n}`),t+=1);t===0&&g("quote","must contain at least one of bid, ask, mid, mark");for(let n of et)be(e[n],`quote.${n}`,!0);if(typeof e.costAccounted!="boolean"&&g("quote.costAccounted","must be a boolean"),e.costAccounted){for(let n of["fees","gasEstimate","priceImpact"])e[n]===null&&g(`quote.${n}`,"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"),ye(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"),B(e.raw,"quote.raw"),e}function ge(e){B(e,"rankResult");for(let t of["rankedOn","ranked","winner","runnersUp","improvementBps","sourcesAnswered","sourcesTried","failed","excluded","darkWindow","instrumentMix","bestPreparable"])rt(e,t,"rankResult");return V(e.rankedOn,cn,"rankResult.rankedOn"),Array.isArray(e.ranked)||g("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&&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,n)=>te(t,`rankResult.runnersUp[${n}]`)),e.improvementBps!==null&&!(typeof e.improvementBps=="number"&&Number.isFinite(e.improvementBps))&&g("rankResult.improvementBps","must be a finite number or null"),ye(e.sourcesAnswered,"rankResult.sourcesAnswered"),ye(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,n)=>tt(t,`failed[${n}]`)),Array.isArray(e.excluded)||g("rankResult.excluded","must be an array"),e.excluded.forEach((t,n)=>tt(t,`excluded[${n}]`)),e.darkWindow!==null&&B(e.darkWindow,"rankResult.darkWindow"),V(e.instrumentMix,ln,"rankResult.instrumentMix"),te(e.bestPreparable,"rankResult.bestPreparable",!0),Object.hasOwn(e,"carry")&&e.carry!==null&&B(e.carry,"rankResult.carry"),e}var dn="arcus_perp",mn="robinhood-4663",bn="quote-only",ne="0.00000480324074074";function st(){return $().venues.arcus}function yn(){return Object.keys(st().markets).sort()}function gn({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=st().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:dn,chain:mn,instrument:"perp",tier:bn,symbolRaw:e,symbol:r,side:t,requestedSize:a,mark:o,fees:null,gasEstimate:null,priceImpact:null,fundingHourly:u,costAccounted:!1,capturedAt:$().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 yn().map(n=>gn({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ot=36e5,Br=24*365;function he(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=S(10000n,0);return E(E(e,r),s)}function it(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=hn(r,t),a=t-u,l=f(ne),c=he(o,a),p=he(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:q(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=he(o,t);return{model:"current-funding-held-constant",horizonHours:t,carryBps:i,carryBpsDisplay:q(i),confidence:"estimate",compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}function hn(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*ot)&&(n+=1);return t>r&&me(e+r*ot)&&(n+=t-r),n}function kn(e){return e.mid??e.mark??e.ask??e.bid??null}function xn(e){let t=kn(e);if(t===null)return null;let n=e.costAccounted===!0,r=f("0");e.fees!==null?r=M(r,e.fees):n=!1,e.priceImpact!==null?r=M(r,e.priceImpact):e.requestedSize&&e.requestedSize.mantissa>0n&&(n=!1),e.gasEstimate===null?n=!1:r=M(r,e.gasEstimate);let s;if(e.fees!==null&&U(e.fees,f("1"))<0&&U(e.fees,f("0"))>=0){let o=M(f("1"),e.fees);s=E(t,o),e.priceImpact!==null&&(s=M(s,E(t,e.priceImpact)))}else s=M(t,r);return{net:s,costAccounted:n,px:t}}function wn(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 Sn(e,t){if(!e||!t||!e.costAccounted||!t.costAccounted||e.instrument!==t.instrument||e.net.mantissa===0n)return null;let n=X(t.net,e.net);return R(E(n,S(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=xn(x);if(A===null)continue;let O=null;if(l&&x.instrument==="perp"&&(O=it(x,a,{nowMs:n}),O.carryBps!==null)){let kt=M(f("1"),R(O.carryBps,S(10000n,0),12));A.net=E(A.net,kt),A.costAccounted=!1}c.push(wn(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=U(x.net,A.net);return O!==0?O:x.venue<A.venue?-1:x.venue>A.venue?1:0});let b=p[0]??null,h=p.slice(1),F=p,z="gross";b&&b.costAccounted&&(h.length===0||h[0].costAccounted)&&(z="net-of-cost");let qe=h.length===0?null:Sn(b,h[0]),yt=c.find(x=>x.tier==="prepare")??null,ae=W(n),gt=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"},Re=null;l&&(Re=An(c));let ht={rankedOn:z,ranked:F,winner:b,runnersUp:h,improvementBps:qe===null?null:Number(q(qe)),sourcesAnswered:i,sourcesTried:r,failed:u,excluded:o,darkWindow:gt,instrumentMix:y,bestPreparable:yt,carry:b?.carry??null,breakEvenHorizonHours:Re};return ge(ht)}function An(e){let t=e.filter(o=>o.instrument==="spot").sort((o,i)=>U(o.net,i.net))[0],n=e.filter(o=>o.instrument==="perp").sort((o,i)=>U(o.net,i.net))[0];if(!t||!n||n.fundingHourly===null)return null;let r=X(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(q(o));return!Number.isFinite(i)||i<0?null:i}catch{return null}}var En="rh_uniswap",vn=4663,$n="prepare",On=1n<<192n,H=18,qn=Object.freeze({v3:180000n,v4:240000n});function xe(){return J()}function Rn(e){return{mantissa:e*e*10n**BigInt(H)/On,scale:H}}function In(e){let t=Rn(BigInt(e.sqrtPriceX96)),n=e.quote==="USDG"?6:18,r=18;if(e.quoteIsToken0){let s=R(E(t,S(10n**BigInt(n),0)),S(10n**BigInt(r),0),H);return s.mantissa===0n?null:R(f("1"),s,H)}return R(E(t,S(10n**BigInt(r),0)),S(10n**BigInt(n),0),H)}function Tn(e){let t=Fe(),n=t.assets[e];return n?S(n.rawPrice,t.oracleScaleExp):null}function _n(e,t){if(e===null||t===null||e.mantissa<=0n||t.mantissa<=0n)return null;let n={...e};return R(t,Nn(n,t),H)}function Nn(e,t){let n=Math.max(e.scale,t.scale);return{mantissa:Q(e,n).mantissa+Q(t,n).mantissa,scale:n}}function Dn(e){let t=xe(),n=qn[e];return n?{wei:BigInt(t.gasPriceWei)*n,units:n,native:"ETH"}:null}function we(){return Object.keys(xe().pools).sort()}function L({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=In(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(S(BigInt(s.feePpm),0),S(1000000n,0),8),l=u.mantissa===0n?f("0"):_n(i,u),c=Dn(s.version),b={venue:En,chain:vn,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"]}},h=Tn(e);return h!==null&&(b.referencePrice=h,b.referenceBasisBps=q(R(E(X(o,h),S(10000n,0)),h,4))),v(b)}function ut({side:e="buy",sizeUsd:t=null}={}){return we().map(n=>L({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var at=12e4,Mn="0x0000000000000000000000000000000000000000",Un="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=L({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>at)throw new Error(`quote is stale (${u}ms old, bound ${at}ms); re-quote before preparing`);let l=J().pools[t],c=l.version==="v4"?Un:Mn,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 jn="hyperliquid_hip3",Fn="hyperliquid",Pn="quote-only";function Y(){return $().venues.hyperliquid_hip3}function ct(){return Object.keys(Y().dexs).sort()}function Bn(){let e=[];for(let[t,n]of Object.entries(Y().dexs))for(let r of Object.keys(n))e.push(`${t}:${r}`);return e.sort()}function Cn(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=Y().dexs[r]?.[s];return o?[{dex:r,ticker:s,market:o}]:[]}let n=[];for(let[r,s]of Object.entries(Y().dexs))Object.hasOwn(s,e)&&n.push({dex:r,ticker:e,market:s[e]});return n}function Hn(e,t){try{return Le().books[`${e}:${t}`]??null}catch{return null}}function Ln(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(q(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 zn(e,t,n,r){let s=Ln(e,t,n);if(!s)return{impact:null,depth:null};let o=Number(q(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 lt({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=Hn(e,t),p=null,y=null,b="fees and gas not captured";if(l.mantissa>0n)if(c){let z=zn(c,r,l,o);p=z.impact,y=z.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:jn,chain:Fn,instrument:"perp",tier:Pn,symbolRaw:`${e}:${t}`,symbol:t,side:r,requestedSize:l,mark:o,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:i,costAccounted:!1,capturedAt:$().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 ft({symbol:e,side:t="buy",sizeUsd:n=null}={}){let r=Cn(e);return r.length===0||r.length>1?null:lt({...r[0],side:t,size:n})}function se({side:e="buy",sizeUsd:t=null,ticker:n=null}={}){let r=[];for(let s of Bn()){let[o,i]=s.split(":");if(n!==null&&i!==n)continue;let u=Y().dexs[o][i];r.push(lt({dex:o,ticker:i,market:u,side:e,size:t}))}return r}var Qn="arcus_spot",Xn="robinhood-4663",Wn="quote-only";function pt(){return $().venues.arcus_spot}function Vn(){return Object.keys(pt().pairs).sort()}function Yn({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=pt().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:Qn,chain:Xn,instrument:"spot",tier:Wn,symbolRaw:e,symbol:e,side:t,requestedSize:a,fees:l,gasEstimate:null,priceImpact:null,fundingHourly:null,costAccounted:!1,capturedAt:$().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 Vn().map(n=>Yn({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var Kn="solana_xstocks",Jn="solana",Gn="quote-only",dt=25e3;function ie(){return Ce()}function Ae(){return Object.keys(ie().tokens).sort()}function Zn(e){let t=ie().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function er(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 Ee({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 h=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,h))r=h,s=o[h].symbolRaw;else return null}else return null;let i=o[r],u=Zn(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"):er(l,c),y=!1;c.mantissa===0n&&(u.liquidityUsd??0)>=dt&&(y=!1);let b={venue:Kn,chain:Jn,instrument:"spot",tier:Gn,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)<dt}};return v(b)}function mt({side:e="buy",sizeUsd:t=null}={}){return Ae().map(n=>Ee({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var tr="ton_stonfi",nr="ton",rr="quote-only",sr=25e3,or=.01;function ue(){return He()}function ve(){return Object.keys(ue().tokens).sort()}function ir(e){let t=ue().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function ur(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 $e({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 h=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,h))r=h,s=o[h].symbolRaw;else return null}else{let h=e.toUpperCase();if(Object.hasOwn(o,h))r=h,s=o[h].symbolRaw;else return null}let i=o[r],u=ir(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"):ur(l,c),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:!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)<sr,impactSizeFractionHint:or}};return v(b)}function bt({side:e="buy",sizeUsd:t=null}={}){return ve().map(n=>$e({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ar=3600*1e3;function Oe(e){return e==null||e===""?null:typeof e=="object"&&e&&typeof e.mantissa=="bigint"?e:f(String(e))}function cr(e,{sizeUsd:t=null}={}){if(typeof e!="string"||!e.trim())throw new TypeError("ticker is required");let n=e.trim().toUpperCase(),r=Oe(t),s=[],o=ft({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=L({symbol:n,sizeUsd:r});i&&s.push(i);let u=Ee({symbol:n,sizeUsd:r});u&&s.push(u);let a=$e({symbol:n,sizeUsd:r});return a&&s.push(a),s}function Fs(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase();if(!t)throw new Error("bestEquityRoute requires ticker");let n=Oe(e.sizeUsd??e.size??null),r=cr(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>ar}}function Ps(){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:Ae().length},{venue:"ton_stonfi",tier:"quote-only",chain:"ton",n:ve().length}],t=[...se(),...re(),...oe(),...ut(),...mt(),...bt()],n=(t[0]?.capturedAt??Date.now())+1e3,{survivors:r,excluded:s}=ee(t,{nowMs:n});return{inventory:e,hip3Dexs:ct(),liveness:{survivors:r.length,excluded:s.length,byReason:s.reduce((o,i)=>(o[i.reason]=(o[i.reason]??0)+1,o),{})},capturedAt:$().capturedAt,custody:"prepare-only",note:"quote-only venues are ranked for discovery; only rh_uniswap is preparable in v1"}}function Bs(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=Oe(e.sizeUsd??e.size??null),s=L({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 Cs(e){return JSON.parse(JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n))}export{Fs as bestEquityRoute,cr as collectEquityQuotes,Ps as equityVenues,Lt as getUniverse,$ as getVenues,je as loadFixtures,Se as prepareEquity,Bs as prepareEquityRoute,ke as rankEquityQuotes,Cs as toJsonSafe,v as validateQuote,ge as validateRankResult};
1
+ var lr=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 D(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 K(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 S(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 q(e){D(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 Q(e,t){return D(e),P(t),t===e.scale?T(e.mantissa,e.scale):t>e.scale?T(e.mantissa*K(t-e.scale),t):T(e.mantissa/K(e.scale-t),t)}function ce(e,t){D(e,"left"),D(t,"right");let n=Math.max(e.scale,t.scale);return[Q(e,n),Q(t,n),n]}function M(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa+r.mantissa,s)}function X(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa-r.mantissa,s)}function E(e,t){D(e,"left"),D(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(D(e,"left"),D(t,"right"),P(n),t.mantissa===0n)throw new RangeError("division by zero");let r=e.mantissa*K(t.scale+n),s=t.mantissa*K(e.scale);return T(r/s,n)}function U(e,t){let[n,r]=ce(e,t);return n.mantissa<r.mantissa?-1:n.mantissa>r.mantissa?1:0}import{readFileSync as Et,existsSync as vt}from"node:fs";import{fileURLToPath as $t}from"node:url";import{dirname as Ot,join as De}from"node:path";import{existsSync as Te,readFileSync as wt}from"node:fs";import{dirname as Ie,join as le}from"node:path";import{fileURLToPath as St}from"node:url";function At(e){let t=Ie(St(e));for(let n=0;n<8;n+=1){let r=le(t,"package.json");if(Te(r))try{let o=JSON.parse(wt(r,"utf8"));if(o&&typeof o.version=="string")return t}catch{}let s=Ie(t);if(s===t)break;t=s}throw new Error(`oracle: could not resolve package root from ${e}`)}function _e(e,t){let n=At(t),r=le(n,"dist","assets",e);return Te(r)?r:le(n,e)}var qt=De(Ot($t(import.meta.url)),"fixtures");function Rt(){try{let e=_e("equities-fixtures",import.meta.url);if(e&&vt(e))return e}catch{}return qt}var It=Rt();var Me=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 Tt(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){Tt(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 j(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 _t(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`),j(o[s],t,`venues.${r}.${s}`)}for(let[r,s]of Object.entries(e.venues.hyperliquid_hip3.dexs))j(s,t,`venues.hyperliquid_hip3.dexs.${r}`)}function Nt(e,t){j(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 Dt(e,t){k(e,t,"root");for(let n of["chainId","block","oracleScaleExp","usdgDecimals","equityDecimals"])_(e[n],t,n);m(e.usdg,t,"usdg"),j(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 Mt(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 Ut(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 jt(e,t){j(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 Ft(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"),j(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 Pt(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 Bt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),j(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 Ct(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"'),j(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 Ht=Object.freeze({venues:_t,universe:Nt,oracles:Dt,nyseHolidays:Mt,dstTransitions:Ut,equityDexPools:jt,rhPoolState:Ft,solanaXstocks:Bt,tonXstocks:Ct,hip3L2Books:Pt});function Lt(e,t){let n=Me[t],r=De(e,n),s;try{s=Et(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 Ht[t](o,n),o}function Ue(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Ue(t)}return e}function je({fixtureDir:e=It}={}){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(Me))t[n]=Lt(e,n);return Ue(t)}var Ne;function N(){return Ne??=je(),Ne}function $(){return N().venues}function zt(){return N().universe}function Fe(){return N().oracles}function Pe(){return N().nyseHolidays}function Be(){return N().dstTransitions}function J(){return N().rhPoolState}function Ce(){return N().solanaXstocks}function He(){return N().tonXstocks}function Le(){return N().hip3L2Books}var pe=1e3,Xe=60*pe,de=60*Xe,ze=24*de,Qt=-5*de,Xt=-4*de,We=240,Ve=570,Ye=960,Ke=1200,Sr=Object.freeze([We,Ve,Ye,Ke]),Ar=Object.freeze(["core","extended","dark"]),Qe,fe;function Wt(){let e=Be().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 Je(){return Qe??=Wt(),Qe}function Vt(){return fe===void 0&&(fe=new Set(Pe().holidayDayIndex)),fe}function Ge(e,t){if(!Number.isSafeInteger(e))throw new TypeError(`${t}: epochMs must be a safe integer number of milliseconds`)}function Yt(e,t){let{coverageStartMs:n,coverageEndMs:r,firstYear:s,lastYear:o}=Je();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 Kt(e){for(let t of Je().rows)if(e>=t.startMs&&e<t.endMs)return!0;return!1}function Jt(e){return Kt(e)?Xt:Qt}function Gt(e){let t=e+Jt(e),n=Math.floor(t/ze),r=t-n*ze,s=new Date(t);return{dayIndex:n,minuteOfDay:Math.floor(r/Xe),msIntoDay:r,weekday:s.getUTCDay()}}function Zt({dayIndex:e,weekday:t}){return t===0||t===6?!1:!Vt().has(e)}function en(e){return e<We?"dark":e<Ve?"extended":e<Ye?"core":e<Ke?"extended":"dark"}function W(e){Ge(e,"sessionState"),Yt(e,"sessionState");let t=Gt(e);return Zt(t)?en(t.minuteOfDay):"dark"}function me(e){return Ge(e,"isDark"),W(e)==="dark"}var G=Object.freeze({DORMANT_VENUE:"dormant-venue",CROSSED_BOOK:"crossed-book",STALE_QUOTE:"stale-quote",STALE_ORACLE:"stale-oracle"}),tn=12e4,nn=6e5;function Z(e,t){e.push(Object.freeze({venue:t.venue,symbol:t.symbol??null,reason:t.reason,evidence:t.evidence??null}))}function rn(e){let t=e.raw?.vol24h;return!!(t===0||t===0||typeof t=="number"&&Number.isFinite(t)&&t<=0)}function sn(e){return!e.bid||!e.ask?!1:U(e.bid,e.ask)>0}function Ze(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??tn,s=t.oracleFreshnessMs??nn,o=t.includeDormant===!0,i=[],u=[];for(let a of e){if(rn(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(sn(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(Ze(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=W(n),c=l==="core"?s:s*2;if(Ze(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 on(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(on(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 un=new Set(["spot","perp"]),an=new Set(["read-only","quote-only","prepare","intent"]),cn=new Set(["buy","sell"]),ln=new Set(["net-of-cost","gross"]),fn=new Set(["homogeneous","heterogeneous"]),pn=["bid","ask","mid","mark"],et=["fees","gasEstimate","priceImpact","fundingHourly"],dn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function g(e,t){throw new TypeError(`${e} ${t}`)}function nt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function B(e,t){nt(e)||g(t,"must be an object")}function rt(e,t,n){Object.hasOwn(e,t)||g(`${n}.${t}`,"is required")}function C(e,t){(typeof e!="string"||e.length===0)&&g(t,"must be a nonempty string")}function V(e,t,n){t.has(e)||g(n,`must be one of ${[...t].join(", ")}`)}function ye(e,t){(!Number.isSafeInteger(e)||e<0)&&g(t,"must be a nonnegative safe integer")}function be(e,t,n=!1){e===null&&n||(nt(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 te(e,t,n=!1){e===null&&n||B(e,t)}function tt(e,t){B(e,t),C(e.venue,`${t}.venue`),C(e.reason,`${t}.reason`),dn.test(e.reason)||g(`${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",...et,"costAccounted","capturedAt","blockOrSeq","raw"])rt(e,n,"quote");C(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"),V(e.instrument,un,"quote.instrument"),V(e.tier,an,"quote.tier"),C(e.symbolRaw,"quote.symbolRaw"),C(e.symbol,"quote.symbol"),V(e.side,cn,"quote.side"),be(e.requestedSize,"quote.requestedSize"),e.requestedSize.mantissa<0n&&g("quote.requestedSize","must not be negative");let t=0;for(let n of pn)Object.hasOwn(e,n)&&(be(e[n],`quote.${n}`),t+=1);t===0&&g("quote","must contain at least one of bid, ask, mid, mark");for(let n of et)be(e[n],`quote.${n}`,!0);if(typeof e.costAccounted!="boolean"&&g("quote.costAccounted","must be a boolean"),e.costAccounted){for(let n of["fees","gasEstimate","priceImpact"])e[n]===null&&g(`quote.${n}`,"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"),ye(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"),B(e.raw,"quote.raw"),e}function ge(e){B(e,"rankResult");for(let t of["rankedOn","ranked","winner","runnersUp","improvementBps","sourcesAnswered","sourcesTried","failed","excluded","darkWindow","instrumentMix","bestPreparable"])rt(e,t,"rankResult");return V(e.rankedOn,ln,"rankResult.rankedOn"),Array.isArray(e.ranked)||g("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&&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,n)=>te(t,`rankResult.runnersUp[${n}]`)),e.improvementBps!==null&&!(typeof e.improvementBps=="number"&&Number.isFinite(e.improvementBps))&&g("rankResult.improvementBps","must be a finite number or null"),ye(e.sourcesAnswered,"rankResult.sourcesAnswered"),ye(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,n)=>tt(t,`failed[${n}]`)),Array.isArray(e.excluded)||g("rankResult.excluded","must be an array"),e.excluded.forEach((t,n)=>tt(t,`excluded[${n}]`)),e.darkWindow!==null&&B(e.darkWindow,"rankResult.darkWindow"),V(e.instrumentMix,fn,"rankResult.instrumentMix"),te(e.bestPreparable,"rankResult.bestPreparable",!0),Object.hasOwn(e,"carry")&&e.carry!==null&&B(e.carry,"rankResult.carry"),e}var mn="arcus_perp",bn="robinhood-4663",yn="quote-only",ne="0.00000480324074074";function st(){return $().venues.arcus}function gn(){return Object.keys(st().markets).sort()}function hn({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=st().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:mn,chain:bn,instrument:"perp",tier:yn,symbolRaw:e,symbol:r,side:t,requestedSize:a,mark:o,fees:null,gasEstimate:null,priceImpact:null,fundingHourly:u,costAccounted:!1,capturedAt:$().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 gn().map(n=>hn({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ot=36e5,Br=24*365;function he(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=S(10000n,0);return E(E(e,r),s)}function it(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=kn(r,t),a=t-u,l=f(ne),c=he(o,a),p=he(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:q(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=he(o,t);return{model:"current-funding-held-constant",horizonHours:t,carryBps:i,carryBpsDisplay:q(i),confidence:"estimate",compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}function kn(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*ot)&&(n+=1);return t>r&&me(e+r*ot)&&(n+=t-r),n}function xn(e){return e.mid??e.mark??e.ask??e.bid??null}function wn(e){let t=xn(e);if(t===null)return null;let n=e.costAccounted===!0,r=f("0");e.fees!==null?r=M(r,e.fees):n=!1,e.priceImpact!==null?r=M(r,e.priceImpact):e.requestedSize&&e.requestedSize.mantissa>0n&&(n=!1),e.gasEstimate===null?n=!1:r=M(r,e.gasEstimate);let s;if(e.fees!==null&&U(e.fees,f("1"))<0&&U(e.fees,f("0"))>=0){let o=M(f("1"),e.fees);s=E(t,o),e.priceImpact!==null&&(s=M(s,E(t,e.priceImpact)))}else s=M(t,r);return{net:s,costAccounted:n,px:t}}function Sn(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 An(e,t){if(!e||!t||!e.costAccounted||!t.costAccounted||e.instrument!==t.instrument||e.net.mantissa===0n)return null;let n=X(t.net,e.net);return R(E(n,S(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=wn(x);if(A===null)continue;let O=null;if(l&&x.instrument==="perp"&&(O=it(x,a,{nowMs:n}),O.carryBps!==null)){let xt=M(f("1"),R(O.carryBps,S(10000n,0),12));A.net=E(A.net,xt),A.costAccounted=!1}c.push(Sn(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=U(x.net,A.net);return O!==0?O:x.venue<A.venue?-1:x.venue>A.venue?1:0});let b=p[0]??null,h=p.slice(1),F=p,z="gross";b&&b.costAccounted&&(h.length===0||h[0].costAccounted)&&(z="net-of-cost");let qe=h.length===0?null:An(b,h[0]),gt=c.find(x=>x.tier==="prepare")??null,ae=W(n),ht=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"},Re=null;l&&(Re=En(c));let kt={rankedOn:z,ranked:F,winner:b,runnersUp:h,improvementBps:qe===null?null:Number(q(qe)),sourcesAnswered:i,sourcesTried:r,failed:u,excluded:o,darkWindow:ht,instrumentMix:y,bestPreparable:gt,carry:b?.carry??null,breakEvenHorizonHours:Re};return ge(kt)}function En(e){let t=e.filter(o=>o.instrument==="spot").sort((o,i)=>U(o.net,i.net))[0],n=e.filter(o=>o.instrument==="perp").sort((o,i)=>U(o.net,i.net))[0];if(!t||!n||n.fundingHourly===null)return null;let r=X(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(q(o));return!Number.isFinite(i)||i<0?null:i}catch{return null}}var vn="rh_uniswap",$n=4663,On="prepare",qn=1n<<192n,H=18,Rn=Object.freeze({v3:180000n,v4:240000n});function xe(){return J()}function In(e){return{mantissa:e*e*10n**BigInt(H)/qn,scale:H}}function Tn(e){let t=In(BigInt(e.sqrtPriceX96)),n=e.quote==="USDG"?6:18,r=18;if(e.quoteIsToken0){let s=R(E(t,S(10n**BigInt(n),0)),S(10n**BigInt(r),0),H);return s.mantissa===0n?null:R(f("1"),s,H)}return R(E(t,S(10n**BigInt(r),0)),S(10n**BigInt(n),0),H)}function _n(e){let t=Fe(),n=t.assets[e];return n?S(n.rawPrice,t.oracleScaleExp):null}function Nn(e,t){if(e===null||t===null||e.mantissa<=0n||t.mantissa<=0n)return null;let n={...e};return R(t,Dn(n,t),H)}function Dn(e,t){let n=Math.max(e.scale,t.scale);return{mantissa:Q(e,n).mantissa+Q(t,n).mantissa,scale:n}}function Mn(e){let t=xe(),n=Rn[e];return n?{wei:BigInt(t.gasPriceWei)*n,units:n,native:"ETH"}:null}function we(){return Object.keys(xe().pools).sort()}function L({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=Tn(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(S(BigInt(s.feePpm),0),S(1000000n,0),8),l=u.mantissa===0n?f("0"):Nn(i,u),c=Mn(s.version),b={venue:vn,chain:$n,instrument:"spot",tier:On,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"]}},h=_n(e);return h!==null&&(b.referencePrice=h,b.referenceBasisBps=q(R(E(X(o,h),S(10000n,0)),h,4))),v(b)}function ut({side:e="buy",sizeUsd:t=null}={}){return we().map(n=>L({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var at=12e4,Un="0x0000000000000000000000000000000000000000",jn="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=L({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>at)throw new Error(`quote is stale (${u}ms old, bound ${at}ms); re-quote before preparing`);let l=J().pools[t],c=l.version==="v4"?jn:Un,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 Fn="hyperliquid_hip3",Pn="hyperliquid",Bn="quote-only";function Y(){return $().venues.hyperliquid_hip3}function ct(){return Object.keys(Y().dexs).sort()}function Cn(){let e=[];for(let[t,n]of Object.entries(Y().dexs))for(let r of Object.keys(n))e.push(`${t}:${r}`);return e.sort()}function Hn(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=Y().dexs[r]?.[s];return o?[{dex:r,ticker:s,market:o}]:[]}let n=[];for(let[r,s]of Object.entries(Y().dexs))Object.hasOwn(s,e)&&n.push({dex:r,ticker:e,market:s[e]});return n}function Ln(e,t){try{return Le().books[`${e}:${t}`]??null}catch{return null}}function zn(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(q(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 Qn(e,t,n,r){let s=zn(e,t,n);if(!s)return{impact:null,depth:null};let o=Number(q(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 lt({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=Ln(e,t),p=null,y=null,b="fees and gas not captured";if(l.mantissa>0n)if(c){let z=Qn(c,r,l,o);p=z.impact,y=z.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:Fn,chain:Pn,instrument:"perp",tier:Bn,symbolRaw:`${e}:${t}`,symbol:t,side:r,requestedSize:l,mark:o,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:i,costAccounted:!1,capturedAt:$().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 ft({symbol:e,side:t="buy",sizeUsd:n=null}={}){let r=Hn(e);return r.length===0||r.length>1?null:lt({...r[0],side:t,size:n})}function se({side:e="buy",sizeUsd:t=null,ticker:n=null}={}){let r=[];for(let s of Cn()){let[o,i]=s.split(":");if(n!==null&&i!==n)continue;let u=Y().dexs[o][i];r.push(lt({dex:o,ticker:i,market:u,side:e,size:t}))}return r}var Xn="arcus_spot",Wn="robinhood-4663",Vn="quote-only";function pt(){return $().venues.arcus_spot}function Yn(){return Object.keys(pt().pairs).sort()}function Kn({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=pt().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:Xn,chain:Wn,instrument:"spot",tier:Vn,symbolRaw:e,symbol:e,side:t,requestedSize:a,fees:l,gasEstimate:null,priceImpact:null,fundingHourly:null,costAccounted:!1,capturedAt:$().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 Yn().map(n=>Kn({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var Jn="solana_xstocks",Gn="solana",Zn="quote-only",dt=25e3;function ie(){return Ce()}function Ae(){return Object.keys(ie().tokens).sort()}function er(e){let t=ie().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function tr(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 Ee({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 h=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,h))r=h,s=o[h].symbolRaw;else return null}else return null;let i=o[r],u=er(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"):tr(l,c),y=!1;c.mantissa===0n&&(u.liquidityUsd??0)>=dt&&(y=!1);let b={venue:Jn,chain:Gn,instrument:"spot",tier:Zn,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)<dt}};return v(b)}function mt({side:e="buy",sizeUsd:t=null}={}){return Ae().map(n=>Ee({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var nr="ton_stonfi",rr="ton",sr="quote-only",or=25e3,ir=.01;function ue(){return He()}function ve(){return Object.keys(ue().tokens).sort()}function ur(e){let t=ue().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function ar(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 $e({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 h=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,h))r=h,s=o[h].symbolRaw;else return null}else{let h=e.toUpperCase();if(Object.hasOwn(o,h))r=h,s=o[h].symbolRaw;else return null}let i=o[r],u=ur(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"):ar(l,c),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:!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)<or,impactSizeFractionHint:ir}};return v(b)}function bt({side:e="buy",sizeUsd:t=null}={}){return ve().map(n=>$e({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var yt=3600*1e3;function Oe(e){return e==null||e===""?null:typeof e=="object"&&e&&typeof e.mantissa=="bigint"?e:f(String(e))}function cr(e,{sizeUsd:t=null}={}){if(typeof e!="string"||!e.trim())throw new TypeError("ticker is required");let n=e.trim().toUpperCase(),r=Oe(t),s=[],o=ft({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=L({symbol:n,sizeUsd:r});i&&s.push(i);let u=Ee({symbol:n,sizeUsd:r});u&&s.push(u);let a=$e({symbol:n,sizeUsd:r});return a&&s.push(a),s}function Fs(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase();if(!t)throw new Error("bestEquityRoute requires ticker");let n=Oe(e.sizeUsd??e.size??null),r=cr(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>yt}}function Ps(){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:Ae().length},{venue:"ton_stonfi",tier:"quote-only",chain:"ton",n:ve().length}],t=[...se(),...re(),...oe(),...ut(),...mt(),...bt()],n=(t[0]?.capturedAt??Date.now())+1e3,{survivors:r,excluded:s}=ee(t,{nowMs:n});return{inventory:e,hip3Dexs:ct(),liveness:{survivors:r.length,excluded:s.length,byReason:s.reduce((o,i)=>(o[i.reason]=(o[i.reason]??0)+1,o),{})},capturedAt:$().capturedAt,custody:"prepare-only",note:"quote-only venues are ranked for discovery; only rh_uniswap is preparable in v1"}}function Bs(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=Oe(e.sizeUsd??e.size??null),s=L({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>yt}}catch(o){return{ok:!1,failureKind:"prepare-refused",ticker:t,error:String(o.message||o)}}}function Cs(e){return JSON.parse(JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n))}export{Fs as bestEquityRoute,cr as collectEquityQuotes,Ps as equityVenues,zt as getUniverse,$ as getVenues,je as loadFixtures,Se as prepareEquity,Bs as prepareEquityRoute,ke as rankEquityQuotes,Cs as toJsonSafe,v as validateQuote,ge as validateRankResult};