mempool

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2026 License: Apache-2.0 Imports: 44 Imported by: 15

README

mempool

[!WARNING]

This mempool implementation is experimental and under active development. It is intended for testing and evaluation purposes. Use in production environments is not recommended without thorough testing and risk assessment.

Please report issues and submit feedback to help improve stability.

Intro

This document specifies the appside mempool implementation of Cosmos EVM.

The EVM mempool is responsible for managing both EVM and Cosmos transactions in a unified pool, enabling Ethereum-compatible transaction flows including out-of-order transactions and nonce gap handling. It serves as a replacement for the default CometBFT FIFO mempool to support Ethereum tooling expectations while maintaining Cosmos SDK compatibility.

The mempool implements a two-tier architecture: a local transaction pool for queuing nonce-gapped transactions and CometBFT broadcasting for executable transactions, preventing network spam while enabling proper EVM transaction semantics.

Contents

Integration

Quick Start

To integrate the EVM mempool in your Cosmos application, follow these steps:

1. Add EVM Mempool to App Struct
type App struct {
    *baseapp.BaseApp
    // ... other keepers
    
    // Cosmos EVM keepers
    FeeMarketKeeper   feemarketkeeper.Keeper
    EVMKeeper         *evmkeeper.Keeper
    EVMMempool        *evmmempool.ExperimentalEVMMempool
}
2. Configure Mempool in NewApp Constructor

The mempool must be initialized after the antehandler has been set in the app.

// Set the EVM priority nonce mempool
if evmtypes.GetChainConfig() != nil {
    mempoolConfig := &evmmempool.EVMMempoolConfig{
        AnteHandler:   app.GetAnteHandler(),
        BlockGasLimit: 100_000_000,
    }

    evmMempool := evmmempool.NewExperimentalEVMMempool(
        app.CreateQueryContext, 
        logger, 
        app.EVMKeeper, 
        app.FeeMarketKeeper, 
        app.txConfig, 
        app.clientCtx, 
        mempoolConfig,
    )
    app.EVMMempool = evmMempool

    // Replace BaseApp mempool
    app.SetMempool(evmMempool)
    
    // Set custom CheckTx handler for nonce gap support
    checkTxHandler := evmmempool.NewCheckTxHandler(evmMempool)
    app.SetCheckTxHandler(checkTxHandler)

    // Set custom PrepareProposal handler
    abciProposalHandler := baseapp.NewDefaultProposalHandler(evmMempool, app)
    abciProposalHandler.SetSignerExtractionAdapter(
        evmmempool.NewEthSignerExtractionAdapter(
            sdkmempool.NewDefaultSignerExtractionAdapter(),
        ),
    )
    app.SetPrepareProposal(abciProposalHandler.PrepareProposalHandler())
}

// Close unsubscribes from the CometBFT event bus (if set) and closes the underlying BaseApp.
func (app *EVMD) Close() error {
	var err error
	if m, ok := app.GetMempool().(*evmmempool.ExperimentalEVMMempool); ok {
		err = m.Close()
	}
	err = errors.Join(err, app.BaseApp.Close())
	msg := "Application gracefully shutdown"
	if err == nil {
		app.Logger().Info(msg)
	} else {
		app.Logger().Error(msg, "error", err)
	}
	return err
}

Configuration Options

The EVMMempoolConfig struct provides several configuration options:

type EVMMempoolConfig struct {
    // Required: AnteHandler for transaction validation
    AnteHandler   sdk.AnteHandler
    
    // Required: Block gas limit for transaction selection
    BlockGasLimit uint64
    
    // Optional: Custom TxPool (defaults to LegacyPool)
    TxPool        *txpool.TxPool
    
    // Optional: Custom Cosmos pool (defaults to PriorityNonceMempool)  
    CosmosPool    sdkmempool.ExtMempool
    
    // Optional: Custom broadcast function for promoted transactions
    BroadCastTxFn func(txs []*ethtypes.Transaction) error
}

Minimal Configuration:

mempoolConfig := &evmmempool.EVMMempoolConfig{
    AnteHandler:   app.GetAnteHandler(),
    BlockGasLimit: 100_000_000, // 100M gas limit
}

Custom Cosmos Mempool Configuration:

The mempool uses a PriorityNonceMempool for Cosmos transactions by default. You can customize the priority calculation:

// Define custom priority calculation for Cosmos transactions
priorityConfig := sdkmempool.PriorityNonceMempoolConfig[math.Int]{
    TxPriority: sdkmempool.TxPriority[math.Int]{
        GetTxPriority: func(goCtx context.Context, tx sdk.Tx) math.Int {
            feeTx, ok := tx.(sdk.FeeTx)
            if !ok {
                return math.ZeroInt()
            }
            
            // Get fee in bond denomination
            bondDenom := "uatom" // or your chain's bond denom
            fee := feeTx.GetFee()
            found, coin := fee.Find(bondDenom)
            if !found {
                return math.ZeroInt()
            }
            
            // Calculate gas price: fee_amount / gas_limit
            gasPrice := coin.Amount.Quo(math.NewIntFromUint64(feeTx.GetGas()))
            return gasPrice
        },
        Compare: func(a, b math.Int) int {
            return a.BigInt().Cmp(b.BigInt()) // Higher values have priority
        },
        MinValue: math.ZeroInt(),
    },
}

mempoolConfig := &evmmempool.EVMMempoolConfig{
    AnteHandler:   app.GetAnteHandler(),
    BlockGasLimit: 100_000_000,
    CosmosPool:    sdkmempool.NewPriorityMempool(priorityConfig),
}

Custom Block Gas Limit:

// Example: 50M gas limit for lower capacity chains
mempoolConfig := &evmmempool.EVMMempoolConfig{
    AnteHandler:   app.GetAnteHandler(),
    BlockGasLimit: 50_000_000,
}
Prerequisites
  1. EVM Module Integration: EVM keeper and module initialized before mempool
  2. FeeMarket Module: Required for base fee calculations
  3. Compatible AnteHandler: Must support EVM transaction validation

Concepts

Problem Statement

The default CometBFT mempool is incompatible with Ethereum tooling (Forge, Hardhat, deployment scripts) due to fundamental differences in transaction ordering expectations:

  1. FIFO vs Priority Ordering: CometBFT uses strict FIFO ordering, while Ethereum tools expect fee-based prioritization
  2. Nonce Gap Rejection: CometBFT immediately rejects out-of-order nonces, while Ethereum tools expect such transactions to queue until executable
  3. Base Fee Dynamics: Transactions may become temporarily invalid due to base fee increases but should remain in the mempool

Example incompatibility from OP Stack deployment:

ERROR unable to publish transaction nonce=39 expected=12: invalid sequence
ERROR unable to publish transaction nonce=40 expected=12: invalid sequence
ERROR unable to publish transaction nonce=41 expected=12: invalid sequence

Real-World Testing: The tests/systemtests/Counter/script/SimpleSends.s.sol script demonstrates typical Ethereum tooling behavior - it sends 10 sequential transactions in a batch, which naturally arrive out of order and create nonce gaps. With the default Cosmos mempool, this script would fail with sequence errors. With the EVM mempool, all transactions are queued locally and promoted as gaps are filled, allowing the script to succeed.

Design Principles
  1. Instant Finality: Designed for Cosmos chains with instant finality (no reorgs)
  2. Two-Tier Architecture: Local queuing + CometBFT broadcasting prevents network spam
  3. Fee-Based Prioritization: Unified fee comparison between EVM and Cosmos transactions
  4. Ethereum Compatibility: Supports nonce gaps and transaction queuing semantics
Dual-Pool Transaction Management

The mempool manages both Cosmos and Ethereum transactions through a unified two-pool system:

Transaction Type Routing

Ethereum Transactions (MsgEthereumTx):

  • Tier 1 (Local): EVM TxPool handles nonce gaps and promotion logic
    • Queued state for nonce-gapped transactions (stored locally, not broadcast)
    • Pending state for immediately executable transactions
    • Background promotion when gaps are filled
  • Tier 2 (Network): CometBFT mempool broadcasts executable transactions

Cosmos Transactions (Bank, Staking, Gov, etc.):

  • Direct to Tier 2: Always go directly to CometBFT mempool (no local queuing)
  • Standard Flow: Follow normal Cosmos SDK validation and broadcasting
  • Priority-Based: Use PriorityNonceMempool for fee-based ordering
Unified Transaction Selection

During block building, both transaction types compete fairly:

// Simplified selection logic
func SelectTransactions() Iterator {
    evmTxs := GetPendingEVMTransactions()      // From local TxPool
    cosmosTxs := GetPendingCosmosTransactions() // From Cosmos mempool
    
    return NewUnifiedIterator(evmTxs, cosmosTxs) // Fee-based priority
}

Fee Comparison:

  • EVM: gas_tip_cap or gas_fee_cap - base_fee
  • Cosmos: (fee_amount / gas_limit) - base_fee
  • Winner: Higher effective tip gets selected first (regardless of type)

This design ensures EVM tooling gets expected nonce gap tolerance while Cosmos transactions maintain standard behavior and network performance is protected from spam.

Transaction States
  • Pending: Immediately executable transactions
  • Queued: Transactions with nonce gaps awaiting prerequisites
  • Promoted: Background transition from queued to pending
Fee Prioritization

Transaction selection uses effective tip calculation:

  • EVM: gas_tip_cap or min(gas_tip_cap, gas_fee_cap - base_fee)
  • Cosmos: (fee_amount / gas_limit) - base_fee

Higher effective tips are prioritized regardless of transaction type. In the event of a tie, EVM transactions are prioritized

Architecture

ExperimentalEVMMempool

The main coordinator implementing Cosmos SDK's ExtMempool interface.

Location: mempool/mempool.go

Methods:

  • Insert(ctx, tx): Routes transactions to appropriate pools
  • Select(ctx, filter): Returns unified iterator over all transactions
  • Remove(tx): Handles transaction removal with EVM-specific logic
  • InsertInvalidNonce(txBytes): Queues nonce-gapped EVM transactions without broadcasting them to the chain. A special failure case is sent via CheckTx, and the transaction is stored locally until it either gets included or evicted.

Configuration:

type EVMMempoolConfig struct {
    TxPool        *txpool.TxPool
    CosmosPool    sdkmempool.ExtMempool
    AnteHandler   sdk.AnteHandler
    BroadCastTxFn func(txs []*ethtypes.Transaction) error
    BlockGasLimit uint64
}
TxPool

Ethereum transaction pool forked from go-ethereum v1.15.11 with Cosmos adaptations.

Location: mempool/txpool/

Modifications:

  • Uses vm.StateDB interface instead of go-ethereum's StateDB
  • Implements BroadcastTxFn callback for transaction promotion. When nonce gaps are filled, the callback broadcasts via the Comet mempool
  • Cosmos-specific reset logic for instant finality. The TxPool was originally built for chains where block reorgs are possible, but this does not apply to instant finality chains, so the mempool ensures that the reorg flow is skipped.

Subpools: Currently uses only LegacyPool for standard EVM transactions

PriorityNonceMempool

Standard Cosmos SDK mempool for handling non-EVM transactions with fee-based prioritization.

Purpose: Manages all Cosmos SDK transactions (bank, staking, governance, etc.) separate from EVM transactions

Features:

  • Fee-based transaction prioritization using configurable priority functions
  • Standard Cosmos nonce validation (strict sequential ordering)
  • Direct integration with CometBFT broadcasting (no local queuing)
  • Compatible with all existing Cosmos SDK transaction types

Default Priority Calculation:

// Default implementation calculates effective gas price
priority = (fee_amount / gas_limit) - base_fee

Configuration: Can be customized via EVMMempoolConfig.CosmosPool parameter to provide different priority algorithms, fee calculation methods, or transaction filtering logic.

Interaction with EVM Pool: During block building, transactions from both pools are combined via the unified iterator, with selection based on fee comparison between the effective tips of both transaction types.

Miner

Transaction ordering mechanism from go-ethereum v1.15.11, unchanged from upstream.

Location: mempool/miner/ordering.go

Functionality:

  • Priority heap-based transaction selection (TransactionsByPriceAndNonce)
  • Per-account nonce ordering
  • Base fee consideration for effective tip calculation
Iterator

Unified iterator combining EVM and Cosmos transaction streams.

Location: mempool/iterator.go

Selection Logic:

func (i *EVMMempoolIterator) shouldUseEVM() bool {
    // 1. Availability check
    // 2. Fee comparison: effective_tip_evm vs effective_tip_cosmos
    // 3. EVM preferred on ties or invalid Cosmos fees
}
CheckTx Handler

Customizes transaction validation to handle nonce gaps specially.

Location: mempool/check_tx.go

Special Handling: On ErrNonceGap for EVM transactions, attempts InsertInvalidNonce() and returns success via the RPC to prevent client errors

Blockchain Interface

Adapter providing go-ethereum compatibility over Cosmos SDK state.

Location: mempool/blockchain.go

Features:

  • Block height synchronization (requires block 1+ for operation)
  • State database interface translation
  • Reorg protection (panics on reorg attempts)

Transaction Flow

The following diagrams illustrate the complete transaction flow architecture, showing how transactions move through the system from initial RPC calls to block inclusion:

Architecture Overview

EVM Mempool Architecture

Transaction Flow

Transaction Flow Comparison

State

The mempool module maintains the following state:

  1. EVM Transaction Pool: Managed by forked go-ethereum txpool

    • Pending transactions (immediately executable)
    • Queued transactions (nonce gaps)
    • Account nonces and balances via StateDB interface
  2. Cosmos Transaction Pool: Standard Cosmos SDK priority mempool

    • Priority-based transaction ordering
    • Fee-based prioritization
  3. Block Height: Requires block 1+ before accepting transactions

Client

JSON-RPC

The mempool extends RPC functionality through the /txpool namespace compatible with go-ethereum:

txpool_status

Returns pool statistics (pending/queued transaction counts).

curl -X POST -H "Content-Type: application/json" \
  --data '{"method":"txpool_status","params":[],"id":1,"jsonrpc":"2.0"}' \
  http://localhost:8545

Example Output:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "pending": 42,
    "queued": 7
  }
}
txpool_content

Returns full transaction content grouped by account and state.

curl -X POST -H "Content-Type: application/json" \
  --data '{"method":"txpool_content","params":[],"id":1,"jsonrpc":"2.0"}' \
  http://localhost:8545
txpool_contentFrom

Returns transactions from a specific address.

curl -X POST -H "Content-Type: application/json" \
  --data '{"method":"txpool_contentFrom","params":["0x1234..."],"id":1,"jsonrpc":"2.0"}' \
  http://localhost:8545
txpool_inspect

Returns transaction summaries without full transaction data.

curl -X POST -H "Content-Type: application/json" \
  --data '{"method":"txpool_inspect","params":[],"id":1,"jsonrpc":"2.0"}' \
  http://localhost:8545

Documentation

Index

Constants

View Source
const (
	CodeTypeNoRetry = uint32(1)
)
View Source
const (
	// SubscriberName is the name of the event bus subscriber for the EVM mempool
	SubscriberName = "evm"
)

Variables

View Source
var (
	ErrNoMessages                  = errors.New("transaction has no messages")
	ErrExpectedOneMessage          = errors.New("expected 1 message")
	ErrExpectedOneError            = errors.New("expected 1 error")
	ErrNotEVMTransaction           = errors.New("transaction is not an EVM transaction")
	ErrMultiMsgEthereumTransaction = errors.New("transaction contains multiple messages with an EVM msg")
	ErrNonceGap                    = errors.New("tx nonce is higher than account nonce")
	ErrNonceLow                    = errors.New("tx nonce is lower than account nonce")
	// ErrQueueFull is aliased from the internal queue package so that external
	// packages (e.g. evmd) can check for this error without importing internal/.
	ErrQueueFull = queue.ErrQueueFull
)
View Source
var AllowUnsafeSyncInsert = false

AllowUnsafeSyncInsert indicates whether to perform synchronous inserts into the mempool for testing purposes. When true, Insert will block until the transaction is fully processed. This should be used only in tests to ensure deterministic behavior

Functions

func ErrAsCheckTxResponse added in v0.7.0

func ErrAsCheckTxResponse(err error) *abci.ResponseCheckTx

ErrAsCheckTxResponse converts an error to a ResponseCheckTx object, respecting error wrapping.

func NewCosmosTransactionsByPriceAndNonce added in v0.7.0

func NewCosmosTransactionsByPriceAndNonce(
	txs map[string][]cosmosTxWithMetadata,
	bondDenom string,
	baseFee *uint256.Int,
) sdkmempool.Iterator

func NewEVMMempoolIterator

func NewEVMMempoolIterator(
	evmIterator *miner.TransactionsByPriceAndNonce,
	cosmosIterator mempool.Iterator,
	logger log.Logger,
	txConfig client.TxConfig,
	blockchain *Blockchain,
) mempool.Iterator

NewEVMMempoolIterator creates a new unified iterator over EVM and Cosmos transactions. It combines iterators from both transaction pools and selects transactions based on fee priority. Returns nil if both iterators are empty or nil. The bondDenom parameter specifies the native token denomination for fee comparisons, and chainId is used for EVM transaction conversion.

Types

type Blockchain

type Blockchain struct {
	// contains filtered or unexported fields
}

Blockchain implements the BlockChain interface required by Ethereum transaction pools. It bridges Cosmos SDK blockchain state with Ethereum's transaction pool system by providing access to block headers, chain configuration, and state databases. This implementation is specifically designed for instant finality chains where reorgs never occur.

func NewBlockchain added in v0.5.0

func NewBlockchain(ctx func(height int64, prove bool) (sdk.Context, error), logger log.Logger, vmKeeper VMKeeperI, feeMarketKeeper FeeMarketKeeperI, blockGasLimit uint64) *Blockchain

NewBlockchain creates a new Blockchain instance that bridges Cosmos SDK state with Ethereum mempools. The getCtxCallback function provides access to Cosmos SDK contexts at different heights, vmKeeper manages EVM state, and feeMarketKeeper handles fee market operations like base fee calculations.

func (*Blockchain) BeginCommit added in v0.7.0

func (b *Blockchain) BeginCommit()

BeginCommit acquires an exclusive lock to prevent mempool state reads during Commit. This avoids data races in the underlying storage (e.g., IAVL) when tests run with -race.

func (*Blockchain) BeginRead added in v0.7.0

func (b *Blockchain) BeginRead()

BeginRead acquires a shared lock for background readers (e.g., txpool reorg). This enables optional coordination with Commit without importing the type.

func (*Blockchain) Config

func (b *Blockchain) Config() *params.ChainConfig

Config returns the Ethereum chain configuration. It should only be called after the chain is initialized. This provides the necessary parameters for EVM execution and transaction validation.

func (*Blockchain) CurrentBlock

func (b *Blockchain) CurrentBlock() *types.Header

CurrentBlock returns the current block header for the app. It constructs an Ethereum-compatible header from the current Cosmos SDK context, including block height, timestamp, gas limits, and base fee (if London fork is active). Returns a zero header as placeholder if the context is not yet available.

func (*Blockchain) EndCommit added in v0.7.0

func (b *Blockchain) EndCommit()

EndCommit releases the exclusive lock acquired by BeginCommit.

func (*Blockchain) EndRead added in v0.7.0

func (b *Blockchain) EndRead()

EndRead releases the shared read lock acquired by BeginRead.

func (*Blockchain) GetBlock

func (b *Blockchain) GetBlock(_ common.Hash, _ uint64) *types.Block

GetBlock retrieves a block by hash and number. Cosmos chains have instant finality, so this method should only be called for the genesis block (block 0) or block 1, as reorgs never occur. Any other call indicates a bug in the mempool logic. Panics if called for blocks beyond block 1, as this would indicate an attempted reorg.

func (*Blockchain) GetCoinDenom added in v0.7.0

func (b *Blockchain) GetCoinDenom() string

GetCoinDenom returns the coin denom used in the EVM. Note: return "" if height=0.

func (*Blockchain) GetLatestContext added in v0.5.0

func (b *Blockchain) GetLatestContext() (sdk.Context, error)

GetLatestContext returns the latest context as updated by the block, or attempts to retrieve it again if unavailable.

func (*Blockchain) NotifyNewBlock

func (b *Blockchain) NotifyNewBlock()

NotifyNewBlock sends a chain head event when a new block is finalized

func (*Blockchain) StateAt

func (b *Blockchain) StateAt(hash common.Hash) (vm.StateDB, error)

StateAt returns the StateDB object for a given block hash. In practice, this always returns the most recent state since the mempool only needs current state for validation. Historical state access is not supported as it's never required by the txpool.

func (*Blockchain) SubscribeChainHeadEvent

func (b *Blockchain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription

SubscribeChainHeadEvent allows subscribers to receive notifications when new blocks are finalized. Returns a subscription that will receive ChainHeadEvent notifications via the provided channel.

type Config added in v0.7.0

type Config struct {
	LegacyPoolConfig *legacypool.Config
	CosmosPoolConfig *sdkmempool.PriorityNonceMempoolConfig[math.Int]
	AnteHandler      sdk.AnteHandler
	BroadCastTxFn    func(txs []*ethtypes.Transaction) error

	// Block gas limit from consensus parameters
	BlockGasLimit uint64
	MinTip        *uint256.Int

	// PendingTxProposalTimeout is the max amount of time to allocate to
	// fetching (or waiting to fetch) pending txs from the evm mempool.
	PendingTxProposalTimeout time.Duration
	// InsertQueueSize is how many txs can be stored in the insert queue
	// pending insertion into the mempool. Note the insert queue is only used
	// for EVM txs.
	InsertQueueSize int
	// EnableTxTracker controls whether the mempool records per-tx lifecycle
	// telemetry (queued/pending/included latencies). Defaults to false.
	EnableTxTracker bool
}

Config defines the configuration for the EVM mempool.

type CosmosTransactionsByPriceAndNonce added in v0.7.0

type CosmosTransactionsByPriceAndNonce struct {
	// contains filtered or unexported fields
}

CosmosTransactionsByPriceAndNonce returns Cosmos transactions in fee-priority order while still honoring nonce ordering within each signer bucket.

func (*CosmosTransactionsByPriceAndNonce) Next added in v0.7.0

func (*CosmosTransactionsByPriceAndNonce) Tx added in v0.7.0

type CosmosTxStore added in v0.7.0

type CosmosTxStore struct {
	// contains filtered or unexported fields
}

CosmosTxStore is a set of cosmos transactions that can be added to or removed from.

func NewCosmosTxStore added in v0.7.0

func NewCosmosTxStore(l log.Logger) *CosmosTxStore

NewCosmosTxStore creates a new CosmosTxStore.

func (*CosmosTxStore) AddTx added in v0.7.0

func (s *CosmosTxStore) AddTx(tx sdk.Tx)

AddTx adds a single tx to the store while constructing a validated snapshot.

func (*CosmosTxStore) InvalidateFrom added in v0.7.0

func (s *CosmosTxStore) InvalidateFrom(tx sdk.Tx) int

InvalidateFrom removes any stored tx that depends on the supplied tx's signer/nonces. It is used for live mempool replacements: once a tx at nonce N changes, any stored tx for the same signer(s) with nonce >= N can no longer be considered valid for proposal building.

func (*CosmosTxStore) Iterator added in v0.7.0

func (s *CosmosTxStore) Iterator() sdkmempool.Iterator

Iterator returns an sdkmempool.Iterator over the txs in the store.

func (*CosmosTxStore) Len added in v0.7.0

func (s *CosmosTxStore) Len() int

Len returns the number of txs in the store.

func (*CosmosTxStore) OrderedIterator added in v0.7.0

func (s *CosmosTxStore) OrderedIterator(bondDenom string, baseFee *uint256.Int) sdkmempool.Iterator

func (*CosmosTxStore) Txs added in v0.7.0

func (s *CosmosTxStore) Txs() []sdk.Tx

Txs returns a copy of the current set of txs in the store.

type EVMMempoolIterator

type EVMMempoolIterator struct {
	// contains filtered or unexported fields
}

EVMMempoolIterator provides a unified iterator over both EVM and Cosmos transactions in the mempool. It implements priority-based transaction selection, choosing between EVM and Cosmos transactions based on their fee values. The iterator maintains state to track transaction types and ensures proper sequencing during block building.

func (*EVMMempoolIterator) Next

Next advances the iterator to the next transaction and returns the updated iterator. It determines which iterator (EVM or Cosmos) provided the current transaction and advances that iterator accordingly. Returns nil when no more transactions are available.

func (*EVMMempoolIterator) Tx

func (i *EVMMempoolIterator) Tx() sdk.Tx

Tx returns the current transaction from the iterator.

type EthSignerExtractionAdapter

type EthSignerExtractionAdapter struct {
	// contains filtered or unexported fields
}

EthSignerExtractionAdapter is the default implementation of SignerExtractionAdapter. It extracts the signers from a cosmos-sdk tx via GetSignaturesV2.

func NewEthSignerExtractionAdapter

func NewEthSignerExtractionAdapter(fallback mempool.SignerExtractionAdapter) EthSignerExtractionAdapter

NewEthSignerExtractionAdapter constructs a new EthSignerExtractionAdapter instance

func (EthSignerExtractionAdapter) GetSigners

func (s EthSignerExtractionAdapter) GetSigners(tx sdk.Tx) ([]mempool.SignerData, error)

GetSigners returns the EVM tx sender. EIP-7702 authorities are NOT enumerated: whether each authorization succeeds on chain (and therefore actually bumps the authority's nonce) is unverifiable without chain state — a failed authorization does not increment the nonce. Eagerly reporting auth.Nonce would falsely evict legitimate pending txs from authorities whose auths failed. Async reset catches authority nonce advances instead. Non-EVM cosmos txs fall through to the SDK default.

type FeeMarketKeeperI

type FeeMarketKeeperI interface {
	GetBlockGasWanted(ctx sdk.Context) uint64
}

type Mempool added in v0.7.0

type Mempool struct {
	// contains filtered or unexported fields
}

Mempool is an application side mempool implementation that operates in conjunction with the CometBFT 'app' configuration. The Mempool handles application side rechecking of txs and supports ABCI methods InesrtTx and ReapTxs.

func NewMempool added in v0.7.0

func NewMempool(
	getCtxCallback func(height int64, prove bool) (sdk.Context, error),
	logger log.Logger,
	vmKeeper VMKeeperI,
	feeMarketKeeper FeeMarketKeeperI,
	txConfig client.TxConfig,
	evmRechecker legacypool.Rechecker,
	cosmosRechecker Rechecker,
	config *Config,
	cosmosPoolMaxTx int,
) *Mempool

func (*Mempool) Close added in v0.7.0

func (m *Mempool) Close() error

func (*Mempool) CountTx added in v0.7.0

func (m *Mempool) CountTx() int

CountTx returns the total number of transactions in both EVM and Cosmos pools. This provides a combined count across all mempool types.

func (*Mempool) GetBlockchain added in v0.7.0

func (m *Mempool) GetBlockchain() *Blockchain

GetBlockchain returns the blockchain interface used for chain head event notifications. This is primarily used to notify the mempool when new blocks are finalized.

func (*Mempool) GetTxPool added in v0.7.0

func (m *Mempool) GetTxPool() *txpool.TxPool

GetTxPool returns the underlying EVM txpool. This provides direct access to the EVM-specific transaction management functionality.

func (*Mempool) HasEventBus added in v0.7.0

func (m *Mempool) HasEventBus() bool

HasEventBus returns true if the blockchain is configured to use an event bus for block notifications.

func (*Mempool) Insert added in v0.7.0

func (m *Mempool) Insert(ctx context.Context, tx sdk.Tx) error

Insert adds a transaction to the appropriate mempool (EVM or Cosmos). EVM transactions are routed to the EVM transaction pool, while all other transactions are inserted into the Cosmos sdkmempool.

func (*Mempool) InsertAsync added in v0.7.0

func (m *Mempool) InsertAsync(tx sdk.Tx) error

InsertAsync adds a transaction to the appropriate mempool (EVM or Cosmos). EVM transactions are routed to the EVM transaction pool, while all other transactions are inserted into the Cosmos sdkmempool. EVM transactions are inserted async, i.e. they are scheduled for promotion only, we do not wait for it to complete.

func (*Mempool) NewCheckTxHandler added in v0.7.0

func (m *Mempool) NewCheckTxHandler(txDecoder sdk.TxDecoder, timeout time.Duration) sdk.CheckTxHandler

NewCheckTxHandler is the handler for ABCI.CheckTx. Note: it's async and doesn't expect the caller to acquire ABCI lock. Used ONLY to support BroadcastTxSync (cosmos rpc). All EVM txs should be inserted via InsertTx handler or EVM RPC.

func (*Mempool) NewInsertTxHandler added in v0.7.0

func (m *Mempool) NewInsertTxHandler(txDecoder sdk.TxDecoder) sdk.InsertTxHandler

NewInsertTxHandler is the handler for ABCI.InsertTx. Used by CometBFT to asynchronously insert a new tx into the mempool. Supersedes ABCI.CheckTx. Handles concurrent requests

func (*Mempool) NewReapTxsHandler added in v0.7.0

func (m *Mempool) NewReapTxsHandler() sdk.ReapTxsHandler

NewReapTxsHandler is the handler for ABCI.ReapTxs. It's used by CometBFT to reap valid txs from the mempool and share them with other peers. Handles concurrent requests.

func (*Mempool) NotifyNewBlock added in v0.7.0

func (m *Mempool) NotifyNewBlock()

NotifyNewBlock manually notifies that there has been a new block produced and it should update its internal data structures.

func (*Mempool) ReapNewValidTxs added in v0.7.0

func (m *Mempool) ReapNewValidTxs(maxBytes uint64, maxGas uint64) ([][]byte, error)

ReapNewValidTxs removes and returns the oldest transactions from the reap list until maxBytes or maxGas limits are reached.

func (*Mempool) RecheckCosmosTxs added in v0.7.0

func (m *Mempool) RecheckCosmosTxs(newHead *ethtypes.Header)

RecheckCosmosTxs triggers a synchronous recheck of cosmos transactions. This should only used for testing.

func (*Mempool) RecheckEVMTxs added in v0.7.0

func (m *Mempool) RecheckEVMTxs(newHead *ethtypes.Header)

RecheckEVMTxs triggers a synchronous recheck of evm transactions. This should only be used for testing.

func (*Mempool) Remove added in v0.7.0

func (m *Mempool) Remove(tx sdk.Tx) error

Remove fallbacks for RemoveWithReason

func (*Mempool) RemoveWithReason added in v0.7.0

func (m *Mempool) RemoveWithReason(_ context.Context, tx sdk.Tx, reason sdkmempool.RemoveReason) error

RemoveWithReason removes a transaction from the appropriate sdkmempool.

NOTE #1: even if removal fails, side effects may have occurred like recording nonce increments.

NOTE #2: This method might be called multiple times for the same tx:

  • during tx re-execution by BlockSTM
  • during tx execution by OptimisticExecution that fails and then inside another finalizeBlock() (e.g. consensus round increment)

func (*Mempool) Select added in v0.7.0

func (m *Mempool) Select(goCtx context.Context, i [][]byte) sdkmempool.Iterator

Select returns a unified iterator over both EVM and Cosmos transactions. The iterator prioritizes transactions based on their fees and manages proper sequencing. The i parameter contains transaction hashes to exclude from selection.

func (*Mempool) SelectBy added in v0.7.0

func (m *Mempool) SelectBy(goCtx context.Context, txs [][]byte, filter func(sdk.Tx) bool)

SelectBy iterates through transactions until the provided filter function returns false. It uses the same unified iterator as Select but allows early termination based on custom criteria defined by the filter function.

func (*Mempool) SetClientCtx added in v0.7.0

func (m *Mempool) SetClientCtx(clientCtx client.Context)

SetClientCtx sets the client context provider for broadcasting transactions

func (*Mempool) SetEventBus added in v0.7.0

func (m *Mempool) SetEventBus(eventBus *cmttypes.EventBus)

SetEventBus sets CometBFT event bus to listen for new block header event.

func (*Mempool) TrackTx added in v0.7.0

func (m *Mempool) TrackTx(hash common.Hash) error

TrackTx submits a tx to be tracked for its tx inclusion metrics.

type RecheckMempool added in v0.7.0

type RecheckMempool struct {
	sdkmempool.ExtMempool
	// contains filtered or unexported fields
}

RecheckMempool wraps an ExtMempool and provides block-driven rechecking of transactions when new blocks are committed. It mirrors the legacypool pattern but simplified for Cosmos mempool behavior (no reorgs, no queued/pending management).

All pool mutations (Insert, Remove) and reads (Select, CountTx) are protected by a RWMutex to ensure thread-safety during recheck operations.

func NewRecheckMempool added in v0.7.0

func NewRecheckMempool(
	defaultCosmosPoolConfig *sdkmempool.PriorityNonceMempoolConfig[math.Int],
	maxTxs int,
	reserver *reserver.ReservationHandle,
	rechecker Rechecker,
	recheckedTxs *heightsync.HeightSync[CosmosTxStore],
	reapList *reaplist.ReapList,
	blockchain *Blockchain,
	logger log.Logger,
) *RecheckMempool

NewRecheckMempool creates a new RecheckMempool.

func (*RecheckMempool) Close added in v0.7.0

func (m *RecheckMempool) Close() error

Close gracefully shuts down the recheck loop.

func (*RecheckMempool) CountTx added in v0.7.0

func (m *RecheckMempool) CountTx() int

CountTx returns the number of transactions in the pool.

func (*RecheckMempool) Insert added in v0.7.0

func (m *RecheckMempool) Insert(_ context.Context, tx sdk.Tx) (err error)

Insert adds a transaction to the pool after running the ante handler. This is the main entry point for new cosmos transactions.

func (*RecheckMempool) OrderedRecheckedTxs added in v0.7.0

func (m *RecheckMempool) OrderedRecheckedTxs(
	ctx context.Context,
	height *big.Int,
	bondDenom string,
	baseFee *uint256.Int,
) sdkmempool.Iterator

OrderedRecheckedTxs returns the rechecked tx snapshot for a height using fee-priority ordering across signer buckets while still honoring nonce order within each bucket.

func (*RecheckMempool) RecheckedTxs added in v0.7.0

func (m *RecheckMempool) RecheckedTxs(ctx context.Context, height *big.Int) sdkmempool.Iterator

RecheckedTxs returns the txs that have been rechecked for a height. The RecheckMempool must be currently operating on this height (i.e. recheck has been triggered on this height via TriggerRecheck). If height is in the past (TriggerRecheck has been called on height + 1), this will panic. If height is in the future, this will block until TriggerReset is called for height, or the context times out.

func (*RecheckMempool) Remove added in v0.7.0

func (m *RecheckMempool) Remove(tx sdk.Tx) error

Remove is a noop for this pool. All removals are processed during the async recheck loop.

func (*RecheckMempool) RemoveWithReason added in v0.7.0

func (m *RecheckMempool) RemoveWithReason(_ context.Context, tx sdk.Tx, _ sdkmempool.RemoveReason) error

RemoveWithReason is a noop for this pool. All removals are processed during the async recheck loop. This must be explicitly defined to prevent Go from promoting the embedded ExtMempool's RemoveWithReason.

func (*RecheckMempool) Select added in v0.7.0

func (m *RecheckMempool) Select(ctx context.Context, txs [][]byte) sdkmempool.Iterator

Select returns an iterator over transactions in the pool.

func (*RecheckMempool) Start added in v0.7.0

func (m *RecheckMempool) Start(initialHead *ethtypes.Header)

Start begins the background recheck loop and initializes the rechecker's context to the latest chain state. The initialHead is used for the first Rechecker.Update call before any recheck has been triggered.

func (*RecheckMempool) TriggerRecheck added in v0.7.0

func (m *RecheckMempool) TriggerRecheck(newHead *ethtypes.Header) <-chan struct{}

TriggerRecheck signals that a new block arrived and returns a channel that closes when the recheck completes (or is superseded by another).

func (*RecheckMempool) TriggerRecheckSync added in v0.7.0

func (m *RecheckMempool) TriggerRecheckSync(newHead *ethtypes.Header)

TriggerRecheckSync triggers a recheck and blocks until complete.

type Rechecker added in v0.7.0

type Rechecker interface {
	// GetContext gets a branch of the current context that transactions should
	// be rechecked against. Changes to ctx will only be persisted back to the
	// Rechecker once the write function is invoked.
	GetContext() (ctx sdk.Context, write func())

	// RecheckCosmos performs validation of a cosmos tx against a context, and
	// returns an updated context.
	RecheckCosmos(ctx sdk.Context, tx sdk.Tx) (sdk.Context, error)

	// Update updates the recheckers context to be the ctx at headers height.
	Update(ctx sdk.Context, header *ethtypes.Header)
}

Rechecker defines the minimal set of methods needed to recheck cosmos transactions and manage the context that the transactions are rechecked against.

type TxConverter added in v0.7.0

type TxConverter interface {
	EVMTxToCosmosTx(tx *ethtypes.Transaction) (sdk.Tx, error)
}

type TxEncoder added in v0.7.0

type TxEncoder struct {
	// contains filtered or unexported fields
}

func NewTxEncoder added in v0.7.0

func NewTxEncoder(txConfig client.TxConfig) *TxEncoder

func (*TxEncoder) CosmosTx added in v0.7.0

func (e *TxEncoder) CosmosTx(tx sdk.Tx) ([]byte, error)

EncodeCosmosTx encodes a cosmos tx to bytes.

func (*TxEncoder) EVMTx added in v0.7.0

func (e *TxEncoder) EVMTx(tx *ethtypes.Transaction) ([]byte, error)

EncodeEVMTx encodes an evm tx to its sdk representation as bytes.

func (*TxEncoder) EVMTxToCosmosTx added in v0.7.0

func (e *TxEncoder) EVMTxToCosmosTx(tx *ethtypes.Transaction) (sdk.Tx, error)

EVMTxToCosmosTx converts an evm transaction to a cosmos transaction

type TxRechecker added in v0.7.0

type TxRechecker struct {
	// contains filtered or unexported fields
}

TxRechecker runs recheckFn on pending and queued txs in the pool, given an sdk context via UpdateCtx.

NOTE: None of the recheckers functions are thread safe.

func NewTxRechecker added in v0.7.0

func NewTxRechecker(anteHandler sdk.AnteHandler, txConverter TxConverter) *TxRechecker

NewTxRechecker creates a new rechecker that can recheck transactions.

func (*TxRechecker) GetContext added in v0.7.0

func (r *TxRechecker) GetContext() (sdk.Context, func())

GetContext returns a branched context. The caller can use the returned function in order to write updates applied to the returned context, back to the context stored by the rechecker for future callers to use.

NOTE: This function is not thread safe with itself or any other Rechecker functions.

func (*TxRechecker) RecheckCosmos added in v0.7.0

func (r *TxRechecker) RecheckCosmos(ctx sdk.Context, tx sdk.Tx) (sdk.Context, error)

RecheckCosmos revalidates a Cosmos transaction against a context. It returns an updated context and an error that occurred while processing.

NOTE: This function is not thread safe with itself or any other Rechecker functions.

func (*TxRechecker) RecheckEVM added in v0.7.0

func (r *TxRechecker) RecheckEVM(ctx sdk.Context, tx *ethtypes.Transaction) (sdk.Context, error)

RecheckEVM revalidates an EVM transaction against a context. It returns an updated context and an error that occurred while processing.

NOTE: This function is not thread safe with itself or any other Rechecker functions.

func (*TxRechecker) Update added in v0.7.0

func (r *TxRechecker) Update(ctx sdk.Context, header *ethtypes.Header)

Update updates the base context for rechecks based on the latest chain state. The caller provides the context directly.

NOTE: This function is not thread safe with itself or any other Rechecker functions.

type VMKeeperI

type VMKeeperI interface {
	GetBaseFee(ctx sdk.Context) *big.Int
	GetParams(ctx sdk.Context) (params vmtypes.Params)
	GetEvmCoinInfo(ctx sdk.Context) (coinInfo vmtypes.EvmCoinInfo)
	GetAccount(ctx sdk.Context, addr common.Address) *statedb.Account
	GetState(ctx sdk.Context, addr common.Address, key common.Hash) common.Hash
	GetCode(ctx sdk.Context, codeHash common.Hash) []byte
	GetCodeHash(ctx sdk.Context, addr common.Address) common.Hash
	ForEachStorage(ctx sdk.Context, addr common.Address, cb func(key common.Hash, value common.Hash) bool)
	SetAccount(ctx sdk.Context, addr common.Address, account statedb.Account) error
	DeleteState(ctx sdk.Context, addr common.Address, key common.Hash)
	SetState(ctx sdk.Context, addr common.Address, key common.Hash, value []byte)
	DeleteCode(ctx sdk.Context, codeHash []byte)
	SetCode(ctx sdk.Context, codeHash []byte, code []byte)
	DeleteAccount(ctx sdk.Context, addr common.Address) error
	KVStoreKeys() map[string]storetypes.StoreKey
}

Directories

Path Synopsis
internal
legacypool
Package legacypool implements the normal EVM execution transaction pool.
Package legacypool implements the normal EVM execution transaction pool.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL