Reputation: 310
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?
Upvotes: 12
Views: 16298
Reputation: 23
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/
Upvotes: 1
Reputation: 33
Here are some steps you can follow to trigger an event in Solidity. I will use simple transaction examples to help you understand.
event NewTransaction(uint256 indexed id, address from, address to, uint256 amount);
function transfer(address _to, uint256 _amount) public {
// Transfer logic here
emit NewTransaction(txId, msg.sender, _to, _amount);
}
web3.js
to 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:
web3.eth.Contract
function is used to create an instance of our contract.contract.events.NewTransaction
event listener to help listen for the NewTransaction
event.Upvotes: 1
Reputation: 21
you can refer this
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.8.0;
contract EventExample {
event DataStored(uint256 val);
uint256 val;
function storeData(uint256 _val) external {
val = _val;
emit DataStored(val);
}
}
Upvotes: 2
Reputation: 19
Event is triggered when you call functions of smart contract via web3. You can just watch events in the node.js to know what happened on-chain.
Upvotes: 2
Reputation: 283
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.
Upvotes: 2
Reputation: 189
You'd have to define the event in your smart contract and have it trigger from a function in your smart contract . To trigger it through node you will have to call the function in your smart contract through web3.
Upvotes: 0
Reputation: 31
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.
Upvotes: 0
Reputation: 2726
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
Upvotes: 16
Reputation: 1809
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
Upvotes: 0
Reputation: 1810
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.
Upvotes: 11