How can I estimate gas fees before sending a transaction?

Viewed 243

I would like to estimate the gas fees for a particular transaction on behalf of my users before sending it.

If I know the current going rate for gas on the Chainweb blockchain, and I know how many units of gas a transaction will consume, then I can multiply them together to provide an estimate of how much it will cost to send a particular transaction.

How do I get those two pieces of information?

First, how can I get the current going rate for gas on Chainweb?

Second, is there a rough way to estimate the number of units of gas a transaction will consume? For example, it costs 21,000 units of gas to transfer Ether from one address to another. How do I determine how many units of gas it will take to transfer KDA from one wallet to another? Or how many units of gas it will take to execute N steps of my contract?

1 Answers

For the going rate I am only certain how to get at the current minimum gas price. It is set in the default config of the Kadena node. Currently: 0.00000001. That has always allowed me to do transactions.

For estimating the gas amount you can use the Pact gas log functionality. Load your contract on a local pact executable and use a .repl file with tests to get a simulation of the gas units cost of the specific contract calls your will perform. In your repl test script you enclose the contract calls you need to measure with

(env-gas 0)(env-gaslog)

to reset the gas log and start, and

(env-gaslog)

To display the gas units consumed since last reset.

Before you can start logging you need to set the gas model to table and a sufficiently high gas limit.

Assume you are working on the coin contract and you need to know how much units of gas the transaction will consume you can use a test as below:

 (env-gasmodel "table")
 (env-gaslimit 150000)
 (load "fungible-v2.pact")
 (load "coin.pact")
 (env-gas 0)  (env-gaslog)
 (create-table coin.coin-table)
 (env-gaslog)

If you want to run the above you need to copy the source code of the coin contract (coin.pact) and fungible-v2 standard (fungible-v2.pact) together in a folder with this repl. You can run the above:

$ pact -t test.repl

For full reference: https://pact-language.readthedocs.io/en/stable/pact-functions.html#env-gas

Related