3

In the documentation and suggested links and this question, it is mentioned that events are bound to methods and fire when a method is called (via a transaction). There is an example of a contract:

contract ClientReceipt {
    event Deposit(
        address indexed _from,
        bytes32 indexed _id,
        uint _value
    );

    function deposit(bytes32 _id) {
        // Any call to this function (even deeply nested) can
        // be detected from the JavaScript API by filtering
        // for `Deposit` to be called.
        Deposit(msg.sender, _id, msg.value);
    }
}

in which an event is fired every time method deposit() is called. I've tried to change the argument types and written the following, simplified, contract:

contract ClientReceipt {
    event Deposit(
        uint256 a
    );

    function deposit(uint256 a) {
        // Any call to this function (even deeply nested) can
        // be detected from the JavaScript API by filtering
        // for `Deposit` to be called.
        Deposit(a);
    }
}

but I get the error:

TypeError: Cannot read property 'event' of undefined

when deploying and calling the method (in browser-solidity).

  • Why doesn't the event fire properly?
  • Can a listener be used as a server from Javascript, in that, every time a method is called from the script?
  • When an event fires in a function that changes the state of the function, does it fire after the state has been changed (the transaction corresponindg to it was mined)?

Edit:

The Javascript event listener:

var abi = /* abi as generated by the compiler */;
var ClientReceipt = web3.eth.contract(abi);
var clientReceipt = ClientReceipt.at(0x123 /* address */);

var event = clientReceipt.Deposit(function(error, result) {
    if (!error)
        console.log(result);
    else {
        // Based on the result call another method of the contract
        clientReceipt.callMethod({gas: 4700000});
    }
});
Sebi
  • 5,294
  • 6
  • 27
  • 52

1 Answers1

2

From your code example, the events do fire properly.

You can use events on a server if you run a NodeJs. Perhaps someone else can chip in with reliability issues.

The event is fired when the block is mined. So, yes, the event is fired after the state has changed.

Side note. An emerging pattern is to prefix your events with Log. So call it event LogDeposit(uint a);.

The stringified object returned:

{
    "logIndex": 0,
    "transactionIndex": 0,
    "transactionHash": "0xa1a1e96217d05ca3f305ea051104da6de62c0df479d680494cc3e4dc013a846d",
    "blockHash": "0x923ede06e8027f07d239980b3d1502397e81958882a06008676647ad62c18e9d",
    "blockNumber": 504,
    "address": "0x1c7dc63b49a32c4b6cbc9c1a0e816b574c00e2fa",
    "type": "mined",
    "event": "Deposit",
    "args": {
        "a": "1"
    }
}
  • They did; I was using browser solidity when I got those errors but in a private test net using geth they do fire. – Sebi Aug 23 '16 at 15:34