2

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.

2
  • 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 Commented Mar 23, 2018 at 11:33
  • 2
    You have to define a web3.eth.defaultAccount
    – sunwarr10r
    Commented May 11, 2018 at 10:34

1 Answer 1

1

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 and acknowledge you have read our privacy policy.

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