WebSockets Quickstart

Working with WebSocket Subscriptions

Introduction

This section dives into using WebSocket subscriptions with the Tensor API. WebSocket subscriptions enable you to stay up-to-date on blockchain events in real-time by creating a persistent connection.

API Endpoint

Mainnet-beta: wss://api.mainnet.tensordev.io/ws

Connection Example

const WebSocket = require("ws");

const TENSOR_API_KEY = process.env.TENSOR_API_KEY;

(() => {
  const socket = new WebSocket("wss://api.mainnet.tensordev.io/ws", {
    headers: {
      "x-tensor-api-key": TENSOR_API_KEY,
    },
  });
  
  // Connection opened
  socket.addEventListener('open', (event) => {
    console.log('WebSocket connection type:', event.type);
    // Send body for the event you want to get subscribed to
    socket.send(JSON.stringify({
        "event": "ping",
        "payload": {}
    }));
	});
	console.log("Connected to Tensor WebSocket Endpoint, waiting for incoming events...");

// Start listening to incoming messages
	socket.addEventListener('message', (event) => {
    // Check if the incoming event has data attached to it
    const event_stringified = event?.data?.toString();
    if (event_stringified !== '' && event_stringified !== null) {
        console.log(JSON.parse(event_stringified)); 
    }
	});
})();

Response

Connected to Tensor WebSocket Endpoint, waiting for incoming events...
WebSocket connection type: open
{ type: 'pong' }

Additional Examples

Be sure to check out the recipes page for additional examples on how to use the WebSockets API!

Tutorials

The following resources are available for you to get started with Tensor WebSocket Subscriptions

  • Stream new transactions for a Collection Recipe
  • Discord Sales Bot Stream Template Github