|
| 1 | +/* eslint-disable no-await-in-loop */ |
| 2 | + |
| 3 | +/** |
| 4 | +* Module to subscribe to blockchain events |
| 5 | +*/ |
| 6 | +import WebSocket from 'ws'; |
| 7 | +import config from 'config'; |
| 8 | +import logger from 'common-files/utils/logger.mjs'; |
| 9 | +import { getContractInstance, getContractAddress } from 'common-files/utils/contract.mjs'; |
| 10 | +import constants from 'common-files/constants/index.mjs'; |
| 11 | + |
| 12 | +const { |
| 13 | +PROPOSERS_CONTRACT_NAME, |
| 14 | +SHIELD_CONTRACT_NAME, |
| 15 | +CHALLENGES_CONTRACT_NAME, |
| 16 | +STATE_CONTRACT_NAME, |
| 17 | +} = constants; |
| 18 | +const { RETRIES, WEBSOCKET_PORT, WEBSOCKET_PING_TIME } = config; |
| 19 | +const wss = new WebSocket.Server({ port: WEBSOCKET_PORT }); |
| 20 | + |
| 21 | +/** |
| 22 | +Function that does some standardised setting up of a websocket's events. |
| 23 | +It logs open, close and error events, sets up a ping and logs the pong. It will |
| 24 | +close the socket on pong failure. The user is expected to handle the reconnect. |
| 25 | +It does not set up the onmessage event because this tends to be case-specific. |
| 26 | +*/ |
| 27 | +function setupWebsocketEvents(ws, socketName) { |
| 28 | +let timeoutID; |
| 29 | +// setup a pinger to ping the websocket correspondent |
| 30 | +const intervalID = setInterval(() => { |
| 31 | +ws.ping(); |
| 32 | +// set up a timeout - will close the websocket, which will trigger a reconnect |
| 33 | +timeoutID = setTimeout(() => { |
| 34 | +logger.warn(`Timed out waiting for ping response from ${socketName}`); |
| 35 | +ws.terminate(); |
| 36 | +}, 2 * WEBSOCKET_PING_TIME); |
| 37 | +}, WEBSOCKET_PING_TIME); |
| 38 | +// check we received a pong in time (clears the timer set by the pinger) |
| 39 | +ws.on('pong', () => { |
| 40 | +// logger.debug(`Got pong from ${socketName} websocket`); |
| 41 | +clearTimeout(timeoutID); |
| 42 | +}); |
| 43 | +ws.on('error', () => { |
| 44 | +logger.debug(`ERROR ${socketName}`); |
| 45 | +}); |
| 46 | +ws.on('open', () => { |
| 47 | +logger.debug(`OPEN ${socketName}`); |
| 48 | +}); |
| 49 | +ws.on('close', err => { |
| 50 | +logger.debug(`CLOSE ${socketName} ${err}`); |
| 51 | +clearInterval(intervalID); |
| 52 | +}); |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | +* Function that tries to get a (named) contract instance and, if it fails, will |
| 57 | +* retry after 3 seconds. After RETRIES attempts, it will give up and throw. |
| 58 | +* This is useful in case nightfall-optimist comes up before the contract |
| 59 | +* is fully deployed. |
| 60 | +*/ |
| 61 | +export async function waitForContract(contractName) { |
| 62 | +let errorCount = 0; |
| 63 | +let error; |
| 64 | +let instance; |
| 65 | +while (errorCount < RETRIES) { |
| 66 | +try { |
| 67 | +error = undefined; |
| 68 | +const address = await getContractAddress(contractName); |
| 69 | +if (address === undefined) throw new Error(`${contractName} contract address was undefined`); |
| 70 | +instance = getContractInstance(contractName, address); |
| 71 | +return instance; |
| 72 | +} catch (err) { |
| 73 | +error = err; |
| 74 | +errorCount++; |
| 75 | +logger.warn(`Unable to get a ${contractName} contract instance will try again in 3 seconds`); |
| 76 | +await new Promise(resolve => setTimeout(() => resolve(), 3000)); |
| 77 | +} |
| 78 | +} |
| 79 | +if (error) throw error; |
| 80 | +return instance; |
| 81 | +} |
| 82 | + |
| 83 | +/** |
| 84 | +* |
| 85 | +* @param callback - The function that distributes events to the event-handler function |
| 86 | +* @param arg - List of arguments to be passed to callback, the first element must be the event-handler functions |
| 87 | +* @returns = List of emitters from each contract. |
| 88 | +*/ |
| 89 | +export async function startEventQueue(callback, ...arg) { |
| 90 | +const contractNames = [ |
| 91 | +STATE_CONTRACT_NAME, |
| 92 | +SHIELD_CONTRACT_NAME, |
| 93 | +CHALLENGES_CONTRACT_NAME, |
| 94 | +PROPOSERS_CONTRACT_NAME, |
| 95 | +]; |
| 96 | +const contracts = await Promise.all(contractNames.map(c => waitForContract(c))); |
| 97 | +const emitters = contracts.map(e => { |
| 98 | +const emitterC = e.events.allEvents(); |
| 99 | +emitterC.on('changed', event => callback(event, arg)); |
| 100 | +emitterC.on('data', event => callback(event, arg)); |
| 101 | +return emitterC; |
| 102 | +}); |
| 103 | +logger.debug('Subscribed to layer 2 state events'); |
| 104 | +return emitters; |
| 105 | +} |
| 106 | + |
| 107 | +export async function subscribeToChallengeWebSocketConnection(callback, ...args) { |
| 108 | +wss.on('connection', ws => { |
| 109 | +ws.on('message', message => { |
| 110 | +if (message === 'challenge') { |
| 111 | +setupWebsocketEvents(ws, 'challenge'); |
| 112 | +callback(ws, args); |
| 113 | +} |
| 114 | +}); |
| 115 | +}); |
| 116 | +logger.debug('Subscribed to Challenge WebSocket connection'); |
| 117 | +} |
| 118 | + |
| 119 | +export async function subscribeToBlockAssembledWebSocketConnection(callback, ...args) { |
| 120 | +wss.on('connection', ws => { |
| 121 | +ws.on('message', message => { |
| 122 | +if (message === 'blocks') { |
| 123 | +setupWebsocketEvents(ws, 'proposer'); |
| 124 | +callback(ws, args); |
| 125 | +} |
| 126 | +}); |
| 127 | +}); |
| 128 | +logger.debug('Subscribed to BlockAssembled WebSocket connection'); |
| 129 | +} |
| 130 | + |
| 131 | +export async function subscribeToInstantWithDrawalWebSocketConnection(callback, ...args) { |
| 132 | +wss.on('connection', ws => { |
| 133 | +ws.on('message', message => { |
| 134 | +if (message === 'instant') { |
| 135 | +setupWebsocketEvents(ws, 'liquidity provider'); |
| 136 | +callback(ws, args); |
| 137 | +} |
| 138 | +}); |
| 139 | +}); |
| 140 | +logger.debug('Subscribed to InstantWithDrawal WebSocket connection'); |
| 141 | +} |
| 142 | + |
| 143 | +export async function subscribeToProposedBlockWebSocketConnection(callback, ...args) { |
| 144 | +wss.on('connection', ws => { |
| 145 | +ws.on('message', message => { |
| 146 | +try { |
| 147 | +if (JSON.parse(message).type === 'sync') { |
| 148 | +logger.info(`SUBSCRIBING TO PROPOSEDBLOCK`); |
| 149 | +setupWebsocketEvents(ws, 'publisher'); |
| 150 | +callback(ws, args); |
| 151 | +} |
| 152 | +} catch (error) { |
| 153 | +logger.debug('Not JSON Message'); |
| 154 | +} |
| 155 | +}); |
| 156 | +}); |
| 157 | +logger.debug('Subscribed to ProposedBlock WebSocket connection'); |
| 158 | +} |
0 commit comments