Search code examples
javascriptethereumweb3js

I have an error when reading a method with web3 (call)


I am trying to learn how to integrate with web3 but I am having some problems. (normal I just started)

But there is a problem that I can't solve.

Uncaught TypeError: Cannot read property 'retrieve' of undefined

I try to call a function but it does not work and I do not know how to solve it.

Here is the code:

const abi_c = [{"inputs": [],"name": "retrieve","outputs": [{"internalType": "uint256","name": "","type": "uint256"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "uint256","name": "num","type": "uint256"}],"name": "store","outputs": [],"stateMutability": "nonpayable","type": "function"}];
const account = "0x644f1439DBfc743853031d79021890af54bCA8Ae";

const web3js = new Web3(window.ethereum);
ethereum.autoRefreshOnNetworkChange = false;

var contract = web3js.eth.contract(abi_c, account);
var result = contract.methods.retrieve().call();
console.log(result);

Solution

  • You need to instantiate the web3js.eth.Contract class with the new keyword.

    var contract = new web3js.eth.Contract(abi_c, account);
    

    Without it, the var contract is pointing only to the uninstantiated definitions and static properties.

    Also, mind the capital C in Contract (docs).


    Then you're going to run into another issue.

    The .call() method returns a Promise, so you need to resolve it using the await expression (in an async function) or the callback function.

    // needs to be in an async function
    async function getResult() {
        var result = await contract.methods.retrieve().call();
        console.log(result);
    }
    
    contract.methods.retrieve().call().then(function (result) {
        // callback function
        console.log(result);
    });