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?
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
So basically you don't trigger the event directly throughout the node.js code.
Let's say you have solidity contract which looks like this:
contract MyContract {
event Deposit(address indexed _from, uint256 _value);
function deposit(uint256 value) public {
...
emit Deposit(msg.sender, value);
...
}
}
In order to trigger the event you have to call the deposit(uint256)
function, which would look like this:
const myContract = new web3.eth.Contract(contract_abi, contract_address);
myContract.deposit("1000").send({ from: "0x..." }) // function call
And only if the transaction generated from the function call is successful and you have subscribed to this type of events you will be able to see the emitted event.
On how to subscribe to event
Events are triggered from within functions. So, you can trigger one by calling a function that calls an event. Here is more information: Solidity Event Documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With