Skip to content

Commit

Permalink
nonce handling improvements (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
ToniRamirezM authored Feb 27, 2024
1 parent a09311f commit 6a126bc
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions ethtxmanager/ethtxmanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,42 @@ func pendingL1Txs(URL string, from common.Address, httpHeaders map[string]string
return mTxs, nil
}

// getTxNonce get the nonce for the given account
func (c *Client) getTxNonce(ctx context.Context, from common.Address) (uint64, error) {
// Get created transactions from the database for the given account
createdTxs, err := c.storage.GetByStatus(ctx, []MonitoredTxStatus{MonitoredTxStatusCreated})
if err != nil {
return 0, fmt.Errorf("failed to get created monitored txs: %w", err)
}

var nonce uint64
if len(createdTxs) > 0 {
// if there are pending txs, we adjust the nonce accordingly
for _, createdTx := range createdTxs {
if createdTx.Nonce > nonce {
nonce = createdTx.Nonce
}
}

nonce++
} else {
// if there are no pending txs, we get the pending nonce from the etherman
if nonce, err = c.etherman.PendingNonce(ctx, from); err != nil {
return 0, fmt.Errorf("failed to get pending nonce: %w", err)
}
}

return nonce, nil
}

// Add a transaction to be sent and monitored
func (c *Client) Add(ctx context.Context, to *common.Address, forcedNonce *uint64, value *big.Int, data []byte) (common.Hash, error) {
var nonce uint64
var err error

if forcedNonce == nil {
// get next nonce
nonce, err = c.etherman.CurrentNonce(ctx, c.from)
nonce, err = c.getTxNonce(ctx, c.from)
if err != nil {
err := fmt.Errorf("failed to get current nonce: %w", err)
log.Errorf(err.Error())
Expand Down Expand Up @@ -703,7 +731,7 @@ func (c *Client) reviewMonitoredTx(ctx context.Context, mTx *monitoredTx, mTxLog
// causing possible side effects and wasting resources.
func (c *Client) reviewMonitoredTxNonce(ctx context.Context, mTx *monitoredTx, mTxLogger *log.Logger) error {
mTxLogger.Debug("reviewing nonce")
nonce, err := c.etherman.CurrentNonce(ctx, mTx.From)
nonce, err := c.getTxNonce(ctx, mTx.From)
if err != nil {
err := fmt.Errorf("failed to load current nonce for acc %v: %w", mTx.From.String(), err)
mTxLogger.Errorf(err.Error())
Expand Down

0 comments on commit 6a126bc

Please sign in to comment.