1

This is my source code in nodejs:

var Web3 = require('web3');
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
var abi = ...
var contract = new web3.eth.Contract(abi, MAIN_CONTRACT_ID);
contract.events.Evt({fromBlock: 0, toBlock: 'latest'},function () {
}).on('data',function (evt) {
        console.log("evt",evt);
    });

But I get this crash:

TypeError: Cannot read property 'on' of undefined
    at Subscription.subscribe (C:\Users\steve\Dropbox\Projects\dsd\dsd\web3test\node_modules\web3\packages\web3-core-subscriptions\src\subscription.js:199:45)
    at Contract._on (C:\Users\steve\Dropbox\Projects\dsd\dsd\web3test\node_modules\web3\packages\web3-eth-contract\src\index.js:623:18)

contract.Evt is undefined for me, contract is defined and contains contract.events.Evt.

How can I fix this?

4
  • Hi! Have you tried contract.Evt ? – d3llafr33 Jul 29 '17 at 11:24
  • contract.Evt is undefined – Stepan Yakovenko Jul 29 '17 at 12:16
  • mmm Is the contract variable defined? As an alternative try this: var contract = web3.eth.contract(abi); var contractInstance = contract.at(address); – d3llafr33 Jul 29 '17 at 12:53
  • Syntax you proposed doesn't work with the package I'm using: npmjs.com/package/web3 It has slightly different api, compared to metamask for instance: web3js.readthedocs.io/en/1.0/index.html – Stepan Yakovenko Jul 29 '17 at 13:47
1

There are two versions of web3 API, old one (used by metamask) and new one (used by lastest web3 from nodejs). This is example for the last version of API. To listen for events you need to have websocket working (http wouldn't work), so run mist.exe with the following options:

--node-wsorigins="*" 
--node-ws 
--node-wsapi "db,eth,net,web3,personal" 
--swarmurl="http://swarm-gateways.net"

This is how you can connect to your geth.exe now:

    var Web3 = require('web3');
    var web3 = new Web3('ws://localhost:8546');
    var abi = ...
    contract = new web3.eth.Contract(abi, CONTRACT_ID_HERE);
    // this will listen to new events
    contract.events.Evt({}, function (err, evt) {
        if (err) {
            console.log(err);
            return;
        }
        console.log(evt)
    });
    // this will grab all events from the past
    contract.getPastEvents('Evt', {fromBlock: startBlock, toBlock: 'latest'}, 
       function (err, arg) {
            if(err) {
                console.error(err);
                return;
            }
            console.log(arg)
        });
};

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.