Web3js – Contract Methods Undefined in JavaScript

javascriptweb3js

I am quite new with javascript web3 so don't be judge too hard.

I am using web3 version 1.0.0 beta.

I am taking the web3 reference this way:

if (typeof web3 !== 'undefined') {
    // If a web3 instance is already provided by Meta Mask.
    web3Provider = web3.currentProvider;
    web3 = new Web3(web3.currentProvider);
} else {
    // Specify default instance if no web3 instance provided
    web3Provider = new Web3.providers.HttpProvider('https://rinkeby.infura.io/v3/1b07b6c661304ef48005e16b43b7efa9');
    web3 = new Web3(web3Provider);
}

And then i am trying to get the contract reference:

var abi = [...];

console.log(abi);

var myContract = web3.eth.contract(abi, "0x2a2a7c53a6cc3d775e80c38d0fc446e73078902f");




myContract.methods.getPoll(1)
.call({from:localAccount}, function(error, result){
    console.log('error: ' + error);
    console.log(result);
})

The error is: Cannot read property 'getPoll' of undefined

Best Answer

You aren't creating the contract object correctly. What version of Web3.js are you using? 1.0 or 0.2.x? Here is how you do it for each:

1.0: var myContract = new web3.eth.Contract(abi, "0x2a2a7c53a6cc3d775e80c38d0fc446e73078902f")

0.2.x: var myContract = web3.eth.contract(abi).at("0x2a2a7c53a6cc3d775e80c38d0fc446e73078902f")

I highly suggest you use 1.0 if you aren't yet, even though it's in beta.