TransWikia.com

Ropsten infura test network + web3 js event listener

Ethereum Asked by Kapil on October 26, 2020

I have deployed contracts on ropsten test network.
truffle.js

ropsten: {
  provider: function() {  
    return new HDWalletProvider(mnemonic, "https://ropsten.infura.io/<api-token>")
  },
  network_id: '*',
  gas:"4000000"
}

store.sol

pragma solidity ^0.4.17;

contract SimpleStorage {
  uint myVariable;
  event emitval();

  function setValue(uint x) public {
    emitval();
    myVariable = x;
  }

  function getValue() public returns (uint) {
    emitval();
    return myVariable;
  }
}

In my node js code I am using web3 js to call/listen methods/events from contracts.

my node js file is

web3.setProvider(new Web3.providers.WebsocketProvider('https://ropsten.infura.io/<api-token>'));

and for listening events I wrote

var contracts = new web3.eth.Contract(importedjson.abi, deployedaddressat)

contracts.events.emitval(function(error, result){
    if(error) { console.log(error);} 
    else { console.log('Event setVal:', result);}
})

When I am calling methods of solidity (setValue() or getValue() which emits emitval() event), I am not able to listen it on node js code.

Could you please help me out.
I am uisng latest web3js version “1.0.0-beta.33”.

2 Answers

Can you try replacing web3.setProvider(new Web3.providers.WebsocketProvider('https://ropsten.infura.io/'));

With

web3.setProvider(new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/'));

It might be a websocket issue as web3 1.0 doesn't support events for http.

Answered by Ashish Mishra on October 26, 2020

I can't see such setVal events in your contract. Indeed, in the contract, the name is emitval. You can try to change your code

contracts.events.emitval(function(error, result){
    if(error) { console.log(error);} 
    else { console.log('Event setVal:', result);}
});

and alternative is to listen to all the contract events using myContract.events.allEvents. ref

Answered by mirg on October 26, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP