const WebSocket = require("ws");
const feedStartRequest = {
jsonrpc: "2.0",
// For this example we're using a hardcoded request ID
id: "req-1",
// The method, either "feed.execute", "feed.start", or "feed.stop"
method: "feed.start",
params: {
// The parameters of the request. These are the same as the execute endpoint on the REST API
execute: {
execProgramId: "0x568732e496819819f2effa240614b8ebe53c2492149443578e155a145e0a351e",
execInputs: "0x9b190a0000000000",
inputEncoding: "auto",
includeDebugInfo: "true",
injectLastResult: "success",
encoding: "json",
},
// The update frequency of the feed in milliseconds
periodicityMs: 5000,
// The scheduling mode, see the API reference for more details
mode: "FIXED",
},
};
const ws = new WebSocket(WS_URL, {
headers: { Authorization: `Bearer ${process.env.SEDA_FAST_API_KEY}` },
});
const applicationState = {
/** Null when there is no feed, otherwise a string */
feedId: null,
/** Number of reports received */
resultsReceived: 0,
};
// Stop the feed after receiving 2 updates
const STOP_AFTER_FEED_RESULTS = 2;
ws.on("open", () => console.log("π Connected"));
ws.on("message", (data) => {
const msg = JSON.parse(data.toString());
// Uncomment this line to see the full message
// console.log("π¨", JSON.stringify(msg, null, 2));
if (msg.method === "authorized") {
console.log("β
Authorized");
// When authorized immediately start the feed
ws.send(JSON.stringify(feedStartRequest));
}
// We check for the same ID that we specified in the executeRequest and store the feed id
if (msg.id === "req-1" && msg.result !== undefined && msg.result.feedId) {
applicationState.feedId = msg.result.feedId;
console.log("β
Feed started:", applicationState.feedId);
}
if (msg.method === "feed.result" && msg.params?.feedId === applicationState.feedId) {
applicationState.resultsReceived += 1;
console.log(`π¬ feed.result ${applicationState.resultsReceived}/${STOP_AFTER_FEED_RESULTS}`);
if (applicationState.resultsReceived >= STOP_AFTER_FEED_RESULTS) {
console.log("π€ Sending feed.stop...");
ws.send(
JSON.stringify({
jsonrpc: "2.0",
id: "req-2",
method: "feed.stop",
params: { feedId: applicationState.feedId },
}),
);
}
}
// We check for the same ID that we specified in the feed.stop message
if (msg.id === "req-2" && msg.result !== undefined) {
console.log("β
Feed stopped");
// Close the connection after receiving the response for the feed.stop request
ws.close(1000, "closed by client");
}
if (msg.error) {
console.error("β", msg.error.code, msg.error.message);
}
});
ws.on("error", (e) => console.error("β", e));
ws.on("close", (code, reason) => {
console.log("π Disconnected", code ? `(${code}${reason ? `: ${reason}` : ""})` : "");
});