arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/coordinator/txmanager.go
coordinator/txmanager.goRaw
  1package coordinator
  2
  3import (
  4	"context"
  5	"fmt"
  6	"math/big"
  7	"strings"
  8	"time"
  9
 10	"github.com/ethereum/go-ethereum"
 11	"github.com/ethereum/go-ethereum/accounts"
 12	"github.com/ethereum/go-ethereum/accounts/abi/bind"
 13	"github.com/ethereum/go-ethereum/core"
 14	"github.com/ethereum/go-ethereum/core/types"
 15	"github.com/hermeznetwork/hermez-node/common"
 16	"github.com/hermeznetwork/hermez-node/db/l2db"
 17	"github.com/hermeznetwork/hermez-node/eth"
 18	"github.com/hermeznetwork/hermez-node/log"
 19	"github.com/hermeznetwork/hermez-node/synchronizer"
 20	"github.com/hermeznetwork/tracerr"
 21)
 22
 23// TxManager handles everything related to ethereum transactions:  It makes the
 24// call to forge, waits for transaction confirmation, and keeps checking them
 25// until a number of confirmed blocks have passed.
 26type TxManager struct {
 27	cfg       Config
 28	ethClient eth.ClientInterface
 29	l2DB      *l2db.L2DB   // Used only to mark forged txs as forged in the L2DB
 30	coord     *Coordinator // Used only to send messages to stop the pipeline
 31	batchCh   chan *BatchInfo
 32	chainID   *big.Int
 33	account   accounts.Account
 34	consts    synchronizer.SCConsts
 35
 36	stats       synchronizer.Stats
 37	vars        synchronizer.SCVariables
 38	statsVarsCh chan statsVars
 39
 40	discardPipelineCh chan int // int refers to the pipelineNum
 41
 42	minPipelineNum int
 43	queue          Queue
 44	// lastSuccessBatch stores the last BatchNum that who's forge call was confirmed
 45	lastSuccessBatch common.BatchNum
 46	// lastPendingBatch common.BatchNum
 47	// accNonce is the account nonce in the last mined block (due to mined txs)
 48	accNonce uint64
 49	// accNextNonce is the nonce that we should use to send the next tx.
 50	// In some cases this will be a reused nonce of an already pending tx.
 51	accNextNonce uint64
 52
 53	lastSentL1BatchBlockNum int64
 54}
 55
 56// NewTxManager creates a new TxManager
 57func NewTxManager(ctx context.Context, cfg *Config, ethClient eth.ClientInterface, l2DB *l2db.L2DB,
 58	coord *Coordinator, scConsts *synchronizer.SCConsts, initSCVars *synchronizer.SCVariables) (*TxManager, error) {
 59	chainID, err := ethClient.EthChainID()
 60	if err != nil {
 61		return nil, tracerr.Wrap(err)
 62	}
 63	address, err := ethClient.EthAddress()
 64	if err != nil {
 65		return nil, tracerr.Wrap(err)
 66	}
 67	accNonce, err := ethClient.EthNonceAt(ctx, *address, nil)
 68	if err != nil {
 69		return nil, err
 70	}
 71	log.Infow("TxManager started", "nonce", accNonce)
 72	return &TxManager{
 73		cfg:               *cfg,
 74		ethClient:         ethClient,
 75		l2DB:              l2DB,
 76		coord:             coord,
 77		batchCh:           make(chan *BatchInfo, queueLen),
 78		statsVarsCh:       make(chan statsVars, queueLen),
 79		discardPipelineCh: make(chan int, queueLen),
 80		account: accounts.Account{
 81			Address: *address,
 82		},
 83		chainID: chainID,
 84		consts:  *scConsts,
 85
 86		vars: *initSCVars,
 87
 88		minPipelineNum: 0,
 89		queue:          NewQueue(),
 90		accNonce:       accNonce,
 91		accNextNonce:   accNonce,
 92	}, nil
 93}
 94
 95// AddBatch is a thread safe method to pass a new batch TxManager to be sent to
 96// the smart contract via the forge call
 97func (t *TxManager) AddBatch(ctx context.Context, batchInfo *BatchInfo) {
 98	select {
 99	case t.batchCh <- batchInfo:
100	case <-ctx.Done():
101	}
102}
103
104// SetSyncStatsVars is a thread safe method to sets the synchronizer Stats
105func (t *TxManager) SetSyncStatsVars(ctx context.Context, stats *synchronizer.Stats, vars *synchronizer.SCVariablesPtr) {
106	select {
107	case t.statsVarsCh <- statsVars{Stats: *stats, Vars: *vars}:
108	case <-ctx.Done():
109	}
110}
111
112// DiscardPipeline is a thread safe method to notify about a discarded pipeline
113// due to a reorg
114func (t *TxManager) DiscardPipeline(ctx context.Context, pipelineNum int) {
115	select {
116	case t.discardPipelineCh <- pipelineNum:
117	case <-ctx.Done():
118	}
119}
120
121func (t *TxManager) syncSCVars(vars synchronizer.SCVariablesPtr) {
122	updateSCVars(&t.vars, vars)
123}
124
125// NewAuth generates a new auth object for an ethereum transaction
126func (t *TxManager) NewAuth(ctx context.Context) (*bind.TransactOpts, error) {
127	gasPrice, err := t.ethClient.EthSuggestGasPrice(ctx)
128	if err != nil {
129		return nil, tracerr.Wrap(err)
130	}
131	if t.cfg.GasPriceIncPerc != 0 {
132		inc := new(big.Int).Set(gasPrice)
133		inc.Mul(inc, new(big.Int).SetInt64(t.cfg.GasPriceIncPerc))
134		// nolint reason: to calculate percentages we use 100
135		inc.Div(inc, new(big.Int).SetUint64(100)) //nolint:gomnd
136		gasPrice.Add(gasPrice, inc)
137	}
138
139	// log.Debugw("TxManager: transaction metadata", "gasPrice", gasPrice)
140
141	auth, err := bind.NewKeyStoreTransactorWithChainID(t.ethClient.EthKeyStore(), t.account, t.chainID)
142	if err != nil {
143		return nil, tracerr.Wrap(err)
144	}
145	auth.Value = big.NewInt(0) // in wei
146	// TODO: Calculate GasLimit based on the contents of the ForgeBatchArgs
147	// This requires a function that estimates the gas usage of the
148	// forgeBatch call based on the contents of the ForgeBatch args:
149	// - length of l2txs
150	// - length of l1Usertxs
151	// - length of l1CoordTxs with authorization signature
152	// - length of l1CoordTxs without authoriation signature
153	// - etc.
154	auth.GasLimit = 1000000
155	auth.GasPrice = gasPrice
156	auth.Nonce = nil
157
158	return auth, nil
159}
160
161func (t *TxManager) shouldSendRollupForgeBatch(batchInfo *BatchInfo) error {
162	nextBlock := t.stats.Eth.LastBlock.Num + 1
163	if !t.canForgeAt(nextBlock) {
164		return tracerr.Wrap(fmt.Errorf("can't forge in the next block: %v", nextBlock))
165	}
166	if t.mustL1L2Batch(nextBlock) && !batchInfo.L1Batch {
167		return tracerr.Wrap(fmt.Errorf("can't forge non-L1Batch in the next block: %v", nextBlock))
168	}
169	margin := t.cfg.SendBatchBlocksMarginCheck
170	if margin != 0 {
171		if !t.canForgeAt(nextBlock + margin) {
172			return tracerr.Wrap(fmt.Errorf("can't forge after %v blocks: %v",
173				margin, nextBlock))
174		}
175		if t.mustL1L2Batch(nextBlock+margin) && !batchInfo.L1Batch {
176			return tracerr.Wrap(fmt.Errorf("can't forge non-L1Batch after %v blocks: %v",
177				margin, nextBlock))
178		}
179	}
180	return nil
181}
182
183func addPerc(v *big.Int, p int64) *big.Int {
184	r := new(big.Int).Set(v)
185	r.Mul(r, big.NewInt(p))
186	// nolint reason: to calculate percentages we divide by 100
187	r.Div(r, big.NewInt(100)) //nolit:gomnd
188	return r.Add(v, r)
189}
190
191func (t *TxManager) sendRollupForgeBatch(ctx context.Context, batchInfo *BatchInfo, resend bool) error {
192	var ethTx *types.Transaction
193	var err error
194	auth, err := t.NewAuth(ctx)
195	if err != nil {
196		return tracerr.Wrap(err)
197	}
198	auth.Nonce = big.NewInt(int64(t.accNextNonce))
199	if resend {
200		auth.Nonce = big.NewInt(int64(batchInfo.EthTx.Nonce()))
201	}
202	for attempt := 0; attempt < t.cfg.EthClientAttempts; attempt++ {
203		if auth.GasPrice.Cmp(t.cfg.MaxGasPrice) > 0 {
204			return tracerr.Wrap(fmt.Errorf("calculated gasPrice (%v) > maxGasPrice (%v)",
205				auth.GasPrice, t.cfg.MaxGasPrice))
206		}
207		// RollupForgeBatch() calls ethclient.SendTransaction()
208		ethTx, err = t.ethClient.RollupForgeBatch(batchInfo.ForgeBatchArgs, auth)
209		// We check the errors via strings because we match the
210		// definition of the error from geth, with the string returned
211		// via RPC obtained by the client.
212		if err == nil {
213			break
214		} else if strings.Contains(err.Error(), core.ErrNonceTooLow.Error()) {
215			log.Warnw("TxManager ethClient.RollupForgeBatch incrementing nonce",
216				"err", err, "nonce", auth.Nonce, "batchNum", batchInfo.BatchNum)
217			auth.Nonce.Add(auth.Nonce, big.NewInt(1))
218			attempt--
219		} else if strings.Contains(err.Error(), core.ErrNonceTooHigh.Error()) {
220			log.Warnw("TxManager ethClient.RollupForgeBatch decrementing nonce",
221				"err", err, "nonce", auth.Nonce, "batchNum", batchInfo.BatchNum)
222			auth.Nonce.Sub(auth.Nonce, big.NewInt(1))
223			attempt--
224		} else if strings.Contains(err.Error(), core.ErrReplaceUnderpriced.Error()) {
225			log.Warnw("TxManager ethClient.RollupForgeBatch incrementing gasPrice",
226				"err", err, "gasPrice", auth.GasPrice, "batchNum", batchInfo.BatchNum)
227			auth.GasPrice = addPerc(auth.GasPrice, 10)
228			attempt--
229		} else if strings.Contains(err.Error(), core.ErrUnderpriced.Error()) {
230			log.Warnw("TxManager ethClient.RollupForgeBatch incrementing gasPrice",
231				"err", err, "gasPrice", auth.GasPrice, "batchNum", batchInfo.BatchNum)
232			auth.GasPrice = addPerc(auth.GasPrice, 10)
233			attempt--
234		} else {
235			log.Errorw("TxManager ethClient.RollupForgeBatch",
236				"attempt", attempt, "err", err, "block", t.stats.Eth.LastBlock.Num+1,
237				"batchNum", batchInfo.BatchNum)
238		}
239		select {
240		case <-ctx.Done():
241			return tracerr.Wrap(common.ErrDone)
242		case <-time.After(t.cfg.EthClientAttemptsDelay):
243		}
244	}
245	if err != nil {
246		return tracerr.Wrap(fmt.Errorf("reached max attempts for ethClient.RollupForgeBatch: %w", err))
247	}
248	if !resend {
249		t.accNextNonce = auth.Nonce.Uint64() + 1
250	}
251	batchInfo.EthTx = ethTx
252	log.Infow("TxManager ethClient.RollupForgeBatch", "batch", batchInfo.BatchNum, "tx", ethTx.Hash())
253	now := time.Now()
254	batchInfo.SendTimestamp = now
255
256	if resend {
257		batchInfo.Debug.ResendNum++
258	}
259	batchInfo.Debug.Status = StatusSent
260	batchInfo.Debug.SendBlockNum = t.stats.Eth.LastBlock.Num + 1
261	batchInfo.Debug.SendTimestamp = batchInfo.SendTimestamp
262	batchInfo.Debug.StartToSendDelay = batchInfo.Debug.SendTimestamp.Sub(
263		batchInfo.Debug.StartTimestamp).Seconds()
264	t.cfg.debugBatchStore(batchInfo)
265
266	if !resend {
267		if batchInfo.L1Batch {
268			t.lastSentL1BatchBlockNum = t.stats.Eth.LastBlock.Num + 1
269		}
270	}
271	if err := t.l2DB.DoneForging(common.TxIDsFromL2Txs(batchInfo.L2Txs), batchInfo.BatchNum); err != nil {
272		return tracerr.Wrap(err)
273	}
274	return nil
275}
276
277// checkEthTransactionReceipt takes the txHash from the BatchInfo and stores
278// the corresponding receipt if found
279func (t *TxManager) checkEthTransactionReceipt(ctx context.Context, batchInfo *BatchInfo) error {
280	txHash := batchInfo.EthTx.Hash()
281	var receipt *types.Receipt
282	var err error
283	for attempt := 0; attempt < t.cfg.EthClientAttempts; attempt++ {
284		receipt, err = t.ethClient.EthTransactionReceipt(ctx, txHash)
285		if ctx.Err() != nil {
286			continue
287		} else if tracerr.Unwrap(err) == ethereum.NotFound {
288			err = nil
289			break
290		} else if err != nil {
291			log.Errorw("TxManager ethClient.EthTransactionReceipt",
292				"attempt", attempt, "err", err)
293		} else {
294			break
295		}
296		select {
297		case <-ctx.Done():
298			return tracerr.Wrap(common.ErrDone)
299		case <-time.After(t.cfg.EthClientAttemptsDelay):
300		}
301	}
302	if err != nil {
303		return tracerr.Wrap(fmt.Errorf("reached max attempts for ethClient.EthTransactionReceipt: %w", err))
304	}
305	batchInfo.Receipt = receipt
306	t.cfg.debugBatchStore(batchInfo)
307	return nil
308}
309
310func (t *TxManager) handleReceipt(ctx context.Context, batchInfo *BatchInfo) (*int64, error) {
311	receipt := batchInfo.Receipt
312	if receipt != nil {
313		if batchInfo.EthTx.Nonce()+1 > t.accNonce {
314			t.accNonce = batchInfo.EthTx.Nonce() + 1
315		}
316		if receipt.Status == types.ReceiptStatusFailed {
317			batchInfo.Debug.Status = StatusFailed
318			_, err := t.ethClient.EthCall(ctx, batchInfo.EthTx, receipt.BlockNumber)
319			log.Warnw("TxManager receipt status is failed", "tx", receipt.TxHash,
320				"batch", batchInfo.BatchNum, "block", receipt.BlockNumber.Int64(),
321				"err", err)
322			batchInfo.EthTxErr = err
323			if batchInfo.BatchNum <= t.lastSuccessBatch {
324				t.lastSuccessBatch = batchInfo.BatchNum - 1
325			}
326			t.cfg.debugBatchStore(batchInfo)
327			return nil, tracerr.Wrap(fmt.Errorf(
328				"ethereum transaction receipt status is failed: %w", err))
329		} else if receipt.Status == types.ReceiptStatusSuccessful {
330			batchInfo.Debug.Status = StatusMined
331			batchInfo.Debug.MineBlockNum = receipt.BlockNumber.Int64()
332			batchInfo.Debug.StartToMineBlocksDelay = batchInfo.Debug.MineBlockNum -
333				batchInfo.Debug.StartBlockNum
334			if batchInfo.Debug.StartToMineDelay == 0 {
335				if block, err := t.ethClient.EthBlockByNumber(ctx,
336					receipt.BlockNumber.Int64()); err != nil {
337					log.Warnw("TxManager: ethClient.EthBlockByNumber", "err", err)
338				} else {
339					batchInfo.Debug.SendToMineDelay = block.Timestamp.Sub(
340						batchInfo.Debug.SendTimestamp).Seconds()
341					batchInfo.Debug.StartToMineDelay = block.Timestamp.Sub(
342						batchInfo.Debug.StartTimestamp).Seconds()
343				}
344			}
345			t.cfg.debugBatchStore(batchInfo)
346			if batchInfo.BatchNum > t.lastSuccessBatch {
347				t.lastSuccessBatch = batchInfo.BatchNum
348			}
349			confirm := t.stats.Eth.LastBlock.Num - receipt.BlockNumber.Int64()
350			return &confirm, nil
351		}
352	}
353	return nil, nil
354}
355
356// TODO:
357// - After sending a message: CancelPipeline, stop all consecutive pending Batches (transactions)
358
359// Queue of BatchInfos
360type Queue struct {
361	list []*BatchInfo
362	// nonceByBatchNum map[common.BatchNum]uint64
363	next int
364}
365
366// NewQueue returns a new queue
367func NewQueue() Queue {
368	return Queue{
369		list: make([]*BatchInfo, 0),
370		// nonceByBatchNum: make(map[common.BatchNum]uint64),
371		next: 0,
372	}
373}
374
375// Len is the length of the queue
376func (q *Queue) Len() int {
377	return len(q.list)
378}
379
380// At returns the BatchInfo at position (or nil if position is out of bounds)
381func (q *Queue) At(position int) *BatchInfo {
382	if position >= len(q.list) {
383		return nil
384	}
385	return q.list[position]
386}
387
388// Next returns the next BatchInfo (or nil if queue is empty)
389func (q *Queue) Next() (int, *BatchInfo) {
390	if len(q.list) == 0 {
391		return 0, nil
392	}
393	defer func() { q.next = (q.next + 1) % len(q.list) }()
394	return q.next, q.list[q.next]
395}
396
397// Remove removes the BatchInfo at position
398func (q *Queue) Remove(position int) {
399	// batchInfo := q.list[position]
400	// delete(q.nonceByBatchNum, batchInfo.BatchNum)
401	q.list = append(q.list[:position], q.list[position+1:]...)
402	if len(q.list) == 0 {
403		q.next = 0
404	} else {
405		q.next = position % len(q.list)
406	}
407}
408
409// Push adds a new BatchInfo
410func (q *Queue) Push(batchInfo *BatchInfo) {
411	q.list = append(q.list, batchInfo)
412	// q.nonceByBatchNum[batchInfo.BatchNum] = batchInfo.EthTx.Nonce()
413}
414
415// func (q *Queue) NonceByBatchNum(batchNum common.BatchNum) (uint64, bool) {
416// 	nonce, ok := q.nonceByBatchNum[batchNum]
417// 	return nonce, ok
418// }
419
420// Run the TxManager
421func (t *TxManager) Run(ctx context.Context) {
422	var statsVars statsVars
423	select {
424	case statsVars = <-t.statsVarsCh:
425	case <-ctx.Done():
426	}
427	t.stats = statsVars.Stats
428	t.syncSCVars(statsVars.Vars)
429	log.Infow("TxManager: received initial statsVars",
430		"block", t.stats.Eth.LastBlock.Num, "batch", t.stats.Eth.LastBatchNum)
431
432	timer := time.NewTimer(longWaitDuration)
433	for {
434		select {
435		case <-ctx.Done():
436			log.Info("TxManager done")
437			return
438		case statsVars := <-t.statsVarsCh:
439			t.stats = statsVars.Stats
440			t.syncSCVars(statsVars.Vars)
441		case pipelineNum := <-t.discardPipelineCh:
442			t.minPipelineNum = pipelineNum + 1
443			if err := t.removeBadBatchInfos(ctx); ctx.Err() != nil {
444				continue
445			} else if err != nil {
446				log.Errorw("TxManager: removeBadBatchInfos", "err", err)
447				continue
448			}
449		case batchInfo := <-t.batchCh:
450			if batchInfo.PipelineNum < t.minPipelineNum {
451				log.Warnw("TxManager: batchInfo received pipelineNum < minPipelineNum",
452					"num", batchInfo.PipelineNum, "minNum", t.minPipelineNum)
453			}
454			if err := t.shouldSendRollupForgeBatch(batchInfo); err != nil {
455				log.Warnw("TxManager: shouldSend", "err", err,
456					"batch", batchInfo.BatchNum)
457				t.coord.SendMsg(ctx, MsgStopPipeline{
458					Reason: fmt.Sprintf("forgeBatch shouldSend: %v", err)})
459				continue
460			}
461			if err := t.sendRollupForgeBatch(ctx, batchInfo, false); ctx.Err() != nil {
462				continue
463			} else if err != nil {
464				// If we reach here it's because our ethNode has
465				// been unable to send the transaction to
466				// ethereum.  This could be due to the ethNode
467				// failure, or an invalid transaction (that
468				// can't be mined)
469				log.Warnw("TxManager: forgeBatch send failed", "err", err,
470					"batch", batchInfo.BatchNum)
471				t.coord.SendMsg(ctx, MsgStopPipeline{
472					Reason: fmt.Sprintf("forgeBatch send: %v", err)})
473				continue
474			}
475			t.queue.Push(batchInfo)
476			if !timer.Stop() {
477				<-timer.C
478			}
479			timer.Reset(t.cfg.TxManagerCheckInterval)
480		case <-timer.C:
481			queuePosition, batchInfo := t.queue.Next()
482			if batchInfo == nil {
483				timer.Reset(longWaitDuration)
484				continue
485			}
486			timer.Reset(t.cfg.TxManagerCheckInterval)
487			if err := t.checkEthTransactionReceipt(ctx, batchInfo); ctx.Err() != nil {
488				continue
489			} else if err != nil { //nolint:staticcheck
490				// Our ethNode is giving an error different
491				// than "not found" when getting the receipt
492				// for the transaction, so we can't figure out
493				// if it was not mined, mined and succesfull or
494				// mined and failed.  This could be due to the
495				// ethNode failure.
496				t.coord.SendMsg(ctx, MsgStopPipeline{
497					Reason: fmt.Sprintf("forgeBatch receipt: %v", err)})
498			}
499
500			confirm, err := t.handleReceipt(ctx, batchInfo)
501			if ctx.Err() != nil {
502				continue
503			} else if err != nil { //nolint:staticcheck
504				// Transaction was rejected
505				if err := t.removeBadBatchInfos(ctx); ctx.Err() != nil {
506					continue
507				} else if err != nil {
508					log.Errorw("TxManager: removeBadBatchInfos", "err", err)
509					continue
510				}
511				t.coord.SendMsg(ctx, MsgStopPipeline{
512					Reason: fmt.Sprintf("forgeBatch reject: %v", err)})
513				continue
514			}
515			now := time.Now()
516			if !t.cfg.EthNoReuseNonce && confirm == nil &&
517				now.Sub(batchInfo.SendTimestamp) > t.cfg.EthTxResendTimeout {
518				log.Infow("TxManager: forgeBatch tx not been mined timeout, resending",
519					"tx", batchInfo.EthTx.Hash(), "batch", batchInfo.BatchNum)
520				if err := t.sendRollupForgeBatch(ctx, batchInfo, true); ctx.Err() != nil {
521					continue
522				} else if err != nil {
523					// If we reach here it's because our ethNode has
524					// been unable to send the transaction to
525					// ethereum.  This could be due to the ethNode
526					// failure, or an invalid transaction (that
527					// can't be mined)
528					log.Warnw("TxManager: forgeBatch resend failed", "err", err,
529						"batch", batchInfo.BatchNum)
530					t.coord.SendMsg(ctx, MsgStopPipeline{
531						Reason: fmt.Sprintf("forgeBatch resend: %v", err)})
532					continue
533				}
534			}
535
536			if confirm != nil && *confirm >= t.cfg.ConfirmBlocks {
537				log.Debugw("TxManager: forgeBatch tx confirmed",
538					"tx", batchInfo.EthTx.Hash(), "batch", batchInfo.BatchNum)
539				t.queue.Remove(queuePosition)
540			}
541		}
542	}
543}
544
545func (t *TxManager) removeBadBatchInfos(ctx context.Context) error {
546	next := 0
547	for {
548		batchInfo := t.queue.At(next)
549		if batchInfo == nil {
550			break
551		}
552		if err := t.checkEthTransactionReceipt(ctx, batchInfo); ctx.Err() != nil {
553			return nil
554		} else if err != nil {
555			// Our ethNode is giving an error different
556			// than "not found" when getting the receipt
557			// for the transaction, so we can't figure out
558			// if it was not mined, mined and succesfull or
559			// mined and failed.  This could be due to the
560			// ethNode failure.
561			next++
562			continue
563		}
564		confirm, err := t.handleReceipt(ctx, batchInfo)
565		if ctx.Err() != nil {
566			return nil
567		} else if err != nil {
568			// Transaction was rejected
569			if t.minPipelineNum <= batchInfo.PipelineNum {
570				t.minPipelineNum = batchInfo.PipelineNum + 1
571			}
572			t.queue.Remove(next)
573			continue
574		}
575		// If tx is pending but is from a cancelled pipeline, remove it
576		// from the queue
577		if confirm == nil {
578			if batchInfo.PipelineNum < t.minPipelineNum {
579				t.queue.Remove(next)
580				continue
581			}
582		}
583		next++
584	}
585	accNonce, err := t.ethClient.EthNonceAt(ctx, t.account.Address, nil)
586	if err != nil {
587		return err
588	}
589	if !t.cfg.EthNoReuseNonce {
590		t.accNextNonce = accNonce
591	}
592	return nil
593}
594
595func (t *TxManager) canForgeAt(blockNum int64) bool {
596	return canForge(&t.consts.Auction, &t.vars.Auction,
597		&t.stats.Sync.Auction.CurrentSlot, &t.stats.Sync.Auction.NextSlot,
598		t.cfg.ForgerAddress, blockNum)
599}
600
601func (t *TxManager) mustL1L2Batch(blockNum int64) bool {
602	lastL1BatchBlockNum := t.lastSentL1BatchBlockNum
603	if t.stats.Sync.LastL1BatchBlock > lastL1BatchBlockNum {
604		lastL1BatchBlockNum = t.stats.Sync.LastL1BatchBlock
605	}
606	return blockNum-lastL1BatchBlockNum >= t.vars.Rollup.ForgeL1L2BatchTimeout-1
607}