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 if err != nil {
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	waitCh := time.After(longWaitDuration)
423
424	var statsVars statsVars
425	select {
426	case statsVars = <-t.statsVarsCh:
427	case <-ctx.Done():
428	}
429	t.stats = statsVars.Stats
430	t.syncSCVars(statsVars.Vars)
431	log.Infow("TxManager: received initial statsVars",
432		"block", t.stats.Eth.LastBlock.Num, "batch", t.stats.Eth.LastBatchNum)
433
434	for {
435		select {
436		case <-ctx.Done():
437			log.Info("TxManager done")
438			return
439		case statsVars := <-t.statsVarsCh:
440			t.stats = statsVars.Stats
441			t.syncSCVars(statsVars.Vars)
442		case pipelineNum := <-t.discardPipelineCh:
443			t.minPipelineNum = pipelineNum + 1
444			if err := t.removeBadBatchInfos(ctx); ctx.Err() != nil {
445				continue
446			} else if err != nil {
447				log.Errorw("TxManager: removeBadBatchInfos", "err", err)
448				continue
449			}
450		case batchInfo := <-t.batchCh:
451			if batchInfo.PipelineNum < t.minPipelineNum {
452				log.Warnw("TxManager: batchInfo received pipelineNum < minPipelineNum",
453					"num", batchInfo.PipelineNum, "minNum", t.minPipelineNum)
454			}
455			if err := t.shouldSendRollupForgeBatch(batchInfo); err != nil {
456				log.Warnw("TxManager: shouldSend", "err", err,
457					"batch", batchInfo.BatchNum)
458				t.coord.SendMsg(ctx, MsgStopPipeline{
459					Reason: fmt.Sprintf("forgeBatch shouldSend: %v", err)})
460				continue
461			}
462			if err := t.sendRollupForgeBatch(ctx, batchInfo, false); ctx.Err() != nil {
463				continue
464			} else if err != nil {
465				// If we reach here it's because our ethNode has
466				// been unable to send the transaction to
467				// ethereum.  This could be due to the ethNode
468				// failure, or an invalid transaction (that
469				// can't be mined)
470				log.Warnw("TxManager: forgeBatch send failed", "err", err,
471					"batch", batchInfo.BatchNum)
472				t.coord.SendMsg(ctx, MsgStopPipeline{
473					Reason: fmt.Sprintf("forgeBatch send: %v", err)})
474				continue
475			}
476			t.queue.Push(batchInfo)
477			waitCh = time.After(t.cfg.TxManagerCheckInterval)
478		case <-waitCh:
479			queuePosition, batchInfo := t.queue.Next()
480			if batchInfo == nil {
481				waitCh = time.After(longWaitDuration)
482				continue
483			}
484			if err := t.checkEthTransactionReceipt(ctx, batchInfo); ctx.Err() != nil {
485				continue
486			} else if err != nil { //nolint:staticcheck
487				// Our ethNode is giving an error different
488				// than "not found" when getting the receipt
489				// for the transaction, so we can't figure out
490				// if it was not mined, mined and succesfull or
491				// mined and failed.  This could be due to the
492				// ethNode failure.
493				t.coord.SendMsg(ctx, MsgStopPipeline{
494					Reason: fmt.Sprintf("forgeBatch receipt: %v", err)})
495			}
496
497			confirm, err := t.handleReceipt(ctx, batchInfo)
498			if ctx.Err() != nil {
499				continue
500			} else if err != nil { //nolint:staticcheck
501				// Transaction was rejected
502				if err := t.removeBadBatchInfos(ctx); ctx.Err() != nil {
503					continue
504				} else if err != nil {
505					log.Errorw("TxManager: removeBadBatchInfos", "err", err)
506					continue
507				}
508				t.coord.SendMsg(ctx, MsgStopPipeline{
509					Reason: fmt.Sprintf("forgeBatch reject: %v", err)})
510				continue
511			}
512			now := time.Now()
513			if !t.cfg.EthNoReuseNonce && confirm == nil &&
514				now.Sub(batchInfo.SendTimestamp) > t.cfg.EthTxResendTimeout {
515				log.Infow("TxManager: forgeBatch tx not been mined timeout, resending",
516					"tx", batchInfo.EthTx.Hash(), "batch", batchInfo.BatchNum)
517				if err := t.sendRollupForgeBatch(ctx, batchInfo, true); ctx.Err() != nil {
518					continue
519				} else if err != nil {
520					// If we reach here it's because our ethNode has
521					// been unable to send the transaction to
522					// ethereum.  This could be due to the ethNode
523					// failure, or an invalid transaction (that
524					// can't be mined)
525					log.Warnw("TxManager: forgeBatch resend failed", "err", err,
526						"batch", batchInfo.BatchNum)
527					t.coord.SendMsg(ctx, MsgStopPipeline{
528						Reason: fmt.Sprintf("forgeBatch resend: %v", err)})
529					continue
530				}
531			}
532
533			if confirm != nil && *confirm >= t.cfg.ConfirmBlocks {
534				log.Debugw("TxManager: forgeBatch tx confirmed",
535					"tx", batchInfo.EthTx.Hash(), "batch", batchInfo.BatchNum)
536				t.queue.Remove(queuePosition)
537			}
538		}
539	}
540}
541
542func (t *TxManager) removeBadBatchInfos(ctx context.Context) error {
543	next := 0
544	for {
545		batchInfo := t.queue.At(next)
546		if batchInfo == nil {
547			break
548		}
549		if err := t.checkEthTransactionReceipt(ctx, batchInfo); ctx.Err() != nil {
550			return nil
551		} else if err != nil {
552			// Our ethNode is giving an error different
553			// than "not found" when getting the receipt
554			// for the transaction, so we can't figure out
555			// if it was not mined, mined and succesfull or
556			// mined and failed.  This could be due to the
557			// ethNode failure.
558			next++
559			continue
560		}
561		confirm, err := t.handleReceipt(ctx, batchInfo)
562		if ctx.Err() != nil {
563			return nil
564		} else if err != nil {
565			// Transaction was rejected
566			if t.minPipelineNum <= batchInfo.PipelineNum {
567				t.minPipelineNum = batchInfo.PipelineNum + 1
568			}
569			t.queue.Remove(next)
570			continue
571		}
572		// If tx is pending but is from a cancelled pipeline, remove it
573		// from the queue
574		if confirm == nil {
575			if batchInfo.PipelineNum < t.minPipelineNum {
576				t.queue.Remove(next)
577				continue
578			}
579		}
580		next++
581	}
582	accNonce, err := t.ethClient.EthNonceAt(ctx, t.account.Address, nil)
583	if err != nil {
584		return err
585	}
586	if !t.cfg.EthNoReuseNonce {
587		t.accNextNonce = accNonce
588	}
589	return nil
590}
591
592func (t *TxManager) canForgeAt(blockNum int64) bool {
593	return canForge(&t.consts.Auction, &t.vars.Auction,
594		&t.stats.Sync.Auction.CurrentSlot, &t.stats.Sync.Auction.NextSlot,
595		t.cfg.ForgerAddress, blockNum)
596}
597
598func (t *TxManager) mustL1L2Batch(blockNum int64) bool {
599	lastL1BatchBlockNum := t.lastSentL1BatchBlockNum
600	if t.stats.Sync.LastL1BatchBlock > lastL1BatchBlockNum {
601		lastL1BatchBlockNum = t.stats.Sync.LastL1BatchBlock
602	}
603	return blockNum-lastL1BatchBlockNum >= t.vars.Rollup.ForgeL1L2BatchTimeout-1
604}