1

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.

  • that is usually a problem of the blockchain node you are trying to connect to it( provider you set ) or maybe the contract is not deployed – Kaki Master Of Time Mar 23 '18 at 11:33
  • 1
    You have to define a web3.eth.defaultAccount – saitam May 11 '18 at 10:34
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.