api

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

Documentation

Overview

Package api provides REST, RPC, GraphQL, and WebSocket APIs for the EVM indexer. API design follows the explorer v2 format for frontend compatibility.

Index

Constants

View Source
const GraphQLSchema = `` /* 5313-byte string literal not displayed */

GraphQL schema for the explorer API

Variables

View Source
var (
	ErrNotFound     = errors.New("not found")
	ErrInvalidParam = errors.New("invalid parameter")
)

Functions

func EnsureTables added in v0.3.1

func EnsureTables(db *sql.DB, prefix string) error

EnsureTables creates all tables required by the API layer if they don't exist. prefix is the chain slug (e.g. "cchain", "zoo", "hanzo", "spc", "pars"). This is idempotent -- safe to call on every startup.

func UserFromContext

func UserFromContext(ctx context.Context) *account.User

UserFromContext extracts the authenticated user from the request context. Returns nil if no user is present (unauthenticated request).

Types

type AccountAPI

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

AccountAPI provides HTTP handlers for user account endpoints. These endpoints require IAM authentication.

func NewAccountAPI

func NewAccountAPI(svc *account.Service) *AccountAPI

NewAccountAPI creates account API handlers backed by the given service.

func (*AccountAPI) HandleAddWatchlistAddress

func (a *AccountAPI) HandleAddWatchlistAddress(w http.ResponseWriter, r *http.Request)

HandleAddWatchlistAddress adds an address to a watchlist.

func (*AccountAPI) HandleCreateAPIKey

func (a *AccountAPI) HandleCreateAPIKey(w http.ResponseWriter, r *http.Request)

HandleCreateAPIKey creates a new API key for the user.

func (*AccountAPI) HandleDeleteAPIKey

func (a *AccountAPI) HandleDeleteAPIKey(w http.ResponseWriter, r *http.Request)

HandleDeleteAPIKey deletes one of the user's API keys.

func (*AccountAPI) HandleDeleteAddressTag

func (a *AccountAPI) HandleDeleteAddressTag(w http.ResponseWriter, r *http.Request)

HandleDeleteAddressTag removes a custom address tag.

func (*AccountAPI) HandleDeleteCustomABI

func (a *AccountAPI) HandleDeleteCustomABI(w http.ResponseWriter, r *http.Request)

HandleDeleteCustomABI removes a custom ABI.

func (*AccountAPI) HandleGetCSRF

func (a *AccountAPI) HandleGetCSRF(w http.ResponseWriter, r *http.Request)

HandleGetCSRF returns a CSRF token header for the authenticated session.

func (*AccountAPI) HandleGetUserInfo

func (a *AccountAPI) HandleGetUserInfo(w http.ResponseWriter, r *http.Request)

HandleGetUserInfo returns the authenticated user's profile.

func (*AccountAPI) HandleGetWatchlistAddresses

func (a *AccountAPI) HandleGetWatchlistAddresses(w http.ResponseWriter, r *http.Request)

HandleGetWatchlistAddresses returns addresses in a watchlist.

func (*AccountAPI) HandleListAPIKeys

func (a *AccountAPI) HandleListAPIKeys(w http.ResponseWriter, r *http.Request)

HandleListAPIKeys returns the user's API keys.

func (*AccountAPI) HandleListAddressTags

func (a *AccountAPI) HandleListAddressTags(w http.ResponseWriter, r *http.Request)

HandleListAddressTags returns the user's custom address tags.

func (*AccountAPI) HandleListCustomABIs

func (a *AccountAPI) HandleListCustomABIs(w http.ResponseWriter, r *http.Request)

HandleListCustomABIs returns the user's custom ABIs.

func (*AccountAPI) HandleListWatchlists

func (a *AccountAPI) HandleListWatchlists(w http.ResponseWriter, r *http.Request)

HandleListWatchlists returns the user's watchlists.

func (*AccountAPI) HandleLogout

func (a *AccountAPI) HandleLogout(w http.ResponseWriter, r *http.Request)

HandleLogout is a no-op for JWT auth but provided for frontend compatibility.

func (*AccountAPI) HandleRemoveWatchlistAddress

func (a *AccountAPI) HandleRemoveWatchlistAddress(w http.ResponseWriter, r *http.Request)

HandleRemoveWatchlistAddress removes an address from a watchlist.

func (*AccountAPI) HandleSetAddressTag

func (a *AccountAPI) HandleSetAddressTag(w http.ResponseWriter, r *http.Request)

HandleSetAddressTag creates or updates an address tag.

func (*AccountAPI) HandleSetCustomABI

func (a *AccountAPI) HandleSetCustomABI(w http.ResponseWriter, r *http.Request)

HandleSetCustomABI creates or updates a custom ABI.

type Address

type Address struct {
	Hash               string          `json:"hash"`
	Name               string          `json:"name,omitempty"`
	ENS                string          `json:"ens_domain_name,omitempty"`
	IsContract         bool            `json:"is_contract"`
	IsVerified         bool            `json:"is_verified,omitempty"`
	IsScam             bool            `json:"is_scam,omitempty"`
	IsProxy            bool            `json:"is_proxy,omitempty"`
	Implementation     *Address        `json:"implementation,omitempty"`
	ImplementationName string          `json:"implementation_name,omitempty"`
	Balance            string          `json:"coin_balance,omitempty"`
	FetchedCoinBalance string          `json:"fetched_coin_balance,omitempty"`
	TransactionCount   *uint64         `json:"tx_count,omitempty"`
	TokenBalance       string          `json:"token_balance,omitempty"`
	TokenCount         *int            `json:"token_count,omitempty"`
	GasUsed            *uint64         `json:"gas_used,omitempty"`
	BlockNumberCreated *uint64         `json:"block_number_balance_updated_at,omitempty"`
	Creator            *Address        `json:"creator_address,omitempty"`
	CreationTxHash     string          `json:"creation_tx_hash,omitempty"`
	Token              *Token          `json:"token,omitempty"`
	HasDecompiledCode  bool            `json:"has_decompiled_code,omitempty"`
	HasValidatedBlocks bool            `json:"has_validated_blocks,omitempty"`
	HasLogs            bool            `json:"has_logs,omitempty"`
	HasTokenTransfers  bool            `json:"has_token_transfers,omitempty"`
	WatchlistNames     []WatchlistName `json:"watchlist_names,omitempty"`
	PrivateTags        []AddressTag    `json:"private_tags,omitempty"`
	PublicTags         []AddressTag    `json:"public_tags,omitempty"`
}

Address in explorer v2 format

type AddressEvent

type AddressEvent struct {
	Address string      `json:"address"`
	Type    string      `json:"type"` // transaction, token_transfer, balance
	Data    interface{} `json:"data"`
}

AddressEvent for address-specific notifications

type AddressSubscription

type AddressSubscription struct {
	Conn    *websocket.Conn
	Address string
}

AddressSubscription for managing address-specific subscriptions

type AddressTag

type AddressTag struct {
	Label       string `json:"label"`
	DisplayName string `json:"display_name"`
	Type        string `json:"address_tag,omitempty"`
	URL         string `json:"url,omitempty"`
}

AddressTag for public/private tagging

type BigInt

type BigInt big.Int

Helper for big.Int JSON handling

func (*BigInt) MarshalJSON

func (b *BigInt) MarshalJSON() ([]byte, error)

func (*BigInt) String

func (b *BigInt) String() string

func (*BigInt) UnmarshalJSON

func (b *BigInt) UnmarshalJSON(data []byte) error

type Block

type Block struct {
	Height             uint64        `json:"height"`
	Hash               string        `json:"hash"`
	ParentHash         string        `json:"parent_hash"`
	Timestamp          time.Time     `json:"timestamp"`
	TransactionCount   int           `json:"tx_count"`
	GasUsed            string        `json:"gas_used"`
	GasLimit           string        `json:"gas_limit"`
	BaseFeePerGas      string        `json:"base_fee_per_gas,omitempty"`
	BurntFees          string        `json:"burnt_fees,omitempty"`
	Priority           string        `json:"priority_fee,omitempty"`
	Size               uint64        `json:"size"`
	Miner              *Address      `json:"miner"`
	Nonce              string        `json:"nonce,omitempty"`
	Difficulty         string        `json:"difficulty,omitempty"`
	TotalDifficulty    string        `json:"total_difficulty,omitempty"`
	StateRoot          string        `json:"state_root,omitempty"`
	TransactionsRoot   string        `json:"transactions_root,omitempty"`
	ReceiptsRoot       string        `json:"receipts_root,omitempty"`
	Withdrawals        []Withdrawal  `json:"withdrawals,omitempty"`
	Rewards            []BlockReward `json:"rewards,omitempty"`
	Type               string        `json:"type"` // block, reorg, uncle
	Confirmations      int           `json:"confirmations,omitempty"`
	InternalTxsIndexed bool          `json:"has_internal_transactions"`
	TokenTransferCount int           `json:"token_transfer_count,omitempty"`
}

Block represents a block in explorer v2 format

type BlockFilters

type BlockFilters struct {
	Type string // block, reorg, uncle
}

BlockFilters for block listing

type BlockReward

type BlockReward struct {
	Type    string   `json:"type"` // block, uncle, emission
	Address *Address `json:"address"`
	Amount  string   `json:"amount"`
}

BlockReward represents a block reward

type ChainStats

type ChainStats struct {
	TotalBlocks         int64   `json:"total_blocks"`
	TotalTransactions   int64   `json:"total_transactions"`
	TotalAddresses      int64   `json:"total_addresses"`
	TotalContracts      int64   `json:"total_contracts,omitempty"`
	TotalTokens         int64   `json:"total_tokens,omitempty"`
	TotalTokenTransfers int64   `json:"total_token_transfers,omitempty"`
	AverageBlockTime    float64 `json:"average_block_time"`
	CoinPrice           string  `json:"coin_price,omitempty"`
	CoinPriceChange     float64 `json:"coin_price_change_percentage,omitempty"`
	TotalGasUsed        string  `json:"total_gas_used,omitempty"`
	GasPrice            string  `json:"gas_prices,omitempty"`
	NetworkUtilization  float64 `json:"network_utilization_percentage,omitempty"`
	TxnsToday           int64   `json:"transactions_today,omitempty"`
	MarketCap           string  `json:"market_cap,omitempty"`
	TVL                 string  `json:"tvl,omitempty"`
}

ChainStats for /v1/explorer/stats

type CoinBalanceEntry

type CoinBalanceEntry struct {
	BlockNumber uint64    `json:"block_number"`
	BlockHash   string    `json:"block_hash,omitempty"`
	Delta       string    `json:"delta,omitempty"`
	Value       string    `json:"value"`
	Timestamp   time.Time `json:"block_timestamp"`
	TxHash      string    `json:"transaction_hash,omitempty"`
}

CoinBalanceEntry represents a single balance history entry

type Config

type Config struct {
	HTTPPort    int
	ChainID     int64
	ChainName   string
	ChainSlug   string // table prefix, e.g. "cchain", "zoo", "hanzo"
	DatabaseURL string
	RPCEndpoint string
}

Config for the API server

type DailyBalanceEntry

type DailyBalanceEntry struct {
	Date  string `json:"date"`
	Value string `json:"value"`
}

DailyBalanceEntry represents balance aggregated by day

type DecodedInput

type DecodedInput struct {
	MethodID   string         `json:"method_id"`
	MethodCall string         `json:"method_call"`
	Parameters []DecodedParam `json:"parameters,omitempty"`
}

DecodedInput represents decoded function call

type DecodedLog

type DecodedLog struct {
	MethodID   string         `json:"method_id"`
	MethodCall string         `json:"method_call"`
	Parameters []DecodedParam `json:"parameters,omitempty"`
}

DecodedLog represents a decoded event

type DecodedParam

type DecodedParam struct {
	Name  string      `json:"name"`
	Type  string      `json:"type"`
	Value interface{} `json:"value"`
}

DecodedParam represents a decoded parameter

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error,omitempty"`
	Message string `json:"message,omitempty"`
}

Error response format

type GasPrice

type GasPrice struct {
	Slow    GasPriceTier `json:"slow"`
	Average GasPriceTier `json:"average"`
	Fast    GasPriceTier `json:"fast"`
}

GasPrice information

type GasPriceTier

type GasPriceTier struct {
	Price     string  `json:"price"`
	FiatPrice string  `json:"fiat_price,omitempty"`
	BaseFee   string  `json:"base_fee,omitempty"`
	Priority  string  `json:"priority_fee,omitempty"`
	Time      float64 `json:"time,omitempty"` // estimated seconds
}

GasPriceTier for gas estimates

type GraphQLError

type GraphQLError struct {
	Message   string                 `json:"message"`
	Locations []GraphQLErrorLocation `json:"locations,omitempty"`
	Path      []interface{}          `json:"path,omitempty"`
}

GraphQLError represents a GraphQL error

type GraphQLErrorLocation

type GraphQLErrorLocation struct {
	Line   int `json:"line"`
	Column int `json:"column"`
}

GraphQLErrorLocation represents error location in query

type GraphQLHandler

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

GraphQLHandler handles GraphQL requests

func NewGraphQLHandler

func NewGraphQLHandler(repo *Repository) *GraphQLHandler

NewGraphQLHandler creates a new GraphQL handler

func (*GraphQLHandler) Handle

func (h *GraphQLHandler) Handle(w http.ResponseWriter, r *http.Request)

Handle processes GraphQL requests

type GraphQLRequest

type GraphQLRequest struct {
	Query         string                 `json:"query"`
	OperationName string                 `json:"operationName"`
	Variables     map[string]interface{} `json:"variables"`
}

GraphQLRequest represents a GraphQL request

type GraphQLResponse

type GraphQLResponse struct {
	Data   interface{}    `json:"data,omitempty"`
	Errors []GraphQLError `json:"errors,omitempty"`
}

GraphQLResponse represents a GraphQL response

type IAMClaims

type IAMClaims struct {
	Sub           string `json:"sub"`
	Iss           string `json:"iss"`
	Aud           string `json:"aud"`
	Exp           int64  `json:"exp"`
	Iat           int64  `json:"iat"`
	Email         string `json:"email"`
	EmailVerified bool   `json:"emailVerified"`
	Name          string `json:"name"`
	DisplayName   string `json:"displayName"`
	Avatar        string `json:"avatar"`
}

IAMClaims represents the claims extracted from a validated JWT.

type IAMConfig

type IAMConfig struct {
	// ServerURL is the IAM OIDC issuer (e.g. https://hanzo.id).
	ServerURL string

	// ClientID is the expected audience in JWT tokens.
	ClientID string

	// Enabled controls whether IAM authentication is active.
	Enabled bool
}

IAMConfig holds configuration for the IAM OIDC middleware.

func IAMConfigFromEnv

func IAMConfigFromEnv() IAMConfig

IAMConfigFromEnv reads IAM configuration from environment variables.

type IAMMiddleware

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

IAMMiddleware provides JWT validation using OIDC discovery and JWKS.

func NewIAMMiddleware

func NewIAMMiddleware(cfg IAMConfig, accountSvc *account.Service) *IAMMiddleware

NewIAMMiddleware creates a new IAM OIDC middleware.

func (*IAMMiddleware) OptionalAuth

func (m *IAMMiddleware) OptionalAuth(next http.Handler) http.Handler

OptionalAuth returns a middleware that validates the JWT if present but does not reject unauthenticated requests. Useful for endpoints where auth is optional but enhances the response.

func (*IAMMiddleware) RequireAuth

func (m *IAMMiddleware) RequireAuth(next http.Handler) http.Handler

RequireAuth returns a middleware that requires a valid JWT bearer token. On success, the authenticated account.User is stored in the request context.

type Implementation

type Implementation struct {
	Address string `json:"address"`
	Name    string `json:"name,omitempty"`
}

Implementation for proxy contracts

type InternalTransaction

type InternalTransaction struct {
	TxHash      string     `json:"transaction_hash"`
	BlockNumber uint64     `json:"block_number"`
	BlockHash   string     `json:"block_hash,omitempty"`
	Index       int        `json:"index"`
	Timestamp   *time.Time `json:"timestamp,omitempty"`
	Type        string     `json:"type"`                // call, create, suicide, reward
	CallType    string     `json:"call_type,omitempty"` // call, delegatecall, staticcall
	From        *Address   `json:"from"`
	To          *Address   `json:"to,omitempty"`
	Value       string     `json:"value"`
	Gas         uint64     `json:"gas_limit"`
	GasUsed     *uint64    `json:"gas_used,omitempty"`
	Input       string     `json:"input,omitempty"`
	Output      string     `json:"output,omitempty"`
	Error       string     `json:"error,omitempty"`
	Success     *bool      `json:"success"` // nil = pending, true/false = finalized
	Created     *Address   `json:"created_contract,omitempty"`
}

InternalTransaction for traces

type Library

type Library struct {
	Name    string `json:"name"`
	Address string `json:"address_hash"`
}

Library for external libraries

type Log

type Log struct {
	TxHash      string      `json:"tx_hash"`
	BlockNumber uint64      `json:"block_number"`
	BlockHash   string      `json:"block_hash"`
	Index       int         `json:"index"`
	Address     *Address    `json:"address"`
	Data        string      `json:"data"`
	Topics      []string    `json:"topics"`
	Decoded     *DecodedLog `json:"decoded,omitempty"`
}

Log represents an event log

type NFT

type NFT struct {
	ID           string                 `json:"id"`
	Token        *Token                 `json:"token"`
	Metadata     map[string]interface{} `json:"metadata,omitempty"`
	Owner        *Address               `json:"owner,omitempty"`
	IsUnique     bool                   `json:"is_unique,omitempty"`
	ImageURL     string                 `json:"image_url,omitempty"`
	AnimationURL string                 `json:"animation_url,omitempty"`
	ExternalURL  string                 `json:"external_app_url,omitempty"`
}

NFT represents an NFT instance

type NextPageParams

type NextPageParams struct {
	BlockNumber      *uint64 `json:"block_number,omitempty"`
	Index            *int    `json:"index,omitempty"`
	ItemsCount       int     `json:"items_count,omitempty"`
	TransactionIndex *int    `json:"transaction_index,omitempty"`
	Hash             string  `json:"hash,omitempty"`
}

NextPageParams for cursor-based pagination

type PaginatedResponse

type PaginatedResponse struct {
	Items          interface{}     `json:"items"`
	NextPageParams *NextPageParams `json:"next_page_params,omitempty"`
}

PaginatedResponse wraps items with pagination info

type Pagination

type Pagination struct {
	Page      int `json:"page"`
	PageSize  int `json:"page_size"`
	TotalRows int `json:"total_rows"`
}

Pagination parameters

type RPCHandler

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

RPCHandler handles Etherscan-compatible API requests

func NewRPCHandler

func NewRPCHandler(repo *Repository) *RPCHandler

NewRPCHandler creates a new RPC handler

func (*RPCHandler) Handle

func (h *RPCHandler) Handle(w http.ResponseWriter, r *http.Request)

Handle processes RPC API requests

type RPCResponse

type RPCResponse struct {
	Status  string      `json:"status"`
	Message string      `json:"message"`
	Result  interface{} `json:"result"`
}

RPCResponse is the Etherscan-style API response

type Repository

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

Repository handles database queries for the API. The prefix field determines table names (e.g. "cchain" → cchain_blocks). This allows one PostgreSQL database to hold data for multiple EVM chains.

func NewRepository

func NewRepository(db *sql.DB, chainID int64, chainSlug ...string) *Repository

NewRepository creates a new repository with chain-specific table prefix. Defaults to "cchain" prefix when chainSlug is omitted.

func (*Repository) GetAddress

func (r *Repository) GetAddress(ctx context.Context, hash string) (*Address, error)

GetAddress returns address details

func (*Repository) GetAddressBalance

func (r *Repository) GetAddressBalance(ctx context.Context, address string) (string, error)

GetAddressBalance returns balance for Etherscan API

func (*Repository) GetAddressCoinBalanceByDay

func (r *Repository) GetAddressCoinBalanceByDay(ctx context.Context, address string, page, pageSize int) (*PaginatedResponse, error)

GetAddressCoinBalanceByDay returns coin balance history aggregated by day

func (*Repository) GetAddressCoinBalanceHistory

func (r *Repository) GetAddressCoinBalanceHistory(ctx context.Context, address string, page, pageSize int) (*PaginatedResponse, error)

GetAddressCoinBalanceHistory returns coin balance history for an address

func (*Repository) GetAddressTokenTransfers

func (r *Repository) GetAddressTokenTransfers(ctx context.Context, address string, page, pageSize int) (*PaginatedResponse, error)

GetAddressTokenTransfers returns token transfers for an address

func (*Repository) GetAddressTransactions

func (r *Repository) GetAddressTransactions(ctx context.Context, address string, page, pageSize int) (*PaginatedResponse, error)

GetAddressTransactions returns transactions for an address

func (*Repository) GetBlockByHash

func (r *Repository) GetBlockByHash(ctx context.Context, hash string) (*Block, error)

GetBlockByHash returns a block by hash

func (*Repository) GetBlockByNumber

func (r *Repository) GetBlockByNumber(ctx context.Context, height uint64) (*Block, error)

GetBlockByNumber returns a block by height

func (*Repository) GetBlocks

func (r *Repository) GetBlocks(ctx context.Context, page, pageSize int, filters *BlockFilters) (*PaginatedResponse, error)

GetBlocks returns paginated blocks

func (*Repository) GetInternalTransactions

func (r *Repository) GetInternalTransactions(ctx context.Context, txHash string, page, pageSize int) (*PaginatedResponse, error)

GetInternalTransactions returns internal transactions for a tx hash

func (*Repository) GetLogs

func (r *Repository) GetLogs(ctx context.Context, address string, fromBlock, toBlock uint64, topics []string, page, pageSize int) (*PaginatedResponse, error)

GetLogs returns event logs with filters

func (*Repository) GetSmartContract

func (r *Repository) GetSmartContract(ctx context.Context, address string) (*SmartContract, error)

GetSmartContract returns verified contract details

func (*Repository) GetStats

func (r *Repository) GetStats(ctx context.Context) (*ChainStats, error)

GetStats returns chain statistics

func (*Repository) GetToken

func (r *Repository) GetToken(ctx context.Context, address string) (*Token, error)

GetToken returns token details

func (*Repository) GetTokens

func (r *Repository) GetTokens(ctx context.Context, page, pageSize int, tokenType string) (*PaginatedResponse, error)

GetTokens returns paginated tokens

func (*Repository) GetTransactionByHash

func (r *Repository) GetTransactionByHash(ctx context.Context, hash string) (*Transaction, error)

GetTransactionByHash returns a transaction by hash

func (*Repository) GetTransactions

func (r *Repository) GetTransactions(ctx context.Context, page, pageSize int, filters *TransactionFilters) (*PaginatedResponse, error)

GetTransactions returns paginated transactions

func (*Repository) GetTransactionsByBlock

func (r *Repository) GetTransactionsByBlock(ctx context.Context, blockNumber uint64, page, pageSize int) (*PaginatedResponse, error)

GetTransactionsByBlock returns transactions for a block

func (*Repository) Search

func (r *Repository) Search(ctx context.Context, query string, limit int) ([]SearchResult, error)

Search performs universal search

func (*Repository) Tbl

func (r *Repository) Tbl(name string) string

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

type SearchResult

type SearchResult struct {
	Type            string  `json:"type"` // address, contract, token, transaction, block, ens
	Address         string  `json:"address,omitempty"`
	Hash            string  `json:"hash,omitempty"`
	BlockNumber     *uint64 `json:"block_number,omitempty"`
	Name            string  `json:"name,omitempty"`
	Symbol          string  `json:"symbol,omitempty"`
	TokenType       string  `json:"token_type,omitempty"`
	ExchangeRate    string  `json:"exchange_rate,omitempty"`
	IsSmartContract bool    `json:"is_smart_contract_verified,omitempty"`
	URL             string  `json:"url,omitempty"`
	Priority        int     `json:"priority,omitempty"`
}

SearchResult for universal search

type Server

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

Server provides REST, RPC, GraphQL and WebSocket APIs

func NewServer

func NewServer(cfg Config, db *sql.DB) *Server

NewServer creates a new API server

func (*Server) BroadcastBlock

func (s *Server) BroadcastBlock(block *Block)

BroadcastBlock sends a new block to all subscribers

func (*Server) BroadcastTransaction

func (s *Server) BroadcastTransaction(tx *Transaction)

BroadcastTransaction sends a new transaction to subscribers

func (*Server) Router

func (s *Server) Router() *mux.Router

Router returns the HTTP router for testing

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run starts the API server

type SmartContract

type SmartContract struct {
	Address                string           `json:"address_hash"`
	Name                   string           `json:"name,omitempty"`
	CompilerVersion        string           `json:"compiler_version,omitempty"`
	OptimizationEnabled    bool             `json:"optimization_enabled"`
	OptimizationRuns       int              `json:"optimization_runs,omitempty"`
	EVMVersion             string           `json:"evm_version,omitempty"`
	SourceCode             string           `json:"source_code,omitempty"`
	ABI                    json.RawMessage  `json:"abi,omitempty"`
	ConstructorArgs        string           `json:"constructor_arguments,omitempty"`
	DecodedConstructorArgs []DecodedParam   `json:"decoded_constructor_arguments,omitempty"`
	IsVerified             bool             `json:"is_verified"`
	VerifiedAt             *time.Time       `json:"verified_at,omitempty"`
	IsProxy                bool             `json:"is_proxy"`
	ProxyType              string           `json:"proxy_type,omitempty"`
	Implementations        []Implementation `json:"implementations,omitempty"`
	ContractSourceCode     []SourceFile     `json:"contract_source_code,omitempty"`
	ExternalLibraries      []Library        `json:"external_libraries,omitempty"`
	Language               string           `json:"language,omitempty"` // solidity, vyper
	LicenseType            string           `json:"license_type,omitempty"`
	IsFullMatch            bool             `json:"is_fully_verified"`
	IsPartialMatch         bool             `json:"is_partially_verified,omitempty"`
}

SmartContract in explorer v2 format

type SourceFile

type SourceFile struct {
	FileName   string `json:"file_name"`
	SourceCode string `json:"source_code"`
}

SourceFile for multi-file contracts

type Token

type Token struct {
	Address        string  `json:"address"`
	Name           string  `json:"name"`
	Symbol         string  `json:"symbol"`
	Decimals       *uint8  `json:"decimals,omitempty"`
	TotalSupply    string  `json:"total_supply,omitempty"`
	CirculatingCap string  `json:"circulating_market_cap,omitempty"`
	Type           string  `json:"type"` // ERC-20, ERC-721, ERC-1155
	HolderCount    *uint64 `json:"holders,omitempty"`
	TransferCount  *uint64 `json:"transfers_count,omitempty"`
	ExchangeRate   string  `json:"exchange_rate,omitempty"`
	IconURL        string  `json:"icon_url,omitempty"`
	Volume24h      string  `json:"volume_24h,omitempty"`
	IsVerified     bool    `json:"is_verified_via_admin_panel,omitempty"`
}

Token in explorer v2 format

type TokenBalance

type TokenBalance struct {
	Token         *Token `json:"token"`
	TokenID       string `json:"token_id,omitempty"`
	Value         string `json:"value"`
	TokenInstance *NFT   `json:"token_instance,omitempty"`
}

TokenBalance for address token holdings

type TokenTotal

type TokenTotal struct {
	Value    string `json:"value,omitempty"`
	Decimals *uint8 `json:"decimals,omitempty"`
	TokenID  string `json:"token_id,omitempty"`
}

TokenTotal for transfer value/tokenId

type TokenTransfer

type TokenTransfer struct {
	TxHash      string      `json:"tx_hash"`
	BlockHash   string      `json:"block_hash,omitempty"`
	BlockNumber uint64      `json:"block_number"`
	LogIndex    int         `json:"log_index"`
	Timestamp   *time.Time  `json:"timestamp,omitempty"`
	From        *Address    `json:"from"`
	To          *Address    `json:"to"`
	Token       *Token      `json:"token"`
	TokenID     string      `json:"token_id,omitempty"`
	Total       *TokenTotal `json:"total,omitempty"`
	TokenIDs    []string    `json:"token_ids,omitempty"` // ERC-1155 batch
	Amounts     []string    `json:"amounts,omitempty"`   // ERC-1155 batch
	Type        string      `json:"type,omitempty"`      // token_minting, token_burning, token_transfer
	Method      string      `json:"method,omitempty"`
}

TokenTransfer in explorer v2 format

type Transaction

type Transaction struct {
	Hash                string          `json:"hash"`
	BlockHash           string          `json:"block_hash,omitempty"`
	BlockNumber         *uint64         `json:"block_number,omitempty"`
	Timestamp           *time.Time      `json:"timestamp,omitempty"`
	Confirmations       int             `json:"confirmations,omitempty"`
	From                *Address        `json:"from"`
	To                  *Address        `json:"to,omitempty"`
	CreatedContract     *Address        `json:"created_contract,omitempty"`
	Value               string          `json:"value"`
	Gas                 uint64          `json:"gas_limit"`
	GasPrice            string          `json:"gas_price"`
	GasUsed             *uint64         `json:"gas_used,omitempty"`
	MaxFeePerGas        string          `json:"max_fee_per_gas,omitempty"`
	MaxPriorityFee      string          `json:"max_priority_fee_per_gas,omitempty"`
	BaseFee             string          `json:"base_fee_per_gas,omitempty"`
	TransactionFee      string          `json:"fee,omitempty"`
	BurntFee            string          `json:"tx_burnt_fee,omitempty"`
	Nonce               uint64          `json:"nonce"`
	Position            *int            `json:"position,omitempty"`
	TransactionIndex    *int            `json:"transaction_index,omitempty"`
	Input               string          `json:"raw_input"`
	DecodedInput        *DecodedInput   `json:"decoded_input,omitempty"`
	Type                int             `json:"type"`
	Status              string          `json:"status,omitempty"` // ok, error, pending
	Result              string          `json:"result,omitempty"` // success, revert, out of gas
	RevertReason        string          `json:"revert_reason,omitempty"`
	Method              string          `json:"method,omitempty"`
	TokenTransfers      []TokenTransfer `json:"token_transfers,omitempty"`
	TokenTransferCount  int             `json:"token_transfers_count,omitempty"`
	InternalTxsCount    int             `json:"internal_txs_count,omitempty"`
	ExchangeRate        string          `json:"exchange_rate,omitempty"`
	Actions             []TxAction      `json:"actions,omitempty"`
	HasErrorInternalTxs bool            `json:"has_error_in_internal_txs"`
}

Transaction in explorer v2 format

type TransactionFilters

type TransactionFilters struct {
	Type   string // transaction type filter
	Method string // method filter
}

TransactionFilters for transaction listing

type TxAction

type TxAction struct {
	Protocol string                 `json:"protocol"`
	Type     string                 `json:"type"`
	Data     map[string]interface{} `json:"data"`
}

TxAction represents a transaction action (swap, bridge, etc.)

type WatchlistName

type WatchlistName struct {
	Label       string `json:"label"`
	DisplayName string `json:"display_name"`
}

WatchlistName for user's address labels

type WebSocketHub

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

WebSocketHub manages WebSocket connections and message broadcasting

func NewWebSocketHub

func NewWebSocketHub() *WebSocketHub

NewWebSocketHub creates a new WebSocket hub

func (*WebSocketHub) BroadcastAddressEvent

func (h *WebSocketHub) BroadcastAddressEvent(address, eventType string, data interface{})

BroadcastAddressEvent sends an event to address-specific subscribers

func (*WebSocketHub) BroadcastBlock

func (h *WebSocketHub) BroadcastBlock(block *Block)

BroadcastBlock sends a new block to all block subscribers

func (*WebSocketHub) BroadcastTokenTransfer

func (h *WebSocketHub) BroadcastTokenTransfer(transfer *TokenTransfer)

BroadcastTokenTransfer notifies address subscribers of token transfers

func (*WebSocketHub) BroadcastTransaction

func (h *WebSocketHub) BroadcastTransaction(tx *Transaction)

BroadcastTransaction sends a new transaction to all transaction subscribers

func (*WebSocketHub) RegisterAddressClient

func (h *WebSocketHub) RegisterAddressClient(conn *websocket.Conn, address string)

RegisterAddressClient registers a client for address-specific updates

func (*WebSocketHub) RegisterBlockClient

func (h *WebSocketHub) RegisterBlockClient(conn *websocket.Conn)

RegisterBlockClient registers a client for block updates

func (*WebSocketHub) RegisterTransactionClient

func (h *WebSocketHub) RegisterTransactionClient(conn *websocket.Conn)

RegisterTransactionClient registers a client for transaction updates

func (*WebSocketHub) Run

func (h *WebSocketHub) Run(ctx context.Context)

Run starts the hub's message processing

func (*WebSocketHub) Stats

func (h *WebSocketHub) Stats() map[string]interface{}

Stats returns current connection statistics

type WebSocketMessage

type WebSocketMessage struct {
	Type      string      `json:"type"`
	Data      interface{} `json:"data,omitempty"`
	Timestamp int64       `json:"timestamp"`
}

WebSocketMessage is the base message format

type Withdrawal

type Withdrawal struct {
	Index          uint64   `json:"index"`
	ValidatorIndex uint64   `json:"validator_index"`
	Address        *Address `json:"address"`
	Amount         string   `json:"amount"`
}

Withdrawal represents a beacon chain withdrawal

Jump to

Keyboard shortcuts

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