1
0
mirror of https://github.com/oceanprotocol/ocean.js.git synced 2024-11-26 20:39:05 +01:00

add generic estimateGas() function

This commit is contained in:
Miquel A. Cabot 2022-04-05 14:53:04 +02:00
parent 05e8a91227
commit 23101a185f

View File

@ -11,6 +11,7 @@ import {
import { Config } from '../models'
import { minAbi } from './minAbi'
import LoggerInstance from './Logger'
import { GASLIMIT_DEFAULT } from './Constants'
export function setContractDefaults(contract: Contract, config: Config): Contract {
if (config) {
@ -162,3 +163,29 @@ export async function amountToUnits(
LoggerInstance.error(`ERROR: FAILED TO CALL DECIMALS(), USING 18', ${e.message}`)
}
}
/**
* Estimates the gas used when a function would be executed on chain
* @param {string} from account that calls the function
* @param {Function} functionToEstimateGas function that we need to estimate the gas
* @param {...any[]} args arguments of the function
* @return {Promise<number>} gas cost of the function
*/
export async function estimateGas(
from: string,
functionToEstimateGas: Function,
...args: any[]
): Promise<number> {
let estimatedGas = GASLIMIT_DEFAULT
try {
estimatedGas = await functionToEstimateGas.apply(null, args).estimateGas(
{
from: from
},
(err, estGas) => (err ? GASLIMIT_DEFAULT : estGas)
)
} catch (e) {
LoggerInstance.error(`ERROR: Estimate gas failed!`, e)
}
return estimatedGas
}