I want to subscribe and listen to events that involve funds moving to my wallet, however I for some reason am not able to establish a socket connection to an Infura node.
First I npm init
and npm web3
.
The code:
const Web3 = require('web3');
class TransactionChecker {
web3;
web3ws;
account;
subscription;
constructor(projectId, account) {
web3ws = new Web3.providers.WebsocketProvider('wss://kovan.infura.io/ws/v3/' + projectId);
web3 = new Web3.providers.HttpProvider('https://kovan.infura.io/v3/' + projectId);
account = account.toLowerCase();
}
subscribe(topic) {
this.subscription = web3ws.eth.subscribe(topic, (err, res) => {
if (err) console.error(err);
});
}
watchTransactions() {
console.log('Watching all pending transactions...');
this.subscription.on('data', (txHash) => {
setTimeout(async () => {
try {
let tx = await this.web3.eth.getTransaction(txHash);
if (tx != null) {
if (this.account == tx.to.toLowerCase()) {
console.log({address: tx.from, value: this.web3.utils.fromWei(tx.value, 'ether'), timestamp: new Date()});
}
}
} catch (err) {
console.error(err);
}
}, 60000)
});
}
}
let txChecker = new TransactionChecker('projectId', 'address');
txChecker.subscribe('pendingTransactions');
txChecker.watchTransactions();
Gives me the following err: 'failed to create stateful backend, closing connection: websocket: bad handshake'
URLs are all good, why the error?