UNPKG

@erfffun/utils

Version:

Energi javascript utilities for web development

54 lines (46 loc) 1.41 kB
import Web3 from 'web3'; import { RPC_URLS, RPC_WS_URLS } from '../constants'; const web3Instances = {}; const web3SocketInstance = {}; const getWeb3 = chainId => { if (!web3Instances[chainId]) { web3Instances[chainId] = new Web3(RPC_URLS[chainId]); } return web3Instances[chainId]; }; export const getWeb3Socket = chainId => { if (!web3SocketInstance[chainId]) { const wsOptions = { clientConfig: { keepalive: true, keepaliveInterval: 60000, }, reconnect: { auto: true, delay: 2500, onTimeout: true, }, }; web3SocketInstance[chainId] = new Web3( new Web3.providers.WebsocketProvider(RPC_WS_URLS[chainId], wsOptions), ); } return web3SocketInstance[chainId]; }; export const subscribeToWeb3Socket = async ( chainId, onLatestBlock = () => {}, // runs the function on new block created getCurrentBlock = () => {}, // returns the latest/current block in parameters onError = () => {}, // error handler for socket connection interruption ) => { const web3ws = await getWeb3Socket(chainId); const subscription = await web3ws.eth.subscribe('newBlockHeaders', onError); subscription.on('data', onLatestBlock); getCurrentBlock(await web3ws.eth.getBlockNumber()); return subscription; }; export const clearSubscriptions = async chainId => { const wsWeb3 = await getWeb3Socket(chainId); await wsWeb3.eth.clearSubscriptions(); }; export default getWeb3;