Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions bootstrap/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,9 @@ func (b *Bootstrap) StartAPIServer(ctx context.Context) error {

// create transaction pool
var txPool requester.TxPool
var err error
if b.config.TxBatchMode {
txPool = requester.NewBatchTxPool(
txPool, err = requester.NewBatchTxPool(
ctx,
b.client,
b.publishers.Transaction,
Expand All @@ -258,7 +259,8 @@ func (b *Bootstrap) StartAPIServer(ctx context.Context) error {
b.keystore,
)
} else {
txPool = requester.NewSingleTxPool(
txPool, err = requester.NewSingleTxPool(
ctx,
b.client,
b.publishers.Transaction,
b.logger,
Expand All @@ -267,6 +269,9 @@ func (b *Bootstrap) StartAPIServer(ctx context.Context) error {
b.keystore,
)
}
if err != nil {
return fmt.Errorf("failed to create transaction pool: %w", err)
}

evm, err := requester.NewEVM(
b.storages.Registers,
Expand Down
24 changes: 14 additions & 10 deletions services/requester/batch_tx_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,22 @@ func NewBatchTxPool(
config config.Config,
collector metrics.Collector,
keystore *keystore.KeyStore,
) *BatchTxPool {
) (*BatchTxPool, error) {
// initialize the available keys metric since it is only updated when sending a tx
collector.AvailableSigningKeys(keystore.AvailableKeys())

singleTxPool := NewSingleTxPool(
singleTxPool, err := NewSingleTxPool(
ctx,
client,
transactionsPublisher,
logger,
config,
collector,
keystore,
)
if err != nil {
return nil, err
}

eoaActivity := expirable.NewLRU[gethCommon.Address, time.Time](
eoaActivityCacheSize,
Expand All @@ -84,7 +88,7 @@ func NewBatchTxPool(

go batchPool.processPooledTransactions(ctx)

return batchPool
return batchPool, nil
}

// Add adds the EVM transaction to the tx pool, grouped with the rest of the
Expand Down Expand Up @@ -161,10 +165,10 @@ func (t *BatchTxPool) processPooledTransactions(ctx context.Context) {
case <-ctx.Done():
return
case <-ticker.C:
latestBlock, account, err := t.fetchFlowLatestBlockAndCOA(ctx)
account, err := t.client.GetAccount(ctx, t.config.COAAddress)
if err != nil {
t.logger.Error().Err(err).Msg(
"failed to get COA / latest Flow block on batch tx submission",
"failed to get COA on batch tx submission",
)
continue
}
Expand All @@ -180,7 +184,7 @@ func (t *BatchTxPool) processPooledTransactions(ctx context.Context) {
for address, pooledTxs := range txsGroupedByAddress {
err := t.batchSubmitTransactionsForSameAddress(
ctx,
latestBlock,
t.getLatestBlockHeader(),
account,
pooledTxs,
)
Expand All @@ -198,7 +202,7 @@ func (t *BatchTxPool) processPooledTransactions(ctx context.Context) {

func (t *BatchTxPool) batchSubmitTransactionsForSameAddress(
ctx context.Context,
latestBlock *flow.Block,
latestBlockHeader *flow.BlockHeader,
account *flow.Account,
pooledTxs []pooledEvmTx,
) error {
Expand All @@ -220,7 +224,7 @@ func (t *BatchTxPool) batchSubmitTransactionsForSameAddress(

script := replaceAddresses(batchRunTxScript, t.config.FlowNetworkID)
flowTx, err := t.buildTransaction(
latestBlock,
latestBlockHeader,
account,
script,
cadence.NewArray(hexEncodedTxs),
Expand All @@ -244,7 +248,7 @@ func (t *BatchTxPool) submitSingleTransaction(
ctx context.Context,
hexEncodedTx cadence.String,
) error {
latestBlock, account, err := t.fetchFlowLatestBlockAndCOA(ctx)
account, err := t.client.GetAccount(ctx, t.config.COAAddress)
if err != nil {
return err
}
Expand All @@ -256,7 +260,7 @@ func (t *BatchTxPool) submitSingleTransaction(

script := replaceAddresses(runTxScript, t.config.FlowNetworkID)
flowTx, err := t.buildTransaction(
latestBlock,
t.getLatestBlockHeader(),
account,
script,
hexEncodedTx,
Expand Down
78 changes: 47 additions & 31 deletions services/requester/single_tx_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/hex"
"fmt"
"sync"
"sync/atomic"
"time"

gethTypes "github.com/ethereum/go-ethereum/core/types"
Expand All @@ -13,14 +14,15 @@ import (
flowGo "github.com/onflow/flow-go/model/flow"
"github.com/rs/zerolog"
"github.com/sethvargo/go-retry"
"golang.org/x/sync/errgroup"

"github.com/onflow/flow-evm-gateway/config"
"github.com/onflow/flow-evm-gateway/metrics"
"github.com/onflow/flow-evm-gateway/models"
"github.com/onflow/flow-evm-gateway/services/requester/keystore"
)

var blockHeaderUpdateFrequency = time.Second * 5
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can increase the update frequency (like every 2 or 3 seconds), but since we get the latest finalized (not sealed) block header, I think this is a good value and we're safe. Any objections?


// SingleTxPool is a simple implementation of the `TxPool` interface that submits
// transactions as soon as they arrive, without any delays or batching strategies.
type SingleTxPool struct {
Expand All @@ -32,23 +34,32 @@ type SingleTxPool struct {
mux sync.Mutex
keystore *keystore.KeyStore
collector metrics.Collector
// latestBlockHeader is stored atomically to avoid races
// between request path and ticker updates.
latestBlockHeader atomic.Value // stores *flow.BlockHeader
// todo add methods to inspect transaction pool state
}

var _ TxPool = &SingleTxPool{}

func NewSingleTxPool(
ctx context.Context,
client *CrossSporkClient,
transactionsPublisher *models.Publisher[*gethTypes.Transaction],
logger zerolog.Logger,
config config.Config,
collector metrics.Collector,
keystore *keystore.KeyStore,
) *SingleTxPool {
) (*SingleTxPool, error) {
latestBlockHeader, err := client.GetLatestBlockHeader(ctx, false)
if err != nil {
return nil, err
}

// initialize the available keys metric since it is only updated when sending a tx
collector.AvailableSigningKeys(keystore.AvailableKeys())

return &SingleTxPool{
singleTxPool := &SingleTxPool{
logger: logger.With().Str("component", "tx-pool").Logger(),
client: client,
txPublisher: transactionsPublisher,
Expand All @@ -57,6 +68,11 @@ func NewSingleTxPool(
collector: collector,
keystore: keystore,
}
singleTxPool.latestBlockHeader.Store(latestBlockHeader)

go singleTxPool.trackLatestBlockHeader(ctx)

return singleTxPool, nil
}

// Add creates a Cadence transaction that wraps the given EVM transaction in
Expand Down Expand Up @@ -93,14 +109,14 @@ func (t *SingleTxPool) Add(
return err
}

latestBlock, account, err := t.fetchFlowLatestBlockAndCOA(ctx)
account, err := t.client.GetAccount(ctx, t.config.COAAddress)
if err != nil {
return err
}

script := replaceAddresses(runTxScript, t.config.FlowNetworkID)
flowTx, err := t.buildTransaction(
latestBlock,
t.getLatestBlockHeader(),
account,
script,
hexEncodedTx,
Expand Down Expand Up @@ -157,7 +173,7 @@ func (t *SingleTxPool) Add(
// buildTransaction creates a Cadence transaction from the provided script,
// with the given arguments and signs it with the configured COA account.
func (t *SingleTxPool) buildTransaction(
latestBlock *flow.Block,
latestBlockHeader *flow.BlockHeader,
account *flow.Account,
script []byte,
args ...cadence.Value,
Expand All @@ -168,7 +184,7 @@ func (t *SingleTxPool) buildTransaction(

flowTx := flow.NewTransaction().
SetScript(script).
SetReferenceBlockID(latestBlock.ID).
SetReferenceBlockID(latestBlockHeader.ID).
SetComputeLimit(flowGo.DefaultMaxTransactionGasLimit)

for _, arg := range args {
Expand All @@ -193,37 +209,37 @@ func (t *SingleTxPool) buildTransaction(
}

// now that the transaction is prepared, store the transaction's metadata
accKey.SetLockMetadata(flowTx.ID(), latestBlock.Height)
accKey.SetLockMetadata(flowTx.ID(), latestBlockHeader.Height)

t.collector.OperatorBalance(account)

return flowTx, nil
}

func (t *SingleTxPool) fetchFlowLatestBlockAndCOA(ctx context.Context) (
*flow.Block,
*flow.Account,
error,
) {
var (
g = errgroup.Group{}
err1, err2 error
latestBlock *flow.Block
account *flow.Account
)
func (t *SingleTxPool) trackLatestBlockHeader(ctx context.Context) {
ticker := time.NewTicker(blockHeaderUpdateFrequency)
defer ticker.Stop()

// execute concurrently so we can speed up all the information we need for tx
g.Go(func() error {
latestBlock, err1 = t.client.GetLatestBlock(ctx, true)
return err1
})
g.Go(func() error {
account, err2 = t.client.GetAccount(ctx, t.config.COAAddress)
return err2
})
if err := g.Wait(); err != nil {
return nil, nil, err
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
blockHeader, err := t.client.GetLatestBlockHeader(ctx, false)
if err != nil {
t.logger.Error().Err(err).Msg(
"failed to update latest Flow block header",
)
continue
}
t.latestBlockHeader.Store(blockHeader)
}
}
}

return latestBlock, account, nil
func (t *SingleTxPool) getLatestBlockHeader() *flow.BlockHeader {
if v := t.latestBlockHeader.Load(); v != nil {
return v.(*flow.BlockHeader)
}
return nil
}
2 changes: 1 addition & 1 deletion tests/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func startEmulator(createTestAccounts bool) (*server.EmulatorServer, error) {
GenesisTokenSupply: genesisToken,
WithContracts: true,
Host: "localhost",
TransactionExpiry: 10,
TransactionExpiry: flow.DefaultTransactionExpiry,
TransactionMaxGasLimit: flow.DefaultMaxTransactionGasLimit,
SetupEVMEnabled: true,
SetupVMBridgeEnabled: false,
Expand Down