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, batchInfo *BatchInfo) (*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
147	gasLimit := t.cfg.ForgeBatchGasCost.Fixed +
148		uint64(len(batchInfo.L1UserTxsExtra))*t.cfg.ForgeBatchGasCost.L1UserTx +
149		uint64(len(batchInfo.L1CoordTxs))*t.cfg.ForgeBatchGasCost.L1CoordTx +
150		uint64(len(batchInfo.L2Txs))*t.cfg.ForgeBatchGasCost.L2Tx
151	auth.GasLimit = gasLimit
152	auth.GasPrice = gasPrice
153	auth.Nonce = nil
154
155	return auth, nil
156}
157
158func (t *TxManager) shouldSendRollupForgeBatch(batchInfo *BatchInfo) error {
159	nextBlock := t.stats.Eth.LastBlock.Num + 1
160	if !t.canForgeAt(nextBlock) {
161		return tracerr.Wrap(fmt.Errorf("can't forge in the next block: %v", nextBlock))
162	}
163	if t.mustL1L2Batch(nextBlock) && !batchInfo.L1Batch {
164		return tracerr.Wrap(fmt.Errorf("can't forge non-L1Batch in the next block: %v", nextBlock))
165	}
166	margin := t.cfg.SendBatchBlocksMarginCheck
167	if margin != 0 {
168		if !t.canForgeAt(nextBlock + margin) {
169			return tracerr.Wrap(fmt.Errorf("can't forge after %v blocks: %v",
170				margin, nextBlock))
171		}
172		if t.mustL1L2Batch(nextBlock+margin) && !batchInfo.L1Batch {
173			return tracerr.Wrap(fmt.Errorf("can't forge non-L1Batch after %v blocks: %v",
174				margin, nextBlock))
175		}
176	}
177	return nil
178}
179
180func addPerc(v *big.Int, p int64) *big.Int {
181	r := new(big.Int).Set(v)
182	r.Mul(r, big.NewInt(p))
183	// nolint reason: to calculate percentages we divide by 100
184	r.Div(r, big.NewInt(100)) //nolit:gomnd
185	return r.Add(v, r)
186}
187
188func (t *TxManager) sendRollupForgeBatch(ctx context.Context, batchInfo *BatchInfo, resend bool) error {
189	var ethTx *types.Transaction
190	var err error
191	auth, err := t.NewAuth(ctx, batchInfo)
192	if err != nil {
193		return tracerr.Wrap(err)
194	}
195	auth.Nonce = big.NewInt(int64(t.accNextNonce))
196	if resend {
197		auth.Nonce = big.NewInt(int64(batchInfo.EthTx.Nonce()))
198	}
199	for attempt := 0; attempt < t.cfg.EthClientAttempts; attempt++ {
200		if auth.GasPrice.Cmp(t.cfg.MaxGasPrice) > 0 {
201			return tracerr.Wrap(fmt.Errorf("calculated gasPrice (%v) > maxGasPrice (%v)",
202				auth.GasPrice, t.cfg.MaxGasPrice))
203		}
204		// RollupForgeBatch() calls ethclient.SendTransaction()
205		ethTx, err = t.ethClient.RollupForgeBatch(batchInfo.ForgeBatchArgs, auth)
206		// We check the errors via strings because we match the
207		// definition of the error from geth, with the string returned
208		// via RPC obtained by the client.
209		if err == nil {
210			break
211		} else if strings.Contains(err.Error(), core.ErrNonceTooLow.Error()) {
212			log.Warnw("TxManager ethClient.RollupForgeBatch incrementing nonce",
213				"err", err, "nonce", auth.Nonce, "batchNum", batchInfo.BatchNum)
214			auth.Nonce.Add(auth.Nonce, big.NewInt(1))
215			attempt--
216		} else if strings.Contains(err.Error(), core.ErrNonceTooHigh.Error()) {
217			log.Warnw("TxManager ethClient.RollupForgeBatch decrementing nonce",
218				"err", err, "nonce", auth.Nonce, "batchNum", batchInfo.BatchNum)
219			auth.Nonce.Sub(auth.Nonce, big.NewInt(1))
220			attempt--
221		} else if strings.Contains(err.Error(), core.ErrReplaceUnderpriced.Error()) {
222			log.Warnw("TxManager ethClient.RollupForgeBatch incrementing gasPrice",
223				"err", err, "gasPrice", auth.GasPrice, "batchNum", batchInfo.BatchNum)
224			auth.GasPrice = addPerc(auth.GasPrice, 10)
225			attempt--
226		} else if strings.Contains(err.Error(), core.ErrUnderpriced.Error()) {
227			log.Warnw("TxManager ethClient.RollupForgeBatch incrementing gasPrice",
228				"err", err, "gasPrice", auth.GasPrice, "batchNum", batchInfo.BatchNum)
229			auth.GasPrice = addPerc(auth.GasPrice, 10)
230			attempt--
231		} else {
232			log.Errorw("TxManager ethClient.RollupForgeBatch",
233				"attempt", attempt, "err", err, "block", t.stats.Eth.LastBlock.Num+1,
234				"batchNum", batchInfo.BatchNum)
235		}
236		select {
237		case <-ctx.Done():
238			return tracerr.Wrap(common.ErrDone)
239		case <-time.After(t.cfg.EthClientAttemptsDelay):
240		}
241	}
242	if err != nil {
243		return tracerr.Wrap(fmt.Errorf("reached max attempts for ethClient.RollupForgeBatch: %w", err))
244	}
245	if !resend {
246		t.accNextNonce = auth.Nonce.Uint64() + 1
247	}
248	batchInfo.EthTx = ethTx
249	log.Infow("TxManager ethClient.RollupForgeBatch", "batch", batchInfo.BatchNum, "tx", ethTx.Hash())
250	now := time.Now()
251	batchInfo.SendTimestamp = now
252
253	if resend {
254		batchInfo.Debug.ResendNum++
255	}
256	batchInfo.Debug.Status = StatusSent
257	batchInfo.Debug.SendBlockNum = t.stats.Eth.LastBlock.Num + 1
258	batchInfo.Debug.SendTimestamp = batchInfo.SendTimestamp
259	batchInfo.Debug.StartToSendDelay = batchInfo.Debug.SendTimestamp.Sub(
260		batchInfo.Debug.StartTimestamp).Seconds()
261	t.cfg.debugBatchStore(batchInfo)
262
263	if !resend {
264		if batchInfo.L1Batch {
265			t.lastSentL1BatchBlockNum = t.stats.Eth.LastBlock.Num + 1
266		}
267	}
268	if err := t.l2DB.DoneForging(common.TxIDsFromL2Txs(batchInfo.L2Txs), batchInfo.BatchNum); err != nil {
269		return tracerr.Wrap(err)
270	}
271	return nil
272}
273
274// checkEthTransactionReceipt takes the txHash from the BatchInfo and stores
275// the corresponding receipt if found
276func (t *TxManager) checkEthTransactionReceipt(ctx context.Context, batchInfo *BatchInfo) error {
277	txHash := batchInfo.EthTx.Hash()
278	var receipt *types.Receipt
279	var err error
280	for attempt := 0; attempt < t.cfg.EthClientAttempts; attempt++ {
281		receipt, err = t.ethClient.EthTransactionReceipt(ctx, txHash)
282		if ctx.Err() != nil {
283			continue
284		} else if tracerr.Unwrap(err) == ethereum.NotFound {
285			err = nil
286			break
287		} else if err != nil {
288			log.Errorw("TxManager ethClient.EthTransactionReceipt",
289				"attempt", attempt, "err", err)
290		} else {
291			break
292		}
293		select {
294		case <-ctx.Done():
295			return tracerr.Wrap(common.ErrDone)
296		case <-time.After(t.cfg.EthClientAttemptsDelay):
297		}
298	}
299	if err != nil {
300		return tracerr.Wrap(fmt.Errorf("reached max attempts for ethClient.EthTransactionReceipt: %w", err))
301	}
302	batchInfo.Receipt = receipt
303	t.cfg.debugBatchStore(batchInfo)
304	return nil
305}
306
307func (t *TxManager) handleReceipt(ctx context.Context, batchInfo *BatchInfo) (*int64, error) {
308	receipt := batchInfo.Receipt
309	if receipt != nil {
310		if batchInfo.EthTx.Nonce()+1 > t.accNonce {
311			t.accNonce = batchInfo.EthTx.Nonce() + 1
312		}
313		if receipt.Status == types.ReceiptStatusFailed {
314			batchInfo.Debug.Status = StatusFailed
315			_, err := t.ethClient.EthCall(ctx, batchInfo.EthTx, receipt.BlockNumber)
316			log.Warnw("TxManager receipt status is failed", "tx", receipt.TxHash,
317				"batch", batchInfo.BatchNum, "block", receipt.BlockNumber.Int64(),
318				"err", err)
319			batchInfo.EthTxErr = err
320			if batchInfo.BatchNum <= t.lastSuccessBatch {
321				t.lastSuccessBatch = batchInfo.BatchNum - 1
322			}
323			t.cfg.debugBatchStore(batchInfo)
324			return nil, tracerr.Wrap(fmt.Errorf(
325				"ethereum transaction receipt status is failed: %w", err))
326		} else if receipt.Status == types.ReceiptStatusSuccessful {
327			batchInfo.Debug.Status = StatusMined
328			batchInfo.Debug.MineBlockNum = receipt.BlockNumber.Int64()
329			batchInfo.Debug.StartToMineBlocksDelay = batchInfo.Debug.MineBlockNum -
330				batchInfo.Debug.StartBlockNum
331			if batchInfo.Debug.StartToMineDelay == 0 {
332				if block, err := t.ethClient.EthBlockByNumber(ctx,
333					receipt.BlockNumber.Int64()); err != nil {
334					log.Warnw("TxManager: ethClient.EthBlockByNumber", "err", err)
335				} else {
336					batchInfo.Debug.SendToMineDelay = block.Timestamp.Sub(
337						batchInfo.Debug.SendTimestamp).Seconds()
338					batchInfo.Debug.StartToMineDelay = block.Timestamp.Sub(
339						batchInfo.Debug.StartTimestamp).Seconds()
340				}
341			}
342			t.cfg.debugBatchStore(batchInfo)
343			if batchInfo.BatchNum > t.lastSuccessBatch {
344				t.lastSuccessBatch = batchInfo.BatchNum
345			}
346			confirm := t.stats.Eth.LastBlock.Num - receipt.BlockNumber.Int64()
347			return &confirm, nil
348		}
349	}
350	return nil, nil
351}
352
353// TODO:
354// - After sending a message: CancelPipeline, stop all consecutive pending Batches (transactions)
355
356// Queue of BatchInfos
357type Queue struct {
358	list []*BatchInfo
359	// nonceByBatchNum map[common.BatchNum]uint64
360	next int
361}
362
363// NewQueue returns a new queue
364func NewQueue() Queue {
365	return Queue{
366		list: make([]*BatchInfo, 0),
367		// nonceByBatchNum: make(map[common.BatchNum]uint64),
368		next: 0,
369	}
370}
371
372// Len is the length of the queue
373func (q *Queue) Len() int {
374	return len(q.list)
375}
376
377// At returns the BatchInfo at position (or nil if position is out of bounds)
378func (q *Queue) At(position int) *BatchInfo {
379	if position >= len(q.list) {
380		return nil
381	}
382	return q.list[position]
383}
384
385// Next returns the next BatchInfo (or nil if queue is empty)
386func (q *Queue) Next() (int, *BatchInfo) {
387	if len(q.list) == 0 {
388		return 0, nil
389	}
390	defer func() { q.next = (q.next + 1) % len(q.list) }()
391	return q.next, q.list[q.next]
392}
393
394// Remove removes the BatchInfo at position
395func (q *Queue) Remove(position int) {
396	// batchInfo := q.list[position]
397	// delete(q.nonceByBatchNum, batchInfo.BatchNum)
398	q.list = append(q.list[:position], q.list[position+1:]...)
399	if len(q.list) == 0 {
400		q.next = 0
401	} else {
402		q.next = position % len(q.list)
403	}
404}
405
406// Push adds a new BatchInfo
407func (q *Queue) Push(batchInfo *BatchInfo) {
408	q.list = append(q.list, batchInfo)
409	// q.nonceByBatchNum[batchInfo.BatchNum] = batchInfo.EthTx.Nonce()
410}
411
412// func (q *Queue) NonceByBatchNum(batchNum common.BatchNum) (uint64, bool) {
413// 	nonce, ok := q.nonceByBatchNum[batchNum]
414// 	return nonce, ok
415// }
416
417// Run the TxManager
418func (t *TxManager) Run(ctx context.Context) {
419	waitCh := time.After(longWaitDuration)
420
421	var statsVars statsVars
422	select {
423	case statsVars = <-t.statsVarsCh:
424	case <-ctx.Done():
425	}
426	t.stats = statsVars.Stats
427	t.syncSCVars(statsVars.Vars)
428	log.Infow("TxManager: received initial statsVars",
429		"block", t.stats.Eth.LastBlock.Num, "batch", t.stats.Eth.LastBatchNum)
430
431	for {
432		select {
433		case <-ctx.Done():
434			log.Info("TxManager done")
435			return
436		case statsVars := <-t.statsVarsCh:
437			t.stats = statsVars.Stats
438			t.syncSCVars(statsVars.Vars)
439		case pipelineNum := <-t.discardPipelineCh:
440			t.minPipelineNum = pipelineNum + 1
441			if err := t.removeBadBatchInfos(ctx); ctx.Err() != nil {
442				continue
443			} else if err != nil {
444				log.Errorw("TxManager: removeBadBatchInfos", "err", err)
445				continue
446			}
447		case batchInfo := <-t.batchCh:
448			if batchInfo.PipelineNum < t.minPipelineNum {
449				log.Warnw("TxManager: batchInfo received pipelineNum < minPipelineNum",
450					"num", batchInfo.PipelineNum, "minNum", t.minPipelineNum)
451			}
452			if err := t.shouldSendRollupForgeBatch(batchInfo); err != nil {
453				log.Warnw("TxManager: shouldSend", "err", err,
454					"batch", batchInfo.BatchNum)
455				t.coord.SendMsg(ctx, MsgStopPipeline{
456					Reason: fmt.Sprintf("forgeBatch shouldSend: %v", err)})
457				continue
458			}
459			if err := t.sendRollupForgeBatch(ctx, batchInfo, false); ctx.Err() != nil {
460				continue
461			} else if err != nil {
462				// If we reach here it's because our ethNode has
463				// been unable to send the transaction to
464				// ethereum.  This could be due to the ethNode
465				// failure, or an invalid transaction (that
466				// can't be mined)
467				log.Warnw("TxManager: forgeBatch send failed", "err", err,
468					"batch", batchInfo.BatchNum)
469				t.coord.SendMsg(ctx, MsgStopPipeline{
470					Reason: fmt.Sprintf("forgeBatch send: %v", err)})
471				continue
472			}
473			t.queue.Push(batchInfo)
474			waitCh = time.After(t.cfg.TxManagerCheckInterval)
475		case <-waitCh:
476			queuePosition, batchInfo := t.queue.Next()
477			if batchInfo == nil {
478				waitCh = time.After(longWaitDuration)
479				continue
480			}
481			if err := t.checkEthTransactionReceipt(ctx, batchInfo); ctx.Err() != nil {
482				continue
483			} else if err != nil { //nolint:staticcheck
484				// Our ethNode is giving an error different
485				// than "not found" when getting the receipt
486				// for the transaction, so we can't figure out
487				// if it was not mined, mined and succesfull or
488				// mined and failed.  This could be due to the
489				// ethNode failure.
490				t.coord.SendMsg(ctx, MsgStopPipeline{
491					Reason: fmt.Sprintf("forgeBatch receipt: %v", err)})
492			}
493
494			confirm, err := t.handleReceipt(ctx, batchInfo)
495			if ctx.Err() != nil {
496				continue
497			} else if err != nil { //nolint:staticcheck
498				// Transaction was rejected
499				if err := t.removeBadBatchInfos(ctx); ctx.Err() != nil {
500					continue
501				} else if err != nil {
502					log.Errorw("TxManager: removeBadBatchInfos", "err", err)
503					continue
504				}
505				t.coord.SendMsg(ctx, MsgStopPipeline{
506					Reason: fmt.Sprintf("forgeBatch reject: %v", err)})
507				continue
508			}
509			now := time.Now()
510			if !t.cfg.EthNoReuseNonce && confirm == nil &&
511				now.Sub(batchInfo.SendTimestamp) > t.cfg.EthTxResendTimeout {
512				log.Infow("TxManager: forgeBatch tx not been mined timeout, resending",
513					"tx", batchInfo.EthTx.Hash(), "batch", batchInfo.BatchNum)
514				if err := t.sendRollupForgeBatch(ctx, batchInfo, true); ctx.Err() != nil {
515					continue
516				} else if err != nil {
517					// If we reach here it's because our ethNode has
518					// been unable to send the transaction to
519					// ethereum.  This could be due to the ethNode
520					// failure, or an invalid transaction (that
521					// can't be mined)
522					log.Warnw("TxManager: forgeBatch resend failed", "err", err,
523						"batch", batchInfo.BatchNum)
524					t.coord.SendMsg(ctx, MsgStopPipeline{
525						Reason: fmt.Sprintf("forgeBatch resend: %v", err)})
526					continue
527				}
528			}
529
530			if confirm != nil && *confirm >= t.cfg.ConfirmBlocks {
531				log.Debugw("TxManager: forgeBatch tx confirmed",
532					"tx", batchInfo.EthTx.Hash(), "batch", batchInfo.BatchNum)
533				t.queue.Remove(queuePosition)
534			}
535		}
536	}
537}
538
539func (t *TxManager) removeBadBatchInfos(ctx context.Context) error {
540	next := 0
541	for {
542		batchInfo := t.queue.At(next)
543		if batchInfo == nil {
544			break
545		}
546		if err := t.checkEthTransactionReceipt(ctx, batchInfo); ctx.Err() != nil {
547			return nil
548		} else if err != nil {
549			// Our ethNode is giving an error different
550			// than "not found" when getting the receipt
551			// for the transaction, so we can't figure out
552			// if it was not mined, mined and succesfull or
553			// mined and failed.  This could be due to the
554			// ethNode failure.
555			next++
556			continue
557		}
558		confirm, err := t.handleReceipt(ctx, batchInfo)
559		if ctx.Err() != nil {
560			return nil
561		} else if err != nil {
562			// Transaction was rejected
563			if t.minPipelineNum <= batchInfo.PipelineNum {
564				t.minPipelineNum = batchInfo.PipelineNum + 1
565			}
566			t.queue.Remove(next)
567			continue
568		}
569		// If tx is pending but is from a cancelled pipeline, remove it
570		// from the queue
571		if confirm == nil {
572			if batchInfo.PipelineNum < t.minPipelineNum {
573				t.queue.Remove(next)
574				continue
575			}
576		}
577		next++
578	}
579	accNonce, err := t.ethClient.EthNonceAt(ctx, t.account.Address, nil)
580	if err != nil {
581		return err
582	}
583	if !t.cfg.EthNoReuseNonce {
584		t.accNextNonce = accNonce
585	}
586	return nil
587}
588
589func (t *TxManager) canForgeAt(blockNum int64) bool {
590	return canForge(&t.consts.Auction, &t.vars.Auction,
591		&t.stats.Sync.Auction.CurrentSlot, &t.stats.Sync.Auction.NextSlot,
592		t.cfg.ForgerAddress, blockNum)
593}
594
595func (t *TxManager) mustL1L2Batch(blockNum int64) bool {
596	lastL1BatchBlockNum := t.lastSentL1BatchBlockNum
597	if t.stats.Sync.LastL1BatchBlock > lastL1BatchBlockNum {
598		lastL1BatchBlockNum = t.stats.Sync.LastL1BatchBlock
599	}
600	return blockNum-lastL1BatchBlockNum >= t.vars.Rollup.ForgeL1L2BatchTimeout-1
601}