Here is an example of both getting new events and old events using web3 contract event subscriptions.
web3.js code
var Web3 = require('web3');
var json = require('./truffle/build/contracts/Contract1.json');
var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8545'));
const testContract = new web3.eth.Contract(json.abi, "0xEcFcaB0A285d3380E488A39B4BB21e777f8A4EaC");
testContract.getPastEvents('Test', {
fromBlock: 0,
toBlock: 'latest'
}).then(
function(events){
events.forEach(event => {
console.log(`past event - transaction hash: ${event.transactionHash}`)
console.log(`past event - sender: - ${event.returnValues.sender}`);
console.log(`past event - id: - ${event.returnValues.id}`);
console.log(`past event - location: - ${web3.utils.hexToUtf8(event.returnValues.location)}`)
});
}
);
testContract.events.Test()
.on('data', function(event){
console.log(`new event - transaction hash: ${event.transactionHash}`)
console.log(`new event - sender: ${event.returnValues.sender}`);
console.log(`new event - id: ${event.returnValues.id}`);
console.log(`new event - location: ${web3.utils.hexToUtf8(event.returnValues.location)}`);
}).on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
console.log(`error`);
});
Assuming two events have occurred before you start running the program, and one occurs after, the output will look something like this:
output
past event - transaction hash: 0xa4f29de6d92c80e110705fe7de3563c3dbf8f05f8b8248596eb6d519468838bf
past event - sender: - 0x627306090abaB3A6e1400e9345bC60c78a8BEf57
past event - id: - 1
past event - location: - home
past event - transaction hash: 0xdbd4aad53513b4e822453ad28109effb7f9eec6e01f2413e625827aca583737e
past event - sender: - 0x627306090abaB3A6e1400e9345bC60c78a8BEf57
past event - id: - 2
past event - location: - work
new event - transaction hash: 0xd9e6a2a8d26c80ffc833e2b20b09736a4c123bccff8af46eb792679526b5b557
new event - sender: 0x627306090abaB3A6e1400e9345bC60c78a8BEf57
new event - id: 3
new event - location: school
solidity contract
pragma solidity 0.5.1;
contract Contract1
{
uint256 private id = 0;
event Test(address sender, uint256 id, bytes32 location);
function myTestFunction(bytes32 _location) external
{
id = id + 1;
emit Test(msg.sender, id, _location);
}
}