Skip to content

Instantly share code, notes, and snippets.

@mempirate
Created October 31, 2019 16:33
Show Gist options
  • Save mempirate/723a41383fd901a3dec6030d2c6a929f to your computer and use it in GitHub Desktop.
Save mempirate/723a41383fd901a3dec6030d2c6a929f to your computer and use it in GitHub Desktop.
const Web3 = require('web3');
class TransactionChecker {
web3;
web3ws;
account;
subscription;
constructor(projectId, account) {
this.web3ws = new Web3(new Web3.providers.WebsocketProvider('wss://rinkeby.infura.io/ws/v3/' + projectId));
this.web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io/v3/' + projectId));
this.account = account.toLowerCase();
}
subscribe(topic) {
this.subscription = this.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(process.env.INFURA_ID, '0xe1Dd30fecAb8a63105F2C035B084BfC6Ca5B1493');
txChecker.subscribe('pendingTransactions');
txChecker.watchTransactions();
@naresh-mudaliar-au1
Copy link

naresh-mudaliar-au1 commented Aug 4, 2022

How can be watched from a single block predefined block to latest (predefined when i deployed my contract) for our offchain users so when i try to do with setInterval with loop my server get stuck after a time.

Did you succeed? What you can do is when a transaction is initiated you need to call this function from outside ex: ui and when the transaction is confirmed we can have delay so that some blocks get added to the chain and transaction is verified. You can clear the interval after that for this function. Let me know if you did any other solution for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment