Integrate
JavaScript SDK
Read prices, venue reports, books, funding and node reports from the web proxy, in a browser or in Node.js.
@markoutlabs/oracle is a client for the web proxy. It runs in a browser and in Node.js 22 or newer. The live prices and the carry board of this site use it.
It reconnects with backoff, sends your subscriptions again after each reconnect, keeps each order book up to date, and keeps every decimal as an exact string.
1. Install
The package is not on npm yet. Copy packages/oracle-js from the docs repository into your project as a workspace package. It depends on partysocket and big.js.
2. Connect and read prices
import { OracleClient, fetchCatalog } from '@markoutlabs/oracle';
const url = 'wss://feeds.markoutlabs.com/v1/ws';
const oracle = new OracleClient({ url });
// Everything the proxy serves, or name the feeds you want.
const catalog = await fetchCatalog(url);
oracle.subscribe({ prices: catalog.prices });
oracle.on('price', (price) => {
if (price.status === 'halted') return; // Never act on a halted price.
console.log(price.symbol, price.price, '±', price.conf, price.status);
});Rules that keep you safe:
- Read
statuson every message. Useokanddegradedprices, and size your risk fromconf. Ahaltedprice has no value. - Keep
price,confandspread_bpsas strings. For maths, usebig.jsor another decimal library. publish_time_nsis nanoseconds as a string.nsToDateandageMsread it without a loss of precision.
subscribe and unsubscribe change the wanted set. Call oracle.close() to stop for good.
3. Show the link state
oracle.on('status', (status) => console.log(status)); // connecting, open, reconnecting, closedAfter a reconnect, the proxy sends the latest state of each topic at once. Until then, oracle.status is reconnecting and the kept values are old. Show that to your users.
The client keeps the latest of everything, so a page can read it at any time: oracle.prices, oracle.books, oracle.venues, oracle.funding and oracle.nodes.
More streams
Order books
oracle.subscribe({ books: ['binance:spot:BTCUSDT'] }); // names from fetchCatalog(url).books
oracle.on('book', (book) => {
if (!book.synced || !book.available) return; // Wait for a snapshot with data.
console.log(book.name, 'bid', book.bestBid(), 'ask', book.bestAsk(), 'mid', book.mid());
});A book is one node's view of one venue book, the top 50 levels. bids(limit) and asks(limit) give [price, size] strings, best first. spreadBps() gives the spread in basis points of the mid. On a gap, the SDK drops the levels and asks for a new snapshot.
What each venue showed
import { venueQuote } from '@markoutlabs/oracle';
oracle.subscribe({ venues: ['CRYPTO.BTC/USDT'] });
oracle.on('venues', ({ symbol, node, report }) => {
for (const entry of report.entries) {
const quote = venueQuote(report, entry); // decimals, not mantissas
console.log(symbol, node, entry.venue, entry.status, quote.bid, quote.ask);
}
});One report is one node's view. The proxy does not combine them.
Funding of perpetuals
import { FUNDING_EXPO, fromMantissa } from '@markoutlabs/oracle';
oracle.subscribe({ funding: ['*'] }); // or names from fetchCatalog(url).funding
oracle.on('funding', ({ funding, node, update }) => {
const rate = fromMantissa(update.rate, FUNDING_EXPO);
console.log(funding, node, rate, update.interval_ns, update.next_funding_time_ns);
});Each venue pays over its own interval: 1, 4 or 8 hours. Compare rates only after you scale them to one interval. A field that the venue does not send is null.
unsubscribe({ funding: ['*'] }) removes every perpetual, also the ones that you named, as the proxy does. The client also forgets their funding.
Node reports
oracle.subscribe({ nodes: true });
oracle.on('nodes', ({ quorum, nodes }) => {
const connected = nodes.filter((node) => node.connection.state === 'connected');
console.log(`${connected.length} of ${nodes.length} nodes connected, quorum ${quorum}`);
});The report is for monitoring. The quorum alone decides a price.
Verify the nodes yourself
The proxy verifies every node and resolves the price for you. A client that must not trust the proxy for the price can do that work itself: the proxy forwards each node's signed frame, and the Verifier checks the signature against the registry and takes the median across the nodes, with the rules of the Rust SDK.
import { OracleClient, Verifier } from '@markoutlabs/oracle';
const url = 'wss://feeds.markoutlabs.com/v1/ws';
// The registry comes from the proxy, but its signature is checked against the
// mainnet governance address that the SDK pins. The proxy cannot forge it.
const verifier = await Verifier.fetch(url);
const oracle = new OracleClient({ url });
oracle.subscribe({ frames: ['CRYPTO.BTC/USD'] });
oracle.on('frame', (frame) => {
const result = verifier.accept(frame);
if (!result.ok) return; // a forged, stale or replayed frame
const price = verifier.resolve(frame.symbol);
if (price?.status === 'halted') return;
console.log(price?.price, '±', price?.conf, price?.status, 'from', price?.nodes, 'nodes');
});What this buys: the price can no longer be wrong because of the proxy. What it does not buy: the proxy can still withhold frames, which shows as halted, not as a wrong price.
Verifier.fetchtakes the same options as the Rust SDK:quorum(3),maxAgeMs(2000),slowMaxAgeMs(25000),maxSkewMs(500) andmaxDivergenceBps(50). A quorum below 3 gives no protection against one bad node.slowMaxAgeMsapplies to the funding and open interest feeds, whose symbols end in.FUNDING_8Hor.OPEN_INTEREST. The nodes publish these feeds every 10 s.maxAgeMsapplies to the other feeds.- An option can have a fraction. The
Verifierthrows aRangeErrorfor a negative or non-finite option, and for aquorumthat is not a whole number of 1 or more. It throws anErrorwhen the registry lists fewer nodes than the quorum. acceptdoes not throw for a bad frame. It returns{ ok: false, reason }, with the reasonunknown_signer,replayed,too_old,from_the_future,incoherent_timestamps,hint_mismatchormalformed.malformedalso covers bytes that are not hex, anrthat is not a valid signature value, and a frame whose symbol does not hash to the signed feed id.resolve(symbol)finds the feed by the keccak256 of the symbol, so give the canonical symbol. It gives the same fields as apricemessage, computed in your process. It returnsnullbefore the first frame of the feed, or when no node's price fits the fixed-point range.- Call
resolveon a timer too, so that a silent node shows ashalted. - Frames cost about one message per node each second for each feed, so subscribe to the feeds you act on.
- The proxy forwards frames only for the feeds in
fetchCatalog(url).frames. A proxy that runs its archive in the same process forwards none: thesubscribedevent lists the names inunknown.
History and the carry board
Each function returns the reply of one GET route of the web proxy:
| Function | What it gives |
|---|---|
fetchCatalog(url) |
The names the proxy serves: prices, venues, books, funding and frames |
fetchHealth(url) |
The proxy's health |
fetchNodes(url) |
The latest node report |
fetchHistory(url, feed, { from, to }) |
A feed's history, for a chart |
fetchCarry(url) |
The carry board's markets |
fetchCarryHourly(url) |
A year of settled funding, by hour |
fetchCarrySettled(url, perps) |
The settled funding of 1 to 4 perpetuals, by day |
Each takes the socket URL and finds the HTTP base. A refusal throws an HttpError with the HTTP status and retryAfter.
Options
| Option | Default | Contents |
|---|---|---|
url |
— | The proxy socket. |
WebSocket |
global | A WebSocket class, for a runtime without a global WebSocket. |
pingIntervalMs |
15000 | How often the SDK pings the proxy. |
pongTimeoutMs |
10000 | How long it waits for a pong before it connects again. |
minReconnectDelayMs |
1000 | The first wait before a reconnect. It doubles after each failure, up to maxReconnectDelayMs (30000). |
In Node.js older than 22, pass the ws package as WebSocket.
Test against a local oracle
scripts/dev.sh in the oracle-proxy repository starts three nodes and a proxy on ws://127.0.0.1:8792/v1/ws. The SDK's live test runs against it:
ORACLE_PROXY_URL=ws://127.0.0.1:8792/v1/ws pnpm test