Skip to content

Commit

Permalink
Add notification of new block using websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
ismaelbej committed Mar 27, 2020
1 parent c24afa5 commit 82e2255
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
19 changes: 15 additions & 4 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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;
}
2 changes: 1 addition & 1 deletion src/config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export default {
port: 5000,
rpcnode: 'http://localhost:8545',
rpcnode: 'ws://localhost:8545',
};
12 changes: 11 additions & 1 deletion src/lib/ethereum.js
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 82e2255

Please sign in to comment.