spamoor

package
v1.1.7 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2025 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// BatcherTxLimit is the maximum number of transactions that can be batched in a single call.
	BatcherTxLimit = 50
	// BatcherBaseGas is the base gas cost for executing a batcher transaction.
	BatcherBaseGas = 50000
	// BatcherGasPerTx is the additional gas cost per transaction in the batch.
	BatcherGasPerTx = 35000
)

Variables

This section is empty.

Functions

This section is empty.

Types

type BatchOptions added in v1.1.6

type BatchOptions struct {
	SendTransactionOptions

	// Maximum number of pending transactions per wallet
	// If 0, no limit is enforced per wallet
	PendingLimit uint64

	// Maximum number of retries for failed submissions
	// If 0, no retries are attempted
	MaxRetries int

	// Pool of clients to assign to wallet groups
	// If set, assigns client 0 to first wallet, client 1 to second wallet, etc.
	// Cycles through the pool if there are more wallets than clients
	ClientPool  *ClientPool
	ClientGroup string // optional client group filter

	// Optional logging callback called after every LogInterval confirmed transactions
	LogFn func(confirmedCount int, totalCount int)

	// Interval for calling LogFn (number of confirmed transactions)
	// If 0, LogFn is never called
	LogInterval int
}

BatchOptions contains options for batch transaction submission.

type BlockInfo added in v1.1.3

type BlockInfo struct {
	Number     uint64
	Hash       common.Hash
	ParentHash common.Hash
	Timestamp  uint64
	GasLimit   uint64
}

BlockInfo represents information about a processed block including hash, parent hash, gas limit, and timestamp for chain reorganization detection.

type BlockStatsCallback added in v1.1.5

type BlockStatsCallback func(blockNumber uint64, walletPoolStats *WalletPoolBlockStats)

BlockStatsCallback is called when a block is processed with statistics for a specific wallet pool

type BlockSubscription added in v1.1.5

type BlockSubscription struct {
	ID         uint64
	WalletPool *WalletPool
	Callback   BlockStatsCallback
}

BlockSubscription represents a subscription to block updates for a specific wallet pool

type BulkBlockStatsCallback added in v1.1.6

type BulkBlockStatsCallback func(blockNumber uint64, allWalletPoolStats map[*WalletPool]*WalletPoolBlockStats)

BulkBlockStatsCallback is called when a block is processed with statistics for ALL wallet pools

type BulkBlockSubscription added in v1.1.6

type BulkBlockSubscription struct {
	ID       uint64
	Callback BulkBlockStatsCallback
}

BulkBlockSubscription represents a subscription to block updates for ALL wallet pools

type Client added in v1.1.3

type Client struct {
	Timeout time.Duration
	// contains filtered or unexported fields
}

Client represents an Ethereum RPC client with additional functionality for transaction management, gas estimation caching, and block height tracking. It wraps the standard go-ethereum ethclient with enhanced features for spam testing and transaction automation.

func NewClient added in v1.1.3

func NewClient(rpchost string) (*Client, error)

NewClient creates a new Client instance with the specified RPC host URL. The rpchost parameter supports special prefixes:

  • headers(key:value|key2:value2) - sets custom HTTP headers
  • group(name) - assigns the client to a named group (can be used multiple times)
  • group(name1,name2,name3) - assigns the client to multiple groups (comma-separated)
  • name(custom_name) - sets a custom display name override

Example: "headers(Authorization:Bearer token|User-Agent:MyApp)group(mainnet)group(primary)name(My Custom Node)http://localhost:8545" Example: "group(mainnet,primary,backup)name(MainNet Primary)http://localhost:8545"

func (*Client) GetBalanceAt added in v1.1.3

func (client *Client) GetBalanceAt(ctx context.Context, wallet common.Address) (*big.Int, error)

GetBalanceAt returns the balance of the given address at the latest block.

func (*Client) GetBlockHeight added in v1.1.3

func (client *Client) GetBlockHeight(ctx context.Context) (uint64, error)

GetBlockHeight returns the current block number. Results are cached for 12 seconds to reduce RPC calls.

func (*Client) GetChainId added in v1.1.3

func (client *Client) GetChainId(ctx context.Context) (*big.Int, error)

GetChainId returns the chain ID of the connected Ethereum network.

func (*Client) GetClientGroup added in v1.1.3

func (client *Client) GetClientGroup() string

GetClientGroup returns the first client group name assigned during initialization. Defaults to "default" if no group was specified. For multiple groups, use GetClientGroups().

func (*Client) GetClientGroups added in v1.1.5

func (client *Client) GetClientGroups() []string

GetClientGroups returns all client group names assigned to this client.

func (*Client) GetClientVersion added in v1.1.3

func (client *Client) GetClientVersion(ctx context.Context) (string, error)

GetClientVersion returns the client version string from the web3_clientVersion RPC call. Results are cached for 30 minutes to reduce RPC calls.

func (*Client) GetEthClient added in v1.1.3

func (client *Client) GetEthClient() *ethclient.Client

GetEthClient returns the underlying go-ethereum ethclient.Client instance.

func (*Client) GetLastBlockHeight added in v1.1.3

func (client *Client) GetLastBlockHeight() (uint64, time.Time)

GetLastBlockHeight returns the last cached block height and the time it was retrieved.

func (*Client) GetName added in v1.1.3

func (client *Client) GetName() string

GetName returns a shortened name for the client derived from the RPC host URL, removing common suffixes like ".ethpandaops.io". If a name override is set, it returns the override instead.

func (*Client) GetNameOverride added in v1.1.6

func (client *Client) GetNameOverride() string

GetNameOverride returns the name override for the client.

func (*Client) GetNonceAt added in v1.1.3

func (client *Client) GetNonceAt(ctx context.Context, wallet common.Address, blockNumber *big.Int) (uint64, error)

GetNonceAt returns the nonce for the given address at the specified block number. If blockNumber is nil, returns the nonce at the latest block.

func (*Client) GetPendingNonceAt added in v1.1.3

func (client *Client) GetPendingNonceAt(ctx context.Context, wallet common.Address) (uint64, error)

GetPendingNonceAt returns the pending nonce for the given address, including transactions in the mempool.

func (*Client) GetRPCHost added in v1.1.3

func (client *Client) GetRPCHost() string

GetRPCHost returns the original RPC host URL used to create this client.

func (*Client) GetSuggestedFee added in v1.1.3

func (client *Client) GetSuggestedFee(ctx context.Context) (*big.Int, *big.Int, error)

GetSuggestedFee returns suggested gas price and tip cap for transactions. Results are cached for 12 seconds to reduce RPC calls. Returns (gasCap, tipCap, error).

func (*Client) GetTransactionReceipt added in v1.1.4

func (client *Client) GetTransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)

GetTransactionReceipt retrieves the receipt for a given transaction hash. Logs the request at trace level.

func (*Client) HasGroup added in v1.1.5

func (client *Client) HasGroup(group string) bool

HasGroup checks if the client belongs to the specified group.

func (*Client) IsEnabled added in v1.1.5

func (client *Client) IsEnabled() bool

IsEnabled returns whether the client is enabled for selection.

func (*Client) SendRawTransaction added in v1.1.4

func (client *Client) SendRawTransaction(ctx context.Context, tx []byte) error

SendRawTransaction submits a raw transaction bytes to the network using eth_sendRawTransaction RPC call.

func (*Client) SendTransaction added in v1.1.4

func (client *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error

SendTransaction submits a transaction to the network using the provided context. Logs the transaction hash at trace level.

func (*Client) SetClientGroups added in v1.1.5

func (client *Client) SetClientGroups(groups []string)

SetClientGroups sets multiple client group names for the client, replacing all existing groups.

func (*Client) SetEnabled added in v1.1.5

func (client *Client) SetEnabled(enabled bool)

SetEnabled sets the enabled state of the client. Disabled clients will not be considered for selection in the client pool.

func (*Client) SetNameOverride added in v1.1.6

func (client *Client) SetNameOverride(name string)

SetNameOverride sets a custom name override for the client. If set, this name will be used instead of the auto-generated name from the RPC host.

func (*Client) UpdateWallet added in v1.1.3

func (client *Client) UpdateWallet(ctx context.Context, wallet *Wallet) error

UpdateWallet refreshes the wallet's chain ID, nonce, and balance by querying the blockchain. If the wallet doesn't have a chain ID set, it will be fetched and assigned.

type ClientPool

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

ClientPool manages a pool of Ethereum RPC clients with health monitoring and selection strategies. It automatically monitors client health by checking block heights and maintains a list of "good" clients that are within 2 blocks of the highest observed block height.

func NewClientPool

func NewClientPool(ctx context.Context, rpcHosts []string, logger logrus.FieldLogger) *ClientPool

NewClientPool creates a new ClientPool with the specified RPC hosts and logger. The pool must be initialized with PrepareClients() before use.

func (*ClientPool) GetAllClients

func (pool *ClientPool) GetAllClients() []*Client

GetAllClients returns a copy of all clients in the pool, regardless of their health status.

func (*ClientPool) GetAllGoodClients

func (pool *ClientPool) GetAllGoodClients() []*Client

GetAllGoodClients returns a copy of all clients currently considered healthy (within 2 blocks of the highest observed block height).

func (*ClientPool) GetClient

func (pool *ClientPool) GetClient(mode ClientSelectionMode, input int, group string) *Client

GetClient returns a client from the pool based on the specified selection mode. Parameters:

  • mode: how to select the client (by index, random, or round-robin)
  • input: used as index when mode is SelectClientByIndex
  • group: client group filter ("" for default, "*" for any, or specific group name)

Returns nil if no suitable clients are available.

func (*ClientPool) PrepareClients

func (pool *ClientPool) PrepareClients() error

PrepareClients initializes all clients in the pool and starts health monitoring. It creates Client instances for each RPC host, determines the chain ID, and begins periodic health checks. Returns an error if no usable clients are found.

type ClientSelectionMode

type ClientSelectionMode uint8

ClientSelectionMode defines how clients are selected from the pool.

var (
	// SelectClientByIndex selects a client by index (modulo pool size).
	SelectClientByIndex ClientSelectionMode = 0
	// SelectClientRandom selects a random client from the pool.
	SelectClientRandom ClientSelectionMode = 1
	// SelectClientRoundRobin selects clients in round-robin fashion.
	SelectClientRoundRobin ClientSelectionMode = 2
)

type FundingRequest added in v1.1.3

type FundingRequest struct {
	Wallet *Wallet
	Amount *uint256.Int
}

FundingRequest represents a request to fund a wallet with a specific amount. Used internally for batch funding operations.

type RebroadcastRequest added in v1.1.6

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

RebroadcastRequest represents a transaction that needs to be rebroadcast

type RootWallet added in v1.1.3

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

RootWallet represents a primary wallet with transaction rate limiting and batching capabilities. It wraps a standard Wallet with a semaphore-based transaction limiter and optional transaction batcher for managing high-volume transaction scenarios.

func InitRootWallet

func InitRootWallet(ctx context.Context, privkey string, client *Client, logger logrus.FieldLogger) (*RootWallet, error)

InitRootWallet creates and initializes a new RootWallet from a private key. It creates the underlying wallet, updates its state from the blockchain, and sets up transaction rate limiting with a default limit of 200 concurrent transactions. Returns the initialized RootWallet and logs wallet information if logger is provided.

func (*RootWallet) GetTxBatcher added in v1.1.3

func (wallet *RootWallet) GetTxBatcher() *TxBatcher

GetTxBatcher returns the transaction batcher instance, or nil if not initialized.

func (*RootWallet) GetWallet added in v1.1.3

func (wallet *RootWallet) GetWallet() *Wallet

GetWallet returns the underlying Wallet instance.

func (*RootWallet) InitTxBatcher added in v1.1.3

func (wallet *RootWallet) InitTxBatcher(ctx context.Context, txpool *TxPool)

InitTxBatcher initializes the transaction batcher with the specified transaction pool. This enables batched transaction processing for improved efficiency.

func (*RootWallet) WithWalletLock added in v1.1.3

func (wallet *RootWallet) WithWalletLock(ctx context.Context, txCount int, lockedLogFn func(), lockedFn func() error) error

WithWalletLock executes a function while holding transaction semaphore locks. It acquires the specified number of transaction slots from the semaphore, calls the optional lockedLogFn when waiting for locks, then executes lockedFn. The locks are automatically released when the function returns.

Parameters:

  • ctx: context for cancellation
  • txCount: number of transaction slots to acquire
  • lockedLogFn: optional function called once when waiting for locks (can be nil)
  • lockedFn: function to execute while holding the locks

type SendTransactionOptions added in v1.1.3

type SendTransactionOptions struct {
	// Client to use for sending (optional, uses pool selection if nil)
	Client *Client
	// ClientGroup to prefer when selecting clients
	ClientGroup string
	// ClientsStartOffset for client selection
	ClientsStartOffset int
	// SubmitCount is the number of times to submit the transaction in the first attempt (default 3)
	SubmitCount int

	// Enable reliable rebroadcasting
	Rebroadcast bool

	// Callbacks
	OnConfirm  TxConfirmFn  // Called only if tx was sent successfully and confirmed
	OnComplete TxCompleteFn // Always called when processing completes
	OnEncode   TxEncodeFn   // Called to encode tx to bytes on-demand
	LogFn      TxLogFn      // Custom logging function (uses default if nil)
}

SendTransactionOptions contains options for transaction submission including client selection, confirmation callbacks, rebroadcast settings, and logging.

type TxBatcher added in v1.1.3

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

TxBatcher manages the deployment and operation of a smart contract that batches multiple fund transfers into a single transaction. It compiles and deploys assembly code that efficiently forwards funds to multiple recipients.

func NewTxBatcher added in v1.1.3

func NewTxBatcher(txpool *TxPool) *TxBatcher

NewTxBatcher creates a new TxBatcher instance with the specified transaction pool. The batcher must be deployed with Deploy() before it can be used.

func (*TxBatcher) Deploy added in v1.1.3

func (b *TxBatcher) Deploy(ctx context.Context, wallet *Wallet, client *Client) error

Deploy compiles and deploys the batcher smart contract to the blockchain. It uses assembly code to create an efficient contract that can forward funds to multiple addresses in a single transaction. The deployment is protected by a mutex to ensure it only happens once.

Parameters:

  • ctx: context for the deployment transaction
  • wallet: wallet to deploy the contract from
  • client: optional client to use (if nil, uses pool's default client)

func (*TxBatcher) GetAddress added in v1.1.3

func (b *TxBatcher) GetAddress() common.Address

GetAddress returns the deployed contract address. Returns zero address if the contract hasn't been deployed yet.

func (*TxBatcher) GetRequestCalldata added in v1.1.3

func (b *TxBatcher) GetRequestCalldata(requests []*FundingRequest) ([]byte, error)

GetRequestCalldata encodes funding requests into calldata format expected by the batcher contract. Each request is encoded as 32 bytes: 20 bytes for the address and 12 bytes for the amount. Returns the encoded calldata that can be used in a transaction to the batcher contract.

type TxCompleteFn added in v1.1.6

type TxCompleteFn func(tx *types.Transaction, receipt *types.Receipt, err error)

TxCompleteFn is a callback function called when transaction processing is complete (confirmed or failed). Always called regardless of success/failure.

type TxConfirmFn added in v1.1.3

type TxConfirmFn func(tx *types.Transaction, receipt *types.Receipt)

TxConfirmFn is a callback function called when a transaction is confirmed or fails. It receives the transaction, receipt (if successful), and any error that occurred.

type TxEncodeFn added in v1.1.6

type TxEncodeFn func(tx *types.Transaction) ([]byte, error)

TxEncodeFn is a callback function called to encode a transaction to bytes. It receives the transaction and should return the encoded bytes.

type TxInfo added in v1.1.3

type TxInfo struct {
	TxHash     common.Hash
	From       common.Address
	To         *common.Address
	Tx         *types.Transaction
	TxFees     *utils.TxFees
	FromWallet *Wallet
	ToWallet   *Wallet
	Options    *SendTransactionOptions
}

TxInfo represents information about a confirmed transaction including the transaction details, associated wallets, and send options.

type TxLogFn added in v1.1.3

type TxLogFn func(client *Client, retry int, rebroadcast int, err error)

TxLogFn is a callback function for logging transaction submission attempts. It receives the client used, retry count, rebroadcast count, and any error.

func GetDefaultLogFn added in v1.1.6

func GetDefaultLogFn(logger logrus.FieldLogger, txTypeName string, txIdx string, tx *types.Transaction) TxLogFn

type TxPool added in v1.1.3

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

TxPool manages transaction submission, confirmation tracking, and chain reorganization handling. It monitors blockchain blocks, tracks transaction confirmations, handles reorgs by re-submitting affected transactions, and provides transaction awaiting functionality with automatic rebroadcasting.

func NewTxPool added in v1.1.3

func NewTxPool(options *TxPoolOptions) *TxPool

NewTxPool creates a new transaction pool with the specified options. It starts background goroutines for block processing and stale transaction handling. The pool automatically begins monitoring the blockchain for new blocks and managing transaction confirmations and reorgs.

func (*TxPool) AwaitTransaction added in v1.1.3

func (p *TxPool) AwaitTransaction(ctx context.Context, wallet *Wallet, tx *types.Transaction) (*types.Receipt, error)

Await waits for a transaction to be confirmed and returns its receipt. It monitors the blockchain for the transaction and handles reorgs by continuing to wait if the transaction gets reorged out of the chain.

func (*TxPool) GetActiveWalletPools added in v1.1.6

func (pool *TxPool) GetActiveWalletPools() []*WalletPool

GetActiveWalletPools returns all active wallet pools

func (*TxPool) GetCurrentBaseFee added in v1.1.6

func (pool *TxPool) GetCurrentBaseFee() *big.Int

GetCurrentBaseFee returns the current base fee of the chain.

func (*TxPool) GetCurrentBaseFeeWithInit added in v1.1.6

func (pool *TxPool) GetCurrentBaseFeeWithInit() (*big.Int, error)

GetCurrentBaseFeeWithInit returns the current base fee, initializing it from RPC if needed.

func (*TxPool) GetCurrentGasLimit added in v1.1.5

func (pool *TxPool) GetCurrentGasLimit() uint64

GetCurrentGasLimit returns the current gas limit of the chain.

func (*TxPool) GetCurrentGasLimitWithInit added in v1.1.5

func (pool *TxPool) GetCurrentGasLimitWithInit() (uint64, error)

GetCurrentGasLimitWithInit returns the current gas limit, initializing it from RPC if needed. This is a convenience method that combines GetCurrentGasLimit and InitializeGasLimit.

func (*TxPool) GetSuggestedFees added in v1.1.6

func (pool *TxPool) GetSuggestedFees(client *Client, baseFeeGwei float64, tipFeeGwei float64) (feeCap *big.Int, tipCap *big.Int, err error)

GetSuggestedFees returns the suggested fees for a transaction. If baseFeeGwei and tipFeeGwei are provided, they are used as the base fee and tip fee. If not provided, the fees are fetched from the client. The fees are returned in wei.

func (*TxPool) SendAndAwaitTransaction added in v1.1.6

func (p *TxPool) SendAndAwaitTransaction(ctx context.Context, wallet *Wallet, tx *types.Transaction, opts *SendTransactionOptions) (*types.Receipt, error)

SendAndAwaitTransaction submits a transaction with custom options and waits for confirmation. Allows specifying client preferences, rebroadcast settings, etc.

Example:

options := &SendOptions{
    Client: specificClient,
    Rebroadcast: true,
}
receipt, err := submitter.SendAndAwaitTransaction(ctx, wallet, tx, options)

func (*TxPool) SendMultiTransactionBatch added in v1.1.6

func (p *TxPool) SendMultiTransactionBatch(ctx context.Context, walletTxs map[*Wallet][]*types.Transaction, opts *BatchOptions) (map[*Wallet][]*types.Receipt, error)

SendMultiTransactionBatch submits transactions for multiple wallets with sliding window submission. Returns receipts in the same order as input transactions for each wallet. Respects both per-wallet PendingLimit and GlobalPendingLimit to control concurrent submissions. Implements retry logic with MaxRetries for failed submissions.

Example:

options := &BatchOptions{
    SendTransactionOptions: SendTransactionOptions{Rebroadcast: true},
    PendingLimit: 50, // 50 pending per wallet
    MaxRetries: 3,    // 3 retries per transaction
}
receipts, err := submitter.SendMultiTransactionBatch(ctx, walletTxs, options)

func (*TxPool) SendTransaction added in v1.1.3

func (p *TxPool) SendTransaction(ctx context.Context, wallet *Wallet, tx *types.Transaction, opts *SendTransactionOptions) error

SendTransaction submits a single transaction with the given options. This is a lower-level interface that provides access to all callback options.

func (*TxPool) SendTransactionBatch added in v1.1.6

func (p *TxPool) SendTransactionBatch(ctx context.Context, wallet *Wallet, txs []*types.Transaction, opts *BatchOptions) ([]*types.Receipt, error)

SendBatchWithOptions submits multiple transactions with custom options and waits for all confirmations. Returns receipts in the same order as input transactions. Respects PendingLimit to control concurrent submissions.

Example:

options := &BatchOptions{
    SendOptions: SendOptions{Rebroadcast: true},
    PendingLimit: 100,
}
receipts, err := submitter.SendBatchWithOptions(ctx, wallet, txs, options)

func (*TxPool) SubscribeToBlockUpdates added in v1.1.5

func (pool *TxPool) SubscribeToBlockUpdates(walletPool *WalletPool, callback BlockStatsCallback) uint64

SubscribeToBlockUpdates subscribes to block update notifications for a specific wallet pool. Returns a unique subscription ID that can be used to unsubscribe later.

func (*TxPool) SubscribeToBulkBlockUpdates added in v1.1.6

func (pool *TxPool) SubscribeToBulkBlockUpdates(callback BulkBlockStatsCallback) uint64

SubscribeToBulkBlockUpdates subscribes to block update notifications for ALL wallet pools. Returns a unique subscription ID that can be used to unsubscribe later.

func (*TxPool) UnsubscribeFromBlockUpdates added in v1.1.5

func (pool *TxPool) UnsubscribeFromBlockUpdates(id uint64)

UnsubscribeFromBlockUpdates removes a block update subscription.

func (*TxPool) UnsubscribeFromBulkBlockUpdates added in v1.1.6

func (pool *TxPool) UnsubscribeFromBulkBlockUpdates(id uint64)

UnsubscribeFromBulkBlockUpdates removes a bulk block update subscription.

type TxPoolOptions added in v1.1.3

type TxPoolOptions struct {
	Context              context.Context
	Logger               *logrus.Entry
	ClientPool           *ClientPool
	ReorgDepth           int // Number of blocks to keep in memory for reorg tracking
	GetActiveWalletPools func() []*WalletPool
}

TxPoolOptions contains configuration options for the transaction pool.

type Wallet added in v1.1.3

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

Wallet represents an Ethereum wallet with private key management, nonce tracking, and balance management. It provides thread-safe operations for transaction building, nonce management, and balance updates. The wallet automatically handles nonce sequencing and provides confirmation tracking for submitted transactions.

func NewWallet added in v1.1.3

func NewWallet(privkey string) (*Wallet, error)

NewWallet creates a new wallet from a private key string. If privkey is empty, generates a new random private key. The privkey parameter accepts hex strings with or without "0x" prefix.

func (*Wallet) AddBalance added in v1.1.3

func (wallet *Wallet) AddBalance(amount *big.Int)

AddBalance adds the specified amount to the wallet's balance. This is typically called when the wallet receives funds.

func (*Wallet) BuildBlobTx added in v1.1.3

func (wallet *Wallet) BuildBlobTx(txData *types.BlobTx) (*types.Transaction, error)

BuildBlobTx builds and signs a blob transaction (EIP-4844). It automatically assigns the next available nonce and signs the transaction.

func (*Wallet) BuildBoundTx added in v1.1.3

func (wallet *Wallet) BuildBoundTx(ctx context.Context, txData *txbuilder.TxMetadata, buildFn func(transactOpts *bind.TransactOpts) (*types.Transaction, error)) (*types.Transaction, error)

BuildBoundTx builds a transaction using the go-ethereum bind package. It sets up a TransactOpts with the wallet's credentials and calls the provided buildFn to construct the actual transaction. Useful for contract interactions.

func (*Wallet) BuildDynamicFeeTx added in v1.1.3

func (wallet *Wallet) BuildDynamicFeeTx(txData *types.DynamicFeeTx) (*types.Transaction, error)

BuildDynamicFeeTx builds and signs a dynamic fee (EIP-1559) transaction. It automatically assigns the next available nonce and signs the transaction.

func (*Wallet) BuildSetCodeTx added in v1.1.3

func (wallet *Wallet) BuildSetCodeTx(txData *types.SetCodeTx) (*types.Transaction, error)

BuildSetCodeTx builds and signs a set code transaction (EIP-7702). It automatically assigns the next available nonce and signs the transaction.

func (*Wallet) GetAddress added in v1.1.3

func (wallet *Wallet) GetAddress() common.Address

GetAddress returns the Ethereum address associated with this wallet.

func (*Wallet) GetBalance added in v1.1.3

func (wallet *Wallet) GetBalance() *big.Int

GetBalance returns the current balance of the wallet. The returned value is thread-safe to read.

func (*Wallet) GetChainId added in v1.1.3

func (wallet *Wallet) GetChainId() *big.Int

GetChainId returns the chain ID this wallet is configured for. Returns nil if no chain ID has been set.

func (*Wallet) GetConfirmedNonce added in v1.1.3

func (wallet *Wallet) GetConfirmedNonce() uint64

GetConfirmedNonce returns the last confirmed nonce for this wallet. This represents the highest nonce that has been confirmed on-chain.

func (*Wallet) GetNextNonce added in v1.1.3

func (wallet *Wallet) GetNextNonce() uint64

GetNextNonce atomically increments and returns the next available nonce. This is used when building transactions to ensure unique nonces.

func (*Wallet) GetNonce added in v1.1.3

func (wallet *Wallet) GetNonce() uint64

GetNonce returns the current pending nonce for this wallet. This nonce is the next nonce that should be used for the next transaction, but it is for informational purposes only. To actually use a nonce, you need to call GetNextNonce() which will increment the nonce and return the next nonce.

func (*Wallet) GetPrivateKey added in v1.1.3

func (wallet *Wallet) GetPrivateKey() *ecdsa.PrivateKey

GetPrivateKey returns the wallet's private key. Handle with care to avoid exposing sensitive data.

func (*Wallet) GetSubmittedTxCount added in v1.1.6

func (wallet *Wallet) GetSubmittedTxCount() uint64

GetSubmittedTxCount returns the total number of transactions submitted by this wallet. This represents the cumulative count of all transactions that have been submitted to the network.

func (*Wallet) IncrementSubmittedTxCount added in v1.1.6

func (wallet *Wallet) IncrementSubmittedTxCount()

IncrementSubmittedTxCount increments the submitted transaction counter. This should be called when a transaction is successfully submitted to the network.

func (*Wallet) ReplaceBlobTx added in v1.1.3

func (wallet *Wallet) ReplaceBlobTx(txData *types.BlobTx, nonce uint64) (*types.Transaction, error)

ReplaceBlobTx builds a replacement blob transaction with a specific nonce. This is useful for replacing stuck blob transactions with higher gas prices.

func (*Wallet) ReplaceDynamicFeeTx added in v1.1.3

func (wallet *Wallet) ReplaceDynamicFeeTx(txData *types.DynamicFeeTx, nonce uint64) (*types.Transaction, error)

ReplaceDynamicFeeTx builds a replacement dynamic fee transaction with a specific nonce. This is useful for replacing stuck transactions with higher gas prices.

func (*Wallet) ResetPendingNonce added in v1.1.3

func (wallet *Wallet) ResetPendingNonce(ctx context.Context, client *Client)

ResetPendingNonce syncs the wallet's pending nonce with the blockchain. This is useful for recovering from nonce mismatches or wallet state corruption. It queries the pending nonce from the client and updates the wallet accordingly.

func (*Wallet) SetAddress added in v1.1.3

func (wallet *Wallet) SetAddress(address common.Address)

SetAddress updates the wallet's Ethereum address. This is typically only used for special cases or testing.

func (*Wallet) SetBalance added in v1.1.3

func (wallet *Wallet) SetBalance(balance *big.Int)

SetBalance sets the wallet's balance to the specified amount. This is typically called when syncing wallet state with the blockchain.

func (*Wallet) SetChainId added in v1.1.3

func (wallet *Wallet) SetChainId(chainid *big.Int)

SetChainId sets the chain ID for this wallet. This affects transaction signing and should match the target network.

func (*Wallet) SetNonce added in v1.1.3

func (wallet *Wallet) SetNonce(nonce uint64)

SetNonce updates both the confirmed and pending nonce if the new nonce is higher. This is typically called when syncing wallet state with the blockchain.

func (*Wallet) SubBalance added in v1.1.3

func (wallet *Wallet) SubBalance(amount *big.Int)

SubBalance subtracts the specified amount from the wallet's balance. This is typically called when a transaction is confirmed to update the balance.

type WalletPool

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

WalletPool manages a pool of child wallets derived from a root wallet with automatic funding and balance monitoring. It provides wallet selection strategies, automatic refills when balances drop below thresholds, and batch funding operations for efficiency.

func NewWalletPool

func NewWalletPool(ctx context.Context, logger logrus.FieldLogger, rootWallet *RootWallet, clientPool *ClientPool, txpool *TxPool) *WalletPool

NewWalletPool creates a new wallet pool with the specified dependencies. The pool must be configured and prepared with PrepareWallets() before use.

func (*WalletPool) AddWellKnownWallet added in v1.1.1

func (pool *WalletPool) AddWellKnownWallet(config *WellKnownWalletConfig)

AddWellKnownWallet adds a named wallet with custom funding configuration. Well-known wallets are created alongside regular numbered wallets.

func (*WalletPool) CheckChildWalletBalance

func (pool *WalletPool) CheckChildWalletBalance(childWallet *Wallet) error

CheckChildWalletBalance checks and refills a specific wallet if needed. This can be used to manually trigger funding for a single wallet.

func (*WalletPool) GetAllWallets

func (pool *WalletPool) GetAllWallets() []*Wallet

GetAllWallets returns a slice containing all wallets (well-known and child wallets). The root wallet is not included in this list.

func (*WalletPool) GetChainId added in v1.1.3

func (pool *WalletPool) GetChainId() *big.Int

GetChainId returns the chain ID from the root wallet.

func (*WalletPool) GetClient

func (pool *WalletPool) GetClient(mode ClientSelectionMode, input int, group string) *Client

GetClient returns a client from the client pool using the specified selection strategy.

func (*WalletPool) GetClientPool

func (pool *WalletPool) GetClientPool() *ClientPool

GetClientPool returns the client pool used for blockchain interactions.

func (*WalletPool) GetConfiguredWalletCount added in v1.1.3

func (pool *WalletPool) GetConfiguredWalletCount() uint64

GetConfiguredWalletCount returns the configured number of child wallets.

func (*WalletPool) GetContext

func (pool *WalletPool) GetContext() context.Context

GetContext returns the context associated with this wallet pool.

func (*WalletPool) GetRootWallet

func (pool *WalletPool) GetRootWallet() *RootWallet

GetRootWallet returns the root wallet that funds all child wallets.

func (*WalletPool) GetSpammerID added in v1.1.6

func (pool *WalletPool) GetSpammerID() uint64

GetSpammerID returns the spammer ID for metrics tracking

func (*WalletPool) GetTransactionTracker added in v1.1.5

func (pool *WalletPool) GetTransactionTracker() func(err error)

GetTransactionTracker returns the transaction tracking callback if set.

func (*WalletPool) GetTxPool

func (pool *WalletPool) GetTxPool() *TxPool

GetTxPool returns the transaction pool used by this wallet pool.

func (*WalletPool) GetVeryWellKnownWalletAddress added in v1.1.5

func (pool *WalletPool) GetVeryWellKnownWalletAddress(name string) common.Address

GetVeryWellKnownWalletAddress derives the address of a "very well known" wallet without registering it. Very well known wallets are derived only from the root wallet's private key and the wallet name, without any scenario seed. This makes them consistent across different scenario runs.

func (*WalletPool) GetWallet

func (pool *WalletPool) GetWallet(mode WalletSelectionMode, input int) *Wallet

GetWallet returns a wallet from the pool using the specified selection strategy. Returns nil if no wallets are available.

func (*WalletPool) GetWalletCount

func (pool *WalletPool) GetWalletCount() uint64

GetWalletCount returns the actual number of child wallets created.

func (*WalletPool) GetWalletName added in v1.1.1

func (pool *WalletPool) GetWalletName(address common.Address) string

GetWalletName returns a human-readable name for the given wallet address. Returns "root" for the root wallet, numbered names for child wallets, custom names for well-known wallets, or "unknown" if not found.

func (*WalletPool) GetWellKnownWallet added in v1.1.1

func (pool *WalletPool) GetWellKnownWallet(name string) *Wallet

GetWellKnownWallet returns a well-known wallet by name. Returns nil if the wallet doesn't exist.

func (*WalletPool) LoadConfig

func (pool *WalletPool) LoadConfig(configYaml string) error

LoadConfig loads wallet pool configuration from YAML string.

func (*WalletPool) MarshalConfig

func (pool *WalletPool) MarshalConfig() (string, error)

MarshalConfig returns the current configuration as a YAML string.

func (*WalletPool) PrepareWallets

func (pool *WalletPool) PrepareWallets() error

PrepareWallets creates all configured wallets and funds them if needed. It generates deterministic wallets based on the root wallet and seed, then funds any wallets below the refill threshold. Also starts the automatic balance monitoring if funding is enabled.

func (*WalletPool) ReclaimFunds added in v1.1.4

func (pool *WalletPool) ReclaimFunds(ctx context.Context, client *Client) error

ReclaimFunds reclaims all funds from child wallets back to the root wallet. This is typically called when shutting down to consolidate remaining funds. After calling this, automatic funding is disabled.

func (*WalletPool) SetRefillAmount

func (pool *WalletPool) SetRefillAmount(amount *uint256.Int)

SetRefillAmount sets the amount sent to wallets when they need funding.

func (*WalletPool) SetRefillBalance

func (pool *WalletPool) SetRefillBalance(balance *uint256.Int)

SetRefillBalance sets the balance threshold below which wallets are automatically refilled.

func (*WalletPool) SetRefillInterval

func (pool *WalletPool) SetRefillInterval(interval uint64)

SetRefillInterval sets the interval in seconds between automatic balance checks.

func (*WalletPool) SetRunFundings added in v1.1.4

func (pool *WalletPool) SetRunFundings(runFundings bool)

SetRunFundings enables or disables automatic wallet funding. When disabled, wallets will not be automatically refilled when their balance drops.

func (*WalletPool) SetSpammerID added in v1.1.6

func (pool *WalletPool) SetSpammerID(spammerID uint64)

SetSpammerID sets the spammer ID for metrics tracking

func (*WalletPool) SetTransactionTracker added in v1.1.5

func (pool *WalletPool) SetTransactionTracker(tracker func(err error))

SetTransactionTracker sets the optional callback to track transaction results for metrics.

func (*WalletPool) SetWalletCount

func (pool *WalletPool) SetWalletCount(count uint64)

SetWalletCount sets the number of child wallets to create.

func (*WalletPool) SetWalletSeed

func (pool *WalletPool) SetWalletSeed(seed string)

SetWalletSeed sets the seed used for deterministic wallet generation. The same seed will always generate the same set of wallets.

type WalletPoolBlockStats added in v1.1.5

type WalletPoolBlockStats struct {
	ConfirmedTxCount uint64
	TotalTxFees      *big.Int
	AffectedWallets  int
	Block            *types.Block
	ConfirmedTxs     []*TxInfo
	Receipts         []*types.Receipt
}

WalletPoolBlockStats contains transaction statistics for a wallet pool in a specific block

type WalletPoolConfig

type WalletPoolConfig struct {
	WalletCount    uint64       `yaml:"wallet_count,omitempty"`
	RefillAmount   *uint256.Int `yaml:"refill_amount"`
	RefillBalance  *uint256.Int `yaml:"refill_balance"`
	RefillInterval uint64       `yaml:"refill_interval"`
	WalletSeed     string       `yaml:"seed"`
}

WalletPoolConfig contains configuration settings for the wallet pool including wallet count, funding amounts, and automatic refill behavior.

func GetDefaultWalletConfig added in v1.1.1

func GetDefaultWalletConfig(scenarioName string) *WalletPoolConfig

GetDefaultWalletConfig returns default wallet pool configuration for a given scenario. It generates a random seed and sets reasonable defaults for refill amounts and intervals.

type WalletSelectionMode

type WalletSelectionMode uint8

WalletSelectionMode defines how wallets are selected from the pool.

var (
	// SelectWalletByIndex selects a wallet by index (modulo pool size).
	SelectWalletByIndex WalletSelectionMode = 0
	// SelectWalletRandom selects a random wallet from the pool.
	SelectWalletRandom WalletSelectionMode = 1
	// SelectWalletRoundRobin selects wallets in round-robin fashion.
	SelectWalletRoundRobin WalletSelectionMode = 2
	// SelectWalletByPendingTxCount selects a wallet by pending tx count (lowest pending tx count first).
	SelectWalletByPendingTxCount WalletSelectionMode = 3
)

type WellKnownWalletConfig added in v1.1.1

type WellKnownWalletConfig struct {
	Name          string
	RefillAmount  *uint256.Int
	RefillBalance *uint256.Int
	VeryWellKnown bool
}

WellKnownWalletConfig defines configuration for a named wallet with custom funding settings. Well-known wallets have specific names and can have different refill amounts than regular wallets.

Jump to

Keyboard shortcuts

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