[Ethereum] call to smart contract function from express project using web3

metamasknodejsweb3js

I'm trying to create a API fo my smart contract functions like following:

router.get('/',function (req,res) {
    var web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/key'));
    var DataPassContract = web3.eth.contract(abi);
    var dataPass = DataPassContract.at('contract address');

    dataPass.add('myaddress','a','a','a',{
        from: 'other address'
    }, (err, result) => {
        if (err) throw err;
        if (result) {
                res.send('yes');
            }
    });
});

When executed i want this function to open Mtamask and ask the client to confirm the transaction but when calling it I get this error:

if (err) throw err;
                 ^

Error: Invalid JSON RPC response: ""

Any help would be appreciated.

Best Answer

You are dealing two separate web3 instance.

  • 1) from your code that is var web3

  • 2) another is window.web3 (provided by metamask)

Please check this

var web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/key'));

Here, you are directly connected to https://ropsten.infura.io/key by web3js.

But web3 (in metamask) has no idea in which blockchain node you are connected to. So you can ignore you manual connection and connect to the blockchain node like this picture.

enter image description here

Then re-write your code like this

    var web3; 
    window.addEventListener('load', function() {
      if (typeof window.web3 === 'undefined') {
        web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/key'));
        //this one needs further wallet management
      } else {
        web3= new Web3(window.web3.currentProvider); 
        //do your other jobs here like below
         var DataPassContract = web3.eth.contract(abi);
      } 
    });

Note: If you are already connected to metamask blockchain node then you can open metamask and ask the client to confirm the transaction.

Related Topic