web3.eth.contract is not a function when making contract

  • Whenever I try and make a contract, I get:

    web3.eth.contract is not a function

    I'm using this code:

    const path = require('path');
    const fs = require('fs');
    const solc = require('solc');
    const Web3 = require('web3');
    const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    // Compile the source code
    let input = fs.readFileSync('./contracts/ProofOfExistence3.sol', 'utf8');
    let output = solc.compile(input, 1);
    let abi = JSON.parse(output.contracts[':ProofOfExistence3'].interface);
    let bytecode = output.contracts[':ProofOfExistence3'].bytecode;
    let gasEstimate = web3.eth.estimateGas({data: bytecode}).then(console.log);
    // Contract object
    let MyContract = web3.eth.contract(abi);

    And if I only run this code below, I get undefined. The same code works in the browser but not in nodejs with the official web3 package.

    const Web3 = require('web3');
    const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

    Returns undefined.

    Any ideas? I'm running "testrpc" locally.

    I think this may be because you are using the new web3 1.0.0-beta.11. Try the documentation from https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#eth-contract, or with the previous version 0.20.0.

    Maybe if you try with `MyContract = web3.eth.contract(abi).at(contractAdress)`

    I'm experiencing the same issue but i'm using geth and its default console running a private chain builted up with geth+puppeth. I deploy my contract simply pasting the web3deply code from remix in the client console (opened by geth) then i instanciate the contract on a var using var myContract = web3.eth.contract(ABI); on any client of my chain. Now i call its functions using: myContract.at("0x9f8cedf1f93e46fac74cb9415db8bbec85f239b4").method(); Is this the right procedure? I mean, the other one listed on web3 documentation does not work for me, since i get back Contract is not a function I a

  • ErwanLent

    ErwanLent Correct answer

    4 years ago

    As Ismael suggested, setting the web3 version to 0.20.0 in my package.json allowed me to use this code.

    npm install ethereumjs-testrpc [email protected]

    Ideally, I would update my code to work with latest package but happy with this solution for now.

    switching to 0.20.0 also worked for me, I could get the instance of the contract with: `let svd = new web3.eth.Contract(abi, scAddress);` but wasn't able to call functions, always throw an error `cannot read property length`

    @Sepultura I encountered the same issue

    It worked for me as well - my usage: npm install ethereumjs-testrpc [email protected]

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM