Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active March 5, 2023 10:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save miguelmota/117caf685b84cba8317f07e1ac6cd0da to your computer and use it in GitHub Desktop.
Save miguelmota/117caf685b84cba8317f07e1ac6cd0da to your computer and use it in GitHub Desktop.
Go estimate ethereum transaction gas limit and add 30% percent
package main
import (
"context"
"fmt"
"log"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
)
func main() {
client, err := ethclient.Dial("https://rinkeby.infura.io")
if err != nil {
log.Fatal(err)
}
tokenAddress := common.HexToAddress("0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1")
estimatedGas, err := client.EstimateGas(context.Background(), ethereum.CallMsg{
To: &tokenAddress,
Data: []byte{0},
})
if err != nil {
log.Fatal(err)
}
gasLimit := int(float64(estimatedGas) * 1.30)
fmt.Println(gasLimit) // 27305
}
@aemet93
Copy link

aemet93 commented May 27, 2022

Why * 1.3?
Thanks!

@miguelmota
Copy link
Author

@aemet93 it's an arbitrary multiplier to make sure transaction goes through quickly. This snippet is outdated and now transactions require max base fee and priority fee

@aemet93
Copy link

aemet93 commented May 27, 2022

@miguelmota thanks for the answer. As I understand, that priority and etc should be set by client.
Now I need to estimate transaction (gas price and gas limit) on the backend and send it to client (to build raw tx).
And I used for it EstimateGas and SuggestGasPrice(), is it wrong?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment