import { Api, Header, Status } from './types' const { types } = require('@joystream/types') const { Block } = require('./db/models') const { ApiPromise, WsProvider } = require('@polkadot/api') const { addBlock } = require('./joystream') const chalk = require('chalk') // TODO allow alternative backends const wsLocation = 'ws://localhost:9944' // 'wss://rome-rpc-endpoint.joystream.org:9944' module.exports = (io: any) => { const handleUpstream = async (api: Api) => { let status: Status = {} let lastHeader: Header api.derive.chain.subscribeNewHeads(async (header: Header) => { if (lastHeader && lastHeader.number === header.number) return console.debug(`skipping seen block`) lastHeader = header status = await addBlock(api, io, header, status) }) } io.on('connection', async (socket: any) => { console.log(chalk.green(`[socket.io] Connection: ${socket.id}`)) socket.on('get blocks', async (limit: number) => { const blocks = await Block.findAll({ limit, order: [['id', 'DESC']] }) socket.emit('blocks', blocks) }) socket.on('disconnect', async () => { console.log(chalk.red(`[socket.io] Disconnect: ${socket.id}`)) }) }) const connectUpstream = async () => { try { 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.`) handleUpstream(api) } catch (e) { //console.log(`[Joystream] upstream connection failed`, e) } } connectUpstream() }