stats

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: 8 Imported by: 0

Documentation

Overview

Package stats provides Prometheus metrics export for blockchain statistics.

Package stats provides blockchain statistics, counters, and caching functionality. Implements gas price oracle, block time calculations, and aggregate metrics.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetMetricsHelp

func GetMetricsHelp() string

GetMetricsHelp returns Prometheus-formatted HELP and TYPE lines

Types

type AddressStats

type AddressStats struct {
	Address            string `json:"address"`
	TransactionCount   int64  `json:"transaction_count"`
	TokenTransferCount int64  `json:"token_transfer_count"`
	InternalTxCount    int64  `json:"internal_tx_count"`
	GasUsed            int64  `json:"gas_used"`
	Balance            string `json:"balance"`
}

AddressStats contains address-specific statistics

type BlockTimeStats

type BlockTimeStats struct {
	AverageBlockTime time.Duration `json:"average_block_time"`
	MinBlockTime     time.Duration `json:"min_block_time"`
	MaxBlockTime     time.Duration `json:"max_block_time"`
	BlocksAnalyzed   int           `json:"blocks_analyzed"`
	UpdatedAt        time.Time     `json:"updated_at"`
}

BlockTimeStats contains block time statistics

type Cache

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

Cache provides in-memory caching for statistics

func NewCache

func NewCache(ttl time.Duration) *Cache

NewCache creates a new cache with specified TTL

type Config

type Config struct {
	CacheTTL              time.Duration
	GasPriceBlocks        int     // Number of blocks to analyze for gas prices
	SlowPercentile        float64 // Percentile for slow gas price
	AveragePercentile     float64 // Percentile for average gas price
	FastPercentile        float64 // Percentile for fast gas price
	SimpleTransactionGas  int64   // Gas for simple ETH transfer
	CounterUpdateInterval time.Duration
	BlockTimeBlocks       int // Number of blocks for block time calculation
}

Config holds statistics service configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible defaults

type Counter

type Counter struct {
	Name      string    `json:"name"`
	Value     int64     `json:"value"`
	UpdatedAt time.Time `json:"updated_at"`
}

Counter represents an aggregate counter value

type Counters

type Counters struct {
	TotalBlocks         int64     `json:"total_blocks"`
	TotalTransactions   int64     `json:"total_transactions"`
	TotalAddresses      int64     `json:"total_addresses"`
	TotalContracts      int64     `json:"total_contracts"`
	TotalTokens         int64     `json:"total_tokens"`
	TotalTokenTransfers int64     `json:"total_token_transfers"`
	VerifiedContracts   int64     `json:"verified_contracts"`
	AverageBlockTime    float64   `json:"average_block_time_seconds"`
	TPS24h              float64   `json:"tps_24h"`
	GasUsed24h          int64     `json:"gas_used_24h"`
	UpdatedAt           time.Time `json:"updated_at"`
}

Counters holds all aggregate statistics

type DailyStats

type DailyStats struct {
	Date  time.Time `json:"date"`
	Count int64     `json:"count"`
}

DailyStats represents daily count statistics

type GasPrice

type GasPrice struct {
	Price       float64 `json:"price"`        // Gas price in Gwei
	PriorityFee float64 `json:"priority_fee"` // Priority fee in Gwei
	BaseFee     float64 `json:"base_fee"`     // Base fee in Gwei
	Time        float64 `json:"time"`         // Estimated confirmation time in ms
	FiatPrice   float64 `json:"fiat_price"`   // Fiat price for simple tx
	Wei         string  `json:"wei"`          // Full price in Wei
}

GasPrice represents gas price for a fee tier

type GasPrices

type GasPrices struct {
	Slow         *GasPrice `json:"slow"`
	Average      *GasPrice `json:"average"`
	Fast         *GasPrice `json:"fast"`
	UpdatedAt    time.Time `json:"updated_at"`
	BaseFee      string    `json:"base_fee"`       // Current base fee
	GasUsedRatio float64   `json:"gas_used_ratio"` // Recent block gas usage
}

GasPrices represents slow/average/fast gas price estimates

type HourlyStats

type HourlyStats struct {
	Hour  time.Time `json:"hour"`
	Value int64     `json:"value"`
}

HourlyStats represents hourly statistics

type MetricDefinition

type MetricDefinition struct {
	Name string
	Type string // counter, gauge, histogram
	Help string
}

MetricDefinition describes a Prometheus metric

func GetMetricDefinitions

func GetMetricDefinitions() []MetricDefinition

GetMetricDefinitions returns all metric definitions

type MetricsExporter

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

MetricsExporter exports statistics as Prometheus metrics

func NewMetricsExporter

func NewMetricsExporter(service *Service) *MetricsExporter

NewMetricsExporter creates a new Prometheus metrics exporter

func (*MetricsExporter) ServeHTTP

func (m *MetricsExporter) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler for Prometheus metrics endpoint

func (*MetricsExporter) StartBackgroundUpdater

func (m *MetricsExporter) StartBackgroundUpdater(ctx context.Context, interval time.Duration)

StartBackgroundUpdater starts a goroutine to periodically update metrics

func (*MetricsExporter) UpdateMetrics

func (m *MetricsExporter) UpdateMetrics(ctx context.Context) error

UpdateMetrics refreshes all metric values

type Service

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

Service provides statistics and caching functionality

func NewService

func NewService(db *sql.DB, config Config, chainSlug ...string) *Service

NewService creates a new statistics service. Defaults to "cchain" prefix when chainSlug is omitted.

func (*Service) GetAddressStats

func (s *Service) GetAddressStats(ctx context.Context, address string) (*AddressStats, error)

GetAddressStats returns statistics for a specific address

func (*Service) GetAverageBlockTime

func (s *Service) GetAverageBlockTime(ctx context.Context) (*BlockTimeStats, error)

GetAverageBlockTime returns block time statistics

func (*Service) GetCounters

func (s *Service) GetCounters(ctx context.Context) (*Counters, error)

GetCounters returns aggregate statistics

func (*Service) GetDailyTransactionStats

func (s *Service) GetDailyTransactionStats(ctx context.Context, days int) ([]DailyStats, error)

GetDailyTransactionStats returns daily transaction counts

func (*Service) GetGasPrices

func (s *Service) GetGasPrices(ctx context.Context) (*GasPrices, error)

GetGasPrices returns current gas price estimates

func (*Service) GetHourlyGasUsage

func (s *Service) GetHourlyGasUsage(ctx context.Context) ([]HourlyStats, error)

GetHourlyGasUsage returns hourly gas usage for the last 24 hours

func (*Service) GetTokenStats

func (s *Service) GetTokenStats(ctx context.Context, tokenAddress string) (*TokenStats, error)

GetTokenStats returns statistics for a specific token

func (*Service) InvalidateCache

func (s *Service) InvalidateCache()

InvalidateCache clears all cached data

func (*Service) StartBackgroundUpdater

func (s *Service) StartBackgroundUpdater(ctx context.Context)

StartBackgroundUpdater starts a background goroutine to update stats periodically

func (*Service) Tbl

func (s *Service) Tbl(name string) string

Tbl returns the prefixed table name, e.g. Tbl("transactions") returns "cchain_transactions"

type TokenStats

type TokenStats struct {
	Address       string    `json:"address"`
	HolderCount   int64     `json:"holder_count"`
	TransferCount int64     `json:"transfer_count"`
	UpdatedAt     time.Time `json:"updated_at"`
}

TokenStats contains token-specific statistics

Jump to

Keyboard shortcuts

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