evm

package
v1.4.4 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package evm provides a unified EVM indexer for all Lux EVM chains. Indexes blocks, transactions, addresses, tokens, smart contracts, and more. Indexes blocks, transactions, addresses, tokens, smart contracts, and more.

Supported chains:

  • Lux C-Chain (mainnet: 96369, testnet: 96368)
  • Zoo EVM (mainnet: 200200, testnet: 200201)
  • Hanzo AI Chain (36963)
  • Any EVM-compatible subnet

Package evm provides advanced EVM indexing types for Phase 5. Includes ERC-4337, MEV, EIP-4844, and multi-chain support.

Index

Constants

View Source
const (
	// DefaultPort for EVM indexer API
	DefaultPort = 4000
	// DefaultDatabase name
	DefaultDatabase = "explorer_evm"
	// ChainID for Lux C-Chain mainnet
	ChainID = 96369
)
View Source
const (
	// BlobTxType is EIP-4844 type 3 transaction
	BlobTxType = 3
	// BlobGasPerBlob is the gas used per blob
	BlobGasPerBlob = 131072 // 2^17
	// MaxBlobsPerBlock is the target number of blobs per block
	MaxBlobsPerBlock = 6
	// BlobFieldElementSize is 32 bytes
	BlobFieldElementSize = 32
	// BlobSize is 128KB (4096 field elements * 32 bytes)
	BlobSize = 4096 * BlobFieldElementSize
)

Blob constants

View Source
const (
	ChainIDLuxMainnet   = 96369
	ChainIDLuxTestnet   = 96368
	ChainIDZooMainnet   = 200200
	ChainIDZooTestnet   = 200201
	ChainIDHanzoMainnet = 36963
)

Chain IDs for supported Lux chains

View Source
const (
	EntryPointV06 = "0x5ff137d4b0fdcd49dca30c7cf57e578a026d2789"
	EntryPointV07 = "0x0000000071727de22e5e9d8baf0edac6f37da032"
)

EntryPoint addresses for ERC-4337

Variables

View Source
var (
	// ERC20 Transfer(address,address,uint256)
	TopicTransferERC20 = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
	// ERC721 Transfer(address,address,uint256)
	TopicTransferERC721 = TopicTransferERC20 // Same signature, different indexed params
	// ERC1155 TransferSingle(address,address,address,uint256,uint256)
	TopicTransferSingle = "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62"
	// ERC1155 TransferBatch(address,address,address,uint256[],uint256[])
	TopicTransferBatch = "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb"
	// ERC-404 ERC20Transfer(address,address,uint256)
	TopicERC404ERC20Transfer = "0xe59fdd36d0d223c0c7d996db7ad796571571382a6e90d1a1bcc1b3d98f725407"
	// ERC-404 ERC721Transfer
	TopicERC404ERC721Transfer = "0xe5f815dc84b8cecdfd4a3a44d5ebb970e4a227bada3008d09589bdb082a5551f"
	// WETH Deposit(address indexed dst, uint256 wad)
	TopicWETHDeposit = "0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c"
	// WETH Withdrawal(address indexed src, uint256 wad)
	TopicWETHWithdrawal = "0x7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65"
)

Well-known event signatures

View Source
var (
	// Uniswap V2 Router
	UniswapV2Router = "0x7a250d5630b4cf539739df2c5dacb4c659f2488d"
	// Uniswap V3 Router
	UniswapV3Router = "0xe592427a0aece92de3edee1f18e0157c05861564"
	// Sushiswap Router
	SushiswapRouter = "0xd9e1ce17f2641f24ae83637ab66a2cca9c378b9f"

	// Aave V2 Lending Pool
	AaveV2LendingPool = "0x7d2768de32b0b80b7a3454c06bdac94a69ddc7a9"
	// Aave V3 Pool
	AaveV3Pool = "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"
	// Compound V2 Comptroller
	CompoundComptroller = "0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b"

	// Event signatures
	TopicSwap        = "0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822" // Swap(address,uint256,uint256,uint256,uint256,address)
	TopicSwapV3      = "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67" // Swap(address,address,int256,int256,uint160,uint128,int24)
	TopicSync        = "0x1c411e9a96e071241c2f21f7726b17ae89e3cab4c78be50e062b03a9fffbbad1" // Sync(uint112,uint112)
	TopicLiquidation = "0xe413a321e8681d831f4dbccbca790d2952b56f977908e45be37335533e005286" // LiquidationCall
)

Common DEX and lending protocol addresses

View Source
var (
	// UserOperationEvent(bytes32 indexed userOpHash, address indexed sender, address indexed paymaster, uint256 nonce, bool success, uint256 actualGasCost, uint256 actualGasUsed)
	TopicUserOperationEvent = "0x49628fd1471006c1482da88028e9ce4dbb080b815c9b0344d39e5a8e6ec1419f"
	// AccountDeployed(bytes32 indexed userOpHash, address indexed sender, address factory, address paymaster)
	TopicAccountDeployed = "0xd51a9c61267aa6196961883ecf5ff2da6619c37dac0fa92122513fb32c032d2d"
	// BeforeExecution()
	TopicBeforeExecution = "0xbb47ee3e183a558b1a2ff0874b079f3fc5478b7454eacf2bfc5af2ff5878f972"
)

Event signatures for ERC-4337

View Source
var DefaultChains = []ChainConfig{
	{
		ChainID:         ChainIDLuxMainnet,
		Name:            "Lux C-Chain",
		Symbol:          "LUX",
		RPCEndpoint:     "https://api.lux.network/ext/bc/C/rpc",
		WSEndpoint:      "wss://api.lux.network/ext/bc/C/ws",
		ExplorerURL:     "https://explorer.lux.network",
		IsTestnet:       false,
		BlockTime:       2000,
		SupportsEIP1559: true,
		SupportsEIP4844: true,
		SupportsEIP4337: true,
		EntryPoints:     []string{EntryPointV06, EntryPointV07},
	},
	{
		ChainID:         ChainIDLuxTestnet,
		Name:            "Lux C-Chain Testnet",
		Symbol:          "LUX",
		RPCEndpoint:     "https://api.testnet.lux.network/ext/bc/C/rpc",
		WSEndpoint:      "wss://api.testnet.lux.network/ext/bc/C/ws",
		ExplorerURL:     "https://explorer.testnet.lux.network",
		IsTestnet:       true,
		BlockTime:       2000,
		SupportsEIP1559: true,
		SupportsEIP4844: true,
		SupportsEIP4337: true,
		EntryPoints:     []string{EntryPointV06, EntryPointV07},
	},
	{
		ChainID:         ChainIDZooMainnet,
		Name:            "Zoo Network",
		Symbol:          "ZOO",
		RPCEndpoint:     "https://api.zoo.network/ext/bc/zoo/rpc",
		WSEndpoint:      "wss://api.zoo.network/ext/bc/zoo/ws",
		ExplorerURL:     "https://explorer.zoo.network",
		IsTestnet:       false,
		BlockTime:       2000,
		SupportsEIP1559: true,
		SupportsEIP4844: true,
		SupportsEIP4337: true,
		EntryPoints:     []string{EntryPointV06, EntryPointV07},
	},
	{
		ChainID:         ChainIDZooTestnet,
		Name:            "Zoo Network Testnet",
		Symbol:          "ZOO",
		RPCEndpoint:     "https://api.testnet.zoo.network/ext/bc/zoo/rpc",
		WSEndpoint:      "wss://api.testnet.zoo.network/ext/bc/zoo/ws",
		ExplorerURL:     "https://explorer.testnet.zoo.network",
		IsTestnet:       true,
		BlockTime:       2000,
		SupportsEIP1559: true,
		SupportsEIP4844: true,
		SupportsEIP4337: true,
		EntryPoints:     []string{EntryPointV06, EntryPointV07},
	},
	{
		ChainID:         ChainIDHanzoMainnet,
		Name:            "Hanzo AI Chain",
		Symbol:          "AI",
		RPCEndpoint:     "https://api.hanzo.ai/ext/bc/hanzo/rpc",
		WSEndpoint:      "wss://api.hanzo.ai/ext/bc/hanzo/ws",
		ExplorerURL:     "https://explorer.hanzo.ai",
		IsTestnet:       false,
		BlockTime:       1000,
		SupportsEIP1559: true,
		SupportsEIP4844: true,
		SupportsEIP4337: true,
		EntryPoints:     []string{EntryPointV06, EntryPointV07},
	},
}

Predefined chain configurations

Functions

func CalculateUserOpHash

func CalculateUserOpHash(op *UserOperation, chainID uint64) string

CalculateUserOpHash calculates the hash of a user operation.

func DecodeCallData

func DecodeCallData(callData string) (selector string, decoded map[string]interface{})

DecodeCallData decodes the callData of a user operation

func DecodeInitCode

func DecodeInitCode(initCode string) (factory string, initData string)

DecodeInitCode decodes the initCode to extract factory and initialization data

func DecodePaymasterAndData

func DecodePaymasterAndData(paymasterAndData string) (paymaster string, data string)

DecodePaymasterAndData decodes paymaster and data

func FormatBigInt

func FormatBigInt(n *big.Int) string

FormatBigInt formats big.Int as hex string

func ParseBigInt

func ParseBigInt(s string) *big.Int

ParseBigInt safely parses a hex string to big.Int

func SortInternalTransactionsByTraceAddress

func SortInternalTransactionsByTraceAddress(itxs []InternalTransaction)

SortInternalTransactionsByTraceAddress sorts internal transactions by trace address

func TraceAddressToString

func TraceAddressToString(addr []int) string

TraceAddressToString converts a trace address to a string representation

Types

type AccessListEntry

type AccessListEntry struct {
	Address     string   `json:"address"`
	StorageKeys []string `json:"storageKeys"`
}

AccessListEntry represents an EIP-2930 access list entry

type AccountFactory

type AccountFactory struct {
	Address            string    `json:"address"`
	TotalAccounts      uint64    `json:"totalAccounts"`
	ImplementationType string    `json:"implementationType,omitempty"` // Safe, Kernel, SimpleAccount, etc.
	FirstSeenBlock     uint64    `json:"firstSeenBlock"`
	LastSeenBlock      uint64    `json:"lastSeenBlock"`
	FirstSeenTimestamp time.Time `json:"firstSeenTimestamp"`
	LastSeenTimestamp  time.Time `json:"lastSeenTimestamp"`
}

AccountFactory represents an ERC-4337 account factory

type Adapter

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

Adapter implements the chain.Adapter interface for C-Chain

func New

func New(rpcEndpoint string, opts ...AdapterOption) *Adapter

New creates a new EVM chain adapter. Defaults to "cchain" prefix when chainSlug is omitted. Auto-detects ZAP transport for luxd endpoints; falls back to HTTP.

func (*Adapter) GetAddressCoinBalanceHistory

func (a *Adapter) GetAddressCoinBalanceHistory(ctx context.Context, db *sql.DB, address string, limit int) ([]AddressCoinBalance, error)

GetAddressCoinBalanceHistory returns coin balance history for an address

func (*Adapter) GetBalance

func (a *Adapter) GetBalance(ctx context.Context, address string) (*big.Int, error)

GetBalance fetches the balance of an address

func (*Adapter) GetBalanceAtBlock

func (a *Adapter) GetBalanceAtBlock(ctx context.Context, address string, blockNumber uint64) (*big.Int, error)

GetBalanceAtBlock fetches native coin balance at a specific block

func (*Adapter) GetBlockByHeight

func (a *Adapter) GetBlockByHeight(ctx context.Context, height uint64) (json.RawMessage, error)

GetBlockByHeight fetches a specific block by number

func (*Adapter) GetBlockByID

func (a *Adapter) GetBlockByID(ctx context.Context, id string) (json.RawMessage, error)

GetBlockByID fetches a specific block by hash

func (*Adapter) GetBlockByNumber

func (a *Adapter) GetBlockByNumber(ctx context.Context, number uint64) (*EVMBlock, error)

GetBlockByNumber fetches a specific block by number and returns a parsed EVMBlock

func (*Adapter) GetCode

func (a *Adapter) GetCode(ctx context.Context, address string) (string, error)

GetCode fetches the code of a contract

func (*Adapter) GetERC721Owner

func (a *Adapter) GetERC721Owner(ctx context.Context, tokenAddress string, tokenID *big.Int) (string, error)

GetERC721Owner fetches the owner of an ERC721 token

func (*Adapter) GetERC1155Balance

func (a *Adapter) GetERC1155Balance(ctx context.Context, tokenAddress, holderAddress string, tokenID *big.Int) (*big.Int, error)

GetERC1155Balance fetches ERC1155 token balance

func (*Adapter) GetInternalTransactions

func (a *Adapter) GetInternalTransactions(ctx context.Context, db *sql.DB, txHash string) ([]InternalTransaction, error)

GetInternalTransactions returns internal transactions for a transaction

func (*Adapter) GetLatestBlock

func (a *Adapter) GetLatestBlock(ctx context.Context) (*EVMBlock, error)

GetLatestBlock fetches the latest block and returns a parsed EVMBlock

func (*Adapter) GetRecentBlocks

func (a *Adapter) GetRecentBlocks(ctx context.Context, limit int) ([]json.RawMessage, error)

GetRecentBlocks fetches recent blocks from C-Chain RPC

func (*Adapter) GetStats

func (a *Adapter) GetStats(ctx context.Context, store storage.Store) (map[string]interface{}, error)

GetStats returns chain-specific statistics using unified storage

func (*Adapter) GetTokenBalance

func (a *Adapter) GetTokenBalance(ctx context.Context, tokenAddress, holderAddress string, blockNumber uint64) (*big.Int, error)

GetTokenBalance fetches ERC20 token balance for an address

func (*Adapter) GetTokenBalanceHistory

func (a *Adapter) GetTokenBalanceHistory(ctx context.Context, db *sql.DB, address string, limit int) ([]TokenBalance, error)

GetTokenBalanceHistory returns token balance history for an address

func (*Adapter) GetTokenHolders

func (a *Adapter) GetTokenHolders(ctx context.Context, db *sql.DB, tokenAddress string, limit, offset int) ([]TokenBalance, error)

GetTokenHolders returns all holders of a token with non-zero balances

func (*Adapter) GetTokenInfo

func (a *Adapter) GetTokenInfo(ctx context.Context, tokenAddress string) (*Token, error)

GetTokenInfo fetches ERC20 token metadata

func (*Adapter) GetTransactionReceipt

func (a *Adapter) GetTransactionReceipt(ctx context.Context, txHash string) (*Transaction, []Log, error)

GetTransactionReceipt fetches a transaction receipt

func (*Adapter) Idx

func (a *Adapter) Idx(name string) string

Idx returns the prefixed index name, e.g. Idx("tx_block") returns "idx_cchain_tx_block"

func (*Adapter) InitSchema

func (a *Adapter) InitSchema(ctx context.Context, store storage.Store) error

InitSchema creates chain-specific database tables using unified storage

func (*Adapter) ParseBlock

func (a *Adapter) ParseBlock(data json.RawMessage) (*chain.Block, error)

ParseBlock parses C-Chain block data

func (*Adapter) ProcessBlock

func (a *Adapter) ProcessBlock(ctx context.Context, db *sql.DB, block *chain.Block) error

ProcessBlock processes a block and extracts all data

func (*Adapter) StoreAddress

func (a *Adapter) StoreAddress(ctx context.Context, db *sql.DB, addr Address) error

StoreAddress stores an address

func (*Adapter) StoreAddressCoinBalance

func (a *Adapter) StoreAddressCoinBalance(ctx context.Context, db *sql.DB, acb AddressCoinBalance) error

StoreAddressCoinBalance stores native coin balance for an address at a block

func (*Adapter) StoreInternalTransaction

func (a *Adapter) StoreInternalTransaction(ctx context.Context, db *sql.DB, itx InternalTransaction) error

StoreInternalTransaction stores an internal transaction

func (*Adapter) StoreLog

func (a *Adapter) StoreLog(ctx context.Context, db *sql.DB, l Log) error

StoreLog stores an event log

func (*Adapter) StoreToken

func (a *Adapter) StoreToken(ctx context.Context, db *sql.DB, t Token) error

StoreToken stores a token

func (*Adapter) StoreTokenBalance

func (a *Adapter) StoreTokenBalance(ctx context.Context, db *sql.DB, tb TokenBalance) error

StoreTokenBalance stores or updates a token balance

func (*Adapter) StoreTokenBalanceHistory

func (a *Adapter) StoreTokenBalanceHistory(ctx context.Context, db *sql.DB, tb TokenBalance) error

StoreTokenBalanceHistory stores token balance history

func (*Adapter) StoreTokenTransfer

func (a *Adapter) StoreTokenTransfer(ctx context.Context, db *sql.DB, t TokenTransfer) error

StoreTokenTransfer stores a token transfer

func (*Adapter) StoreTransaction

func (a *Adapter) StoreTransaction(ctx context.Context, db *sql.DB, tx Transaction) error

StoreTransaction stores a transaction

func (*Adapter) Tbl

func (a *Adapter) Tbl(name string) string

Tbl returns the prefixed table name, e.g. Tbl("blocks") returns "cchain_blocks"

func (*Adapter) TraceBlock

func (a *Adapter) TraceBlock(ctx context.Context, blockNumber uint64, timestamp time.Time) ([]InternalTransaction, error)

TraceBlock traces all transactions in a block

func (*Adapter) TraceTransaction

func (a *Adapter) TraceTransaction(ctx context.Context, txHash string, blockNumber uint64, timestamp time.Time) ([]InternalTransaction, error)

TraceTransaction traces internal calls for a transaction using debug_traceTransaction

func (*Adapter) UpdateExtendedStats

func (a *Adapter) UpdateExtendedStats(ctx context.Context, db *sql.DB) error

UpdateExtendedStats updates chain-specific statistics

func (*Adapter) UpdateTokenHolderCount

func (a *Adapter) UpdateTokenHolderCount(ctx context.Context, db *sql.DB, tokenAddress string) error

UpdateTokenHolderCount updates the holder count for a token

type AdapterOption

type AdapterOption func(*Adapter)

AdapterOption configures the adapter

func WithPrefix

func WithPrefix(prefix string) AdapterOption

WithPrefix sets the table name prefix (e.g. "zoo", "hanzo", "spc", "pars")

func WithTraceTimeout

func WithTraceTimeout(timeout string) AdapterOption

WithTraceTimeout sets the trace timeout

func WithTracerType

func WithTracerType(t TracerType) AdapterOption

WithTracerType sets the tracer type

func WithTransport added in v1.4.0

func WithTransport(t transport.Transport) AdapterOption

WithTransport sets an explicit transport (ZAP or HTTP). If not set, the constructor auto-detects based on the endpoint URL.

type Address

type Address struct {
	Hash            string    `json:"hash"`
	Balance         string    `json:"balance"`
	TxCount         uint64    `json:"txCount"`
	IsContract      bool      `json:"isContract"`
	ContractCode    string    `json:"contractCode,omitempty"`
	ContractCreator string    `json:"contractCreator,omitempty"`
	ContractTxHash  string    `json:"contractTxHash,omitempty"`
	CreatedAt       time.Time `json:"createdAt"`
	UpdatedAt       time.Time `json:"updatedAt"`
}

Address represents an account or contract

type AddressCoinBalance

type AddressCoinBalance struct {
	AddressHash    string    `json:"addressHash"`
	BlockNumber    uint64    `json:"blockNumber"`
	Value          string    `json:"value"`
	ValueFetchedAt time.Time `json:"valueFetchedAt"`
}

AddressCoinBalance represents native coin balance history

type ArbitrageTx

type ArbitrageTx struct {
	ID                string    `json:"id"`
	TransactionHash   string    `json:"transactionHash"`
	BlockNumber       uint64    `json:"blockNumber"`
	ArbitragerAddress string    `json:"arbitragerAddress"`
	ProfitETH         string    `json:"profitEth"`
	ProfitUSD         string    `json:"profitUsd,omitempty"`
	PathLength        int       `json:"pathLength"` // Number of swaps
	Tokens            []string  `json:"tokens"`
	Pools             []string  `json:"pools"`
	IsAtomic          bool      `json:"isAtomic"` // Flash loan based
	Timestamp         time.Time `json:"timestamp"`
}

ArbitrageTx represents a detected arbitrage transaction

type BlobData

type BlobData struct {
	VersionedHash   string    `json:"versionedHash"`
	Commitment      string    `json:"commitment"`     // KZG commitment
	Proof           string    `json:"proof"`          // KZG proof
	Data            string    `json:"data,omitempty"` // Actual blob data (optional, may be pruned)
	Size            uint64    `json:"size"`
	TransactionHash string    `json:"transactionHash"`
	BlockNumber     uint64    `json:"blockNumber"`
	BlobIndex       uint64    `json:"blobIndex"`
	StorageURI      string    `json:"storageUri,omitempty"` // Link to external blob storage
	Timestamp       time.Time `json:"timestamp"`
}

BlobData represents stored blob data

type BlobIndexer

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

BlobIndexer handles EIP-4844 blob transaction indexing

func NewBlobIndexer

func NewBlobIndexer(adapter *Adapter, db *sql.DB, storageURI string) *BlobIndexer

NewBlobIndexer creates a new blob indexer

func (*BlobIndexer) GetBlobData

func (b *BlobIndexer) GetBlobData(ctx context.Context, versionedHash string) (*BlobData, error)

GetBlobData retrieves blob data by versioned hash

func (*BlobIndexer) GetBlobTransaction

func (b *BlobIndexer) GetBlobTransaction(ctx context.Context, hash string) (*BlobTransaction, error)

GetBlobTransaction retrieves a blob transaction by hash

func (*BlobIndexer) GetBlobTransactions

func (b *BlobIndexer) GetBlobTransactions(ctx context.Context, limit, offset int) ([]BlobTransaction, error)

GetBlobTransactions retrieves blob transactions with pagination

func (*BlobIndexer) GetBlobsByTransaction

func (b *BlobIndexer) GetBlobsByTransaction(ctx context.Context, txHash string) ([]BlobData, error)

GetBlobsByTransaction retrieves all blobs for a transaction

func (*BlobIndexer) GetBlockBlobGas

func (b *BlobIndexer) GetBlockBlobGas(ctx context.Context, blockNumber uint64) (map[string]interface{}, error)

GetBlockBlobGas retrieves blob gas info for a block

func (*BlobIndexer) GetStats

func (b *BlobIndexer) GetStats(ctx context.Context) (map[string]interface{}, error)

GetStats retrieves blob statistics

func (*BlobIndexer) InitSchema

func (b *BlobIndexer) InitSchema() error

InitSchema creates blob database tables

func (*BlobIndexer) ProcessBlock

func (b *BlobIndexer) ProcessBlock(ctx context.Context, blockNumber uint64) error

ProcessBlock processes a block for blob transactions

func (*BlobIndexer) PruneOldBlobs

func (b *BlobIndexer) PruneOldBlobs(ctx context.Context, retentionDays int) (int64, error)

PruneOldBlobs removes blob data older than retention period

func (*BlobIndexer) StoreBlobData

func (b *BlobIndexer) StoreBlobData(ctx context.Context, blob BlobData) error

StoreBlobData stores blob data

func (*BlobIndexer) StoreBlobTransaction

func (b *BlobIndexer) StoreBlobTransaction(ctx context.Context, tx BlobTransaction) error

StoreBlobTransaction stores a blob transaction

func (*BlobIndexer) UpdateStats

func (b *BlobIndexer) UpdateStats(ctx context.Context) error

UpdateStats updates blob statistics

type BlobTransaction

type BlobTransaction struct {
	Hash                string    `json:"hash"`
	BlockNumber         uint64    `json:"blockNumber"`
	BlockHash           string    `json:"blockHash"`
	From                string    `json:"from"`
	To                  string    `json:"to"`
	Value               string    `json:"value"`
	MaxFeePerBlobGas    string    `json:"maxFeePerBlobGas"`
	BlobGasUsed         uint64    `json:"blobGasUsed"`
	BlobGasPrice        string    `json:"blobGasPrice"`
	BlobVersionedHashes []string  `json:"blobVersionedHashes"`
	BlobCount           int       `json:"blobCount"`
	TransactionIndex    uint64    `json:"transactionIndex"`
	Timestamp           time.Time `json:"timestamp"`
}

BlobTransaction represents an EIP-4844 type 3 transaction

type Block

type Block struct {
	Number           uint64    `json:"number"`
	Hash             string    `json:"hash"`
	ParentHash       string    `json:"parentHash"`
	Timestamp        time.Time `json:"timestamp"`
	Miner            string    `json:"miner"`
	Difficulty       *big.Int  `json:"difficulty,omitempty"`
	TotalDifficulty  *big.Int  `json:"totalDifficulty,omitempty"`
	GasLimit         uint64    `json:"gasLimit"`
	GasUsed          uint64    `json:"gasUsed"`
	BaseFeePerGas    *big.Int  `json:"baseFeePerGas,omitempty"`
	TransactionCount int       `json:"transactionCount"`
	UncleCount       int       `json:"uncleCount"`
}

Block represents a block for indexing purposes

type BlockReward

type BlockReward struct {
	BlockNumber uint64    `json:"blockNumber"`
	BlockHash   string    `json:"blockHash"`
	Validator   string    `json:"validator"`
	BaseReward  string    `json:"baseReward"`
	TxFeeReward string    `json:"txFeeReward"`
	UncleReward string    `json:"uncleReward"`
	TotalReward string    `json:"totalReward"`
	BurntFees   string    `json:"burntFees"` // EIP-1559
	Timestamp   time.Time `json:"timestamp"`
}

BlockReward represents validator/miner rewards

type Bundle

type Bundle struct {
	TransactionHash string    `json:"transactionHash"`
	BlockNumber     uint64    `json:"blockNumber"`
	BlockHash       string    `json:"blockHash"`
	BundlerAddress  string    `json:"bundlerAddress"`
	OperationCount  int       `json:"operationCount"`
	OperationHashes []string  `json:"operationHashes"`
	TotalGasUsed    uint64    `json:"totalGasUsed"`
	GasPrice        string    `json:"gasPrice"`
	Timestamp       time.Time `json:"timestamp"`
}

Bundle represents a bundler's transaction containing multiple UserOperations

type Bundler

type Bundler struct {
	Address            string    `json:"address"`
	TotalOperations    uint64    `json:"totalOperations"`
	TotalBundles       uint64    `json:"totalBundles"`
	TotalGasSponsored  string    `json:"totalGasSponsored"`
	SuccessRate        float64   `json:"successRate"`
	FirstSeenBlock     uint64    `json:"firstSeenBlock"`
	LastSeenBlock      uint64    `json:"lastSeenBlock"`
	FirstSeenTimestamp time.Time `json:"firstSeenTimestamp"`
	LastSeenTimestamp  time.Time `json:"lastSeenTimestamp"`
}

Bundler represents an ERC-4337 bundler

type CallFrame

type CallFrame struct {
	Type    string       `json:"type"`
	From    string       `json:"from"`
	To      string       `json:"to"`
	Value   string       `json:"value,omitempty"`
	Gas     string       `json:"gas"`
	GasUsed string       `json:"gasUsed"`
	Input   string       `json:"input"`
	Output  string       `json:"output,omitempty"`
	Error   string       `json:"error,omitempty"`
	Calls   []*CallFrame `json:"calls,omitempty"`
}

CallFrame represents a call in the callTracer output

type ChainAdapter

type ChainAdapter struct {
	Adapter  *Adapter
	Config   ChainConfig
	ERC4337  *ERC4337Indexer
	MEV      *MEVIndexer
	Blob     *BlobIndexer
	Enhanced *EnhancedIndexer
	// contains filtered or unexported fields
}

ChainAdapter wraps an adapter with chain-specific configuration

type ChainConfig

type ChainConfig struct {
	ChainID     uint64 `json:"chainId"`
	Name        string `json:"name"`
	Symbol      string `json:"symbol"`
	RPCEndpoint string `json:"rpcEndpoint"`
	WSEndpoint  string `json:"wsEndpoint,omitempty"`
	ExplorerURL string `json:"explorerUrl,omitempty"`
	IsTestnet   bool   `json:"isTestnet"`
	BlockTime   int    `json:"blockTimeMs"`
	// Feature support
	SupportsEIP1559 bool     `json:"supportsEip1559"`
	SupportsEIP4844 bool     `json:"supportsEip4844"`
	SupportsEIP4337 bool     `json:"supportsEip4337"`
	EntryPoints     []string `json:"entryPoints,omitempty"`
}

ChainConfig represents configuration for a specific chain

type Config

type Config struct {
	ChainName    string
	ChainID      int64
	RPCEndpoint  string
	HTTPPort     int
	PollInterval time.Duration
}

Config for EVM indexer

type CrossChainTransaction

type CrossChainTransaction struct {
	ID              string    `json:"id"`
	SourceChainID   uint64    `json:"sourceChainId"`
	DestChainID     uint64    `json:"destChainId"`
	SourceTxHash    string    `json:"sourceTxHash"`
	DestTxHash      string    `json:"destTxHash,omitempty"`
	BridgeProtocol  string    `json:"bridgeProtocol"` // Warp, LayerZero, etc.
	TokenAddress    string    `json:"tokenAddress,omitempty"`
	Amount          string    `json:"amount,omitempty"`
	Sender          string    `json:"sender"`
	Recipient       string    `json:"recipient"`
	Status          string    `json:"status"` // pending, completed, failed
	SourceTimestamp time.Time `json:"sourceTimestamp"`
	DestTimestamp   time.Time `json:"destTimestamp,omitempty"`
}

CrossChainTransaction links transactions across chains

type DecodedInput

type DecodedInput struct {
	Method     string                 `json:"method"`
	MethodID   string                 `json:"methodId"`
	Parameters map[string]interface{} `json:"parameters,omitempty"`
}

DecodedInput represents decoded transaction input data

type ERC4337Indexer

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

ERC4337Indexer handles ERC-4337 Account Abstraction indexing

func NewERC4337Indexer

func NewERC4337Indexer(adapter *Adapter, db *sql.DB) *ERC4337Indexer

NewERC4337Indexer creates a new ERC-4337 indexer

func (*ERC4337Indexer) GetBundlers

func (e *ERC4337Indexer) GetBundlers(ctx context.Context, limit, offset int) ([]Bundler, error)

GetBundlers retrieves bundlers with pagination

func (*ERC4337Indexer) GetFactories

func (e *ERC4337Indexer) GetFactories(ctx context.Context, limit, offset int) ([]AccountFactory, error)

GetFactories retrieves account factories with pagination

func (*ERC4337Indexer) GetPaymasters

func (e *ERC4337Indexer) GetPaymasters(ctx context.Context, limit, offset int) ([]Paymaster, error)

GetPaymasters retrieves paymasters with pagination

func (*ERC4337Indexer) GetSmartAccounts

func (e *ERC4337Indexer) GetSmartAccounts(ctx context.Context, limit, offset int) ([]SmartAccount, error)

GetSmartAccounts retrieves smart accounts with pagination

func (*ERC4337Indexer) GetStats

func (e *ERC4337Indexer) GetStats(ctx context.Context) (map[string]interface{}, error)

GetStats retrieves ERC-4337 statistics

func (*ERC4337Indexer) GetUserOperation

func (e *ERC4337Indexer) GetUserOperation(ctx context.Context, hash string) (*UserOperation, error)

GetUserOperation retrieves a user operation by hash

func (*ERC4337Indexer) GetUserOperationsBySender

func (e *ERC4337Indexer) GetUserOperationsBySender(ctx context.Context, sender string, limit, offset int) ([]UserOperation, error)

GetUserOperationsBySender retrieves user operations for a sender

func (*ERC4337Indexer) InitSchema

func (e *ERC4337Indexer) InitSchema() error

InitSchema creates ERC-4337 database tables

func (*ERC4337Indexer) ProcessBlock

func (e *ERC4337Indexer) ProcessBlock(ctx context.Context, blockNumber uint64, blockHash string, timestamp time.Time) error

ProcessBlock scans a block for ERC-4337 activity

func (*ERC4337Indexer) StoreBundle

func (e *ERC4337Indexer) StoreBundle(ctx context.Context, b Bundle) error

StoreBundle stores a bundle

func (*ERC4337Indexer) StoreUserOperation

func (e *ERC4337Indexer) StoreUserOperation(ctx context.Context, op *UserOperation) error

StoreUserOperation stores a user operation

func (*ERC4337Indexer) UpdateStats

func (e *ERC4337Indexer) UpdateStats(ctx context.Context) error

UpdateStats updates ERC-4337 statistics

type EVMBlock

type EVMBlock struct {
	Number       uint64    `json:"number"`
	Hash         string    `json:"hash"`
	ParentHash   string    `json:"parentHash"`
	Nonce        string    `json:"nonce"`
	Miner        string    `json:"miner"`
	Difficulty   string    `json:"difficulty"`
	GasLimit     uint64    `json:"gasLimit"`
	GasUsed      uint64    `json:"gasUsed"`
	Timestamp    time.Time `json:"timestamp"`
	TxCount      int       `json:"txCount"`
	BaseFee      string    `json:"baseFeePerGas,omitempty"`
	Size         uint64    `json:"size"`
	Transactions []string  `json:"transactions"`
}

EVMBlock represents a parsed EVM block

type EnhancedBlock

type EnhancedBlock struct {
	Hash             string    `json:"hash"`
	ParentHash       string    `json:"parentHash"`
	Number           uint64    `json:"number"`
	Timestamp        time.Time `json:"timestamp"`
	Miner            string    `json:"miner"`
	Difficulty       string    `json:"difficulty"`
	TotalDifficulty  string    `json:"totalDifficulty"`
	Size             uint64    `json:"size"`
	GasLimit         uint64    `json:"gasLimit"`
	GasUsed          uint64    `json:"gasUsed"`
	BaseFeePerGas    string    `json:"baseFeePerGas,omitempty"`
	ExtraData        string    `json:"extraData"`
	StateRoot        string    `json:"stateRoot"`
	TransactionsRoot string    `json:"transactionsRoot"`
	ReceiptsRoot     string    `json:"receiptsRoot"`
	LogsBloom        string    `json:"logsBloom"`
	TxCount          int       `json:"txCount"`
	UncleCount       int       `json:"uncleCount"`
	UncleHashes      []string  `json:"uncleHashes,omitempty"`
	// EIP-4844 fields
	BlobGasUsed      uint64 `json:"blobGasUsed,omitempty"`
	ExcessBlobGas    uint64 `json:"excessBlobGas,omitempty"`
	ParentBeaconRoot string `json:"parentBeaconBlockRoot,omitempty"`
	// EIP-4895 withdrawals
	Withdrawals     []Withdrawal `json:"withdrawals,omitempty"`
	WithdrawalsRoot string       `json:"withdrawalsRoot,omitempty"`
	// Rewards
	Reward *BlockReward `json:"reward,omitempty"`
}

Enhanced block with all new fields

type EnhancedIndexer

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

EnhancedIndexer handles advanced block and transaction indexing

func NewEnhancedIndexer

func NewEnhancedIndexer(adapter *Adapter, db *sql.DB) *EnhancedIndexer

NewEnhancedIndexer creates a new enhanced indexer

func (*EnhancedIndexer) CleanupOldPendingTxs

func (e *EnhancedIndexer) CleanupOldPendingTxs(ctx context.Context, maxAgeHours int) (int64, error)

CleanupOldPendingTxs removes stale pending transactions

func (*EnhancedIndexer) GetBlockReward

func (e *EnhancedIndexer) GetBlockReward(ctx context.Context, blockNumber uint64) (*BlockReward, error)

GetBlockReward retrieves block reward information

func (*EnhancedIndexer) GetPendingTransactions

func (e *EnhancedIndexer) GetPendingTransactions(ctx context.Context, limit, offset int) ([]PendingTransaction, error)

GetPendingTransactions retrieves pending transactions

func (*EnhancedIndexer) GetRevertReason

func (e *EnhancedIndexer) GetRevertReason(ctx context.Context, txHash string) (*TransactionRevertReason, error)

GetRevertReason retrieves and decodes revert reason for a failed transaction

func (*EnhancedIndexer) GetStats

func (e *EnhancedIndexer) GetStats(ctx context.Context) (map[string]interface{}, error)

GetStats retrieves enhanced statistics

func (*EnhancedIndexer) GetWithdrawals

func (e *EnhancedIndexer) GetWithdrawals(ctx context.Context, blockNumber uint64) ([]Withdrawal, error)

GetWithdrawals retrieves withdrawals for a block

func (*EnhancedIndexer) GetWithdrawalsByValidator

func (e *EnhancedIndexer) GetWithdrawalsByValidator(ctx context.Context, validatorIndex uint64, limit, offset int) ([]Withdrawal, error)

GetWithdrawalsByValidator retrieves withdrawals for a validator

func (*EnhancedIndexer) InitSchema

func (e *EnhancedIndexer) InitSchema() error

InitSchema creates enhanced indexing database tables

func (*EnhancedIndexer) MarkPendingTxConfirmed

func (e *EnhancedIndexer) MarkPendingTxConfirmed(ctx context.Context, hash string) error

MarkPendingTxConfirmed marks a pending transaction as confirmed

func (*EnhancedIndexer) MarkPendingTxReplaced

func (e *EnhancedIndexer) MarkPendingTxReplaced(ctx context.Context, originalHash, replacementHash string) error

MarkPendingTxReplaced marks a pending transaction as replaced

func (*EnhancedIndexer) ProcessEnhancedBlock

func (e *EnhancedIndexer) ProcessEnhancedBlock(ctx context.Context, blockNumber uint64) error

ProcessEnhancedBlock processes a block with all enhanced features

func (*EnhancedIndexer) StoreAccessList

func (e *EnhancedIndexer) StoreAccessList(ctx context.Context, txHash string, accessList []AccessListEntry) error

StoreAccessList stores transaction access list entries

func (*EnhancedIndexer) StoreBlockReward

func (e *EnhancedIndexer) StoreBlockReward(ctx context.Context, reward BlockReward) error

StoreBlockReward stores a block reward

func (*EnhancedIndexer) StoreEnhancedBlock

func (e *EnhancedIndexer) StoreEnhancedBlock(ctx context.Context, block EnhancedBlock) error

StoreEnhancedBlock stores an enhanced block

func (*EnhancedIndexer) StorePendingTransaction

func (e *EnhancedIndexer) StorePendingTransaction(ctx context.Context, tx PendingTransaction) error

StorePendingTransaction stores or updates a pending transaction

func (*EnhancedIndexer) StoreReplacedTransaction

func (e *EnhancedIndexer) StoreReplacedTransaction(ctx context.Context, r ReplacedTransaction) error

StoreReplacedTransaction stores a replaced transaction record

func (*EnhancedIndexer) StoreRevertReason

func (e *EnhancedIndexer) StoreRevertReason(ctx context.Context, r TransactionRevertReason) error

StoreRevertReason stores a transaction revert reason

func (*EnhancedIndexer) StoreUncle

func (e *EnhancedIndexer) StoreUncle(ctx context.Context, uncle Uncle) error

StoreUncle stores an uncle block

func (*EnhancedIndexer) StoreWithdrawal

func (e *EnhancedIndexer) StoreWithdrawal(ctx context.Context, w Withdrawal) error

StoreWithdrawal stores a withdrawal

func (*EnhancedIndexer) UpdateStats

func (e *EnhancedIndexer) UpdateStats(ctx context.Context) error

UpdateStats updates enhanced statistics

type EnhancedTransaction

type EnhancedTransaction struct {
	Hash                 string `json:"hash"`
	BlockHash            string `json:"blockHash"`
	BlockNumber          uint64 `json:"blockNumber"`
	TransactionIndex     uint64 `json:"transactionIndex"`
	From                 string `json:"from"`
	To                   string `json:"to"`
	Value                string `json:"value"`
	Gas                  uint64 `json:"gas"`
	GasPrice             string `json:"gasPrice,omitempty"`
	MaxFeePerGas         string `json:"maxFeePerGas,omitempty"`
	MaxPriorityFeePerGas string `json:"maxPriorityFeePerGas,omitempty"`
	GasUsed              uint64 `json:"gasUsed"`
	CumulativeGasUsed    uint64 `json:"cumulativeGasUsed"`
	EffectiveGasPrice    string `json:"effectiveGasPrice"`
	Nonce                uint64 `json:"nonce"`
	Input                string `json:"input"`
	Type                 uint8  `json:"type"` // 0=legacy, 1=2930, 2=1559, 3=4844
	Status               uint8  `json:"status"`
	ContractAddress      string `json:"contractAddress,omitempty"`
	// EIP-2930 access list
	AccessList []AccessListEntry `json:"accessList,omitempty"`
	// EIP-4844 blob fields
	MaxFeePerBlobGas    string   `json:"maxFeePerBlobGas,omitempty"`
	BlobVersionedHashes []string `json:"blobVersionedHashes,omitempty"`
	BlobGasUsed         uint64   `json:"blobGasUsed,omitempty"`
	BlobGasPrice        string   `json:"blobGasPrice,omitempty"`
	// Revert info
	RevertReason string `json:"revertReason,omitempty"`
	// Timing
	Timestamp        time.Time `json:"timestamp"`
	ConfirmationTime int64     `json:"confirmationTimeMs,omitempty"` // Time from first seen to confirmed
}

EnhancedTransaction with all new fields

type Indexer

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

Indexer is the main EVM chain indexer

func NewIndexer

func NewIndexer(cfg Config, store storage.Store) (*Indexer, error)

NewIndexer creates a new EVM indexer with the unified storage

func (*Indexer) Init

func (idx *Indexer) Init(ctx context.Context) error

Init initializes the EVM indexer schema

func (*Indexer) Run

func (idx *Indexer) Run(ctx context.Context) error

Run starts the EVM indexer

func (*Indexer) Subscriber added in v1.4.4

func (idx *Indexer) Subscriber() *Subscriber

Subscriber returns the indexer's internal WebSocket subscriber so an embedder (e.g. luxfi/explorer) can install a Subscriber.OnBroadcast callback to bridge block events into its own pub/sub fabric.

Returns nil if the indexer was constructed without an internal subscriber (currently always non-nil — NewIndexer always allocates one — but the contract permits nil so callers must guard).

type InternalTransaction

type InternalTransaction struct {
	ID           string    `json:"id"`
	TxHash       string    `json:"txHash"`
	BlockNumber  uint64    `json:"blockNumber"`
	TraceIndex   uint64    `json:"traceIndex"`
	TraceAddress []int     `json:"traceAddress"` // Position in call tree [0], [0,1], [0,1,0], etc.
	CallType     string    `json:"callType"`     // call, delegatecall, staticcall, callcode, create, create2, selfdestruct
	From         string    `json:"from"`
	To           string    `json:"to"`
	Value        string    `json:"value"`
	Gas          uint64    `json:"gas"`
	GasUsed      uint64    `json:"gasUsed"`
	Input        string    `json:"input"`
	Output       string    `json:"output"`
	Error        string    `json:"error,omitempty"`
	Timestamp    time.Time `json:"timestamp"`
	// For create/create2
	CreatedContractAddress string `json:"createdContractAddress,omitempty"`
	CreatedContractCode    string `json:"createdContractCode,omitempty"`
	Init                   string `json:"init,omitempty"` // Contract init code for creates
}

InternalTransaction represents an internal call trace

type LiquidationTx

type LiquidationTx struct {
	ID                  string    `json:"id"`
	TransactionHash     string    `json:"transactionHash"`
	BlockNumber         uint64    `json:"blockNumber"`
	LiquidatorAddress   string    `json:"liquidatorAddress"`
	BorrowerAddress     string    `json:"borrowerAddress"`
	Protocol            string    `json:"protocol"` // Aave, Compound, etc.
	CollateralToken     string    `json:"collateralToken"`
	DebtToken           string    `json:"debtToken"`
	CollateralSeized    string    `json:"collateralSeized"`
	DebtRepaid          string    `json:"debtRepaid"`
	LiquidatorProfitETH string    `json:"liquidatorProfitEth"`
	Timestamp           time.Time `json:"timestamp"`
}

LiquidationTx represents a detected liquidation

type Log

type Log struct {
	TxHash      string   `json:"txHash"`
	LogIndex    uint64   `json:"logIndex"`
	BlockNumber uint64   `json:"blockNumber"`
	Address     string   `json:"address"`
	Topics      []string `json:"topics"`
	Data        string   `json:"data"`
	Removed     bool     `json:"removed"`
}

Log represents an EVM event log

type MEVIndexer

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

MEVIndexer handles MEV transaction detection and indexing

func NewMEVIndexer

func NewMEVIndexer(adapter *Adapter, db *sql.DB) *MEVIndexer

NewMEVIndexer creates a new MEV indexer

func (*MEVIndexer) GetMEVTransactions

func (m *MEVIndexer) GetMEVTransactions(ctx context.Context, mevType string, limit, offset int) ([]MEVTransaction, error)

GetMEVTransactions retrieves MEV transactions with filters

func (*MEVIndexer) GetSandwiches

func (m *MEVIndexer) GetSandwiches(ctx context.Context, limit, offset int) ([]SandwichAttack, error)

GetSandwiches retrieves sandwich attacks

func (*MEVIndexer) GetStats

func (m *MEVIndexer) GetStats(ctx context.Context) (map[string]interface{}, error)

GetStats retrieves MEV statistics

func (*MEVIndexer) InitSchema

func (m *MEVIndexer) InitSchema() error

InitSchema creates MEV database tables

func (*MEVIndexer) ProcessBlock

func (m *MEVIndexer) ProcessBlock(ctx context.Context, blockNumber uint64) error

ProcessBlock analyzes a block for MEV activity

func (*MEVIndexer) StoreArbitrage

func (m *MEVIndexer) StoreArbitrage(ctx context.Context, a ArbitrageTx) error

StoreArbitrage stores an arbitrage transaction

func (*MEVIndexer) StoreLiquidation

func (m *MEVIndexer) StoreLiquidation(ctx context.Context, l LiquidationTx) error

StoreLiquidation stores a liquidation transaction

func (*MEVIndexer) StoreMEVTransaction

func (m *MEVIndexer) StoreMEVTransaction(ctx context.Context, tx MEVTransaction) error

StoreMEVTransaction stores an MEV transaction

func (*MEVIndexer) StoreSandwich

func (m *MEVIndexer) StoreSandwich(ctx context.Context, s SandwichAttack) error

StoreSandwich stores a sandwich attack

func (*MEVIndexer) UpdateStats

func (m *MEVIndexer) UpdateStats(ctx context.Context) error

UpdateStats updates MEV statistics

type MEVTransaction

type MEVTransaction struct {
	ID               string    `json:"id"`
	TransactionHash  string    `json:"transactionHash"`
	BlockNumber      uint64    `json:"blockNumber"`
	MEVType          MEVType   `json:"mevType"`
	ExtractorAddress string    `json:"extractorAddress"`
	VictimAddress    string    `json:"victimAddress,omitempty"`
	Protocol         string    `json:"protocol,omitempty"` // e.g., Uniswap, Aave
	ProfitETH        string    `json:"profitEth"`
	ProfitUSD        string    `json:"profitUsd,omitempty"`
	GasCostETH       string    `json:"gasCostEth"`
	RelatedTxHashes  []string  `json:"relatedTxHashes,omitempty"` // For sandwiches
	Timestamp        time.Time `json:"timestamp"`
	Confidence       float64   `json:"confidence"` // Detection confidence 0-1
}

MEVTransaction represents a detected MEV transaction

type MEVType

type MEVType string

MEVType identifies the type of MEV activity

const (
	MEVTypeSandwich    MEVType = "sandwich"
	MEVTypeArbitrage   MEVType = "arbitrage"
	MEVTypeLiquidation MEVType = "liquidation"
	MEVTypeJIT         MEVType = "jit_liquidity" // Just-in-time liquidity
	MEVTypeBackrun     MEVType = "backrun"
	MEVTypeFrontrun    MEVType = "frontrun"
	MEVTypePrivate     MEVType = "private" // Private/flashbots tx
)

type MultiChainIndexer

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

MultiChainIndexer manages multiple chain adapters

func NewMultiChainIndexer

func NewMultiChainIndexer(db *sql.DB) *MultiChainIndexer

NewMultiChainIndexer creates a new multi-chain indexer

func (*MultiChainIndexer) AddChain

func (m *MultiChainIndexer) AddChain(ctx context.Context, config ChainConfig) error

AddChain adds a chain to the multi-chain indexer

func (*MultiChainIndexer) GetChain

func (m *MultiChainIndexer) GetChain(chainID uint64) (*ChainAdapter, bool)

GetChain returns a chain adapter by ID

func (*MultiChainIndexer) GetChainSyncStatus

func (m *MultiChainIndexer) GetChainSyncStatus(ctx context.Context) ([]map[string]interface{}, error)

GetChainSyncStatus retrieves sync status for all chains

func (*MultiChainIndexer) GetChains

func (m *MultiChainIndexer) GetChains() map[uint64]*ChainAdapter

GetChains returns all chain adapters

func (*MultiChainIndexer) GetCrossChainTransaction

func (m *MultiChainIndexer) GetCrossChainTransaction(ctx context.Context, id string) (*CrossChainTransaction, error)

GetCrossChainTransaction retrieves a cross-chain transaction

func (*MultiChainIndexer) GetCrossChainTransactionsByAddress

func (m *MultiChainIndexer) GetCrossChainTransactionsByAddress(ctx context.Context, address string, limit, offset int) ([]CrossChainTransaction, error)

GetCrossChainTransactionsByAddress retrieves cross-chain transactions for an address

func (*MultiChainIndexer) GetStats

func (m *MultiChainIndexer) GetStats(ctx context.Context) (map[string]interface{}, error)

GetStats retrieves multi-chain statistics

func (*MultiChainIndexer) InitSchema

func (m *MultiChainIndexer) InitSchema() error

InitSchema creates multi-chain database tables

func (*MultiChainIndexer) LoadDefaultChains

func (m *MultiChainIndexer) LoadDefaultChains(ctx context.Context) error

LoadDefaultChains loads and activates default chain configurations

func (*MultiChainIndexer) RemoveChain

func (m *MultiChainIndexer) RemoveChain(ctx context.Context, chainID uint64) error

RemoveChain removes a chain from the indexer

func (*MultiChainIndexer) StartAllChains

func (m *MultiChainIndexer) StartAllChains(ctx context.Context) error

StartAllChains starts indexing for all configured chains

func (*MultiChainIndexer) StartChain

func (m *MultiChainIndexer) StartChain(ctx context.Context, chainID uint64) error

StartChain starts indexing for a specific chain

func (*MultiChainIndexer) StopAllChains

func (m *MultiChainIndexer) StopAllChains()

StopAllChains stops indexing for all chains

func (*MultiChainIndexer) StopChain

func (m *MultiChainIndexer) StopChain(chainID uint64) error

StopChain stops indexing for a specific chain

func (*MultiChainIndexer) StoreCrossChainTransaction

func (m *MultiChainIndexer) StoreCrossChainTransaction(ctx context.Context, tx CrossChainTransaction) error

StoreCrossChainTransaction stores a cross-chain transaction

func (*MultiChainIndexer) UpdateStats

func (m *MultiChainIndexer) UpdateStats(ctx context.Context) error

UpdateStats updates multi-chain statistics

type NodeEvent

type NodeEvent struct {
	ChainID   string    `json:"chain_id"`
	Type      string    `json:"type"` // "put" or "delete"
	Prefix    string    `json:"prefix"`
	Key       string    `json:"key"`
	Value     []byte    `json:"value,omitempty"`
	Timestamp time.Time `json:"timestamp"`
}

NodeEvent represents an event from the node's hookdb

type Paymaster

type Paymaster struct {
	Address            string    `json:"address"`
	TotalOperations    uint64    `json:"totalOperations"`
	TotalGasSponsored  string    `json:"totalGasSponsored"`
	TotalEthSponsored  string    `json:"totalEthSponsored"`
	UniqueAccounts     uint64    `json:"uniqueAccounts"`
	FirstSeenBlock     uint64    `json:"firstSeenBlock"`
	LastSeenBlock      uint64    `json:"lastSeenBlock"`
	FirstSeenTimestamp time.Time `json:"firstSeenTimestamp"`
	LastSeenTimestamp  time.Time `json:"lastSeenTimestamp"`
}

Paymaster represents an ERC-4337 paymaster

type PendingPoolConfig

type PendingPoolConfig struct {
	RPCURL        string
	PollInterval  time.Duration
	MaxPendingAge time.Duration
	OnNewPending  func(*PendingTransaction)
	OnRemoved     func(string)
}

PendingPoolConfig configures the pending pool monitor

type PendingPoolMonitor

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

PendingPoolMonitor monitors the pending transaction pool (mempool)

func NewPendingPoolMonitor

func NewPendingPoolMonitor(config PendingPoolConfig) *PendingPoolMonitor

NewPendingPoolMonitor creates a new pending transaction pool monitor

func (*PendingPoolMonitor) GetPendingByAddress

func (m *PendingPoolMonitor) GetPendingByAddress(address string) []*PendingTransaction

GetPendingByAddress returns pending transactions for a specific address

func (*PendingPoolMonitor) GetPendingTransaction

func (m *PendingPoolMonitor) GetPendingTransaction(hash string) *PendingTransaction

GetPendingTransaction returns a specific pending transaction by hash

func (*PendingPoolMonitor) GetPendingTransactions

func (m *PendingPoolMonitor) GetPendingTransactions() []*PendingTransaction

GetPendingTransactions returns all current pending transactions

func (*PendingPoolMonitor) GetStats

func (m *PendingPoolMonitor) GetStats() *PendingPoolStats

GetStats returns current pool statistics

func (*PendingPoolMonitor) Start

func (m *PendingPoolMonitor) Start(ctx context.Context) error

Start begins monitoring the pending pool

func (*PendingPoolMonitor) Stop

func (m *PendingPoolMonitor) Stop()

Stop stops the monitor

type PendingPoolStats

type PendingPoolStats struct {
	TotalCount      int       `json:"totalCount"`
	PendingCount    int       `json:"pendingCount"`
	QueuedCount     int       `json:"queuedCount"`
	TotalGasPrice   *big.Int  `json:"totalGasPrice"`
	AverageGasPrice *big.Int  `json:"averageGasPrice"`
	MinGasPrice     *big.Int  `json:"minGasPrice"`
	MaxGasPrice     *big.Int  `json:"maxGasPrice"`
	OldestTxTime    time.Time `json:"oldestTxTime"`
	NewestTxTime    time.Time `json:"newestTxTime"`
	TotalValue      *big.Int  `json:"totalValue"`
	UniqueFromAddrs int       `json:"uniqueFromAddresses"`
	UniqueToAddrs   int       `json:"uniqueToAddresses"`
	ContractCalls   int       `json:"contractCalls"`
	SimpleTransfers int       `json:"simpleTransfers"`
	TokenTransfers  int       `json:"tokenTransfers"`
	UpdatedAt       time.Time `json:"updatedAt"`
}

PendingPoolStats represents mempool statistics

type PendingTransaction

type PendingTransaction struct {
	Hash           string        `json:"hash"`
	From           string        `json:"from"`
	To             string        `json:"to"`
	Value          string        `json:"value"`
	Gas            uint64        `json:"gas"`
	GasPrice       string        `json:"gasPrice,omitempty"`
	MaxFeePerGas   string        `json:"maxFeePerGas,omitempty"`
	MaxPriorityFee string        `json:"maxPriorityFeePerGas,omitempty"`
	Nonce          uint64        `json:"nonce"`
	Input          string        `json:"input"`
	Type           uint8         `json:"type"`
	V              string        `json:"v,omitempty"`
	R              string        `json:"r,omitempty"`
	S              string        `json:"s,omitempty"`
	FirstSeenAt    time.Time     `json:"firstSeenAt"`
	LastSeenAt     time.Time     `json:"lastSeenAt"`
	FirstSeen      time.Time     `json:"firstSeen"`            // Alias for enhanced compatibility
	LastSeen       time.Time     `json:"lastSeen"`             // Alias for enhanced compatibility
	SeenCount      int           `json:"seenCount"`            // Times seen in mempool
	Status         string        `json:"status"`               // pending, replaced, dropped, confirmed
	ReplacedBy     string        `json:"replacedBy,omitempty"` // Hash of replacing tx
	GasEstimate    uint64        `json:"gasEstimate,omitempty"`
	DecodedInput   *DecodedInput `json:"decodedInput,omitempty"`
}

PendingTransaction represents a transaction in the mempool

type ReplacedTransaction

type ReplacedTransaction struct {
	OriginalHash    string    `json:"originalHash"`
	ReplacementHash string    `json:"replacementHash"`
	BlockNumber     uint64    `json:"blockNumber"`
	From            string    `json:"from"`
	Nonce           uint64    `json:"nonce"`
	OldGasPrice     string    `json:"oldGasPrice"`
	NewGasPrice     string    `json:"newGasPrice"`
	ReplacementType string    `json:"replacementType"` // speedup, cancel
	Timestamp       time.Time `json:"timestamp"`
}

ReplacedTransaction tracks transaction replacements

type SandwichAttack

type SandwichAttack struct {
	ID                string    `json:"id"`
	BlockNumber       uint64    `json:"blockNumber"`
	FrontrunTxHash    string    `json:"frontrunTxHash"`
	VictimTxHash      string    `json:"victimTxHash"`
	BackrunTxHash     string    `json:"backrunTxHash"`
	AttackerAddress   string    `json:"attackerAddress"`
	VictimAddress     string    `json:"victimAddress"`
	TokenAddress      string    `json:"tokenAddress"`
	PoolAddress       string    `json:"poolAddress"`
	VictimLossETH     string    `json:"victimLossEth"`
	AttackerProfitETH string    `json:"attackerProfitEth"`
	Timestamp         time.Time `json:"timestamp"`
}

SandwichAttack represents a detected sandwich attack

type SmartAccount

type SmartAccount struct {
	Address          string    `json:"address"`
	FactoryAddress   string    `json:"factoryAddress,omitempty"`
	DeploymentTxHash string    `json:"deploymentTxHash,omitempty"`
	DeploymentBlock  uint64    `json:"deploymentBlock"`
	TotalOperations  uint64    `json:"totalOperations"`
	TotalGasUsed     string    `json:"totalGasUsed"`
	CreatedAt        time.Time `json:"createdAt"`
	UpdatedAt        time.Time `json:"updatedAt"`
}

SmartAccount represents an ERC-4337 smart contract account

type Subscriber

type Subscriber struct {
	OnBroadcast func(eventType string, data any) // optional, see header
	// contains filtered or unexported fields
}

Subscriber handles WebSocket for live block streaming.

External pub/sub hook (2026-05-21):

`OnBroadcast` is an optional callback fired on every BroadcastBlock / BroadcastTransaction. It lets an enclosing process — e.g. luxfi/explorer which embeds this indexer as a library — re- publish the same events to its own pub/sub fabric (SSE channels, gRPC streams, NATS, etc.) without touching the indexer's own WebSocket flow.

The callback is invoked synchronously from the indexing goroutine, so implementations must NOT block on slow consumers (use a buffered channel + drop-on-full, the way luxfi/explorer's SSE registry does).

Zero-value (nil) is a no-op: existing WebSocket subscribers see no change, and the indexer keeps working standalone.

func NewSubscriber

func NewSubscriber() *Subscriber

func (*Subscriber) BroadcastBlock

func (s *Subscriber) BroadcastBlock(block *EVMBlock)

func (*Subscriber) HandleWebSocket

func (s *Subscriber) HandleWebSocket(w http.ResponseWriter, r *http.Request)

func (*Subscriber) Run

func (s *Subscriber) Run(ctx context.Context)

type Token

type Token struct {
	Address     string    `json:"address"`
	Name        string    `json:"name"`
	Symbol      string    `json:"symbol"`
	Decimals    uint8     `json:"decimals"`
	TotalSupply string    `json:"totalSupply"`
	TokenType   string    `json:"tokenType"` // ERC20, ERC721, ERC1155
	HolderCount uint64    `json:"holderCount"`
	TxCount     uint64    `json:"txCount"`
	CreatedAt   time.Time `json:"createdAt"`
	UpdatedAt   time.Time `json:"updatedAt"`
}

Token represents an ERC20/721/1155 token contract

type TokenBalance

type TokenBalance struct {
	TokenAddress  string    `json:"tokenAddress"`
	HolderAddress string    `json:"holderAddress"`
	Balance       string    `json:"balance"`
	TokenID       string    `json:"tokenId,omitempty"` // For ERC721/1155
	BlockNumber   uint64    `json:"blockNumber"`
	UpdatedAt     time.Time `json:"updatedAt"`
}

TokenBalance represents a token balance for an address

type TokenTransfer

type TokenTransfer struct {
	ID           string    `json:"id"`
	TxHash       string    `json:"txHash"`
	LogIndex     uint64    `json:"logIndex"`
	BlockNumber  uint64    `json:"blockNumber"`
	TokenAddress string    `json:"tokenAddress"`
	TokenType    string    `json:"tokenType"` // ERC20, ERC721, ERC1155
	From         string    `json:"from"`
	To           string    `json:"to"`
	Value        string    `json:"value"`   // amount for ERC20, tokenId for NFT
	TokenID      string    `json:"tokenId"` // for ERC721/1155
	Timestamp    time.Time `json:"timestamp"`
}

TokenTransfer represents an ERC20/721/1155 transfer

type TracerType

type TracerType string

TracerType specifies which tracer to use

const (
	// TracerCallTracer uses geth's built-in callTracer (recommended)
	TracerCallTracer TracerType = "callTracer"
	// TracerJS uses custom JavaScript tracer for internal transaction tracing
	TracerJS TracerType = "js"
	// TracerParity uses trace_replayBlockTransactions (Parity/Nethermind)
	TracerParity TracerType = "parity"
)

type Transaction

type Transaction struct {
	Hash             string    `json:"hash"`
	BlockHash        string    `json:"blockHash"`
	BlockNumber      uint64    `json:"blockNumber"`
	From             string    `json:"from"`
	To               string    `json:"to"`
	Value            string    `json:"value"`
	Gas              uint64    `json:"gas"`
	GasPrice         string    `json:"gasPrice"`
	GasUsed          uint64    `json:"gasUsed"`
	Nonce            uint64    `json:"nonce"`
	Input            string    `json:"input"`
	TransactionIndex uint64    `json:"transactionIndex"`
	Type             uint8     `json:"type"`
	Status           *int      `json:"status"` // nil = pending, 1 = success, 0 = fail
	ContractAddress  string    `json:"contractAddress,omitempty"`
	Timestamp        time.Time `json:"timestamp"`
}

Transaction represents an EVM transaction

type TransactionRevertReason

type TransactionRevertReason struct {
	TransactionHash string `json:"transactionHash"`
	RevertReason    string `json:"revertReason"`
	DecodedReason   string `json:"decodedReason,omitempty"` // Human readable
	ErrorSelector   string `json:"errorSelector,omitempty"` // 4-byte selector
	ErrorName       string `json:"errorName,omitempty"`     // Error name if known
}

TransactionRevertReason contains decoded revert information

type TxPoolContent

type TxPoolContent struct {
	Pending map[string]map[string]*PendingTransaction `json:"pending"`
	Queued  map[string]map[string]*PendingTransaction `json:"queued"`
}

TxPoolContent represents the response from txpool_content

type Uncle

type Uncle struct {
	Hash        string    `json:"hash"`
	BlockNumber uint64    `json:"blockNumber"` // Block that included this uncle
	UncleIndex  uint64    `json:"uncleIndex"`
	ParentHash  string    `json:"parentHash"`
	Miner       string    `json:"miner"`
	Difficulty  string    `json:"difficulty"`
	GasLimit    uint64    `json:"gasLimit"`
	GasUsed     uint64    `json:"gasUsed"`
	Timestamp   time.Time `json:"timestamp"`
	Reward      string    `json:"reward"`
}

Uncle represents an uncle/ommer block

type UncleBlock

type UncleBlock struct {
	Hash             string    `json:"hash"`
	Number           uint64    `json:"number"`
	ParentHash       string    `json:"parentHash"`
	Nonce            string    `json:"nonce,omitempty"`
	Sha3Uncles       string    `json:"sha3Uncles"`
	LogsBloom        string    `json:"logsBloom"`
	TransactionsRoot string    `json:"transactionsRoot"`
	StateRoot        string    `json:"stateRoot"`
	ReceiptsRoot     string    `json:"receiptsRoot"`
	Miner            string    `json:"miner"`
	Difficulty       string    `json:"difficulty"`
	TotalDifficulty  string    `json:"totalDifficulty,omitempty"`
	ExtraData        string    `json:"extraData"`
	Size             uint64    `json:"size"`
	GasLimit         uint64    `json:"gasLimit"`
	GasUsed          uint64    `json:"gasUsed"`
	Timestamp        time.Time `json:"timestamp"`

	// Nephew block info (the block that included this uncle)
	NephewHash   string `json:"nephewHash"`
	NephewNumber uint64 `json:"nephewNumber"`
	UncleIndex   int    `json:"uncleIndex"`

	// Reward info
	MinerReward string `json:"minerReward"`
	UncleReward string `json:"uncleReward"`

	// Indexing metadata
	IndexedAt time.Time `json:"indexedAt"`
}

UncleBlock represents an uncle (ommer) block

type UncleIndexer

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

UncleIndexer indexes uncle blocks

func NewUncleIndexer

func NewUncleIndexer(rpcURL string, blockReward *big.Int) *UncleIndexer

NewUncleIndexer creates a new uncle block indexer

func (*UncleIndexer) CalculateUncleReward

func (u *UncleIndexer) CalculateUncleReward(uncleNumber, nephewNumber uint64) *UncleReward

CalculateUncleReward calculates the reward for an uncle block Based on Ethereum's uncle reward formula: Uncle reward = (uncle_number + 8 - nephew_number) / 8 * block_reward Nephew reward = block_reward / 32 per uncle included

func (*UncleIndexer) GetAllUncles

func (u *UncleIndexer) GetAllUncles(ctx context.Context, blockNumber uint64, blockHash string) ([]*UncleBlock, error)

GetAllUncles returns all uncle blocks for a given block

func (*UncleIndexer) GetUncle

func (u *UncleIndexer) GetUncle(ctx context.Context, blockNumberOrHash string, index int) (*UncleBlock, error)

GetUncle returns an uncle block by block hash/number and uncle index

func (*UncleIndexer) GetUncleCount

func (u *UncleIndexer) GetUncleCount(ctx context.Context, blockNumberOrHash string) (int, error)

GetUncleCount returns the number of uncles in a block

func (*UncleIndexer) GetUncleStats

func (u *UncleIndexer) GetUncleStats(ctx context.Context, fromBlock, toBlock uint64) (*UncleStats, error)

GetUncleStats calculates uncle statistics for a block range

func (*UncleIndexer) IndexBlockUncles

func (u *UncleIndexer) IndexBlockUncles(ctx context.Context, block *Block) ([]*UncleBlock, error)

IndexBlockUncles indexes all uncles for a block and returns the results

type UncleReward

type UncleReward struct {
	UncleBlockNumber  uint64   `json:"uncleBlockNumber"`
	NephewBlockNumber uint64   `json:"nephewBlockNumber"`
	UncleReward       *big.Int `json:"uncleReward"`  // Reward to uncle miner
	NephewReward      *big.Int `json:"nephewReward"` // Additional reward to nephew miner
}

UncleReward represents uncle mining reward calculation

type UncleStats

type UncleStats struct {
	BlockRange       [2]uint64 `json:"blockRange"`
	TotalBlocks      int       `json:"totalBlocks"`
	BlocksWithUncles int       `json:"blocksWithUncles"`
	TotalUncles      int       `json:"totalUncles"`
	MaxUnclesInBlock int       `json:"maxUnclesInBlock"`
	UniqueMiners     int       `json:"uniqueMiners"`
	TotalUncleReward *big.Int  `json:"totalUncleReward"`
	AvgUncleDepth    float64   `json:"avgUncleDepth"` // Average (nephew - uncle) depth
}

UncleStats represents uncle statistics for a range of blocks

type UserOperation

type UserOperation struct {
	Hash                 string    `json:"hash"`
	Sender               string    `json:"sender"`
	Nonce                string    `json:"nonce"`
	InitCode             string    `json:"initCode,omitempty"`
	CallData             string    `json:"callData"`
	CallGasLimit         uint64    `json:"callGasLimit"`
	VerificationGasLimit uint64    `json:"verificationGasLimit"`
	PreVerificationGas   uint64    `json:"preVerificationGas"`
	MaxFeePerGas         string    `json:"maxFeePerGas"`
	MaxPriorityFeePerGas string    `json:"maxPriorityFeePerGas"`
	PaymasterAndData     string    `json:"paymasterAndData,omitempty"`
	Signature            string    `json:"signature"`
	EntryPoint           string    `json:"entryPoint"`
	BlockNumber          uint64    `json:"blockNumber"`
	BlockHash            string    `json:"blockHash"`
	TransactionHash      string    `json:"transactionHash"`
	BundlerAddress       string    `json:"bundlerAddress"`
	PaymasterAddress     string    `json:"paymasterAddress,omitempty"`
	FactoryAddress       string    `json:"factoryAddress,omitempty"`
	Status               uint8     `json:"status"` // 1 = success, 0 = reverted
	RevertReason         string    `json:"revertReason,omitempty"`
	ActualGasCost        string    `json:"actualGasCost"`
	ActualGasUsed        uint64    `json:"actualGasUsed"`
	Timestamp            time.Time `json:"timestamp"`
	EntryPointVersion    string    `json:"entryPointVersion"` // v0.6 or v0.7
}

UserOperation represents an ERC-4337 user operation

type Withdrawal

type Withdrawal struct {
	Index          uint64    `json:"index"`
	ValidatorIndex uint64    `json:"validatorIndex"`
	Address        string    `json:"address"`
	Amount         string    `json:"amount"` // In Gwei
	BlockNumber    uint64    `json:"blockNumber"`
	BlockHash      string    `json:"blockHash"`
	Timestamp      time.Time `json:"timestamp"`
}

Withdrawal represents an EIP-4895 withdrawal

Directories

Path Synopsis
Package account provides user account management for the EVM indexer.
Package account provides user account management for the EVM indexer.
Package api provides REST, RPC, GraphQL, and WebSocket APIs for the EVM indexer.
Package api provides REST, RPC, GraphQL, and WebSocket APIs for the EVM indexer.
Package charts provides time-series data for blockchain visualization.
Package charts provides time-series data for blockchain visualization.
Package contracts provides smart contract verification and proxy detection.
Package contracts provides smart contract verification and proxy detection.
Package defi provides DeFi protocol indexing for the Lux EVM indexer.
Package defi provides DeFi protocol indexing for the Lux EVM indexer.
Package market provides coin/token price fetching and caching from external price oracles (CoinGecko, CoinMarketCap).
Package market provides coin/token price fetching and caching from external price oracles (CoinGecko, CoinMarketCap).
Package search provides unified search functionality across all indexed blockchain entities.
Package search provides unified search functionality across all indexed blockchain entities.
Package stats provides Prometheus metrics export for blockchain statistics.
Package stats provides Prometheus metrics export for blockchain statistics.
Package transport provides pluggable RPC transports for the EVM indexer.
Package transport provides pluggable RPC transports for the EVM indexer.

Jump to

Keyboard shortcuts

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