Cannot read property 'contract' of undefined. Node api interacting with smart contract

by SwimmingG   Last Updated January 13, 2018 22:28 PM

Hi I'm trying to interact with an Ethereum smart contract from my node js api.

My controller function is as follows:

var web3 = require('web3');

module.exports.getTokenBalance = function(req, res) {
var abi = //long ABI
var MyContract = web3.eth.contract(abi);

  // initiate contract for an address
  var myContractInstance = MyContract.at('...');
  myContractInstance.balanceOf.call('addr', function(err, data) {

  }
}

I'm using the web3@0.20 package. When I try to call this API function I get the following error "Cannot read property 'contract' of undefined."

Am I missing something stupid?



Answers 1


require('web3') returns a class. You need to instantiate it first. Note the capital W:

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
// (or some other provider)

// web3.eth.contract should work down here.
smarx
smarx
January 13, 2018 23:31 PM

Related Questions


Unable to work with web3.js on geth

Updated April 20, 2018 19:28 PM



Deploy several contracts at once with webjs 1.0

Updated April 09, 2018 12:28 PM