Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat] estimate tx fee #12

Merged
merged 6 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
bump gas
  • Loading branch information
nkitlabs committed Nov 18, 2024
commit 2749f8f8b1f72c69b9a8e1f6158cf681ff83161c
3 changes: 1 addition & 2 deletions relayer/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -439,13 +439,12 @@ func (a *App) ShowKey(chainName string, keyName string) (string, error) {
}

cp, exist := a.targetChains[chainName]

if !exist {
return "", fmt.Errorf("chain name does not exist: %s", chainName)
}

if !cp.IsKeyNameExist(keyName) {
return "", fmt.Errorf("key name does not exist: %s", chainName)
return "", fmt.Errorf("key name does not exist: %s", keyName)
}

return cp.ShowKey(keyName), nil
Expand Down
42 changes: 41 additions & 1 deletion relayer/chains/evm/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ type Client interface {
) (decimal.NullDecimal, error)
Query(ctx context.Context, gethAddr gethcommon.Address, data []byte) ([]byte, error)
EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error)
EstimateGasPrice(ctx context.Context) (*big.Int, error)
EstimateGasTipCap(ctx context.Context) (*big.Int, error)
BroadcastTx(ctx context.Context, tx *gethtypes.Transaction) (string, error)
GetBalance(ctx context.Context, gethAddr gethcommon.Address) (*big.Int, error)
}
Expand Down Expand Up @@ -295,7 +297,7 @@ func (c *client) Query(ctx context.Context, gethAddr gethcommon.Address, data []
return res, nil
}

// EstimateGas estimates the gas of the given message.
// EstimateGas estimates the gas being used of the given message.
func (c *client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error) {
newCtx, cancel := context.WithTimeout(ctx, c.QueryTimeout)
defer cancel()
Expand All @@ -315,6 +317,44 @@ func (c *client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64,
return gas, nil
}

// EstimateGasPrice estimates the gas price of the EVM chain.
func (c *client) EstimateGasPrice(ctx context.Context) (*big.Int, error) {
newCtx, cancel := context.WithTimeout(ctx, c.QueryTimeout)
defer cancel()

gasPrice, err := c.client.SuggestGasPrice(newCtx)
if err != nil {
c.Log.Error(
"Failed to estimate gas price",
zap.Error(err),
zap.String("chain_name", c.ChainName),
zap.String("endpoint", c.selectedEndpoint),
)
return nil, err
}

return gasPrice, nil
}

// EstimateGasTipCap estimates the gas tip cap of the EVM chain.
func (c *client) EstimateGasTipCap(ctx context.Context) (*big.Int, error) {
newCtx, cancel := context.WithTimeout(ctx, c.QueryTimeout)
defer cancel()

gasTipCap, err := c.client.SuggestGasTipCap(newCtx)
if err != nil {
c.Log.Error(
"Failed to estimate gas tip cap",
zap.Error(err),
zap.String("chain_name", c.ChainName),
zap.String("endpoint", c.selectedEndpoint),
)
return nil, err
}

return gasTipCap, nil
}

// BroadcastTx sends the transaction to the EVM chain.
func (c *client) BroadcastTx(ctx context.Context, tx *gethtypes.Transaction) (string, error) {
c.Log.Debug(
Expand Down
2 changes: 1 addition & 1 deletion relayer/chains/evm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type EVMChainProviderConfig struct {
GasLimit uint64 `mapstructure:"gas_limit" toml:"gas_limit,omitempty"`

GasType GasType `mapstructure:"gas_type" toml:"gas_type"`
GasPrice uint64 `mapstructure:"gas_price" toml:"gas_price,omitempty"`
MaxGasPrice uint64 `mapstructure:"max_gas_price" toml:"max_gas_price,omitempty"`
MaxBaseFee uint64 `mapstructure:"max_base_fee" toml:"max_base_fee,omitempty"`
MaxPriorityFee uint64 `mapstructure:"max_priority_fee" toml:"max_priority_fee,omitempty"`
GasMultiplier float64 `mapstructure:"gas_multiplier" toml:"gas_multiplier"`
Expand Down
26 changes: 26 additions & 0 deletions relayer/chains/evm/gas.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package evm

import (
"fmt"
"math/big"
"reflect"
)

Expand Down Expand Up @@ -59,3 +60,28 @@ func ToGasType(s string) GasType {

return GasTypeUndefined
}

// GasInfo contains the gas type and gas information being used for submitting a transaction.
type GasInfo struct {
Type GasType
GasPrice *big.Int
GasPriorityFee *big.Int
GasBaseFee *big.Int
}

// NewGasLegacyInfo creates a new GasInfo instance with gas type legacy.
func NewGasLegacyInfo(gasPrice *big.Int) GasInfo {
return GasInfo{
Type: GasTypeLegacy,
GasPrice: gasPrice,
}
}

// NewGasEIP1559Info creates a new GasInfo instance with gas type EIP1559.
func NewGasEIP1559Info(gasPriorityFee, gasBaseFee *big.Int) GasInfo {
return GasInfo{
Type: GasTypeEIP1559,
GasPriorityFee: gasPriorityFee,
GasBaseFee: gasBaseFee,
}
}
113 changes: 96 additions & 17 deletions relayer/chains/evm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package evm
import (
"context"
"fmt"
"math"
"math/big"
"path"
"strings"
Expand Down Expand Up @@ -162,6 +161,16 @@ func (cp *EVMChainProvider) RelayPacket(
return fmt.Errorf("[EVMProvider] failed to connect client: %w", err)
}

gasInfo, err := cp.EstimateGas(ctx)
if err != nil {
cp.Log.Error(
"failed to estimate gas",
zap.Error(err),
zap.String("chain_name", cp.ChainName),
)
return fmt.Errorf("failed to estimate gas: %w", err)
}

retryCount := 0
for retryCount < cp.Config.MaxRetry {
cp.Log.Info(
Expand All @@ -172,7 +181,8 @@ func (cp *EVMChainProvider) RelayPacket(
zap.Int("retry_count", retryCount),
)

txHash, err := cp.handleRelay(ctx, packet, retryCount)
// create and submit a transaction; if failed, retry, no need to bump gas.
txHash, err := cp.handleRelay(ctx, packet, gasInfo)
if err != nil {
cp.Log.Error(
"HandleRelay error",
Expand Down Expand Up @@ -260,6 +270,19 @@ func (cp *EVMChainProvider) RelayPacket(
zap.Int("retry_count", retryCount),
)

// bump gas and retry
gasInfo, err = cp.BumpGas(ctx, gasInfo)
if err != nil {
cp.Log.Error(
"cannot bump gas",
zap.Error(err),
zap.String("chain_name", cp.ChainName),
zap.Uint64("tunnel_id", packet.TunnelID),
zap.Uint64("sequence", packet.Sequence),
zap.Int("retry_count", retryCount),
)
}

retryCount += 1
}

Expand All @@ -270,7 +293,7 @@ func (cp *EVMChainProvider) RelayPacket(
func (cp *EVMChainProvider) handleRelay(
ctx context.Context,
packet *bandtypes.Packet,
retryCount int,
gasInfo GasInfo,
) (txHash string, err error) {
calldata, err := cp.createCalldata(packet)
if err != nil {
Expand All @@ -280,11 +303,9 @@ func (cp *EVMChainProvider) handleRelay(
if len(cp.FreeSenders) == 0 {
return "", fmt.Errorf("no key available to relay packet")
}
sender := <-cp.FreeSenders

defer func() {
cp.FreeSenders <- sender
}()
sender := <-cp.FreeSenders
defer func() { cp.FreeSenders <- sender }()

cp.Log.Debug(
fmt.Sprintf("Relaying packet using address: %v", sender.Address),
Expand All @@ -294,7 +315,7 @@ func (cp *EVMChainProvider) handleRelay(
zap.Uint64("sequence", packet.Sequence),
)

tx, err := cp.newRelayTx(ctx, calldata, sender.Address, retryCount)
tx, err := cp.newRelayTx(ctx, calldata, sender.Address, gasInfo)
if err != nil {
return "", fmt.Errorf("failed to create an evm transaction: %w", err)
}
Expand Down Expand Up @@ -369,6 +390,68 @@ func (cp *EVMChainProvider) GetEffectiveGas(
}
}

// EstimateGas estimates the gas for the transaction.
func (cp *EVMChainProvider) EstimateGas(ctx context.Context) (GasInfo, error) {
switch cp.GasType {
case GasTypeLegacy:
gasPrice, err := cp.Client.EstimateGasPrice(ctx)
if err != nil {
return GasInfo{}, err
}

if gasPrice.Cmp(big.NewInt(int64(cp.Config.MaxGasPrice))) > 0 {
gasPrice = big.NewInt(int64(cp.Config.MaxGasPrice))
}

return NewGasLegacyInfo(gasPrice), nil
case GasTypeEIP1559:
priorityFee, err := cp.Client.EstimateGasTipCap(ctx)
if err != nil {
return GasInfo{}, err
}

if priorityFee.Cmp(big.NewInt(int64(cp.Config.MaxPriorityFee))) > 0 {
priorityFee = big.NewInt(int64(cp.Config.MaxPriorityFee))
}

return NewGasEIP1559Info(priorityFee, big.NewInt(int64(cp.Config.MaxBaseFee))), nil
default:
return GasInfo{}, fmt.Errorf("unsupported gas type: %v", cp.GasType)
}
}

// BumpGas bumps the gas price.
func (cp *EVMChainProvider) BumpGas(
ctx context.Context,
gasInfo GasInfo,
) (GasInfo, error) {
switch gasInfo.Type {
case GasTypeLegacy:
// calculate new gas price and compare with the one being setup in the configuration.
// TODO: if not set this, should query from the contract.
newGasPrice := MultiplyBigIntWithFloat64(gasInfo.GasPrice, cp.Config.GasMultiplier)
if newGasPrice.Cmp(big.NewInt(int64(cp.Config.MaxGasPrice))) > 0 {
newGasPrice = big.NewInt(int64(cp.Config.MaxGasPrice))
}

return NewGasLegacyInfo(newGasPrice), nil
case GasTypeEIP1559:
// calculate new priority fee and compare with the one being setup in the configuration.
// TODO: if not set this, should query from the contract.
newPriorityFee := MultiplyBigIntWithFloat64(gasInfo.GasPriorityFee, cp.Config.GasMultiplier)
if newPriorityFee.Cmp(big.NewInt(int64(cp.Config.MaxPriorityFee))) > 0 {
newPriorityFee = big.NewInt(int64(cp.Config.MaxPriorityFee))
}

// this can be fixed value, no need to query from chain.
newBaseFee := big.NewInt(int64(cp.Config.MaxBaseFee))

return NewGasEIP1559Info(newPriorityFee, newBaseFee), nil
default:
return GasInfo{}, fmt.Errorf("unsupported gas type: %v", cp.GasType)
}
}

// queryTunnelInfo queries the target contract information.
func (cp *EVMChainProvider) queryTunnelInfo(
ctx context.Context,
Expand Down Expand Up @@ -398,7 +481,7 @@ func (cp *EVMChainProvider) newRelayTx(
ctx context.Context,
data []byte,
sender gethcommon.Address,
retryCount int,
gasInfo GasInfo,
) (*gethtypes.Transaction, error) {
nonce, err := cp.Client.GetNonce(ctx, sender)
if err != nil {
Expand All @@ -420,25 +503,21 @@ func (cp *EVMChainProvider) newRelayTx(
}
}

multiplier := math.Pow(cp.Config.GasMultiplier, float64(retryCount))

// set fee info
var tx *gethtypes.Transaction
switch cp.GasType {
case GasTypeLegacy:
bumpedGasPrice := int64(math.Round(float64(cp.Config.GasPrice) * multiplier))

tx = gethtypes.NewTx(&gethtypes.LegacyTx{
Nonce: nonce,
To: &cp.TunnelRouterAddress,
Value: decimal.NewFromInt(0).BigInt(),
Data: data,
Gas: gasLimit,
GasPrice: big.NewInt(bumpedGasPrice),
GasPrice: gasInfo.GasPrice,
})

case GasTypeEIP1559:
bumpedPriorityFee := int64(math.Round(float64(cp.Config.MaxPriorityFee) * multiplier))
gasFeeCap := new(big.Int).Add(gasInfo.GasBaseFee, gasInfo.GasPriorityFee)

tx = gethtypes.NewTx(&gethtypes.DynamicFeeTx{
ChainID: big.NewInt(int64(cp.Config.ChainID)),
Expand All @@ -447,8 +526,8 @@ func (cp *EVMChainProvider) newRelayTx(
Value: decimal.NewFromInt(0).BigInt(),
Data: data,
Gas: gasLimit,
GasFeeCap: big.NewInt(bumpedPriorityFee + int64(cp.Config.MaxBaseFee)),
GasTipCap: big.NewInt(bumpedPriorityFee),
GasFeeCap: gasFeeCap,
GasTipCap: gasInfo.GasPriorityFee,
})

default:
Expand Down
1 change: 1 addition & 0 deletions relayer/chains/evm/sender.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ func LoadKeyInfo(homePath, chainName string) (KeyInfo, error) {

keyInfoDir := path.Join(homePath, keyDir, chainName, infoDir)
keyInfoPath := path.Join(keyInfoDir, infoFileName)

if _, err := os.Stat(keyInfoPath); err != nil {
// don't return error if file doesn't exist
return keyInfo, nil
Expand Down
11 changes: 11 additions & 0 deletions relayer/chains/evm/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package evm

import (
"fmt"
"math/big"
"strings"

gethcommon "github.com/ethereum/go-ethereum/common"
Expand All @@ -23,3 +24,13 @@ func HexToAddress(s string) (gethcommon.Address, error) {
func ConvertPrivateKeyStrToHex(privateKey string) string {
return strings.TrimPrefix(privateKey, privateKeyPrefix)
}

// MultiplyWithFloat64 multiplies a big.Int value with a float64 multiplier and convert back to big.Int.
func MultiplyBigIntWithFloat64(value *big.Int, multiplier float64) *big.Int {
multiplierBig := big.NewFloat(multiplier)
valueBig := new(big.Float).SetInt(value)
valueBig.Mul(valueBig, multiplierBig)

valueBigInt, _ := valueBig.Int(nil)
return valueBigInt
}