乐闻世界logo
搜索文章和话题

How can I listen the event emitted from smart contract in web3 js?

1个答案

1

Listening for events emitted by smart contracts in Web3.js is an effective way to enable your frontend application to respond in real-time to on-chain operations. Here is a systematic step-by-step guide along with a simple example to demonstrate how to achieve this:

Steps:

  1. Deploy the Smart Contract: Ensure your smart contract is deployed on the blockchain and includes triggerable events.

  2. Obtain the Smart Contract's ABI and Address: To interact with the smart contract, you must know its ABI (Application Binary Interface) and the deployed address.

  3. Create a Contract Instance with Web3.js: Use the smart contract's ABI and address to create a contract instance.

  4. Listen for Events: Use the contract instance to call the .events method to listen for specific events.

Example:

Suppose we have a simple smart contract that includes an event named DataUpdated, which is triggered when data is updated:

solidity
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract MyContract { event DataUpdated(uint256 newValue); uint256 public data; function updateData(uint256 _data) public { data = _data; emit DataUpdated(_data); } }

Here is an example of how to use Web3.js to listen for the DataUpdated event:

javascript
// Import the Web3 module const Web3 = require('web3'); // Connect to an Ethereum node const web3 = new Web3('ws://localhost:8546'); // Smart contract ABI const abi = [ { "constant": true, "inputs": [], "name": "data", "outputs": [{"name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function" }, { "anonymous": false, "inputs": [{"indexed": false, "name": "newValue", "type": "uint256"}], "name": "DataUpdated", "type": "event" } ]; // Smart contract address const contractAddress = '0x. ..'; // Create a contract instance const myContract = new web3.eth.Contract(abi, contractAddress); // Listen for DataUpdated events myContract.events.DataUpdated({ fromBlock: 0 }, function(error, event) { if (error) console.log(error); console.log('Data Updated:', event.returnValues.newValue); });

Summary:

This code will listen for all DataUpdated events starting from block 0 and print the new value to the console. This enables your application to respond in real-time to changes in the contract's state, providing a more dynamic and interactive user experience.

Note that this example uses WebSocket (ws://localhost:8546), which is necessary for real-time updates. If you use an HTTP connection, you will not be able to listen for events in real-time.

2024年8月14日 22:06 回复

你的答案