Event triggering in solidity

Yajnesh Rai picture Yajnesh Rai · Feb 22, 2016 · Viewed 10.1k times · Source

I'm currently working on ethereum platform(node.js and solidity). My question is how do I trigger an event in solidity(contract) using node.js?

Answer

Muhammad Altabba picture Muhammad Altabba · Jan 10, 2018

Here is a sample event definition at smart contract:

contract Coin {
    //Your smart contract properties...

    // Sample event definition: use 'event' keyword and define the parameters
    event Sent(address from, address to, uint amount);


    function send(address receiver, uint amount) public {
        //Some code for your intended logic...

        //Call the event that will fire at browser (client-side)
        emit Sent(msg.sender, receiver, amount);
    }
}

The line event Sent(address from, address to, uint amount); declares a so-called “event” which is fired in the last line of the function send. User interfaces (as well as server applications of course) can listen for those events being fired on the blockchain without much cost. As soon as it is fired, the listener will also receive the arguments from, to and amount, which makes it easy to track transactions. In order to listen for this event, you would use.

Javascript code that will catch the event and write some message in the browser console:

Coin.Sent().watch({}, '', function(error, result) {
    if (!error) {
        console.log("Coin transfer: " + result.args.amount +
            " coins were sent from " + result.args.from +
            " to " + result.args.to + ".");
        console.log("Balances now:\n" +
            "Sender: " + Coin.balances.call(result.args.from) +
            "Receiver: " + Coin.balances.call(result.args.to));
    }
})

Ref: http://solidity.readthedocs.io/en/develop/introduction-to-smart-contracts.html