@oracle-agent/oracle 0.20.0 → 0.20.2
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.
- package/dist/assets/equities-fixtures/bridge_routes.json +159 -0
- package/dist/assets/equities-fixtures/dst_transitions.json +29 -0
- package/dist/assets/equities-fixtures/equity_dex_pools.json +154 -0
- package/dist/assets/equities-fixtures/hip3_l2books.json +2711 -0
- package/dist/assets/equities-fixtures/nyse_holidays.json +1 -0
- package/dist/assets/equities-fixtures/oracles.json +100 -0
- package/dist/assets/equities-fixtures/rh_pool_state.json +244 -0
- package/dist/assets/equities-fixtures/solana_xstocks.json +704 -0
- package/dist/assets/equities-fixtures/ton_xstocks.json +35 -0
- package/dist/assets/equities-fixtures/universe.json +411 -0
- package/dist/assets/equities-fixtures/venues.json +3542 -0
- package/dist/bin/desk-server.mjs +2 -2
- package/dist/bin/oracle-data-mcp.mjs +7 -7
- package/dist/bin/oracle-equities.mjs +8 -8
- package/dist/bin/oracle-public-server.mjs +4 -4
- package/dist/cli/commands/sign.mjs +31 -19
- package/dist/data/desk-data.mjs +2 -2
- package/dist/equities/index.mjs +1 -1
- package/dist/index.mjs +15 -15
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{realpathSync as yt}from"node:fs";import{fileURLToPath as sr}from"node:url";var pr=Object.freeze({mantissa:10000n,scale:0});function F(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 F(t),Object.freeze({mantissa:e,scale:t})}function _(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`);F(e.scale)}function Y(e){return F(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(F(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){_(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 _(e),F(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){_(e,"left"),_(t,"right");let n=Math.max(e.scale,t.scale);return[Q(e,n),Q(t,n),n]}function D(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa+r.mantissa,s)}function W(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa-r.mantissa,s)}function E(e,t){_(e,"left"),_(t,"right");let n=e.scale+t.scale;return F(n),T(e.mantissa*t.mantissa,n)}function R(e,t,n=Math.max(e?.scale??0,t?.scale??0)){if(_(e,"left"),_(t,"right"),F(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 U(e,t){let[n,r]=ce(e,t);return n.mantissa<r.mantissa?-1:n.mantissa>r.mantissa?1:0}import{readFileSync as St}from"node:fs";import{fileURLToPath as $t}from"node:url";import{dirname as At,join as Te}from"node:path";var Et=Te(At($t(import.meta.url)),"fixtures"),Ne=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 vt(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){vt(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 N(e,t,n){Number.isSafeInteger(e)||d(t,`${n} must be a safe integer`)}function M(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 qt(e,t){k(e,t,"root"),N(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`),M(o[s],t,`venues.${r}.${s}`)}for(let[r,s]of Object.entries(e.venues.hyperliquid_hip3.dexs))M(s,t,`venues.hyperliquid_hip3.dexs.${r}`)}function Ot(e,t){M(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 Rt(e,t){k(e,t,"root");for(let n of["chainId","block","oracleScaleExp","usdgDecimals","equityDecimals"])N(e[n],t,n);m(e.usdg,t,"usdg"),M(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 It(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)=>N(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 Tt(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"])N(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 Nt(e,t){M(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 _t(e,t){k(e,t,"root"),N(e.capturedAt,t,"capturedAt"),N(e.block,t,"block"),N(e.chainId,t,"chainId"),m(e.gasPriceWei,t,"gasPriceWei"),m(e.stateView,t,"stateView"),M(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 Dt(e,t){k(e,t,"root"),N(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 Ut(e,t){k(e,t,"root"),N(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),M(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 Mt(e,t){k(e,t,"root"),N(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),e.chain!=="ton"&&d(t,'chain must be "ton"'),M(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 jt=Object.freeze({venues:qt,universe:Ot,oracles:Rt,nyseHolidays:It,dstTransitions:Tt,equityDexPools:Nt,rhPoolState:_t,solanaXstocks:Ut,tonXstocks:Mt,hip3L2Books:Dt});function Pt(e,t){let n=Ne[t],r=Te(e,n),s;try{s=St(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 jt[t](o,n),o}function _e(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))_e(t)}return e}function De({fixtureDir:e=Et}={}){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(Ne))t[n]=Pt(e,n);return _e(t)}var Ie;function j(){return Ie??=De(),Ie}function q(){return j().venues}function Ue(){return j().oracles}function Me(){return j().nyseHolidays}function je(){return j().dstTransitions}function J(){return j().rhPoolState}function Pe(){return j().solanaXstocks}function Fe(){return j().tonXstocks}function Be(){return j().hip3L2Books}var fe=1e3,ze=60*fe,pe=60*ze,Ce=24*pe,Ft=-5*pe,Bt=-4*pe,Le=240,Qe=570,We=960,Ve=1200,kr=Object.freeze([Le,Qe,We,Ve]),xr=Object.freeze(["core","extended","dark"]),He,le;function Ct(){let e=je().dstTransitions.map(r=>({year:r.year,startMs:r.startUtc*fe,endMs:r.endUtc*fe}));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 Xe(){return He??=Ct(),He}function Ht(){return le===void 0&&(le=new Set(Me().holidayDayIndex)),le}function Ke(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}=Xe();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 Lt(e){for(let t of Xe().rows)if(e>=t.startMs&&e<t.endMs)return!0;return!1}function Qt(e){return Lt(e)?Bt:Ft}function Wt(e){let t=e+Qt(e),n=Math.floor(t/Ce),r=t-n*Ce,s=new Date(t);return{dayIndex:n,minuteOfDay:Math.floor(r/ze),msIntoDay:r,weekday:s.getUTCDay()}}function Vt({dayIndex:e,weekday:t}){return t===0||t===6?!1:!Ht().has(e)}function Xt(e){return e<Le?"dark":e<Qe?"extended":e<We?"core":e<Ve?"extended":"dark"}function V(e){Ke(e,"sessionState"),zt(e,"sessionState");let t=Wt(e);return Vt(t)?Xt(t.minuteOfDay):"dark"}function de(e){return Ke(e,"isDark"),V(e)==="dark"}var G=Object.freeze({DORMANT_VENUE:"dormant-venue",CROSSED_BOOK:"crossed-book",STALE_QUOTE:"stale-quote",STALE_ORACLE:"stale-oracle"}),Kt=12e4,Yt=6e5;function Z(e,t){e.push(Object.freeze({venue:t.venue,symbol:t.symbol??null,reason:t.reason,evidence:t.evidence??null}))}function Jt(e){let t=e.raw?.vol24h;return!!(t===0||t===0||typeof t=="number"&&Number.isFinite(t)&&t<=0)}function Gt(e){return!e.bid||!e.ask?!1:U(e.bid,e.ask)>0}function Ye(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??Kt,s=t.oracleFreshnessMs??Yt,o=t.includeDormant===!0,i=[],u=[];for(let a of e){if(Jt(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(Gt(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(Ye(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=V(n),c=l==="core"?s:s*2;if(Ye(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 Zt(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(Zt(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 en=new Set(["spot","perp"]),tn=new Set(["read-only","quote-only","prepare","intent"]),nn=new Set(["buy","sell"]),rn=new Set(["net-of-cost","gross"]),sn=new Set(["homogeneous","heterogeneous"]),on=["bid","ask","mid","mark"],Je=["fees","gasEstimate","priceImpact","fundingHourly"],un=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function h(e,t){throw new TypeError(`${e} ${t}`)}function Ze(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function B(e,t){Ze(e)||h(t,"must be an object")}function et(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 X(e,t,n){t.has(e)||h(n,`must be one of ${[...t].join(", ")}`)}function be(e,t){(!Number.isSafeInteger(e)||e<0)&&h(t,"must be a nonnegative safe integer")}function me(e,t,n=!1){e===null&&n||(Ze(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 Ge(e,t){B(e,t),C(e.venue,`${t}.venue`),C(e.reason,`${t}.reason`),un.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",...Je,"costAccounted","capturedAt","blockOrSeq","raw"])et(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"),X(e.instrument,en,"quote.instrument"),X(e.tier,tn,"quote.tier"),C(e.symbolRaw,"quote.symbolRaw"),C(e.symbol,"quote.symbol"),X(e.side,nn,"quote.side"),me(e.requestedSize,"quote.requestedSize"),e.requestedSize.mantissa<0n&&h("quote.requestedSize","must not be negative");let t=0;for(let n of on)Object.hasOwn(e,n)&&(me(e[n],`quote.${n}`),t+=1);t===0&&h("quote","must contain at least one of bid, ask, mid, mark");for(let n of Je)me(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"),be(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 ye(e){B(e,"rankResult");for(let t of["rankedOn","ranked","winner","runnersUp","improvementBps","sourcesAnswered","sourcesTried","failed","excluded","darkWindow","instrumentMix","bestPreparable"])et(e,t,"rankResult");return X(e.rankedOn,rn,"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"),be(e.sourcesAnswered,"rankResult.sourcesAnswered"),be(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)=>Ge(t,`failed[${n}]`)),Array.isArray(e.excluded)||h("rankResult.excluded","must be an array"),e.excluded.forEach((t,n)=>Ge(t,`excluded[${n}]`)),e.darkWindow!==null&&B(e.darkWindow,"rankResult.darkWindow"),X(e.instrumentMix,sn,"rankResult.instrumentMix"),te(e.bestPreparable,"rankResult.bestPreparable",!0),Object.hasOwn(e,"carry")&&e.carry!==null&&B(e.carry,"rankResult.carry"),e}var an="arcus_perp",cn="robinhood-4663",ln="quote-only",ne="0.00000480324074074";function tt(){return q().venues.arcus}function fn(){return Object.keys(tt().markets).sort()}function pn({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=tt().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:an,chain:cn,instrument:"perp",tier:ln,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 fn().map(n=>pn({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var nt=36e5,jr=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=$(10000n,0);return E(E(e,r),s)}function rt(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=dn(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: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=he(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 dn(e,t){if(t<=0)return 0;let n=0,r=Math.floor(t);for(let s=0;s<r;s+=1)de(e+s*nt)&&(n+=1);return t>r&&de(e+r*nt)&&(n+=t-r),n}function mn(e){return e.mid??e.mark??e.ask??e.bid??null}function bn(e){let t=mn(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&&U(e.fees,f("1"))<0&&U(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 yn(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 hn(e,t){if(!e||!t||!e.costAccounted||!t.costAccounted||e.instrument!==t.instrument||e.net.mantissa===0n)return null;let n=W(t.net,e.net);return R(E(n,$(10000n,0)),t.net,4)}function ge(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=bn(x);if(A===null)continue;let O=null;if(l&&x.instrument==="perp"&&(O=rt(x,a,{nowMs:n}),O.carryBps!==null)){let wt=D(f("1"),R(O.carryBps,$(10000n,0),12));A.net=E(A.net,wt),A.costAccounted=!1}c.push(yn(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,g=p.slice(1),P=p,L="gross";b&&b.costAccounted&&(g.length===0||g[0].costAccounted)&&(L="net-of-cost");let Oe=g.length===0?null:hn(b,g[0]),gt=c.find(x=>x.tier==="prepare")??null,ae=V(n),kt=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=gn(c));let xt={rankedOn:L,ranked:P,winner:b,runnersUp:g,improvementBps:Oe===null?null:Number(S(Oe)),sourcesAnswered:i,sourcesTried:r,failed:u,excluded:o,darkWindow:kt,instrumentMix:y,bestPreparable:gt,carry:b?.carry??null,breakEvenHorizonHours:Re};return ye(xt)}function gn(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=W(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 kn="rh_uniswap",xn=4663,wn="prepare",Sn=1n<<192n,H=18,$n=Object.freeze({v3:180000n,v4:240000n});function ke(){return J()}function An(e){return{mantissa:e*e*10n**BigInt(H)/Sn,scale:H}}function En(e){let t=An(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 vn(e){let t=Ue(),n=t.assets[e];return n?$(n.rawPrice,t.oracleScaleExp):null}function qn(e,t){if(e===null||t===null||e.mantissa<=0n||t.mantissa<=0n)return null;let n={...e};return R(t,On(n,t),H)}function On(e,t){let n=Math.max(e.scale,t.scale);return{mantissa:Q(e,n).mantissa+Q(t,n).mantissa,scale:n}}function Rn(e){let t=ke(),n=$n[e];return n?{wei:BigInt(t.gasPriceWei)*n,units:n,native:"ETH"}:null}function xe(){return Object.keys(ke().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=ke(),s=r.pools[e];if(!s)return null;let o=En(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"):qn(i,u),c=Rn(s.version),b={venue:kn,chain:xn,instrument:"spot",tier:wn,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=vn(e);return g!==null&&(b.referencePrice=g,b.referenceBasisBps=S(R(E(W(o,g),$(10000n,0)),g,4))),v(b)}function st({side:e="buy",sizeUsd:t=null}={}){return xe().map(n=>z({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ot=12e4,In="0x0000000000000000000000000000000000000000",Tn="0x84b75b19A3cdf8E2F56d0507d22D442847B2053C";function we(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>ot)throw new Error(`quote is stale (${u}ms old, bound ${ot}ms); re-quote before preparing`);let l=J().pools[t],c=l.version==="v4"?Tn:In,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 Nn="hyperliquid_hip3",_n="hyperliquid",Dn="quote-only";function K(){return q().venues.hyperliquid_hip3}function it(){return Object.keys(K().dexs).sort()}function Un(){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 Mn(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 jn(e,t){try{return Be().books[`${e}:${t}`]??null}catch{return null}}function Pn(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 Fn(e,t,n,r){let s=Pn(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 ut({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=jn(e,t),p=null,y=null,b="fees and gas not captured";if(l.mantissa>0n)if(c){let L=Fn(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 P={venue:Nn,chain:_n,instrument:"perp",tier:Dn,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&&(P.raw.vol24hFixed=u),a!==null&&(P.raw.oiFixed=a),c?.bids?.[0]&&c?.asks?.[0]&&(P.bid=f(String(c.bids[0].px)),P.ask=f(String(c.asks[0].px))),v(P)}function at({symbol:e,side:t="buy",sizeUsd:n=null}={}){let r=Mn(e);return r.length===0||r.length>1?null:ut({...r[0],side:t,size:n})}function se({side:e="buy",sizeUsd:t=null,ticker:n=null}={}){let r=[];for(let s of Un()){let[o,i]=s.split(":");if(n!==null&&i!==n)continue;let u=K().dexs[o][i];r.push(ut({dex:o,ticker:i,market:u,side:e,size:t}))}return r}var Bn="arcus_spot",Cn="robinhood-4663",Hn="quote-only";function ct(){return q().venues.arcus_spot}function zn(){return Object.keys(ct().pairs).sort()}function Ln({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=ct().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:Bn,chain:Cn,instrument:"spot",tier:Hn,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=>Ln({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var Qn="solana_xstocks",Wn="solana",Vn="quote-only",lt=25e3;function ie(){return Pe()}function Se(){return Object.keys(ie().tokens).sort()}function Xn(e){let t=ie().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function Kn(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=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=Xn(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"):Kn(l,c),y=!1;c.mantissa===0n&&(u.liquidityUsd??0)>=lt&&(y=!1);let b={venue:Qn,chain:Wn,instrument:"spot",tier:Vn,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)<lt}};return v(b)}function ft({side:e="buy",sizeUsd:t=null}={}){return Se().map(n=>$e({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var Yn="ton_stonfi",Jn="ton",Gn="quote-only",Zn=25e3,er=.01;function ue(){return Fe()}function Ae(){return Object.keys(ue().tokens).sort()}function tr(e){let t=ue().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function nr(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=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=tr(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"):nr(l,c),b={venue:Yn,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:!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)<Zn,impactSizeFractionHint:er}};return v(b)}function pt({side:e="buy",sizeUsd:t=null}={}){return Ae().map(n=>Ee({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}function ve(e){return e==null||e===""?null:typeof e=="object"&&e&&typeof e.mantissa=="bigint"?e:f(String(e))}function rr(e,{sizeUsd:t=null}={}){if(typeof e!="string"||!e.trim())throw new TypeError("ticker is required");let n=e.trim().toUpperCase(),r=ve(t),s=[],o=at({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=$e({symbol:n,sizeUsd:r});u&&s.push(u);let a=Ee({symbol:n,sizeUsd:r});return a&&s.push(a),s}function dt(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase();if(!t)throw new Error("bestEquityRoute requires ticker");let n=ve(e.sizeUsd??e.size??null),r=rr(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=e.nowMs??r[0].capturedAt+1e3,o=ge(r,{nowMs:s,horizonHours:e.horizonHours!=null?Number(e.horizonHours):void 0,skipLiveness:e.skipLiveness===!0});return{ticker:t,...o}}function mt(){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:xe().length},{venue:"solana_xstocks",tier:"quote-only",chain:"solana",n:Se().length},{venue:"ton_stonfi",tier:"quote-only",chain:"ton",n:Ae().length}],t=[...se(),...re(),...oe(),...st(),...ft(),...pt()],n=(t[0]?.capturedAt??Date.now())+1e3,{survivors:r,excluded:s}=ee(t,{nowMs:n});return{inventory:e,hip3Dexs:it(),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 bt(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=ve(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=we({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 qe(e){return JSON.parse(JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n))}function ht(){return`oracle equities <command>
|
|
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>
|
|
3
3
|
|
|
4
4
|
Commands:
|
|
5
5
|
venues inventory + tiers + liveness snapshot
|
|
@@ -11,10 +11,10 @@ Options:
|
|
|
11
11
|
--horizon <hours> enable funding-adjusted heterogeneous ranking
|
|
12
12
|
--json machine readable output
|
|
13
13
|
--fixtures offline mode (default in v1)
|
|
14
|
-
`}function
|
|
15
|
-
`)}function
|
|
16
|
-
`)}function
|
|
17
|
-
`)}function
|
|
18
|
-
${
|
|
19
|
-
`),0}function
|
|
20
|
-
`),process.exit(1)}export{
|
|
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)+`
|
|
20
|
+
`),process.exit(1)}export{wr as main};
|