Get Price Feeds using Websocket

WebSocket provides full-duplex communication channels over a single TCP connection. It enables real-time communication between a client and a server without requiring the client to constantly pull the server for updates. WebSocket is designed to be implemented in web browsers and web servers but can be used by any client or server application.

Developers can easily integrate the ThirdFi Price Oracle WebSocket into their decentralized applications, enabling them to retrieve the latest price data and execute transactions on the blockchain-based on that data.

WebSocket Authentication

const socket = io("https://api.thirdfi.org", {
  path: `/ws/`,
  extraHeaders: {
    "x-sec-key": THIRDFI_API_KEY,
    "x-sec-sign": hash,
    "x-sec-ts": timeStamp,
  },
  transport: ["polling"],
  reconnection: true,
  autoConnect: true,
});

For authentication, the websocket requires ThirdFi API Key and ThirdFi SECRET Key. The API key is used for making the API requests and the Secret is used for hashing the baseURL with the timestamp. The API headers contain the API key, hash value and timestamp to work as expected.

The Hash can be generated using the "crypto" library present in javascript.

const hash = crypto.createHmac('sha256', {{THIRDFI_SECERET_KEY}})
							.update({{CONNECTION_STRING}}).digest('hex');

For Complete Authentication guide, check Authentication Page

Socket Connection

socket.on("connect", () => {
  // Listen to Room by Network and its pair
  socket.emit("joinRoom", {
    network: "BSC",
    pair: "ETHUSD",
  });
});

socket.on("joinRoom", async (msg) => {
  console.log("ROOM", msg);
  // Expected Output
  // ROOM { Answer: 30369.47, Pair: 'BNB-BTCUSD' }
});

socket.on("message", (msg) => {
  console.log("[Message]:", msg);
});

socket.on("disconnect", () => {
  console.log("disconnected");
});

The web socket can be connected using the socket.on method can be used to interact with the websocket.

socket eventDescription
connectEstablish connection with the websocket URL. It also contains socket.emit with "joinRoom" to connect with a specific ROOM containing the network and pair.
joinRoomIt is used for Subscribing to a specific room related to the specified network and trading pair. After joining the room, the response will be logged.
messageIt will provide a message(msg) if the socket is connected.
disconnectThis event will log when the socket will be disconnected.

Complete Code

Below is the Nodejs code(javascript) that can be used to try out the Price Oracle Websocket.

Libraries used:

  • Express - Express is a minimal Nodejs framework used for creating a local web server here.
  • Crypto - It is used for hashing the sign message for the header.
  • Moment - It is used for timestamping(in milliseconds) to the request.
  • Socket.io-client - It is used for connecting the websocket connection.
const express = require("express");
const crypto = require("crypto");
const moment = require("moment");
const io = require("socket.io-client");

//create a server object:
const app = express();
const port = 3001;

const BASE_URL = "https://api.thirdfi.org";

const THIRDFI_API_KEY = "";
const THIRDFI_SEC_KEY = "";

const timeStamp = moment().unix();
const baseString = `${BASE_URL}/ws/&emit=price_feed&timestamp=${timeStamp}`;
const hash = crypto
  .createHmac("sha256", THIRDFI_SEC_KEY)
  .update(baseString)
  .digest("hex");

const socket = io(BASE_URL, {
  path: `/ws/`,
  extraHeaders: {
    "x-sec-key": THIRDFI_API_KEY,
    "x-sec-sign": hash,
    "x-sec-ts": timeStamp,
  },
  transport: ["polling"],
  reconnection: true,
  autoConnect: true,
});

socket.on("connect", () => {
  // // Listen to Room by Network and its pair
  socket.emit("joinRoom", {
    network: "BSC",
    pair: "ETHUSD",
  });
});

socket.on("joinRoom", async (msg) => {
  console.log("ROOM", msg);
  // Expected Output
  // ROOM { Answer: 30369.47, Pair: 'BNB-BTCUSD' }
});

socket.on("message", (msg) => {
  console.log("[Message]:", msg);
});

socket.on("disconnect", () => {
  console.log("disconnected");
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

Subscribing to the Websocket

  1. Open an empty folder in your code editor.
  2. Initialize it by running npm init -y.
  3. Make sure you already have Nodejs installed and then install dependencies using thenpm i express moment socket.io-client, crypto library is already provided by javascript.
  4. Copy-Paste the above code in the index.js file.
  5. Get your API key from the ThirdFi Dashboard and put the secrets in the THIRDFI_API_KEY and THIRDFI_SEC_KEY.
  6. Subscribe to the WebSocket by running the node index.js in the console.
➜  node index.js

Example app listening at http://localhost:3001
[Message]: Connected
ROOM { Answer: 1848.44, Pair: 'BSC-ETHUSD' }
ROOM { Answer: 1848.54, Pair: 'BSC-ETHUSD' }
...
...

The websocket event is triggered whenever Chainlink Aggregator Event is updated. Updates will be posted in the console where the server is running.

To Unsubscribe, just click cmd+C or ctrl+C. This will stop the node server and unsubscribe to the price feed event.