Calling allEvents – Works in Truffle Console but Not in Application?

eventstruffleweb3js

I am trying to retrieve the events associated with the default MetaCoin contract in Truffle. I am able to do this from the Truffle console, but not from within app.js. I am using Truffle 4.0.1 with Webpack and TestRPC. The abbreviated version of the contract is as follows:

contract MetaCoin {
    mapping (address => uint) balances;

    event Transfer(address indexed _from, address indexed _to, uint256 _value);

    function MetaCoin() {
        balances[tx.origin] = 10000;
    }

    function sendCoin(address receiver, uint amount) returns(bool sufficient) {
        if (balances[msg.sender] < amount) return false;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        Transfer(msg.sender, receiver, amount);
        return true;
    }
}

In the project's app.js, I do the following when using sendCoin to verify that the event is working.

MetaCoin.deployed().then(function(instance) {
  meta = instance;
  return meta.sendCoin(receiver, amount, {from: account});
}).then(function(tx) {
  self.setStatus("Transaction complete!");
  console.log("the transaction:", tx);
});

When I view a transaction in the browser Javascript console I can verify that the transaction object does indeed have have an entry under logs with _from, _to, and _value so this seems to be working. The problem I am having is using allEvents from the Javascript API to get all past events. In my app.js, I have added an additional function:

fetchLogs: function() {
var self = this;
var meta;
var event_data;
var event_data2;
MetaCoin.deployed().then(function(instance) {
  meta = instance;
  console.log("working");
  var events = meta.allEvents({fromBlock: 0, toBlock: 'latest'});
  events.get(function(error, log) {
    event_data = log;
    console.log(event_data);
  });
});

},

When I view the browser console, I get the message "working" and then undefined where I should get an object with all of the past logs.

However, by using the same Javascript in the Truffle Console, I am able to see the logs by doing the following process:

> var meta;
> MetaCoin.deployed().then(function(instance) { meta = instance});
> var events = meta.allEvents({fromBlock: 0, toBlock: 'latest'});
> var event_data;
> events.get( (error, log) => {event_data = log;});
> event_data;

When I do this in the Truffle Console I get the a list of objects corresponding to every transaction that's been performed so far. So why does this work in the console, and not on my Truffle application?

Best Answer

Are you using MetaMask injected web3?

I had the exact same problem and then found this issue on github.

Turns out if I change my code not to use injected web3 but a local one I can fetch events. So this seems to be an issue of MetaMask.

Hope this also fixes your problem...it took me almost 2 days to realize it was related to MetaMask.

Related Topic