1

I am new to Etherium smart contracts. I have created a smart contract and deployed it on https://kovan.etherscan.io. Now I am trying to access this contract from node js. below is my code but I am not getting how to set provider and further things. Can anybody help me with this?

const Web3 = require('web3');
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:8546', null, {});

module.exports = {
        tmp1: function (req, res, next){
                try{
                        Image(req,res)
                }
                catch(err){
                        console.error(err)
                }
        }
}
function Image (req,res){ 
        const abi =[{ my json of abi}];
        var contractInstance = web3.eth.contract(abi).at('0xB02542CF6C19B70813694EB9CFD60C10a796d83f');
        var result = contractInstance.buyCoordinator(req.query.coordinator,req.query.coimage).call();
        console.log(result);
        res.send(result);
}

I am totally confused about how to set provider https://kovan.etherscan.io and how exactly it will work or know that I have deployed contract here and my account address.

  • result returns promise, so you have to async/await it or use .then() – rstormsf Apr 27 at 8:44
0

The reason your method won't work is because you aren't connecting to Kovan testnet anywhere. Go to http://infura.io and create a Kovan testnet account (if you don't have one already). Infura provides you with an "API KEY" for kovan.

import Web3 from 'web3' //or const Web3 = require('web3'); or direct import from node_modules

const testnet = `https://kovan.infura.io/'+API_KEY
const web3 = new Web3( new Web3.providers.HttpProvider(testnet) )

Another way of doing it is in conjunction with Truffle and Infura: On creating an infura kovan testnet account, you also get the 12 words for mnemonic.

const Web3 = require(‘web3’);
const MNEMONIC = <YOUR 12 words e.g.: ‘aquaman superman batman shazam flash wonderwoman greenlantern ironman captainamerica hulk blackwidow thanos’>
const API_KEY = ..

const provider = new HDWalletProvider(MNEMONIC, ‘https://kovan.infura.io/'+API_KEY);
const web3 = new Web3(provider);
  • I create a new API key. Now it seems the provider is set properly. Thanx!! – Varsh May 2 at 6:32
  • Great thanks! Please upvote the answer and mark it as the solution! – Rahul Kothari May 2 at 9:43

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.