12

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?

3
  • 3
    You might wish to try the Ethereum Stackexchange site for that kind of questions. Commented Mar 3, 2016 at 21:09
  • 9
    I disagree: it is a programming question and therefore perfectly suitable for StackOverflow (non-programming Ethereum questions are a different case). Commented Jun 5, 2016 at 16:02
  • Answer posted here stackoverflow.com/questions/72639036/… Commented Jun 16, 2022 at 11:24

10 Answers 10

16

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

Sign up to request clarification or add additional context in comments.

1 Comment

Better to use getPastEvents and trigger it twice for sure
11

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

2

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

Comments

2

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.

Comments

2

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);
   }
 }

Comments

1

Here are some steps you can follow to trigger an event in Solidity. I will use simple transaction examples to help you understand.

  1. Define an event. Example:
event NewTransaction(uint256 indexed id, address from, address to, uint256 amount);
  1. 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);
}
  1. Use 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:

  • Contract address and ABI is used to interact with the Solidity contract.
  • web3.eth.Contract function is used to create an instance of our contract.
  • We are defining contract.events.NewTransaction event listener to help listen for the NewTransaction event.
  • At last, we logged in the event data in the console when the event is triggered.

Comments

1

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

0

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

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.