I use web3.js and try to take a value of the variable from the smart contract.

My code for it is:

var contract = web3.eth.contract(abi).at(address);

where abi - json array and address - valid working address.

Part of abi json object is

      "constant": true,
      "inputs": [],
      "name": "weiRaised",
      "outputs": [
          "name": "",
          "type": "uint256"
      "payable": false,
      "type": "function"

When I use this code:


I see "weiRaised" in the console.

But if I use


I see 'undefined'.

What I am doing wrong? How Can I get the variable from the smart contract, based on abi and web3.js?


After printing stuff on the console, God let me go to sleep with joy =)

var contract = web3.eth.contract(abi).at(address);
async function getContractPublicVariable() {
    const weiRaised = await contract.methods.weiRaised.call().call();

so the idea is contract.methods.VARIABLENAME.call().call();


Web3.js will automagically map the ABI functions onto the contract object that you get back from web3.eth.contract(abi).at(address).

This means you can access the value of the variables by doing something like:

let weiRaisedValue = contract.weiRaised.call()

  • console.log(contract.weiRaised.call()); - TypeError: contract.weiRaised is undefined
    – Sergei
    Nov 29 '17 at 19:05
  • 1
    @Sergei Are you using web3 v1.0? In that case it should be contract.methods.weiRaised.call().then(function (res) { console.log(res); }). More info from web3 v1.0 documentation.
    – Ismael
    Nov 30 '17 at 21:56
  • console.log(web3.version); gives this: Object { api: "0.20.2", node: Getter, getNode: e(), network: Getter, getNetwork: e(), ethereum: Getter, getEthereum: e(), whisper: Getter, getWhisper: e() }
    – Sergei
    Dec 1 '17 at 23:53
  • your code gives this error to me: TypeError: contract.methods is undefined
    – Sergei
    Dec 1 '17 at 23:53

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.