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?
-
3You might wish to try the Ethereum Stackexchange site for that kind of questions.q9f– q9f2016-03-03 21:09:08 +00:00Commented Mar 3, 2016 at 21:09
-
9I disagree: it is a programming question and therefore perfectly suitable for StackOverflow (non-programming Ethereum questions are a different case).bortzmeyer– bortzmeyer2016-06-05 16:02:55 +00:00Commented Jun 5, 2016 at 16:02
-
Answer posted here stackoverflow.com/questions/72639036/…ShivaPendem– ShivaPendem2022-06-16 11:24:48 +00:00Commented Jun 16, 2022 at 11:24
10 Answers
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
1 Comment
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.
Comments
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.
Comments
Here are some steps you can follow to trigger an event in Solidity. I will use simple transaction examples to help you understand.
- Define an event. Example:
event NewTransaction(uint256 indexed id, address from, address to, uint256 amount);
- Emit an event in the contract. Here's how you can do it:
function transfer(address _to, uint256 _amount) public {
// Transfer logic here
emit NewTransaction(txId, msg.sender, _to, _amount);
}
- Use
web3.jsto interact with the Solidity contract. Here's how you can do this:
// Import the web3.js library
const Web3 = require('web3');
// Connect to the local Ethereum node using HTTP
const web3 = new Web3('http://localhost:8545');
// Define the contract address and ABI
const contractAddress = '0x123...'; // replace with your contract address
const abi = [...]; // replace with your contract ABI
// Create an instance of the contract using web3.js
const contract = new web3.eth.Contract(abi, contractAddress);
// Listen for the NewTransaction event using web3.js
const transferEvent = contract.events.NewTransaction({ fromBlock: 0, toBlock: 'latest' });
// Log the event data when the event is triggered
transferEvent.on('data', (event) => {
console.log(event.returnValues);
});
Code Explanation:
- Contract address and ABI is used to interact with the Solidity contract.
web3.eth.Contractfunction is used to create an instance of our contract.- We are defining
contract.events.NewTransactionevent listener to help listen for theNewTransactionevent. - At last, we logged in the event data in the console when the event is triggered.
Comments
First of all triggering the event is not something related to your web3 script. The event should be called in the function which you call by your nodejs project.
As an example let's think in your solidity smart contract there is an event called "ValueSet()" and a function called "setValue"
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SampleContract {
// Define an event
event ValueSet(address indexed setter, uint256 newValue);
uint256 private value;
// Function to set a new value and trigger the event
function setValue(uint256 _newValue) public {
value = _newValue;
// Trigger the event
emit ValueSet(msg.sender, _newValue); //This is where the event is triggered. This must be included in the function.
}
// Function to get the current value
function getValue() public view returns (uint256) {
return value;
}
}
When you call the function from your web3 script the event will be triggered.
For web3js
sampleContract.methods.setvalue(123).send();
For ethersjs
sampleContract.setValue(123).send();
(Contract object initialization, provider/signer initialization must be done according to the web3js and ethersjs docs)
https://web3js.readthedocs.io/en/v1.10.0/web3-eth-contract.html# https://docs.ethers.org/v6/
Comments
Events allow the convenient usage of the EVM logging facilities, which in turn can be used to “call” JavaScript callbacks in the user interface of a dapp, which listen for these events, you can check here for detail
Comments
Add event emit to a function and than call that function. You can also use mock contract (only if necessary) in case you just use events for debugging and don't need an event in contract itself. In this case get a return from your contract function into a mock's function and than fire an event there with that return value. In JS you just need to only call mock's function and then read an event.