123456789101112131415161718192021222324252627282930313233343536373839404142 |
- const { Block } = require('./db/models')
- const chalk = require('chalk')
- const { types } = require('@joystream/types')
- const { ApiPromise, WsProvider } = require('@polkadot/api')
- const wsLocation = 'wss://rome-rpc-endpoint.joystream.org:9944'
- module.exports = (io) => {
- const initializeSocket = async () => {
- console.debug(`[Joystream] Connecting to ${wsLocation}`)
- const provider = new WsProvider(wsLocation)
- const api = await ApiPromise.create({ provider, types })
- await api.isReady
- console.debug(`[Joystream] Connected.`)
- api.derive.chain.subscribeNewHeads(async (header) => {
- const id = Number(header.number)
- const exists = await Block.findByPk(id)
- if (exists) return
- const timestamp = (await api.query.timestamp.now()).toNumber()
- const last = await Block.findByPk(id - 1)
- const blocktime = last ? timestamp - last.timestamp : 6000
- const block = await Block.create({
- id,
- timestamp,
- blocktime,
- author: header.author?.toString(),
- })
- console.log('[Joystream] block', block.id, block.blocktime, block.author)
- io.emit('block', block)
- })
- }
- io.on('connection', (socket) => {
- socket.emit('welcome', 'Websockets are awesome!')
- console.log(chalk.green(`[socket.io] Connection: ${socket.id}`))
- socket.on('disconnect', async () => {
- console.log(chalk.red(`[socket.io] Disconnect: ${socket.id}`))
- })
- })
- initializeSocket()
- }
|