Skip to content

Commit 0864122

Browse files
authored
Merge pull request #617 from EYBlockchain/estimate-gas
Better Gas estimation for on-chain calls
2 parents 1740fdd + af95a23 commit 0864122

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

‎wallet/src/common-files/utils/contract.js

+24-7
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ const { proposerUrl } = global.config;
1010

1111
const options = global.config.WEB3_OPTIONS;
1212

13+
// This is hardcoded because we just use it for all estimation.
14+
const gasEstimateEndpoint =
15+
'https://vqxy02tr5e.execute-api.us-east-2.amazonaws.com/production/estimateGas';
16+
1317
// returns a web3 contract instance
1418
export async function getContractInstance(contractName, deployedAddress) {
1519
const web3 = Web3.connection();
@@ -41,18 +45,31 @@ export function getContractAddress(contractName) {
4145
*/
4246
export async function submitTransaction(unsignedTransaction, contractAddress, fee) {
4347
const web3 = Web3.connection();
44-
let gasPrice = 20000000000;
45-
const gas = (await web3.eth.getBlock('latest')).gasLimit;
46-
const blockGasPrice = 2 * Number(await web3.eth.getGasPrice());
47-
if (blockGasPrice > gasPrice) gasPrice = blockGasPrice;
48+
const blockGasPrice = Number(await web3.eth.getGasPrice());
4849
const from = await Web3.getAccount();
50+
let proposedGasPrice = blockGasPrice; // This is the backup value if external estimation fails;
51+
try {
52+
// Call the endpoint to estimate the gas fee.
53+
const res = (await axios.get(gasEstimateEndpoint)).data.result;
54+
proposedGasPrice = Number(res?.ProposeGasPrice) * 10 ** 9 || blockGasPrice;
55+
} catch (error) {
56+
console.log('Gas Estimation Failed: ', error);
57+
}
58+
// Estimate the gasLimit
59+
const gasLimit = await web3.eth.estimateGas({
60+
from,
61+
to: contractAddress,
62+
data: unsignedTransaction,
63+
});
64+
65+
const gasLimitWithBuffer = Math.ceil(Number(gasLimit) * 1.1); // 10% seems a reasonable buffer.
66+
4967
const tx = {
5068
from,
5169
to: contractAddress,
5270
data: unsignedTransaction,
53-
gas: web3.utils.toHex(gas),
54-
gasPrice: web3.utils.toHex(gasPrice),
55-
// maxPriorityFeePerGas: web3.utils.toHex(1 * 10 ** 9),
71+
gas: web3.utils.toHex(gasLimitWithBuffer),
72+
gasPrice: web3.utils.toHex(proposedGasPrice),
5673
};
5774

5875
if (fee) tx.value = web3.utils.toHex(fee);

0 commit comments

Comments
 (0)