ponder-sh / ponder

A backend framework for crypto apps
https://ponder.sh
MIT License
531 stars 74 forks source link

[feature] support websocket channel messages in Ponder #959

Open hskang9 opened 2 weeks ago

hskang9 commented 2 weeks ago

I think Ponder's greatest advantage over other web3 backend frameworks is that it can use other native javascript libraries, and I have found a way to integrate websocket for Ponder to deliver realtime update on next web3 consumer app.

Usage

So far here is how I integrate into Ponder.

First, add a file called Server.js and make code like this.

const server = require('http').createServer();

const io = require('socket.io')(server, {
  transports: ['trade', 'order', 'day', 'hour', 'min']
});

let tick = 0;
// 1. listen for socket connections
io.on('connection', (client: { emit: (arg0: string, arg1: { name: number; value: any; }) => void; }) => {

});

server.listen(process.env.WS_PORT);

export default io;

Then, inside on each ponder.on, make io emit an event with transport channel.

import io from "./Server";

ponder.on("matchingEngine:someEvent", async ({ event, context }) => {
  const { Analysis, Token, Pair } = context.db;
  const chainId = context.network.chainId;
  await PairAddedHandleTokenPairOrderbook(
    event,
    chainId,
    Analysis,
    Token,
    Pair
  );

  io.emit("trade", {...})
});

Is there any consideration on adding websocket inside the ponder to add io in the argument of ponder.on function?