Web3.js – Can’t Deploy Contract with Web3.js and Ganache-CLI

contract-deploymentganache-clisolcweb3js

I'm using the solc module to compile a Solidity contract. The compilation step looks to be working correctly, however, when I attempt to deploy the contract to the Ganache network (in a Mocha test), the promise never resolves. Here's what I've already checked:

1) Increasing the timeout to 3 minutes – still nothing

2) Another promise using await, which resolved correctly, so I don't think it's a Mocha config issue with promises

3) Estimated gas – I should have more than enough based on the estimateGas function

4) Updating all versions (web3, solc, ganache-cli) to their most recent versions

Here's the compile.js code:

const path = require('path');
const fs = require('fs');
const solc = require('solc');

const contractPath = path.resolve(__dirname, 'MyContract.sol');
const source = fs.readFileSync(contractPath, 'utf8');

let jsonContractSource = JSON.stringify({
    language: 'Solidity',
    sources: {
      'Task': {
          content: source,
       },
    },
    settings: { 
        outputSelection: {
            '*': {
                '*': ['abi',"evm.bytecode"],   
             // here point out the output of the compiled result
            },
        },
    },
});


module.exports = JSON.parse(solc.compile(jsonContractSource)).contracts.Task.MyContract;

And the test file:

const ganache = require('ganache-cli');
const Web3 = require('web3');
const provider = ganache.provider()
const web3 = new Web3(provider);
const { abi, evm } = require('../../contracts/compile');

let accounts;
let myContract;

before(async function() {

    accounts = await web3.eth.getAccounts()

    myContract = await new web3.eth.Contract(abi)
        .deploy({data: "0x" + evm.bytecode.object, arguments: []})
        .send({from: accounts[0], gas: 5000000});

    console.log("finished")

});

EDIT: One other thing – I was able to deploy a contract to the Ganache network with Remix, so I think the problem is isolated to the ganache-cli.

Best Answer

Found the answer. It turns out that the web3 options aren't exactly optional for Ganache:

I had to change:

const provider = ganache.provider()
const web3 = new Web3(provider);

To:

const provider = ganache.provider()
const OPTIONS = {
  defaultBlock: "latest",
  transactionConfirmationBlocks: 1,
  transactionBlockTimeout: 5
};
const web3 = new Web3(provider, null, OPTIONS);
Related Topic