- How are events declared?
- How can we emit events?
- How and where do we listen for events?
The syntax used to declare events is as followed
event EventName (type1 name1, typei namei);
for example the following event is declared when to have the following parameters. Notice we are only declaring the event inside the contract but outside any function. We are not initializing the event or emmiting anythings yet.
event addedDog(address owner, string name, uint dogId, string breed);
Events can be emited by calling it within a function using the following syntax
EventName (value1, valuei);
for example combining both concepts into a dog Deposit Receipt;
contract DogReceipt { event DogDeposit( address indexed _from, address indexed _to, bytes32 indexed _id, string _name, string _breed, uint _value ); function dogDeposit(address _to, bytes32 _id, string _name, string _breed){ DogDeposit(msg.sender, _to, _id, _name, _breed, msg.value); } }
We listen for events using JavaScript API.
for example:
var abi = /* abi as generated by the compiler */; var ContractName = web3.eth.contract(abi); var contractName = ContractName.at(0x123 /* address */); var event = ContractName.EventName(); // watch for changes event.watch(function(error, result){ // result will contain various information // including the argumets given to the Deposit // call. if (!error) console.log(result); }); // Or pass a callback to start watching immediately var event = contractName.EventName(function(error, result) { if (!error) console.log(result); });
Here is the API for our DogReceipt. I just coppied and pasted the API
var abi = [ { "constant": false, "inputs": [ { "name": "_to", "type": "address" }, { "name": "_id", "type": "bytes32" }, { "name": "_name", "type": "string" }, { "name": "_breed", "type": "string" } ], "name": "dogDeposit", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_from", "type": "address" }, { "indexed": true, "name": "_to", "type": "address" }, { "indexed": true, "name": "_id", "type": "bytes32" }, { "indexed": false, "name": "_name", "type": "string" }, { "indexed": false, "name": "_breed", "type": "string" }, { "indexed": false, "name": "_value", "type": "uint256" } ], "name": "DogDeposit", "type": "event" } ]; var DogReceipt = web3.eth.contract(abi); var dogReceipt = DogReceipt.at(0x779831119fe1e7bb6c6dc6f36d2daad38d6e7fe8); var event = DogReceipt.DogDeposit(); // watch for changes event.watch(function(error, result){ // result will contain various information // including the argumets given to the Deposit // call. if (!error) console.log(result); }); // Or pass a callback to start watching immediately var event = dogReceipt.DogDeposit(function(error, result) { if (!error) console.log(result); });
Contract is live at