From 82e2255ba1f419943f5fb19130fc0c4563d581c0 Mon Sep 17 00:00:00 2001 From: Ismael Bejarano Date: Fri, 27 Mar 2020 16:04:29 -0300 Subject: [PATCH] Add notification of new block using websockets --- src/app.js | 19 +++++++++++++++---- src/config.js | 2 +- src/lib/ethereum.js | 12 +++++++++++- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/app.js b/src/app.js index ce200fb..2f2532e 100644 --- a/src/app.js +++ b/src/app.js @@ -2,9 +2,10 @@ import express from 'express'; import logger from 'morgan'; import cors from 'cors'; import http from 'http'; +import socketIo from 'socket.io'; import api from './routes/api'; -import { initialize as initializeContracts } from './controllers/Contracts'; -import { initialize as initializeEthereum } from './lib/ethereum'; +import contracts from './controllers/Contracts'; +import ethereum from './lib/ethereum'; export function createApp() { const app = express(); @@ -37,9 +38,19 @@ export function createApp() { } export async function createServer(app, config) { - await initializeContracts(config); - await initializeEthereum(config); + await contracts.initialize(config); + const eventEmitter = await ethereum.initialize(config); const server = http.createServer(app); + const io = socketIo(server); + io.on('connect', (socket) => { + console.log('New client', socket.id); + eventEmitter.on('newBlock', (block) => { + socket.emit('newBlock', block.number); + }); + socket.on('disconnect', () => { + console.log('Client disconnected', socket.id); + }); + }); server.listen(config.port || 5000); return server; } diff --git a/src/config.js b/src/config.js index 1ff383c..cc79e6e 100644 --- a/src/config.js +++ b/src/config.js @@ -1,4 +1,4 @@ export default { port: 5000, - rpcnode: 'http://localhost:8545', + rpcnode: 'ws://localhost:8545', }; diff --git a/src/lib/ethereum.js b/src/lib/ethereum.js index 94f7d51..8ecdcee 100644 --- a/src/lib/ethereum.js +++ b/src/lib/ethereum.js @@ -1,6 +1,9 @@ +import EventEmitter from 'events'; import Web3 from 'web3'; import LRU from 'lru-cache'; +class EthereumEmitter extends EventEmitter {} + const web3 = new Web3(); export const getBalance = web3.eth.getBalance; @@ -37,8 +40,15 @@ export function initialize(config) { if (typeof config.web3provider !== 'undefined') { web3.setProvider(config.web3provider); } else { - web3.setProvider(new Web3.providers.HttpProvider(config.rpcnode || 'http://localhost:8545')); + web3.setProvider(new Web3.providers.WebsocketProvider(config.rpcnode || 'ws://localhost:8545')); } + const eventEmitter = new EthereumEmitter(); + web3.eth.subscribe('newBlockHeaders', (err, result) => { + if (!err) { + eventEmitter.emit('newBlock', result); + } + }); + return eventEmitter; } // Can query by number or hash, but only cache by hash