@oracle-agent/oracle 0.24.1 → 0.24.3
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/skills/chain/SKILL.md +34 -0
- package/dist/assets/skills/chain-defi-ecosystem-analysis/SKILL.md +181 -0
- package/dist/assets/skills/chain-ecosystem-gap-analysis/SKILL.md +162 -0
- package/dist/assets/skills/cross-chain-twap-execution/SKILL.md +125 -0
- package/dist/assets/skills/defi-protocol-pmf-assessment/SKILL.md +332 -0
- package/dist/assets/skills/evm-contract-research.md +8 -3
- package/dist/assets/skills/multi-venue-prepare-only-ranking/SKILL.md +93 -0
- package/dist/assets/skills/oracle-access-control/SKILL.md +71 -0
- package/dist/assets/skills/oracle-action-arming/SKILL.md +99 -0
- package/dist/assets/skills/oracle-airdrop-calculator/SKILL.md +111 -0
- package/dist/assets/skills/oracle-desk-product/SKILL.md +341 -0
- package/dist/assets/skills/oracle-evm/SKILL.md +55 -0
- package/dist/assets/skills/oracle-harness/SKILL.md +44 -0
- package/dist/assets/skills/oracle-mcp-install/SKILL.md +140 -0
- package/dist/assets/skills/oracle-multichain-convert/SKILL.md +87 -0
- package/dist/assets/skills/oracle-native-harness/SKILL.md +32 -0
- package/dist/assets/skills/oracle-ownership-gate/SKILL.md +42 -0
- package/dist/assets/skills/oracle-public-product-ux/SKILL.md +114 -0
- package/dist/assets/skills/oracle-tailscale/SKILL.md +32 -0
- package/dist/assets/skills/oracle-thin-client/SKILL.md +47 -0
- package/dist/assets/skills/perp-venue-funding-research/SKILL.md +161 -0
- package/dist/assets/skills/polymarket/SKILL.md +160 -0
- package/dist/assets/skills/protocol-api-key-integration/SKILL.md +141 -0
- package/dist/assets/skills/self-custodial-onchain-execution/SKILL.md +1284 -0
- package/dist/assets/skills/setup/SKILL.md +40 -0
- package/dist/assets/skills/stable-launch-ops/SKILL.md +89 -0
- package/dist/assets/skills/trade-loop-circuit-breaker/SKILL.md +441 -0
- package/dist/assets/skills/venue-capability-boundaries/SKILL.md +32 -0
- package/dist/bin/desk-server.mjs +16 -16
- package/dist/bin/oracle-data-mcp.mjs +1 -1
- package/dist/bin/oracle-equities.mjs +1 -1
- package/dist/bin/oracle-gateway.mjs +18 -15
- package/dist/bin/oracle-init.mjs +9 -9
- package/dist/cli/commands/bootstrap.mjs +1 -1
- package/dist/cli/commands/chat.mjs +86 -77
- package/dist/cli/commands/doctor.mjs +8 -6
- package/dist/cli/commands/eval.mjs +1 -1
- package/dist/cli/commands/harness.mjs +6 -6
- package/dist/cli/commands/model.mjs +87 -78
- package/dist/cli/commands/receipt.mjs +5 -0
- package/dist/cli/commands/setup.mjs +1 -1
- package/dist/cli/commands/venues.mjs +3 -0
- package/dist/cli/commands/watch.mjs +16 -0
- package/dist/equities/index.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/public/install.ps1 +102 -0
- package/public/install.sh +1 -1
- package/public/oracle-splash/downloads/index.html +2 -0
- package/public/oracle-splash/index.html +1 -0
- package/public/oracle-splash/install.ps1 +102 -0
- package/public/oracle-splash/install.sh +1 -1
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var h={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},L=new Map(Object.values(h).map(o=>[o.chainId,o]));function l(o){let n=o?.transactionHash||o?.hash||o?.txid||null;return n?{happened:!0,hash:String(n),note:null}:{happened:!1,hash:null,note:"no transaction hash \u2014 the action did not succeed"}}var S=new Set(["evm","evm-swap","evm-bridge","btc","sol"]),I=Object.freeze({swap:5,bridge:5,perps:0,nft:0});var T=Object.freeze([...S]);var q=Object.freeze({N:1<<17,r:8,p:1}),G=256*1024*1024,W=16*1024;import{homedir as f}from"node:os";import{join as d}from"node:path";var g=process.env.ORACLE_PUBLIC_DESKTOP==="1",x=g?process.env.ORACLE_CONFIG_DIR||d(f(),".config","oracle"):d(f(),".config","oracle"),K=g?x:d(f(),".config","mad-desk");var ee="0".repeat(64),re=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});var te=Promise.resolve();var Ne=Object.freeze([{type:"function",function:{name:"vault_status",description:"Read local Oracle vault/signer readiness. Never returns key material.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_status",description:"Ping the loopback signer. Fails closed if it is not running.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_execute",description:"Broadcast one already-confirmed local artifact. Requires a one-use confirmationNonce from the local signer TTY confirm. Cannot mint confirmation itself.",parameters:{type:"object",properties:{artifact:{type:"object"},confirmationNonce:{type:"string",minLength:32,maxLength:128}},required:["artifact","confirmationNonce"],additionalProperties:!1}}},{type:"function",function:{name:"signer_disarm",description:"Global kill switch. Stops the local signer from broadcasting.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"receipt_report",description:"Receipt or it did not happen. Requires transactionHash/hash/txid.",parameters:{type:"object",properties:{receipt:{type:"object"},transactionHash:{type:"string"},hash:{type:"string"},txid:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"watch_create",description:"Create an alert-only watch. Never execute.",parameters:{type:"object",properties:{chain:{type:"string"},token:{type:"string"},condition:{type:"string"},note:{type:"string"}},required:["chain","token","condition"],additionalProperties:!1}}},{type:"function",function:{name:"watch_list",description:"List local alert-only watches.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"portfolio_snapshot",description:"How to read the one portfolio snapshot. knownUsd is incomplete if a provider is missing.",parameters:{type:"object",properties:{},additionalProperties:!1}}}]);import p from"node:fs";import A from"node:os";import u from"node:path";import{fileURLToPath as _}from"node:url";var O=u.dirname(_(import.meta.url)),Be=u.resolve(O,"../..");function y(){return process.env.ORACLE_FAKE_HOME||A.homedir()}function b(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function m(){return b()?process.env.ORACLE_CONFIG_DIR||u.join(y(),".config","oracle"):u.join(y(),".config","oracle")}function R(){return u.join(m(),"desk.json")}function C(){return u.join(m(),"env")}function c({force:o=!1}={}){if(c._done&&!o)return c._result||null;c._done=!0;let n={},r=(t,e)=>{if(e==null)return;let i=String(e).trim();i&&(process.env[t]!=null&&String(process.env[t]).trim()!==""||(process.env[t]=i,n[t]=i))};try{let t=C();if(p.existsSync(t))for(let e of p.readFileSync(t,"utf8").split(/\r?\n/)){let i=e.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!i||i[2].startsWith("#"))continue;let a=i[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),r(i[1],a)}}catch{}try{let t=R();if(p.existsSync(t)){let e=JSON.parse(p.readFileSync(t,"utf8"));e&&typeof e=="object"&&(r("ORACLE_DESK_URL",e.deskUrl||e.dataUrl||e.url),r("ORACLE_DATA_URL",e.dataUrl||e.deskUrl||e.url),r("ORACLE_API_URL",e.apiUrl||e.dataUrl||e.deskUrl),r("ORACLE_PUBLIC_URL",e.publicUrl||e.deskUrl||e.dataUrl),r("ORACLE_EXEC_URL",e.execUrl),r("MAD_DESK_URL",e.deskUrl||e.dataUrl))}}catch{}let s=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return s&&(r("ORACLE_DESK_URL",s),r("ORACLE_DATA_URL",s),r("ORACLE_API_URL",s),r("ORACLE_PUBLIC_URL",s),r("MAD_DESK_URL",s)),c._result=Object.keys(n).length?n:null,c._result}try{c()}catch{}var er={name:"receipt",summary:"say whether an on-chain action happened (hash or it did not)",group:"read",usage:"oracle receipt --hash <txid> | oracle receipt --json '<receipt>'",async run(o){let n=o.argv||[],r={},s=n.indexOf("--hash"),t=n.indexOf("--json");if(s>=0)r={transactionHash:n[s+1]};else if(t>=0)try{r=JSON.parse(n[t+1]||"{}")}catch(i){return process.stderr.write(`receipt: bad json: ${i.message}
|
|
2
|
+
`),1}let e=l(r);return n.includes("--quiet")?process.stdout.write(`${JSON.stringify(e)}
|
|
3
|
+
`):e.happened?process.stdout.write(`happened ${e.hash}
|
|
4
|
+
`):process.stdout.write(`did not happen ${e.note}
|
|
5
|
+
`),e.happened?0:2}};export{er as default};
|
|
@@ -2,7 +2,7 @@ import{spawnSync as bt}from"node:child_process";import{stdin as O,stdout as be}f
|
|
|
2
2
|
`)+`
|
|
3
3
|
`}import S from"node:fs";import ze from"node:os";import ee from"node:path";import M from"node:fs";import De from"node:os";import A from"node:path";import{fileURLToPath as Me}from"node:url";var Ne=A.dirname(Me(import.meta.url)),Dt=A.resolve(Ne,"../..");function H(){return process.env.ORACLE_FAKE_HOME||De.homedir()}function Ke(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function k(){return Ke()?process.env.ORACLE_CONFIG_DIR||A.join(H(),".config","oracle"):A.join(H(),".config","oracle")}function Fe(){return A.join(k(),"desk.json")}function He(){return A.join(k(),"env")}function R({force:e=!1}={}){if(R._done&&!e)return R._result||null;R._done=!0;let t={},r=(n,s)=>{if(s==null)return;let i=String(s).trim();i&&(process.env[n]!=null&&String(process.env[n]).trim()!==""||(process.env[n]=i,t[n]=i))};try{let n=He();if(M.existsSync(n))for(let s of M.readFileSync(n,"utf8").split(/\r?\n/)){let i=s.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!i||i[2].startsWith("#"))continue;let a=i[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),r(i[1],a)}}catch{}try{let n=Fe();if(M.existsSync(n)){let s=JSON.parse(M.readFileSync(n,"utf8"));s&&typeof s=="object"&&(r("ORACLE_DESK_URL",s.deskUrl||s.dataUrl||s.url),r("ORACLE_DATA_URL",s.dataUrl||s.deskUrl||s.url),r("ORACLE_API_URL",s.apiUrl||s.dataUrl||s.deskUrl),r("ORACLE_PUBLIC_URL",s.publicUrl||s.deskUrl||s.dataUrl),r("ORACLE_EXEC_URL",s.execUrl),r("MAD_DESK_URL",s.deskUrl||s.dataUrl))}}catch{}let o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(r("ORACLE_DESK_URL",o),r("ORACLE_DATA_URL",o),r("ORACLE_API_URL",o),r("ORACLE_PUBLIC_URL",o),r("MAD_DESK_URL",o)),R._result=Object.keys(t).length?t:null,R._result}try{R()}catch{}function N(){return process.env.HERMES_HOME?A.resolve(process.env.HERMES_HOME):A.join(H(),".hermes")}function _(e){return M.mkdirSync(e,{recursive:!0}),e}var qe=/(TOKEN|SECRET|PASSWORD|KEY|AUTH|PRIVATE|MNEMONIC|SEED)/i;function z(e="oracle"){return ee.join(N(),"profiles",e,".env")}function Be(e){let t={};for(let r of String(e||"").split(/\r?\n/)){let o=r.trim();if(!o||o.startsWith("#"))continue;let n=o.indexOf("=");if(n<=0)continue;let s=o.slice(0,n).trim(),i=o.slice(n+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t[s]=i}return t}function We(e="oracle"){let t=z(e);return S.existsSync(t)?Be(S.readFileSync(t,"utf8")):{}}function ge(e,t,r){if(!t||qe.test(t)===!1&&/[^A-Z0-9_]/.test(t),!/^[A-Z][A-Z0-9_]*$/.test(t)){let f=new Error(`invalid env key '${t}'`);throw f.code="BAD_KEY",f}if(r==null||String(r).trim()===""){let f=new Error(`empty value for ${t}`);throw f.code="EMPTY",f}let o=z(e);_(ee.dirname(o));let n=S.existsSync(o)?S.readFileSync(o,"utf8"):"",s=n?n.split(/\r?\n/):[],i=[],a=!1,c=`${t}=${String(r)}`;for(let f of s)f.startsWith(`${t}=`)?(i.push(c),a=!0):(f.length||i.length)&&i.push(f);for(a||(i.length&&i[i.length-1]!==""&&i.push(""),i.push(c));i.length&&i[i.length-1]==="";)i.pop();i.push(""),S.writeFileSync(o,i.join(`
|
|
4
4
|
`),{mode:384});try{S.chmodSync(o,384)}catch{}return{path:o,key:t,set:!0}}function q(e="oracle"){let t=We(e),r={};for(let o of F()){if(!o.required.length){r[o.key]="manual";continue}let n=o.required.filter(s=>!String(t[s]||"").trim());r[o.key]=n.length?"unset":"ready"}return{profile:e,statuses:r,envPath:z(e)}}function B(e="oracle"){let{statuses:t}=q(e);return me({profile:e,statuses:t})}function ye(e,t,r,o={}){let n=D(t);if(!n){let i=new Error(`unknown platform '${t}'`);throw i.code="UNKNOWN_PLATFORM",i}if(!n.required.length){let i=new Error(`${n.key} uses hermes interactive setup (oracle setup messaging)`);throw i.code="NEEDS_INTERACTIVE",i}let s=n.required[0];ge(e,s,r);for(let[i,a]of Object.entries(o||{}))a!=null&&String(a).trim()&&ge(e,i,a);return{platform:n.key,set:n.required,profile:e,path:z(e)}}function Ve(){return ee.join(k(),"setup-state.json")}function W(e={}){_(k());let t=Ve(),r={};if(S.existsSync(t))try{r=JSON.parse(S.readFileSync(t,"utf8"))}catch{r={}}let o={...r,...e,updatedAt:new Date().toISOString(),host:ze.hostname()};return S.writeFileSync(t,JSON.stringify(o,null,2)+`
|
|
5
|
-
`,{mode:384}),o}import ve from"node:fs";import L from"node:path";var Je="0.19.0",Jt=`hermes-agent==${Je}`;var we="0.12.1",Gt=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${we}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${we}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function Ge(){return L.join(k(),"runtime")}function Ye(){return L.join(Ge(),"venv")}function Xe(e){let t=process.platform==="win32"?"Scripts":"bin",r=process.platform==="win32"?`${e}.exe`:e;return L.join(Ye(),t,r)}function Ze(){return Xe("hermes")}function Qe(e){let t=process.platform==="win32"&&!L.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let r of(process.env.PATH||"").split(L.delimiter))if(r)for(let o of t){let n=L.join(r,`${e}${o}`);try{if(ve.existsSync(n))return n}catch{}}return null}function ke(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=
|
|
5
|
+
`,{mode:384}),o}import ve from"node:fs";import L from"node:path";var Je="0.19.0",Jt=`hermes-agent==${Je}`;var we="0.12.1",Gt=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${we}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${we}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function Ge(){return L.join(k(),"runtime")}function Ye(){return L.join(Ge(),"venv")}function Xe(e){let t=process.platform==="win32"?"Scripts":"bin",r=process.platform==="win32"?`${e}.exe`:e;return L.join(Ye(),t,r)}function Ze(){return Xe("hermes")}function Qe(e){let t=process.platform==="win32"&&!L.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let r of(process.env.PATH||"").split(L.delimiter))if(r)for(let o of t){let n=L.join(r,`${e}${o}`);try{if(ve.existsSync(n))return n}catch{}}return null}function ke(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=Ze();if(ve.existsSync(e))return{ok:!0,bin:e,source:"managed"};let t=Qe("hermes");return t?{ok:!0,bin:t,source:"path"}:{ok:!1,bin:null,source:null}}import{createHash as et,randomBytes as oe,timingSafeEqual as tt}from"node:crypto";import w from"node:fs";import x from"node:path";import rt from"node:readline/promises";import{spawn as ot,spawnSync as nt}from"node:child_process";var I=Object.freeze({"anthropic-oauth":{aliases:["anthropic-oauth","anthropic","claude","claude-oauth"],clientId:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",authorizeUrl:"https://claude.ai/oauth/authorize",tokenUrl:"https://platform.claude.com/v1/oauth/token",redirectUri:"https://console.anthropic.com/oauth/code/callback",scope:"org:create_api_key user:profile user:inference",baseUrl:"https://api.anthropic.com/v1",model:"claude-sonnet-4-6",protocol:"anthropic-messages"},"openai-codex":{aliases:["openai-codex","openai-oauth","codex","codex-oauth"],clientId:"app_EMoamEEZ73f0CkXaXp7hrann",issuer:"https://auth.openai.com",tokenUrl:"https://auth.openai.com/oauth/token",baseUrl:"https://chatgpt.com/backend-api/codex",model:"gpt-5.6-sol",protocol:"responses"},"xai-oauth":{aliases:["xai-oauth","xai","grok","grok-oauth"],clientId:"b1a00492-073a-47ea-816f-4c329264a828",issuer:"https://auth.x.ai",discoveryUrl:"https://auth.x.ai/.well-known/openid-configuration",deviceUrl:"https://auth.x.ai/oauth2/device/code",scope:"openid profile email offline_access grok-cli:access api:access",baseUrl:"https://api.x.ai/v1",model:"grok-4.5",protocol:"responses"}}),st=12e4;function it(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function b(e){let t=String(e||"").trim().toLowerCase();for(let[r,o]of Object.entries(I))if(o.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function K(e){let t=b(e);return{id:t,...I[t]}}function g(e,t={}){if(!w.existsSync(e))return t;try{let r=JSON.parse(w.readFileSync(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid object");return r}catch{throw new Error(`credential store is unreadable or corrupt: ${x.basename(e)}`)}}function xe(e){_(e),process.platform!=="win32"&&w.chmodSync(e,448)}function E(e,t){xe(x.dirname(e));let r=`${e}.${process.pid}.${oe(4).toString("hex")}.tmp`;w.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
6
6
|
`,{mode:384}),w.renameSync(r,e),process.platform!=="win32"&&w.chmodSync(e,384)}function at(e){if(process.platform!=="linux")return!1;let t=e("secret-tool",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return!t.error&&t.status===0}function te(e){let t=String(e||"").trim().toLowerCase();if(!/^[a-z0-9][a-z0-9._-]*$/.test(t))throw new Error(`invalid API-key provider: ${e||"(empty)"}`);return t}function $(e={}){let t=String(e.accessToken||e.access_token||"").trim(),r=String(e.refreshToken||e.refresh_token||"").trim(),o=Number(e.expiresAt||e.expires_at||0);if(Number.isFinite(o)&&o>=1e9&&o<1e12&&(o=o*1e3),!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(o)?o:0,tokenType:String(e.tokenType||e.token_type||"Bearer"),source:String(e.source||"oracle"),...e.discovery?{discovery:e.discovery}:{},...e.scope?{scope:e.scope}:{},...e.idToken||e.id_token?{idToken:String(e.idToken||e.id_token)}:{}}}function ct(e={}){let t=e.file||x.join(k(),"oauth.json"),r=e.metadataFile||x.join(x.dirname(t),"oauth-meta.json"),o=e.linksFile||x.join(x.dirname(t),"oauth-links.json"),n=()=>typeof e.now=="function"?Number(e.now()):Date.now(),s=e.spawnFn||nt,i=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&at(s),a=i?"linux-secret-service":"private-file",c=`${t}.lock`;async function f(h){xe(x.dirname(c));let d;for(let u=0;u<400;u+=1)try{d=w.openSync(c,"wx",384);break}catch(l){if(l?.code!=="EEXIST")throw l;try{Date.now()-w.statSync(c).mtimeMs>3e5&&w.unlinkSync(c)}catch{}await new Promise(p=>setTimeout(p,25))}if(d===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await h()}finally{try{w.closeSync(d)}catch{}try{w.unlinkSync(c)}catch{}}}function y(h,d="oauth"){return["application","oracle","kind",d,"provider",h]}function j(h){if(!w.existsSync(o))return null;let u=g(o,{providers:{}}).providers?.[h];if(!Array.isArray(u))return null;let l=[];for(let p of u)if(x.isAbsolute(String(p||"")))try{let m=g(p,{});if(h==="anthropic-oauth"&&m.claudeAiOauth){let T=$(m.claudeAiOauth);l.push({...T,refreshToken:"",source:"external-access-only"});continue}let v=m.credential_pool&&typeof m.credential_pool=="object"?m.credential_pool:null;if(v){let T=v[h]||v[h.replace(/-oauth$/,"")]||[],Ue=Array.isArray(T)?T:T?[T]:[];for(let Z of Ue)if(!(!Z||typeof Z!="object"))try{let je=$(Z);l.push({...je,refreshToken:"",source:"external-access-only"})}catch{}}}catch{}return l.length?l.find(p=>!p.expiresAt||p.expiresAt>n()+st)||l[0]:null}function de(h){let d=b(h);if(i){let p=s("secret-tool",["lookup",...y(d)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!p.error&&p.status===0&&String(p.stdout||"").trim())try{return $(JSON.parse(String(p.stdout).trim()))}catch{}return j(d)}let l=g(t,{providers:{}}).providers?.[d];if(l)try{return $(l)}catch{}return j(d)}function Re(h,d){let u=b(h),l=$(d);if(i){let m=s("secret-tool",["store",`--label=Oracle ${u} OAuth`,...y(u)],{input:JSON.stringify(l),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected OAuth credential");let v=g(r,{providers:{}});return v.providers||={},v.providers[u]={expiresAt:l.expiresAt,source:l.source},E(r,v),l}let p=g(t,{providers:{}});return p.providers||={},p.providers[u]=l,E(t,p),l}function Le(h){let d=b(h);if(i){let p=s("secret-tool",["clear",...y(d)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=g(r,{providers:{}});return m.providers&&delete m.providers[d],E(r,m),!p.error&&p.status===0}let u=g(t,{providers:{}}),l=!!u.providers?.[d];return u.providers&&delete u.providers[d],E(t,u),l}function fe(h){let d=te(h);if(i){let u=s("secret-tool",["lookup",...y(d,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return u.error||u.status!==0?"":String(u.stdout||"").trim()}return String(g(t,{apiKeys:{}}).apiKeys?.[d]||"").trim()}function $e(h,d){let u=te(h),l=String(d||"").trim();if(!l)throw new Error("API key is empty");if(i){let m=s("secret-tool",["store",`--label=Oracle ${u} API key`,...y(u,"api-key")],{input:l,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected API key");let v=g(r,{providers:{},apiKeys:{}});return v.apiKeys||={},v.apiKeys[u]={configured:!0},E(r,v),!0}let p=g(t,{providers:{},apiKeys:{}});return p.apiKeys||={},p.apiKeys[u]=l,E(t,p),!0}function Ie(h){let d=te(h);if(i){let p=s("secret-tool",["clear",...y(d,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=g(r,{providers:{},apiKeys:{}});return m.apiKeys&&delete m.apiKeys[d],E(r,m),!p.error&&p.status===0}let u=g(t,{providers:{},apiKeys:{}}),l=!!u.apiKeys?.[d];return u.apiKeys&&delete u.apiKeys[d],E(t,u),l}function Ce(){let h={},d={};if(i){let u=g(r,{providers:{},apiKeys:{}});for(let[l,p]of Object.entries(u.providers||{}))h[l]={loggedIn:!!de(l),expiresAt:Number(p.expiresAt||0),source:String(p.source||"oracle"),storage:a};for(let l of Object.keys(u.apiKeys||{}))d[l]={configured:!!fe(l),storage:a}}else{let u=g(t,{providers:{},apiKeys:{}});for(let[l,p]of Object.entries(u.providers||{}))h[l]={loggedIn:!!p?.accessToken,expiresAt:Number(p?.expiresAt||0),source:String(p?.source||"oracle"),storage:a};for(let[l,p]of Object.entries(u.apiKeys||{}))d[l]={configured:!!p,storage:a}}for(let u of Object.keys(I)){if(h[u])continue;let l=j(u);l&&(h[u]={loggedIn:!0,expiresAt:l.expiresAt,source:l.source,storage:"external-access-source"})}return{storage:a,providers:h,apiKeys:d}}return Object.freeze({file:t,storage:a,get:de,set:Re,remove:Le,getApiKey:fe,setApiKey:$e,removeApiKey:Ie,status:Ce,withLock:f})}var Se;function C(){return Se||=ct(),Se}function re(e){return Buffer.from(e).toString("base64url")}function ut(){let e=re(oe(32));return{verifier:e,challenge:re(et("sha256").update(e).digest()),state:re(oe(24))}}function lt(e,t){let r=Buffer.from(String(e||"")),o=Buffer.from(String(t||""));return r.length===o.length&&tt(r,o)}function pt(e){let t=String(e),r=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd.exe",["/d","/s","/c","start","",t]]:["xdg-open",[t]];try{return ot(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function ne(e){return new URLSearchParams(e).toString()}async function P(e,t){if(!e?.ok){let o="";try{o=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${o?`, ${o}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function dt(e){if(e)return String(await e()).trim();let t=rt.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function se(e,t={}){let r=String(e.access_token||"").trim(),o=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let n=Number(e.expires_in||3600);return $({accessToken:r,refreshToken:o,expiresAt:it(t)+Math.max(1,n)*1e3,tokenType:e.token_type||"Bearer",idToken:e.id_token,source:"oracle",...t.discovery?{discovery:t.discovery}:{},...e.scope?{scope:e.scope}:{}})}async function ft(e){let t=I["anthropic-oauth"],r=e.pkce||ut(),o=new URLSearchParams({code:"true",client_id:t.clientId,response_type:"code",redirect_uri:t.redirectUri,scope:t.scope,code_challenge:r.challenge,code_challenge_method:"S256",state:r.state}),n=`${t.authorizeUrl}?${o}`;e.output(`Open: ${n}`),e.openFn(n);let s=await dt(e.inputFn),[i,a]=s.split("#",2);if(!i||!lt(a,r.state))throw new Error("Claude OAuth state mismatch");let c=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/json","user-agent":"axios/1.7.9"},body:JSON.stringify({grant_type:"authorization_code",client_id:t.clientId,code:i,state:a,redirect_uri:t.redirectUri,code_verifier:r.verifier})});return se(await P(c,"Claude OAuth token exchange"),e)}async function ht(e){let t=I["openai-codex"],r=await P(await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:t.clientId})}),"Codex device authorization");if(!r.user_code||!r.device_auth_id)throw new Error("Codex device authorization returned incomplete data");let o=`${t.issuer}/codex/device`;e.output(`Open: ${o}`),e.output(`Code: ${r.user_code}`),e.openFn(o);let n=Math.max(3,Number(r.interval||5)),s;for(let a=0;a<Math.ceil(900/n);a+=1){await e.sleepFn(n*1e3);let c=await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_auth_id:r.device_auth_id,user_code:r.user_code})});if(c.ok){s=await P(c,"Codex device authorization");break}if(![403,404].includes(c.status))throw new Error(`Codex device authorization failed (HTTP ${c.status})`)}if(!s)throw new Error("Codex device authorization timed out");let i=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:ne({grant_type:"authorization_code",code:s.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:s.code_verifier})});return se(await P(i,"Codex OAuth token exchange"),e)}function V(e){let t=new URL(String(e)),r=t.hostname.toLowerCase();if(t.protocol!=="https:"||r!=="x.ai"&&!r.endsWith(".x.ai"))throw new Error("xAI OAuth discovery returned an untrusted endpoint");return t.toString()}async function mt(e){let t=I["xai-oauth"],r=await P(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");V(r.authorization_endpoint);let o=V(r.token_endpoint),n=await P(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:ne({client_id:t.clientId,scope:t.scope})}),"xAI device authorization");if(!n.device_code||!n.user_code||!n.verification_uri)throw new Error("xAI device authorization returned incomplete data");let s=V(n.verification_uri_complete||n.verification_uri);e.output(`Open: ${s}`),e.output(`Code: ${n.user_code}`),e.openFn(s);let i=Math.max(1,Number(n.interval||5)),a=Math.ceil(Math.max(1,Number(n.expires_in||600))/i);for(let c=0;c<a;c+=1){let f=await e.fetchFn(o,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:ne({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:n.device_code})});if(f.ok){let j=await P(f,"xAI OAuth token exchange");return se(j,{...e,discovery:{authorization_endpoint:V(r.authorization_endpoint),token_endpoint:o}})}let y="";try{y=String((await f.json())?.error||"")}catch{}if(y==="slow_down")await e.sleepFn((i+1)*1e3);else if(y==="authorization_pending")await e.sleepFn(i*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${f.status}${y?`, ${y}`:""})`)}throw new Error("xAI device authorization timed out")}async function Ae(e,t={}){let r=b(e),o={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(n=>new Promise(s=>setTimeout(s,n))),openFn:t.openFn||pt,output:t.output||(n=>process.stdout.write(`${n}
|
|
7
7
|
`)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?ft(o):r==="openai-codex"?ht(o):mt(o)}import Y from"node:fs";import ie from"node:path";var gt=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","custom","anthropic-oauth","openai-codex","xai-oauth"]);function J(e){return String(e||"").trim()||void 0}function yt(e,{required:t=!1}={}){let r=J(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!gt.has(r))throw new Error(`unsupported provider: ${r}`);return r}function wt(e,{required:t=!1}={}){let r=J(e);if(!r){if(t)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function vt(e){let t=J(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(t)}catch{throw new Error("invalid custom base URL")}let o=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),n=o==="localhost"||o==="127.0.0.1"||o==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function G({provider:e,model:t,baseUrl:r}={},{requireModel:o=!1}={}){let n=yt(e),s=wt(t,{required:o});if(n==="custom")return{provider:n,...s?{model:s}:{},baseUrl:vt(r)};if(J(r))throw new Error("baseUrl is only supported for the custom provider");return{...n?{provider:n}:{},...s?{model:s}:{}}}var kt=new Set(["auto","standalone","hermes","remote","arch"]);function St(){return ie.join(k(),"model.json")}function U(e){return String(e||"").trim()||void 0}function xt(e={}){let t=U(e.backend)?.toLowerCase()||"auto",r=G({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),o=U(e.apiKeyEnv),n=Number.parseInt(String(e.contextLength||""),10),s=U(e.reasoningEffort),i=U(e.computeHost||e.remoteHost),a=U(e.computeUser||e.remoteUser),c=U(e.computePath||e.remotePath);if(!kt.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))throw new Error("api key env must be an uppercase environment variable name");if(t==="remote"&&!i)throw new Error("remote backend requires computeHost");return{backend:t,...r,...o?{apiKeyEnv:o}:{},...Number.isFinite(n)&&n>0?{contextLength:n}:{},...s?{reasoningEffort:s}:{},...i?{computeHost:i}:{},...a?{computeUser:a}:{},...c?{computePath:c}:{}}}function _e(e){let t=xt(e),r=St();_(ie.dirname(r)),process.platform!=="win32"&&Y.chmodSync(ie.dirname(r),448);let o=`${r}.${process.pid}.tmp`;return Y.writeFileSync(o,`${JSON.stringify(t,null,2)}
|
|
8
8
|
`,{mode:384}),Y.renameSync(o,r),process.platform!=="win32"&&Y.chmodSync(r,384),t}var Ee=Object.freeze({openrouter:{model:"openrouter/auto"},openai:{model:"gpt-4.1-mini"},anthropic:{model:"claude-sonnet-4-6"},xai:{model:"grok-4.5"},deepseek:{model:"deepseek-chat"},gemini:{model:"gemini-2.5-flash"},kimi:{model:"kimi-k3"},mistral:{model:"mistral-large-latest"},custom:{model:""}});function ae(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function At(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function _t(e="API key: "){if(!process.stdin.isTTY||!process.stdin.setRawMode)throw new Error("non-interactive API-key input requires --stdin");return process.stdout.write(e),new Promise((t,r)=>{let o="",n=()=>{process.stdin.off("data",s),process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var E={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},oe=new Map(Object.values(E).map(e=>[e.chainId,e]));import m from"node:fs";import C from"node:path";import{homedir as M}from"node:os";function x(e){let n=e?.transactionHash||e?.hash||e?.txid||null;return n?{happened:!0,hash:String(n),note:null}:{happened:!1,hash:null,note:"no transaction hash \u2014 the action did not succeed"}}import l from"node:path";var U=new Set(["evm","evm-swap","evm-bridge","btc","sol"]),ce=Object.freeze({swap:5,bridge:5,perps:0,nft:0});var ue=Object.freeze([...U]);var ye=Object.freeze({N:1<<17,r:8,p:1}),Se=256*1024*1024,Ee=16*1024;import{homedir as v}from"node:os";import{join as A}from"node:path";var O=process.env.ORACLE_PUBLIC_DESKTOP==="1",D=O?process.env.ORACLE_CONFIG_DIR||A(v(),".config","oracle"):A(v(),".config","oracle"),_e=O?D:A(v(),".config","mad-desk");var ke="0".repeat(64),Le=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});var Pe=Promise.resolve();function R(e){return{vault:l.join(e,"vault.json"),policy:l.join(e,"signer-policy.json"),policyKey:l.join(e,"policy-integrity-key"),ledger:l.join(e,"signer-ledger.json"),token:l.join(e,"signer-token"),lock:l.join(e,"signer.lock")}}function $(){return process.env.ORACLE_CONFIG_DIR||C.join(M(),".config","oracle")}function h(){let e=R(C.join($(),"signer"));return{vaultExists:m.existsSync(e.vault),policyConfigured:m.existsSync(e.policy),armed:m.existsSync(e.vault)&&!m.existsSync(e.lock),disarmed:m.existsSync(e.lock),note:"Keys stay on this machine. Exact confirmation is required before any broadcast."}}var lr=Object.freeze([{type:"function",function:{name:"vault_status",description:"Read local Oracle vault/signer readiness. Never returns key material.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_status",description:"Ping the loopback signer. Fails closed if it is not running.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_execute",description:"Broadcast one already-confirmed local artifact. Requires a one-use confirmationNonce from the local signer TTY confirm. Cannot mint confirmation itself.",parameters:{type:"object",properties:{artifact:{type:"object"},confirmationNonce:{type:"string",minLength:32,maxLength:128}},required:["artifact","confirmationNonce"],additionalProperties:!1}}},{type:"function",function:{name:"signer_disarm",description:"Global kill switch. Stops the local signer from broadcasting.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"receipt_report",description:"Receipt or it did not happen. Requires transactionHash/hash/txid.",parameters:{type:"object",properties:{receipt:{type:"object"},transactionHash:{type:"string"},hash:{type:"string"},txid:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"watch_create",description:"Create an alert-only watch. Never execute.",parameters:{type:"object",properties:{chain:{type:"string"},token:{type:"string"},condition:{type:"string"},note:{type:"string"}},required:["chain","token","condition"],additionalProperties:!1}}},{type:"function",function:{name:"watch_list",description:"List local alert-only watches.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"portfolio_snapshot",description:"How to read the one portfolio snapshot. knownUsd is incomplete if a provider is missing.",parameters:{type:"object",properties:{},additionalProperties:!1}}}]);import P from"node:fs";import Z from"node:path";import g from"node:fs";import F from"node:os";import f from"node:path";import{fileURLToPath as H}from"node:url";var q=f.dirname(H(import.meta.url)),gr=f.resolve(q,"../..");function k(){return process.env.ORACLE_FAKE_HOME||F.homedir()}function G(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function w(){return G()?process.env.ORACLE_CONFIG_DIR||f.join(k(),".config","oracle"):f.join(k(),".config","oracle")}function W(){return f.join(w(),"desk.json")}function J(){return f.join(w(),"env")}function p({force:e=!1}={}){if(p._done&&!e)return p._result||null;p._done=!0;let n={},r=(i,t)=>{if(t==null)return;let s=String(t).trim();s&&(process.env[i]!=null&&String(process.env[i]).trim()!==""||(process.env[i]=s,n[i]=s))};try{let i=J();if(g.existsSync(i))for(let t of g.readFileSync(i,"utf8").split(/\r?\n/)){let s=t.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let a=s[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),r(s[1],a)}}catch{}try{let i=W();if(g.existsSync(i)){let t=JSON.parse(g.readFileSync(i,"utf8"));t&&typeof t=="object"&&(r("ORACLE_DESK_URL",t.deskUrl||t.dataUrl||t.url),r("ORACLE_DATA_URL",t.dataUrl||t.deskUrl||t.url),r("ORACLE_API_URL",t.apiUrl||t.dataUrl||t.deskUrl),r("ORACLE_PUBLIC_URL",t.publicUrl||t.deskUrl||t.dataUrl),r("ORACLE_EXEC_URL",t.execUrl),r("MAD_DESK_URL",t.deskUrl||t.dataUrl))}}catch{}let o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(r("ORACLE_DESK_URL",o),r("ORACLE_DATA_URL",o),r("ORACLE_API_URL",o),r("ORACLE_PUBLIC_URL",o),r("MAD_DESK_URL",o)),p._result=Object.keys(n).length?n:null,p._result}try{p()}catch{}var z=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","custom","anthropic-oauth","openai-codex","xai-oauth"]);function y(e){return String(e||"").trim()||void 0}function V(e,{required:n=!1}={}){let r=y(e)?.toLowerCase();if(!r){if(n)throw new Error("model provider is required");return}if(!z.has(r))throw new Error(`unsupported provider: ${r}`);return r}function K(e,{required:n=!1}={}){let r=y(e);if(!r){if(n)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function Y(e){let n=y(e);if(!n||n.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(n)}catch{throw new Error("invalid custom base URL")}let o=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),i=o==="localhost"||o==="127.0.0.1"||o==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&i)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function L({provider:e,model:n,baseUrl:r}={},{requireModel:o=!1}={}){let i=V(e),t=K(n,{required:o});if(i==="custom")return{provider:i,...t?{model:t}:{},baseUrl:Y(r)};if(y(r))throw new Error("baseUrl is only supported for the custom provider");return{...i?{provider:i}:{},...t?{model:t}:{}}}var X=new Set(["auto","standalone","hermes","remote","arch"]);function Q(){return Z.join(w(),"model.json")}function d(e){return String(e||"").trim()||void 0}function ee(e={}){let n=d(e.backend)?.toLowerCase()||"auto",r=L({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:n==="standalone"}),o=d(e.apiKeyEnv),i=Number.parseInt(String(e.contextLength||""),10),t=d(e.reasoningEffort),s=d(e.computeHost||e.remoteHost),a=d(e.computeUser||e.remoteUser),c=d(e.computePath||e.remotePath);if(!X.has(n))throw new Error(`unsupported backend: ${n}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(n))throw new Error("remote compute backends are disabled in the public desktop");if(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))throw new Error("api key env must be an uppercase environment variable name");if(n==="remote"&&!s)throw new Error("remote backend requires computeHost");return{backend:n,...r,...o?{apiKeyEnv:o}:{},...Number.isFinite(i)&&i>0?{contextLength:i}:{},...t?{reasoningEffort:t}:{},...s?{computeHost:s}:{},...a?{computeUser:a}:{},...c?{computePath:c}:{}}}function I(){let e=Q();if(!P.existsSync(e))return null;try{return ee(JSON.parse(P.readFileSync(e,"utf8")))}catch{return null}}var re=new Set(["127.0.0.1","::1","localhost"]);function _({env:e=process.env,vault:n=null}={}){let r=n||h(),o=[];for(let[i,t]of Object.entries(E)){let s=(t.rpcEnv||[]).some(c=>String(e[c]||"").trim()),a="prepare";t.evm?s&&(a="live"):a="unavailable",o.push({key:i,chainId:t.chainId,name:t.name,family:"evm",status:a,execute:!!(r.vaultExists&&r.armed&&!r.disarmed),note:s?"rpc configured":"public read/prepare; set RPC for live reads"})}return o.push({key:"solana",chainId:null,name:"Solana",family:"sol",status:"prepare",execute:!1,note:"Jupiter quote/prepare; local sol signer"},{key:"bitcoin",chainId:null,name:"Bitcoin",family:"btc",status:"prepare",execute:!1,note:"Esplora read; local btc signer"},{key:"hyperliquid-l1",chainId:null,name:"Hyperliquid L1",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not an EVM signer family"},{key:"polymarket",chainId:null,name:"Polymarket",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not a signer family"}),o}function te({env:e=process.env,model:n=I(),vault:r=h(),signerReachable:o=!1,quote:i=null}={}){let t=[],s=(u,S,N,T=null)=>t.push({id:u,status:S,detail:N,fix:T}),a=(()=>{let[u,S]=process.versions.node.split(".").map(Number);return u>20||u===20&&S>=19})();s("node",a?"ok":"fail",`node ${process.versions.node}`,a?null:"install node >= 20.19"),n?n.backend==="hermes"?s("model","warn","backend=hermes (opt-in attach)","oracle model --backend standalone"):s("model","ok",`${n.backend||"auto"} ${n.provider||""} ${n.model||""}`.trim()):s("model","fail","no model.json","oracle setup model"),r.vaultExists?r.disarmed?s("vault","warn","vault present, DISARMED","oracle signer (re-arm after confirm)"):s("vault",r.armed?"ok":"warn",r.armed?"present, armed":"present, not armed"):s("vault","fail","no local vault","oracle sign init");let c=e.ORACLE_SIGNER_HOST||"127.0.0.1";return re.has(c)?s("signer",o?"ok":"warn",o?`loopback ${c}:${e.ORACLE_SIGNER_PORT||9462}`:"loopback signer not reachable",o?null:"oracle signer"):s("signer","fail",`signer host ${c} is not loopback`,"unset ORACLE_SIGNER_HOST"),i?i.ok?s("quote","ok",i.detail||"net quote returned"):s("quote","warn",i.detail||"quote unavailable","check network / oracle data serve"):s("quote","warn","quote not probed",null),{ok:!t.some(u=>u.status==="fail"),checks:t,venues:_({env:e,vault:r})}}async function Ir(e=process.env){let n=e.ORACLE_SIGNER_HOST||"127.0.0.1",r=e.ORACLE_SIGNER_PORT||9462;try{return(await fetch(`http://${n}:${r}/status`,{signal:AbortSignal.timeout(1500)})).ok}catch{return!1}}async function Nr(){try{let e=await fetch("https://api.dexscreener.com/latest/dex/search?q=WETH%20USDC",{signal:AbortSignal.timeout(4e3)});if(!e.ok)return{ok:!1,detail:`dexscreener ${e.status}`};let r=(await e.json())?.pairs?.[0];return!r?.chainId||!r?.priceUsd?{ok:!1,detail:"no pair"}:{ok:!0,detail:`${r.chainId} ${r.baseToken?.symbol}/${r.quoteToken?.symbol} $${r.priceUsd}`}}catch(e){return{ok:!1,detail:e instanceof Error?e.message:"quote failed"}}}var Tr={name:"venues",summary:"label every shipped venue live / prepare / unavailable",group:"read",usage:"oracle venues [--json]",async run(e){let n=e.argv.includes("--json"),r=_();if(n)return process.stdout.write(`${JSON.stringify({venues:r},null,2)}
|
|
2
|
+
`),0;for(let o of r)process.stdout.write(`${o.status.padEnd(12)} ${o.key.padEnd(16)} ${o.name} exec=${o.execute?"local":"no"}
|
|
3
|
+
`);return 0}};export{x as classifyReceipt,Tr as default,te as firstHourReport,Nr as probeQuote,Ir as probeSigner,h as vaultStatus};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import c from"node:fs";import i from"node:path";import{randomUUID as y}from"node:crypto";import{homedir as S}from"node:os";function g(n=process.env){return n.ORACLE_CONFIG_DIR||i.join(S(),".config","oracle")}function h(n=process.env){return i.join(g(n),"watches.json")}function a(n=process.env){let e=h(n);if(!c.existsSync(e))return{watches:[]};try{let t=JSON.parse(c.readFileSync(e,"utf8"));return{watches:Array.isArray(t.watches)?t.watches:[]}}catch{return{watches:[]}}}function l(n,e=process.env){let t=h(e);c.mkdirSync(i.dirname(t),{recursive:!0,mode:448});let r=`${t}.${process.pid}.tmp`;c.writeFileSync(r,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,{mode:384}),c.renameSync(r,t)}function f(n=process.env){return a(n).watches}function w({chain:n,token:e,condition:t,note:r}={},o=process.env){if(!n||!e||!t)throw new Error("watch requires chain, token, condition");let d={id:y(),chain:String(n),token:String(e),condition:String(t),note:r?String(r):null,actionMode:"alert_only",createdAt:new Date().toISOString()},u=a(o);return u.watches.push(d),l(u,o),d}function p(n,e=process.env){let t=a(e),r=t.watches.filter(o=>o.id!==n);return r.length===t.watches.length?!1:(l({watches:r},e),!0)}var m=`oracle watch <list|add|rm> ...
|
|
3
|
+
|
|
4
|
+
oracle watch list
|
|
5
|
+
oracle watch add --chain base --token WETH --condition "price < 2000"
|
|
6
|
+
oracle watch rm <id>
|
|
7
|
+
|
|
8
|
+
Always alert_only. No execute. Arm is a separate exact action.
|
|
9
|
+
`;function s(n,e){let t=n.indexOf(e);return t>=0?n[t+1]:void 0}var W={name:"watch",summary:"alert-only price/token watches (never execute)",group:"read",usage:m,async run(n){let e=n.argv||[],t=e[0]||"list";if(t==="list"||t==="--json"){let r=f();if(e.includes("--json")||t==="--json")process.stdout.write(`${JSON.stringify({watches:r},null,2)}
|
|
10
|
+
`);else if(!r.length)process.stdout.write(`no watches
|
|
11
|
+
`);else for(let o of r)process.stdout.write(`${o.id} ${o.chain} ${o.token} ${o.condition} ${o.actionMode}
|
|
12
|
+
`);return 0}if(t==="add"){let r=w({chain:s(e,"--chain"),token:s(e,"--token"),condition:s(e,"--condition"),note:s(e,"--note")});return process.stdout.write(`${r.id} alert_only ${r.chain} ${r.token} ${r.condition}
|
|
13
|
+
`),0}if(t==="rm"||t==="remove"){let r=e[1];if(!r)return process.stderr.write(`watch rm <id>
|
|
14
|
+
`),1;let o=p(r);return process.stdout.write(o?`removed
|
|
15
|
+
`:`not found
|
|
16
|
+
`),o?0:1}return process.stderr.write(m),1}};export{W as default};
|
package/dist/equities/index.mjs
CHANGED
|
@@ -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 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};
|
|
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,e);return Te(r)?r:le(n,"dist","assets",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};
|