#Read pearls and follow trades
This guide builds a small Node.js client that lists pearls and follows their trades. It is for a developer connecting to NACRE for the first time. It only reads. Buys and sells use the queue service.
You need Node.js 20 or newer, because the sample uses the built-in fetch. Amounts are bigint strings. Upsert each trade by txid, because the same transaction is pushed again when its status changes.
The indexer listens on port 3001 and the WebSocket path is /ws. Port 3000 is the website, not the API, unless a gateway in front of you maps the paths onto one host.
#Prepare
mkdir nacre-quickstart && cd nacre-quickstart
npm init -y
npm install ws tsx typescript @types/wsexport API_BASE="http://127.0.0.1:3001"
export WS_URL="ws://127.0.0.1:3001/ws"#The client
Save this file as index.ts. It does three things:
GET /api/v1/tokens?sort=trending&limit=5loads five pearls.- It URL-encodes the first pearl id and loads
GET /api/v1/tokens/:id/trades?limit=10. - It opens
/ws, subscribes totokens:newandtoken:<id>, and upserts trades bytxid.
The interfaces below include only the fields this file prints. The full objects are in the WebSocket feed. status is curve while layers are still selling, and amm after the pearl is harvested. A trade's size is tokens (whole tokens), not a layer count. One layer is 1,000,000 tokens.
import WebSocket from "ws";
const API_BASE = process.env.API_BASE ?? "http://127.0.0.1:3001";
const WS_URL = process.env.WS_URL ?? "ws://127.0.0.1:3001/ws";
const GRAINS_PER_PRL = 100_000_000n;
interface Pearl {
id: string;
name: string;
symbol: string;
status: "curve" | "amm";
step: number;
confirmedStep: number;
nextPrice: string;
progressBps: number;
}
interface Trade {
txid: string;
tokenId: string;
kind: "launch" | "buy" | "sell" | "transfer" | "graduate";
phase?: "curve" | "amm";
address: string;
tokens: number;
grains: string;
status: "queued" | "mempool" | "confirmed" | "dropped";
time: number;
}
function formatPrl(grains: string): string {
const value = BigInt(grains);
const whole = value / GRAINS_PER_PRL;
const frac = (value % GRAINS_PER_PRL).toString().padStart(8, "0").replace(/0+$/, "");
return frac ? `${whole}.${frac}` : `${whole}`;
}
async function fetchJson<T>(path: string): Promise<T> {
const res = await fetch(`${API_BASE}${path}`);
if (!res.ok) {
const err = await res.text();
throw new Error(`HTTP ${res.status} on ${path}: ${err}`);
}
return res.json() as Promise<T>;
}
async function main() {
const page = await fetchJson<{ items: Pearl[]; nextCursor: string | null }>(
"/api/v1/tokens?sort=trending&limit=5",
);
console.log(`listed ${page.items.length} pearls`);
for (const pearl of page.items) {
const pct = (pearl.progressBps / 100).toFixed(2);
console.log(
`- [${pearl.symbol}] ${pearl.name} | status=${pearl.status} | layer=${pearl.step}/800 (${pct}%) | next=${formatPrl(pearl.nextPrice)} PRL`,
);
}
const target = page.items[0];
if (!target) {
console.log("no pearls yet; waiting for tokens:new");
}
const trades = new Map<string, Trade>();
if (target) {
const encodedId = encodeURIComponent(target.id);
const history = await fetchJson<{ items: Trade[]; nextCursor: string | null }>(
`/api/v1/tokens/${encodedId}/trades?limit=10`,
);
for (const trade of history.items) trades.set(trade.txid, trade);
console.log(`loaded ${trades.size} recent trades for ${target.symbol}`);
}
const ws = new WebSocket(WS_URL);
ws.on("open", () => {
const channels = ["tokens:new"];
if (target) channels.push(`token:${target.id}`);
ws.send(JSON.stringify({ op: "sub", ch: channels }));
console.log("subscribed", channels);
});
const heartbeat = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ op: "ping" }));
}
}, 25_000);
ws.on("message", (raw) => {
const msg = JSON.parse(raw.toString()) as {
op: string;
seq?: number;
ch?: string;
data?: Record<string, unknown>;
message?: string;
};
if (msg.op === "pong") return;
if (msg.op === "error") {
console.error("ws error:", msg.message);
return;
}
if (msg.op !== "event" || !msg.ch || !msg.data) return;
if (msg.ch === "tokens:new") {
const created = msg.data as unknown as Pearl;
console.log(`new pearl ${created.symbol} (${created.id})`);
return;
}
if (!msg.ch.startsWith("token:")) return;
const payload = msg.data as { type: "token"; token: Pearl } | { type: "trade"; trade: Trade };
if (payload.type === "token") {
console.log(
`pearl ${payload.token.symbol} layer=${payload.token.step} confirmed=${payload.token.confirmedStep} status=${payload.token.status}`,
);
return;
}
const trade = payload.trade;
const existed = trades.has(trade.txid);
trades.set(trade.txid, trade);
console.log(
`${existed ? "update" : "trade"} ${trade.kind} tokens=${trade.tokens} ${formatPrl(trade.grains)} PRL status=${trade.status} txid=${trade.txid.slice(0, 12)}...`,
);
});
ws.on("close", () => {
clearInterval(heartbeat);
console.log("socket closed; reconnect with backoff and subscribe again");
});
}
main().catch((err) => {
console.error(err);
process.exit(1);
});#Run it
npx tsx index.tsIf the list is empty, leave the process running. A launch shows up on tokens:new. After a disconnect, open a new socket, send sub again, and pull the trade list once more so you do not miss a message. The WebSocket feed describes seq and replay.
#Next
Subscribe to more channels in the WebSocket feed, or look up every HTTP route in the Indexer HTTP API.