1

I want to build an API to manage the smart contract events and I wonder how to do it using Node.js. Anyone that can help?

  • Are you aware of web3js api or JSON RPC? – ivicaa Apr 13 '18 at 19:27
2

You would want to use the web3 module. The installation via npm works like this

npm install -g web3

Make sure that you install web3 1.0

There is one thing you have be careful about if you want to work with events and logs. You have to connect to the websocket and not to the http protocol.

var Web3 = require('web3');
var web3 = new Web3(new web3.providers.WebsocketProvider('ws://localhost:8546'));

Depending on what you want to do with the events you can either use:

myContract.once('MyEvent', {
    filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
    fromBlock: 0
}, function(error, event){ console.log(event); });

if you want to read just one event or

myContract.events.MyEvent({
    filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, 
// Using an array means OR: e.g. 20 or 23
    fromBlock: 0
}, function(error, event){ console.log(event); })
.on('data', function(event){
    console.log(event); // same results as the optional callback above
})
.on('changed', function(event){
    // remove event from local database
})
.on('error', console.error);

if you want to subscribe to an event. This is fired each time when the event is emitted in your smart contract. Or

myContract.getPastEvents('MyEvent', {
    filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
    fromBlock: 0,
    toBlock: 'latest'
}, function(error, events){ console.log(events); })
.then(function(events){
    console.log(events) // same results as the optional callback above
});

if you want read past events.

You can find the web3 documentation about the event handling here.

https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#events

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.