How to calculate how much of gas fee would transaction use?

Does ts sdk have a method where i can calculate how much gas fee the transaction uses?

1 Like

@sway You can use getTransactionCost from the Provider class:

From an instantiated contract:

const { maxFee } = await myContract.functions
      .increment_count(1337)
      .txParams({ gasPrice })
      .getTransactionCost();

Or from a Transaction request:

const transactionRequest = new ScriptTransactionRequest({
  gasPrice: 1,
  gasLimit: 1000
})

const resources = await wallet.getResourcesToSpend([[1000, BaseAssetId]]);

request.addResources(resources);

const { maxFee } = await provider.getTransactionCost()

The maxFee value is the estimated max fee that this transaction will cost, and it needs to carry enough funds to cover it.

UPDATE:

@sway, be aware of the gasLimit value that you are using, this drastically impacts on the estimated maxFee. A high gasLimt value, means a higher maxFee.

One approach that you can use to avoid this problem is to get the gasUsed by the transaction and set it to the gasLimit:

const transactionRequest = new ScriptTransactionRequest({
  gasPrice: 1,
  gasLimit: 1000
})

const resources = await wallet.getResourcesToSpend([[1000, BaseAssetId]]);

request.addResources(resources);

const { maxFee, gasUsed } = await provider.getTransactionCost()

transactionRequest.gasLimit = gasUsed
1 Like

How does it work, why gasLimit affects the maxFee, isn’t it controversial? Is it a bug?