'Trying to subscribe to a specific event on ETH using Web3, but not sure how to retrieve the returned data and use it
I'm trying to build a Javascript Bot subscribing to specific events on a contract, I have written some lines of code but I'm not sure how the EventEmitter returns data and how I can use it. Can anyone give me an example on how I can retrieve specific data (like transaction hash/ parameters of the event) each time web3.eth.subscribe() fires ?
Here's the code I've written :
const Web3 = require('web3')
const web3 = new Web3(new Web3.providers.HttpProvider("https://api.avax-
test.network/ext/bc/C/rpc") )
web3.eth.subscribe(
'logs',
{
address : 'some contract address',
topics : ['Keccak-256 hash(the event)']
},
function(error,result){
if(!error)
console.log(result);
}
)
.on("connected",function(subscriptionId){ //to check if subscription is successful
print(subscriptionId);
})
Solution 1:[1]
If you listen to contract events like this, they will not have any parameters in the returned object. Instead, if you need the parameters you need to get the events from the contract object. There are two options (example shows how to get the "Transfer" events)
Option one
let options = {
filter: {
value: ['1000', '1337'] //Only get events where transfer value was 1000 or 1337
},
fromBlock: 0, //Number || "earliest" || "pending" || "latest"
toBlock: 'latest'
};
const myContract = new Web3.Contract(ABI, CONTRACT_ADDRESS);
myContract.getPastEvents('Transfer', options)
.then(results => console.log(results))
.catch(err => throw err);
Option two
let options = {
filter: {
value: [],
},
fromBlock: 0
};
const myContract = new Web3.Contract(ABI, CONTRACT_ADDRESS);
myContract.events.Transfer(options)
.on('data', event => console.log(event))
.on('changed', changed => console.log(changed))
.on('error', err => throw err)
.on('connected', str => console.log(str))
source: https://www.coinclarified.com/p/3-ways-to-subscribe-to-events-with-web3-js/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mamo |