[Ethereum] How estimate smart contract deployment and transactions price

priceropsten

I can deploy the same smart contract and invoking four transactions on it on Ropsten network.

How can I estimate the price of the exactly same operations but on the Mainnet network?

Best Answer

You can achieve this without sending any actual transactions.

//create a web3 instance
const web3 = new Web3(Web3.givenProvider || "ws://localhost:8546");

//create contract instance, leave address empty if creating new contract
myContract = new web3.eth.Contract(jsonInterface, address, options)

//check gas needed to deploy contract
myContract.deploy({
    data: 'BYTECODE',
    arguments: [123, 'My String']
})
.estimateGas((err, gas) => {
    console.log(gas);
});

//check gas needed to execute method calls of contract
myContract.methods.myMethod(123).estimateGas(function(error, gasAmount){
    ...
});

//to get current gas price of the network
web3.eth.getGasPrice([callback])

After this you can multiple the gasprice of the network with the estimated gas of the contract deployment to get the actual price to deploy contract and you can do this with every transaction you want to send

Related Topic