After more than a week of google searches, scouring stack exchange, combining bits and pieces of what I found, and with my own trial and error, I finally came up with everything needed to successfully deploy a compiled smart contract ganache. It wasn't easy to figure out. I haven't seen a full solution presented anywhere in my searches, so I wanted to share my findings here, in case you're in a similar situation.
The first key thing is to only use versions of web3 and ganache-cli that are compatible. I've noted my findings in the code below. It looks like very recent web3 and recent ganache versions are currently incompatible due to bugs, which are probably being fixed. If you'd like to reproduce those problems, simply upgrade to a version of web3 later than 1.0.0-beta.37 and try the code posted below.
The second thing I learned was how to correctly implement the async programming, which takes a little care, especially if you're new to JavaScript as I am.
Here is fully working code to deploy a contract from its compiled JSON representation using Web3 and gnache:
// Tested using web3@^1.0.0-beta.37 and ganache-cli@^6.4.1
const ganache = require('ganache-cli');
const Web3 = require('web3');
const fs = require("fs");
async function deploy() {
const provider = ganache.provider();
provider.setMaxListeners(15); // Suppress MaxListenersExceededWarning warning
const web3 = new Web3(provider);
this.accounts = await web3.eth.getAccounts();
// Read in the compiled contract code and fetch ABI description and the bytecode as objects
const compiled = JSON.parse(fs.readFileSync("output/contracts.json"));
const abi = compiled.contracts["ContractName.sol"]["ContractName"].abi;
const bytecode = compiled.contracts['ContractName.sol']['ContractName'].evm.bytecode.object;
// Deploy the contract and send it gas to run.
this.contract = await new web3.eth.Contract(abi)
.deploy({data:'0x'+ bytecode, arguments: []})
.send({from: this.accounts[0], gas:'5000000'});
return this;
}
deploy().then(useContract);
function useContract(result) {
// Use result.accounts and result.contract here to do what you like.
console.log('Contract deployed to: ' + result.contract.options.address);
console.log('Owner address is: ' + result.accounts[0]);
}
If this helps you, please upvote. I'm a new contributor here. Thanks!