Skip to content

Commit

Permalink
Merge pull request #8 from zarbanio/feat-add-retries-to-sender
Browse files Browse the repository at this point in the history
chore: add retry to dex trader
  • Loading branch information
amintalebi authored Dec 11, 2024
2 parents 1364850 + 8924f88 commit c578301
Showing 1 changed file with 32 additions and 13 deletions.
45 changes: 32 additions & 13 deletions internal/dextrader/dextrader.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log"
"math/big"
"time"

"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -95,22 +96,40 @@ func (c *client) GetExecutorAddress() common.Address {
}

func (c *client) Trade(ctx context.Context, token0, token1 domain.Token, poolFee *big.Int, amountsIn, amountOutMinimum decimal.Decimal) (*types.Transaction, error) {
gasPrice, err := c.eth.SuggestGasPrice(context.Background())
if err != nil {
return nil, err
}
const maxRetries = 10
const retryDelay = time.Second

auth, err := chain.GetAccountAuth(ctx, c.eth, c.executor.PrivateKey())
if err != nil {
return nil, err
}
var lastErr error

auth.GasPrice = gasPrice
tx, err := c.dexTrader.Trade(auth, token0.Address(), token1.Address(), poolFee, math.Denormalize(amountsIn, token0.Decimals()), math.Denormalize(amountOutMinimum, token1.Decimals()))
if err != nil {
return nil, err
for attempt := 1; attempt <= maxRetries; attempt++ {
gasPrice, err := c.eth.SuggestGasPrice(context.Background())
if err != nil {
lastErr = fmt.Errorf("attempt %d: failed to suggest gas price: %w", attempt, err)
time.Sleep(retryDelay)
continue
}

auth, err := chain.GetAccountAuth(ctx, c.eth, c.executor.PrivateKey())
if err != nil {
lastErr = fmt.Errorf("attempt %d: failed to get account auth: %w", attempt, err)
time.Sleep(retryDelay)
continue
}

auth.GasPrice = gasPrice
tx, err := c.dexTrader.Trade(auth, token0.Address(), token1.Address(), poolFee, math.Denormalize(amountsIn, token0.Decimals()), math.Denormalize(amountOutMinimum, token1.Decimals()))
if err != nil {
lastErr = fmt.Errorf("attempt %d: trade execution failed: %w", attempt, err)
time.Sleep(retryDelay)
continue
}

// Trade succeeded
return tx, nil
}
return tx, nil

// All retries failed
return nil, fmt.Errorf("trade failed after %d attempts: %w", maxRetries, lastErr)
}

func (c *client) EstimateDexTradeGasFee(token0, token1 domain.Token, poolFee *big.Int, amountIn, amountOutMinimum decimal.Decimal) (decimal.Decimal, error) {
Expand Down

0 comments on commit c578301

Please sign in to comment.