common

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: Apache-2.0 Imports: 26 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	RollingLogLevelFlag        = "rolling-log-level"
	RollingLogMaxSizeFlag      = "rolling-log-max-size"
	RollingLogMaxAgeFlag       = "rolling-log-max-age"
	RollingLogBackupsFlag      = "rolling-log-backups"
	RollingLogFileLocationFlag = "rolling-log-file-location"
	RollingLogFormat           = "rolling-log-format"
)
View Source
const (
	ProcessStartLogText = "Process Started"
	// cors related flags
	CorsHeadersFlag         = "cors-headers"           // comma separated list of headers, or * for all, default simple cors specification headers
	CorsCredentialsFlag     = "cors-credentials"       // comma separated list of headers, or * for all, default simple cors specification headers
	CorsOriginFlag          = "cors-origin"            // comma separated list of origins, or * for all, default enabled completely
	CorsMethodsFlag         = "cors-methods"           // comma separated list of methods, default "GET,POST,PUT,DELETE,OPTIONS"
	CDNCacheDurationFlag    = "cdn-cache-duration"     // how long to cache the preflight response default 24 hours (in seconds) "86400"
	RelaysHealthEnableFlag  = "relays-health-enable"   // enable relays health check, default true
	RelayHealthIntervalFlag = "relays-health-interval" // interval between each relay health check, default 5m
	SharedStateFlag         = "shared-state"
	// Disable relay retries when we get node errors.
	// This feature is suppose to help with successful relays in some chains that return node errors on rare race conditions on the serviced chains.
	SetRelayCountOnNodeErrorFlag = "set-retry-count-on-node-error"
	// SetRelayRetryLimitFlag controls the maximum number of retry attempts on relay errors
	// (both node errors and protocol errors) for consumers and smart routers.
	SetRelayRetryLimitFlag = "set-relay-retry-limit"
	// BatchNodeErrorOnAny controls batch request error detection for JSON-RPC batch requests
	BatchNodeErrorOnAnyFlag = "batch-node-error-on-any"

	// UseStaticSpecFlag allows loading specs from various sources instead of the blockchain.
	// This flag can be specified multiple times to aggregate specs from multiple sources.
	// Later sources override earlier ones for the same chain ID (last-wins).
	//
	// Supported formats:
	//   - Local file:      --use-static-spec ./specs/eth.json
	//   - Local directory: --use-static-spec ./specs/
	//   - GitHub URL:      --use-static-spec https://github.com/owner/repo/tree/branch/path/to/specs
	//   - GitLab URL:      --use-static-spec https://gitlab.com/owner/repo/-/tree/branch/path/to/specs
	//
	// Multiple local files can be specified either as separate flags or comma-separated:
	//   --use-static-spec file1.json --use-static-spec file2.json
	//   --use-static-spec file1.json,file2.json
	//
	// Example with multiple sources (order matters - later overrides earlier):
	//   --use-static-spec https://github.com/magma-Devs/smart-router-specs/tree/main/specs \
	//   --use-static-spec https://gitlab.com/myorg/specs/-/tree/main \
	//   --use-static-spec ./local-overrides/
	//
	// For private GitHub/GitLab repositories, use the corresponding token flag.
	UseStaticSpecFlag = "use-static-spec"

	// GitHubTokenFlag is a GitHub personal access token for accessing private repositories.
	// Also provides higher API rate limits (5,000 requests/hour vs 60 for unauthenticated).
	// Required URL format: https://github.com/{owner}/{repo}/tree/{branch}/{path}
	// Example: --github-token ghp_xxxxxxxxxxxx
	GitHubTokenFlag = "github-token"

	// GitLabTokenFlag is a GitLab personal access token for accessing private repositories.
	// Supports both gitlab.com and self-hosted GitLab instances.
	// The token must have at least "Reporter" role with "read_repository" scope.
	// Required URL format: https://gitlab.com/{owner}/{repo}/-/tree/{branch}/{path}
	// Example: --gitlab-token glpat-xxxxxxxxxxxx
	GitLabTokenFlag = "gitlab-token"

	EpochDurationFlag       = "epoch-duration" // duration of each epoch for time-based epoch system (standalone mode)
	DefaultEpochDuration    = 30 * time.Minute // default epoch duration for regular mode (if using time-based epochs)
	StandaloneEpochDuration = 15 * time.Minute // default epoch duration for standalone/static provider mode

	// ShutdownGracePeriodFlag controls how long graceful shutdown waits for in-flight
	// requests and WebSocket clients to finish before forcing exit. Default 25s leaves
	// a 5s margin under Kubernetes' default terminationGracePeriodSeconds of 30s.
	ShutdownGracePeriodFlag        = "shutdown-grace-period"
	DefaultShutdownGracePeriod     = 25 * time.Second
	EnableSelectionStatsHeaderFlag = "enable-selection-stats" // enable selection stats header for debugging provider selection // allows the user to manually load a spec providing a path, this is useful to test spec changes before they hit the blockchain

	// weighted selection flags (new system replacing tiers)
	UseWeightedSelection                = "use-weighted-provider-selection"         // enable weighted random selection based on composite QoS scores
	ProviderOptimizerAvailabilityWeight = "provider-optimizer-availability-weight"  // weight for availability score (default: 0.4)
	ProviderOptimizerLatencyWeight      = "provider-optimizer-latency-weight"       // weight for latency score (default: 0.3)
	ProviderOptimizerSyncWeight         = "provider-optimizer-sync-weight"          // weight for sync score (default: 0.2)
	ProviderOptimizerStakeWeight        = "provider-optimizer-stake-weight"         // weight for stake (default: 0.1)
	ProviderOptimizerMinSelectionChance = "provider-optimizer-min-selection-chance" // minimum selection probability for any provider (default: 0.01)

	// optimizer qos server flags
	OptimizerQosServerAddressFlag          = "optimizer-qos-server-address"    // address of the optimizer qos server to send the qos reports
	OptimizerQosListenFlag                 = "optimizer-qos-listen"            // enable listening for qos reports on metrics endpoint
	OptimizerQosServerPushIntervalFlag     = "optimizer-qos-push-interval"     // interval to push the qos reports to the optimizer qos server
	OptimizerQosServerSamplingIntervalFlag = "optimizer-qos-sampling-interval" // interval to sample the qos reports
	// websocket flags
	RateLimitWebSocketFlag                       = "rate-limit-websocket-requests-per-connection"
	BanDurationForWebsocketRateLimitExceededFlag = "ban-duration-for-websocket-rate-limit-exceeded"
	LimitParallelWebsocketConnectionsPerIpFlag   = "limit-parallel-websocket-connections-per-ip"
	LimitWebsocketIdleTimeFlag                   = "limit-websocket-connection-idle-time"
	RateLimitRequestPerSecondFlag                = "rate-limit-requests-per-second"
	SkipWebsocketVerificationFlag                = "skip-websocket-verification"
	// specification default flags
	PeriodicProbeProvidersFlagName         = "enable-periodic-probe-providers"
	PeriodicProbeProvidersIntervalFlagName = "periodic-probe-providers-interval"
	ProbeUpdateWeightFlagName              = "probe-update-weight"

	// batch request size limit
	MaxBatchRequestSizeFlag        = "max-batch-request-size"
	DefaultMaxBatchRequestSize int = 0 // 0 means unlimited

	// DisableBatchRequestRetryFlag prevents batch requests from being retried on consumer/smartrouter side
	DisableBatchRequestRetryFlag = "disable-batch-request-retry"

	ShowProviderEndpointInMetricsFlagName = "show-provider-address-in-metrics"

	MemoryGCThresholdGBFlagName      = "memory-gc-threshold-gb"     // Memory GC threshold in GB (0 = disabled)
	MaxSessionsPerProviderFlagName   = "max-sessions-per-provider"  // Max number of sessions allowed per provider
	DefaultProcessingTimeoutFlagName = "default-processing-timeout" // default timeout for relay processing
	MinRelayTimeoutFlagName          = "min-relay-timeout"          // minimum relay timeout floor (default 1s)

	// ResponseCompressionFlag controls the encoding used by the fiber compress
	// middleware on client-facing responses. Accepted values: "gzip", "brotli", "off".
	// Default is "gzip" because brotli in Go (andybalholm/brotli) costs ~3x more CPU
	// than gzip for similar wire savings on typical JSON-RPC payloads.
	ResponseCompressionFlag    = "response-compression"
	ResponseCompressionGzip    = "gzip"
	ResponseCompressionBrotli  = "brotli"
	ResponseCompressionOff     = "off"
	DefaultResponseCompression = ResponseCompressionGzip
)
View Source
const (
	CONSISTENCY_SELECT_ALL_PROVIDERS = 1
	NO_STATE                         = 0
)
View Source
const (
	PlainTextConnection                = "allow-plaintext-connection"
	EndpointsConfigName                = "endpoints"
	DirectRPCConfigName                = "direct-rpc"
	BackupDirectRPCConfigName          = "backup-direct-rpc"
	StaticProvidersConfigName          = "static-providers" // Deprecated: use DirectRPCConfigName
	BackupProvidersConfigName          = "backup-providers" // Deprecated: use BackupDirectRPCConfigName
	SaveConfigFlagName                 = "save-conf"
	GeolocationFlag                    = "geolocation"
	TestModeFlagName                   = "test-mode"
	MaximumConcurrentProvidersFlagName = "concurrent-providers"
	StatusCodeMetadataKey              = "status-code"
	VersionMetadataKey                 = "lavap-version"
	LavaChainIdMetadataKey             = "lavap-chain-id"
	TimeOutForFetchingLavaBlocksFlag   = "timeout-for-fetching-lava-blocks"
)
View Source
const (
	URL_QUERY_PARAMETERS_SEPARATOR_FROM_PATH        = "?"
	URL_QUERY_PARAMETERS_SEPARATOR_OTHER_PARAMETERS = "&"
	IP_FORWARDING_HEADER_NAME                       = "X-Forwarded-For"
	PROVIDER_ADDRESS_HEADER_NAME                    = "Lava-Provider-Address"
	RETRY_COUNT_HEADER_NAME                         = "Lava-Retries"
	PROVIDER_LATEST_BLOCK_HEADER_NAME               = "Provider-Latest-Block"
	GUID_HEADER_NAME                                = "Lava-Guid"
	ERRORED_PROVIDERS_HEADER_NAME                   = "Lava-Errored-Providers"
	NODE_ERRORS_PROVIDERS_HEADER_NAME               = "Lava-Node-Errors-providers"
	REPORTED_PROVIDERS_HEADER_NAME                  = "Lava-Reported-Providers"
	LAVA_RELAY_PROTOCOL_HEADER_NAME                 = "Lava-Relay-Protocol"
	USER_REQUEST_TYPE                               = "lava-user-request-type"
	STATEFUL_API_HEADER                             = "lava-stateful-api"
	STATEFUL_ALL_PROVIDERS_HEADER_NAME              = "lava-fast-tx-participants"
	REQUESTED_BLOCK_HEADER_NAME                     = "lava-parsed-requested-block"
	LAVA_IDENTIFIED_NODE_ERROR_HEADER               = "lava-identified-node-error"
	LAVA_HEDGE_TRIGGERED_HEADER                     = "lava-hedge-triggered"
	SMART_ROUTER_VERSION_HEADER_NAME                = "Smart-Router-Version"
	LAVA_CONSUMER_PROCESS_GUID                      = "lava-consumer-process-guid"
	// these headers need to be lowercase
	BLOCK_PROVIDERS_ADDRESSES_HEADER_NAME       = "lava-providers-block"
	RELAY_TIMEOUT_HEADER_NAME                   = "lava-relay-timeout"
	EXTENSION_OVERRIDE_HEADER_NAME              = "lava-extension"
	FORCE_CACHE_REFRESH_HEADER_NAME             = "lava-force-cache-refresh"
	LAVA_DEBUG_RELAY                            = "lava-debug-relay"
	LAVA_LB_UNIQUE_ID_HEADER                    = "lava-lb-unique-id"
	SELECTION_STATS_HEADER_NAME                 = "lava-selection-stats"
	STICKINESS_HEADER_NAME                      = "lava-stickiness"
	SELECT_PROVIDER_HEADER_NAME                 = "lava-select-provider"
	CROSS_VALIDATION_HEADER_MAX_PARTICIPANTS    = "lava-cross-validation-max-participants"
	CROSS_VALIDATION_HEADER_AGREEMENT_THRESHOLD = "lava-cross-validation-agreement-threshold"
	CROSS_VALIDATION_ALL_PROVIDERS_HEADER_NAME  = "lava-cross-validation-all-providers"
	CROSS_VALIDATION_STATUS_HEADER_NAME         = "lava-cross-validation-status"
	CROSS_VALIDATION_AGREEING_PROVIDERS_HEADER  = "lava-cross-validation-agreeing-providers"
	// send http request to /lava/health to see if the process is up - (ret code 200)
	DEFAULT_HEALTH_PATH                                       = "/lava/health"
	MAXIMUM_ALLOWED_TIMEOUT_EXTEND_MULTIPLIER_BY_THE_CONSUMER = 4
)
View Source
const (
	GrpcDescriptorSourceReflection = "reflection"
	GrpcDescriptorSourceFile       = "file"
	GrpcDescriptorSourceHybrid     = "hybrid"
)

GrpcDescriptorSource constants for DescriptorSource field

View Source
const (
	// JSON-RPC error patterns
	JSONRPCMethodNotFound     = "method not found"
	JSONRPCMethodNotSupported = "method not supported"
	JSONRPCUnknownMethod      = "unknown method"
	JSONRPCMethodDoesNotExist = "method does not exist"
	JSONRPCInvalidMethod      = "invalid method"
	JSONRPCErrorCode          = "-32601" // JSON-RPC 2.0 method not found error code

	// Generic unsupported patterns (catch-all for "method X not supported" format)
	GenericNotSupported = "not supported"

	// REST API error patterns
	RESTEndpointNotFound = "endpoint not found"
	RESTRouteNotFound    = "route not found"
	RESTPathNotFound     = "path not found"
	RESTMethodNotAllowed = "method not allowed"

	// gRPC error patterns
	GRPCMethodNotImplemented = "method not implemented"
	GRPCUnimplemented        = "unimplemented"
	GRPCNotImplemented       = "not implemented"
	GRPCServiceNotFound      = "service not found"

	// HTTP status codes for unsupported endpoints
	HTTPStatusNotFound         = 404
	HTTPStatusMethodNotAllowed = 405

	// JSON-RPC error code for method not found
	JSONRPCMethodNotFoundCode = -32601

	// JSON-RPC error code for invalid params
	JSONRPCInvalidParamsCode = -32602

	// Solana non-retryable error codes
	// - Error code -32009: Slot was skipped or missing in long-term storage (permanent)
	// Note: -32007 (ledger jump to snapshot) IS retryable as another provider may have the data
	SolanaMissingInLongTermStorageCode = -32009

	// Solana non-retryable error patterns (message-based)
	SolanaMissingInLongTermStorage = "missing in long-term storage"
)

Error pattern constants for unsupported method detection

View Source
const (
	// MaxIdleConns controls the maximum number of idle (keep-alive) connections across all hosts.
	// For 1000 req/s with ~500ms latency, we need ~500 concurrent connections.
	// Setting higher to allow headroom for spikes.
	// Go default: 100
	DefaultMaxIdleConns = 1000

	// MaxIdleConnsPerHost controls the maximum idle (keep-alive) connections to keep per-host.
	// This is critical for blockchain node connections where we repeatedly connect to the same node.
	// For 1000 req/s to a single host with ~500ms latency, need ~500 idle connections.
	// Go default: 2 (way too low for high-concurrency!)
	DefaultMaxIdleConnsPerHost = 500

	// MaxConnsPerHost limits the total number of connections per host, including those in active use.
	// This is the CRITICAL limit - if too low, requests will queue and cause cascading latency.
	// For 1000 req/s with ~1s worst-case latency, need up to 1000 connections.
	// Go default: 0 (unlimited - can cause node overload)
	DefaultMaxConnsPerHost = 0 // unlimited - let the upstream node enforce its own limits

	// IdleConnTimeout is the maximum amount of time an idle connection will remain idle before closing.
	// Keeps connections alive for reuse but eventually closes them to avoid resource leaks.
	// Go default: 90s
	DefaultIdleConnTimeout = 90 * time.Second

	// TLSHandshakeTimeout is the maximum amount of time waiting to perform a TLS handshake.
	// Go default: 10s
	DefaultTLSHandshakeTimeout = 10 * time.Second

	// ExpectContinueTimeout limits the time the client will wait between sending the request headers
	// and receiving the go-ahead to send the request body.
	// Go default: 1s
	DefaultExpectContinueTimeout = 1 * time.Second

	// ResponseHeaderTimeout is the amount of time to wait for a server's response headers.
	// This should be relatively high for blockchain nodes as they may be slow under load.
	// Go default: 0 (no timeout - can hang forever)
	DefaultResponseHeaderTimeout = 0

	// DialTimeout is the maximum amount of time a dial will wait for a connect to complete.
	// Go default: 30s
	DefaultDialTimeout = 10 * time.Second

	// KeepAlive specifies the interval between keep-alive probes for an active network connection.
	// Go default: 30s
	DefaultKeepAlive = 30 * time.Second

	// DefaultHTTPTimeout is the default timeout for the entire request/response cycle.
	// Set to 5 minutes to handle slow blockchain node operations like trace_block.
	// Go default: 0 (no timeout - requests can hang forever)
	DefaultHTTPTimeout = 5 * time.Minute

	// DefaultTLSSessionCacheSize is the number of TLS session tickets to cache.
	// This enables TLS session resumption, which skips the expensive certificate
	// verification on subsequent connections to the same host.
	// Each cached session saves ~10-15% CPU on TLS handshakes.
	DefaultTLSSessionCacheSize = 1024
)

HTTP Connection Pool Configuration These values are optimized for high-throughput scenarios (1000+ req/s) where providers handle many simultaneous requests to blockchain nodes.

View Source
const (
	TimePerCU                           = uint64(100 * time.Millisecond)
	CacheWriteTimeout                   = 5 * time.Second
	AverageWorldLatency                 = 300 * time.Millisecond
	CommunicateWithLocalLavaNodeTimeout = (3 * time.Second) + AverageWorldLatency
	DefaultTimeoutSeconds               = 30 // default timeout in seconds, can be overridden by flag
	CacheTimeout                        = 50 * time.Millisecond
	// On subscriptions we must use context.Background(),
	// we cant have a context.WithTimeout() context, meaning we can hang for ever.
	// to avoid that we introduced a first reply timeout using a routine.
	// if the first reply doesn't return after the specified timeout a timeout error will occur
	SubscriptionFirstReplyTimeout = 10 * time.Second
)

Variables

View Source
var (
	// Connection errors (1001-1009)
	LavaErrorConnectionTimeout = registerError(&LavaError{
		Code: 1001, Name: "PROTOCOL_CONNECTION_TIMEOUT", Category: CategoryInternal,
		Description: "Network operation timed out connecting to provider", Retryable: true,
	})
	LavaErrorConnectionRefused = registerError(&LavaError{
		Code: 1002, Name: "PROTOCOL_CONNECTION_REFUSED", Category: CategoryInternal,
		Description: "Provider connection refused", Retryable: true,
	})
	LavaErrorDNSFailure = registerError(&LavaError{
		Code: 1003, Name: "PROTOCOL_DNS_FAILURE", Category: CategoryInternal,
		Description: "DNS resolution failed", Retryable: true,
	})
	LavaErrorTLSMismatch = registerError(&LavaError{
		Code: 1004, Name: "PROTOCOL_TLS_MISMATCH", Category: CategoryInternal,
		Description: "HTTP/HTTPS protocol mismatch", Retryable: false,
	})
	LavaErrorConnectionReset = registerError(&LavaError{
		Code: 1005, Name: "PROTOCOL_CONNECTION_RESET", Category: CategoryInternal,
		Description: "Connection reset by peer", Retryable: true,
	})
	LavaErrorConnectionClosed = registerError(&LavaError{
		Code: 1006, Name: "PROTOCOL_CONNECTION_CLOSED", Category: CategoryInternal,
		Description: "Connection closed (EOF)", Retryable: true,
	})
	LavaErrorNetworkUnreachable = registerError(&LavaError{
		Code: 1009, Name: "PROTOCOL_NETWORK_UNREACHABLE", Category: CategoryInternal,
		Description: "Network or host unreachable (no route)", Retryable: true,
	})
	LavaErrorContextDeadline = registerError(&LavaError{
		Code: 1007, Name: "PROTOCOL_CONTEXT_DEADLINE", Category: CategoryInternal,
		Description: "Caller's context.Context deadline expired before the relay completed (can fire at any layer — consumer request timeout, processing timeout, subrequest timeout)", Retryable: true,
	})
	LavaErrorContextCanceled = registerError(&LavaError{
		Code: 1008, Name: "PROTOCOL_CONTEXT_CANCELED", Category: CategoryInternal,
		Description: "Request context was canceled (client disconnect or relay race resolved)", Retryable: false,
	})

	// Provider availability (1010-1019)
	LavaErrorNoProviders = registerError(&LavaError{
		Code: 1010, Name: "PROTOCOL_NO_PROVIDERS", Category: CategoryInternal,
		Description: "No providers/pairings available", Retryable: false,
	})
	LavaErrorAllEndpointsDisabled = registerError(&LavaError{
		Code: 1011, Name: "PROTOCOL_ALL_ENDPOINTS_DISABLED", Category: CategoryInternal,
		Description: "All provider endpoints disabled", Retryable: false,
	})
	LavaErrorProviderUnavailable = registerError(&LavaError{
		Code: 1012, Name: "PROTOCOL_PROVIDER_UNAVAILABLE", Category: CategoryInternal,
		Description: "Provider service unavailable (gRPC UNAVAILABLE)", Retryable: true,
	})
	LavaErrorProviderAborted = registerError(&LavaError{
		Code: 1013, Name: "PROTOCOL_PROVIDER_ABORTED", Category: CategoryInternal,
		Description: "Provider aborted (gRPC ABORTED)", Retryable: true,
	})
	LavaErrorProviderDataLoss = registerError(&LavaError{
		Code: 1014, Name: "PROTOCOL_PROVIDER_DATA_LOSS", Category: CategoryInternal,
		Description: "Provider data loss (gRPC DATA_LOSS)", Retryable: true,
	})
	LavaErrorInsufficientProviders = registerError(&LavaError{
		Code: 1015, Name: "PROTOCOL_INSUFFICIENT_PROVIDERS", Category: CategoryInternal,
		Description: "Insufficient providers available for addon or cross-validation", Retryable: false,
	})

	// Rate limiting / CU (1020-1029)
	LavaErrorRateLimited = registerError(&LavaError{
		Code: 1020, Name: "PROTOCOL_RATE_LIMITED", Category: CategoryInternal,
		SubCategory: SubCategoryRateLimit,
		Description: "Lava-side rate limit exceeded", Retryable: false,
	})
	LavaErrorMaxCUExceeded = registerError(&LavaError{
		Code: 1021, Name: "PROTOCOL_MAX_CU_EXCEEDED", Category: CategoryInternal,
		Description: "Maximum compute units exceeded for session", Retryable: false,
	})
	LavaErrorBatchSizeExceeded = registerError(&LavaError{
		Code: 1022, Name: "PROTOCOL_BATCH_SIZE_EXCEEDED", Category: CategoryInternal,
		Description: "Batch request size exceeded limit", Retryable: false,
	})
	LavaErrorCUMismatch = registerError(&LavaError{
		Code: 1023, Name: "PROTOCOL_CU_MISMATCH", Category: CategoryInternal,
		Description: "CU accounting inconsistency or security violation", Retryable: false,
	})

	// Session errors (1030-1039)
	LavaErrorSessionNotFound = registerError(&LavaError{
		Code: 1030, Name: "PROTOCOL_SESSION_NOT_FOUND", Category: CategoryInternal,
		Description: "Session does not exist", Retryable: false,
	})
	LavaErrorEpochMismatch = registerError(&LavaError{
		Code: 1031, Name: "PROTOCOL_EPOCH_MISMATCH", Category: CategoryInternal,
		Description: "Epoch mismatch or too old", Retryable: false,
	})
	LavaErrorConsumerBlocked = registerError(&LavaError{
		Code: 1032, Name: "PROTOCOL_CONSUMER_BLOCKED", Category: CategoryInternal,
		Description: "Consumer is blocklisted", Retryable: false,
	})
	LavaErrorConsumerNotRegistered = registerError(&LavaError{
		Code: 1033, Name: "PROTOCOL_CONSUMER_NOT_REGISTERED", Category: CategoryInternal,
		Description: "Consumer not registered", Retryable: false,
	})
	LavaErrorRelayNumberMismatch = registerError(&LavaError{
		Code: 1034, Name: "PROTOCOL_RELAY_NUMBER_MISMATCH", Category: CategoryInternal,
		Description: "Relay number mismatch", Retryable: false,
	})
	LavaErrorSessionOutOfSync = registerError(&LavaError{
		Code: 1035, Name: "PROTOCOL_SESSION_OUT_OF_SYNC", Category: CategoryInternal,
		Description: "Session out of sync", Retryable: false,
	})
	LavaErrorInvalidRelayRequest = registerError(&LavaError{
		Code: 1036, Name: "PROTOCOL_INVALID_RELAY_REQUEST", Category: CategoryInternal,
		Description: "Relay request validation failed (wrong provider/specID/chainID/seen block/content hash)", Retryable: false,
	})
	LavaErrorRequestBlockMismatch = registerError(&LavaError{
		Code: 1037, Name: "PROTOCOL_REQUEST_BLOCK_MISMATCH", Category: CategoryInternal,
		Description: "Block height mismatch between consumer request and provider state", Retryable: true,
	})
	LavaErrorSessionAccountingFailed = registerError(&LavaError{
		Code: 1038, Name: "PROTOCOL_SESSION_ACCOUNTING_FAILED", Category: CategoryInternal,
		Description: "Session accounting (OnSessionDone/OnSessionFailure) failed", Retryable: false,
	})
	LavaErrorSubscriptionCleanupFailed = registerError(&LavaError{
		Code: 1039, Name: "PROTOCOL_SUBSCRIPTION_CLEANUP_FAILED", Category: CategoryInternal,
		Description: "Subscription consumer removal (RemoveConsumer) failed", Retryable: false,
	})

	// Verification / consensus (1040-1049)
	LavaErrorFinalizationError = registerError(&LavaError{
		Code: 1040, Name: "PROTOCOL_FINALIZATION_ERROR", Category: CategoryInternal,
		Description: "Provider finalization data incorrect", Retryable: true,
	})
	LavaErrorConsistencyError = registerError(&LavaError{
		Code: 1041, Name: "PROTOCOL_CONSISTENCY_ERROR", Category: CategoryInternal,
		Description: "Response consistency validation failed", Retryable: true,
	})
	LavaErrorHashConsensusError = registerError(&LavaError{
		Code: 1042, Name: "PROTOCOL_HASH_CONSENSUS_ERROR", Category: CategoryInternal,
		Description: "Conflicting response hashes detected", Retryable: true,
	})
	LavaErrorNoResponseTimeout = registerError(&LavaError{
		Code: 1043, Name: "PROTOCOL_NO_RESPONSE_TIMEOUT", Category: CategoryInternal,
		Description: "Relay race timeout — no provider returned any response (success or error) within the protocol-level cutoff. Distinct from PROTOCOL_CONTEXT_DEADLINE (1007) which is the caller's own context expiring.", Retryable: true,
	})
	LavaErrorRelayProcessingFailed = registerError(&LavaError{
		Code: 1044, Name: "PROTOCOL_RELAY_PROCESSING_FAILED", Category: CategoryInternal,
		Description: "Relay response processing failed on consumer side", Retryable: true,
	})

	// Subscriptions (1050-1059)
	LavaErrorSubscriptionNotFound = registerError(&LavaError{
		Code: 1050, Name: "PROTOCOL_SUBSCRIPTION_NOT_FOUND", Category: CategoryInternal,
		Description: "Subscription not found", Retryable: false,
	})
	LavaErrorSubscriptionInitFailed = registerError(&LavaError{
		Code: 1051, Name: "PROTOCOL_SUBSCRIPTION_INIT_FAILED", Category: CategoryInternal,
		Description: "Failed to initialize subscription", Retryable: false,
	})
	LavaErrorWebSocketIdleTimeout = registerError(&LavaError{
		Code: 1052, Name: "PROTOCOL_WEBSOCKET_IDLE_TIMEOUT", Category: CategoryInternal,
		Description: "WebSocket idle timeout", Retryable: false,
	})
	LavaErrorSubscriptionAlreadyExists = registerError(&LavaError{
		Code: 1053, Name: "PROTOCOL_SUBSCRIPTION_ALREADY_EXISTS", Category: CategoryInternal,
		Description: "Subscription already exists for this consumer/key", Retryable: false,
	})
)
View Source
var (
	// Generic node errors (2000-2099)
	LavaErrorNodeMethodNotFound = registerError(&LavaError{
		Code: 2001, Name: "NODE_METHOD_NOT_FOUND", Category: CategoryExternal,
		SubCategory: SubCategoryUnsupportedMethod,
		Description: "Method does not exist on this node (unknown to the API surface); non-retryable", Retryable: false,
	})
	// NODE_METHOD_NOT_SUPPORTED: the method exists but this node has disabled
	// it (e.g. provider tier, admin config). Distinct from NODE_METHOD_NOT_FOUND
	// in that it IS retryable on another provider. The Name field is a
	// Prometheus label so keep it stable — the distinction lives in the
	// description and the Retryable flag.
	LavaErrorNodeMethodNotSupported = registerError(&LavaError{
		Code: 2002, Name: "NODE_METHOD_NOT_SUPPORTED", Category: CategoryExternal,
		Description: "Method exists but is DISABLED on this specific node (provider tier / policy / admin config). Retryable on a different provider. Distinct from NODE_METHOD_NOT_FOUND (2001) which means the method does not exist at all.", Retryable: true,
	})
	LavaErrorNodeInternalError = registerError(&LavaError{
		Code: 2003, Name: "NODE_INTERNAL_ERROR", Category: CategoryExternal,
		Description: "Internal node error", Retryable: true,
	})
	LavaErrorNodeServerError = registerError(&LavaError{
		Code: 2004, Name: "NODE_SERVER_ERROR", Category: CategoryExternal,
		Description: "Generic server error", Retryable: true,
	})
	LavaErrorNodeRateLimited = registerError(&LavaError{
		Code: 2005, Name: "NODE_RATE_LIMITED", Category: CategoryExternal,
		SubCategory: SubCategoryRateLimit,
		Description: "Rate limited by node", Retryable: true,
	})
	LavaErrorNodeServiceUnavailable = registerError(&LavaError{
		Code: 2006, Name: "NODE_SERVICE_UNAVAILABLE", Category: CategoryExternal,
		Description: "Node temporarily unavailable", Retryable: true,
	})
	LavaErrorNodeSyncing = registerError(&LavaError{
		Code: 2007, Name: "NODE_SYNCING", Category: CategoryExternal,
		Description: "Node is syncing/catching up", Retryable: true,
	})
	LavaErrorNodeUnimplemented = registerError(&LavaError{
		Code: 2008, Name: "NODE_UNIMPLEMENTED", Category: CategoryExternal,
		SubCategory: SubCategoryUnsupportedMethod,
		Description: "gRPC method unimplemented", Retryable: false,
	})
	LavaErrorNodeEndpointNotFound = registerError(&LavaError{
		Code: 2009, Name: "NODE_ENDPOINT_NOT_FOUND", Category: CategoryExternal,
		SubCategory: SubCategoryUnsupportedMethod,
		Description: "REST endpoint not found", Retryable: false,
	})
	LavaErrorNodeMethodNotAllowed = registerError(&LavaError{
		Code: 2010, Name: "NODE_METHOD_NOT_ALLOWED", Category: CategoryExternal,
		SubCategory: SubCategoryUnsupportedMethod,
		Description: "REST method not allowed", Retryable: false,
	})
	LavaErrorNodeLimitExceeded = registerError(&LavaError{
		Code: 2011, Name: "NODE_LIMIT_EXCEEDED", Category: CategoryExternal,
		SubCategory: SubCategoryRateLimit,
		Description: "Request exceeds node limit (e.g., eth_getLogs range)", Retryable: false,
	})
	LavaErrorNodeResourceNotFound = registerError(&LavaError{
		Code: 2012, Name: "NODE_RESOURCE_NOT_FOUND", Category: CategoryExternal,
		Description: "Resource not found at node level", Retryable: true,
	})
	LavaErrorNodeResourceUnavailable = registerError(&LavaError{
		Code: 2013, Name: "NODE_RESOURCE_UNAVAILABLE", Category: CategoryExternal,
		Description: "Resource exists but unavailable", Retryable: true,
	})
	LavaErrorNodeGatewayTimeout = registerError(&LavaError{
		Code: 2014, Name: "NODE_GATEWAY_TIMEOUT", Category: CategoryExternal,
		Description: "Gateway timeout (HTTP 504 from provider)", Retryable: true,
	})
	LavaErrorNodeBadGateway = registerError(&LavaError{
		Code: 2015, Name: "NODE_BAD_GATEWAY", Category: CategoryExternal,
		Description: "Bad gateway (HTTP 502 from provider)", Retryable: true,
	})
	// NODE_UNAUTHORIZED: upstream rejected the smart-router's credentials
	// (HTTP 401). Non-retryable because the same credentials are reused on
	// every attempt — retrying just multiplies the same auth failure across
	// providers. Operator must fix the auth-config for the affected endpoint.
	LavaErrorNodeUnauthorized = registerError(&LavaError{
		Code: 2016, Name: "NODE_UNAUTHORIZED", Category: CategoryExternal,
		Description: "Upstream rejected router credentials (HTTP 401)", Retryable: false,
	})

	// Bitcoin/UTXO node errors (2100-2149)
	// Source: Bitcoin Core src/rpc/protocol.h
	LavaErrorNodeBitcoinWarmup = registerError(&LavaError{
		Code: 2101, Name: "NODE_BITCOIN_WARMUP", Category: CategoryExternal,
		Description: "Node still warming up (RPC_IN_WARMUP, Bitcoin -28)", Retryable: true,
	})
	LavaErrorNodeBitcoinInitialDownload = registerError(&LavaError{
		Code: 2102, Name: "NODE_BITCOIN_INITIAL_DOWNLOAD", Category: CategoryExternal,
		Description: "Node in initial block download (RPC_CLIENT_IN_INITIAL_DOWNLOAD, Bitcoin -10)", Retryable: true,
	})
	LavaErrorNodeBitcoinNotConnected = registerError(&LavaError{
		Code: 2103, Name: "NODE_BITCOIN_NOT_CONNECTED", Category: CategoryExternal,
		Description: "Node not connected / shutting down (RPC_CLIENT_NOT_CONNECTED, Bitcoin -9)", Retryable: true,
	})

	// Solana node errors (2150-2169)
	LavaErrorNodeSolanaUnhealthy = registerError(&LavaError{
		Code: 2150, Name: "NODE_SOLANA_UNHEALTHY", Category: CategoryExternal,
		Description: "Solana node behind/unhealthy (-32005)", Retryable: true,
	})
)
View Source
var (
	// Transaction errors (3000-3099)
	LavaErrorChainNonceTooLow = registerError(&LavaError{
		Code: 3001, Name: "CHAIN_NONCE_TOO_LOW", Category: CategoryExternal,
		Description: "Nonce/sequence too low", Retryable: false,
	})
	LavaErrorChainNonceTooHigh = registerError(&LavaError{
		Code: 3002, Name: "CHAIN_NONCE_TOO_HIGH", Category: CategoryExternal,
		Description: "Nonce too high", Retryable: false,
	})
	LavaErrorChainInsufficientFunds = registerError(&LavaError{
		Code: 3003, Name: "CHAIN_INSUFFICIENT_FUNDS", Category: CategoryExternal,
		Description: "Insufficient funds for transfer/gas", Retryable: false,
	})
	LavaErrorChainGasTooLow = registerError(&LavaError{
		Code: 3004, Name: "CHAIN_GAS_TOO_LOW", Category: CategoryExternal,
		Description: "Intrinsic gas too low", Retryable: false,
	})
	LavaErrorChainGasLimitExceeded = registerError(&LavaError{
		Code: 3005, Name: "CHAIN_GAS_LIMIT_EXCEEDED", Category: CategoryExternal,
		Description: "Exceeds block gas limit", Retryable: false,
	})
	LavaErrorChainTxUnderpriced = registerError(&LavaError{
		Code: 3006, Name: "CHAIN_TX_UNDERPRICED", Category: CategoryExternal,
		Description: "Transaction gas price too low", Retryable: false,
	})
	LavaErrorChainTxAlreadyKnown = registerError(&LavaError{
		Code: 3007, Name: "CHAIN_TX_ALREADY_KNOWN", Category: CategoryExternal,
		Description: "Transaction already in mempool", Retryable: false,
	})
	LavaErrorChainTxReplacementUnderpriced = registerError(&LavaError{
		Code: 3008, Name: "CHAIN_TX_REPLACEMENT_UNDERPRICED", Category: CategoryExternal,
		Description: "Replacement tx gas too low", Retryable: false,
	})
	LavaErrorChainMempoolFull = registerError(&LavaError{
		Code: 3009, Name: "CHAIN_MEMPOOL_FULL", Category: CategoryExternal,
		Description: "Mempool/tx pool is full", Retryable: false,
	})
	LavaErrorChainTxTooLarge = registerError(&LavaError{
		Code: 3010, Name: "CHAIN_TX_TOO_LARGE", Category: CategoryExternal,
		Description: "Transaction exceeds size limit", Retryable: false,
	})
	LavaErrorChainMaxFeeBelowBase = registerError(&LavaError{
		Code: 3011, Name: "CHAIN_MAX_FEE_BELOW_BASE", Category: CategoryExternal,
		Description: "Max fee per gas below base fee", Retryable: false,
	})
	LavaErrorChainInvalidSequence = registerError(&LavaError{
		Code: 3012, Name: "CHAIN_INVALID_SEQUENCE", Category: CategoryExternal,
		Description: "Invalid sequence (Cosmos nonce equivalent)", Retryable: false,
	})
	LavaErrorChainInsufficientFee = registerError(&LavaError{
		Code: 3013, Name: "CHAIN_INSUFFICIENT_FEE", Category: CategoryExternal,
		Description: "Insufficient fee", Retryable: false,
	})
	LavaErrorChainTxRejected = registerError(&LavaError{
		Code: 3014, Name: "CHAIN_TX_REJECTED", Category: CategoryExternal,
		Description: "Transaction rejected by network rules", Retryable: false,
	})
	LavaErrorChainDoubleSpend = registerError(&LavaError{
		Code: 3015, Name: "CHAIN_DOUBLE_SPEND", Category: CategoryExternal,
		Description: "Double spend / UTXO already spent", Retryable: false,
	})
	LavaErrorChainInvalidSignature = registerError(&LavaError{
		Code: 3016, Name: "CHAIN_INVALID_SIGNATURE", Category: CategoryExternal,
		Description: "Invalid transaction signature", Retryable: false,
	})

	// Execution errors (3100-3199)
	LavaErrorChainExecutionReverted = registerError(&LavaError{
		Code: 3101, Name: "CHAIN_EXECUTION_REVERTED", Category: CategoryExternal,
		Description: "Smart contract execution reverted", Retryable: false,
	})
	LavaErrorChainOutOfGas = registerError(&LavaError{
		Code: 3102, Name: "CHAIN_OUT_OF_GAS", Category: CategoryExternal,
		Description: "Out of gas during execution", Retryable: false,
	})
	LavaErrorChainStackOverflow = registerError(&LavaError{
		Code: 3103, Name: "CHAIN_STACK_OVERFLOW", Category: CategoryExternal,
		Description: "Stack limit reached", Retryable: false,
	})
	LavaErrorChainInvalidOpcode = registerError(&LavaError{
		Code: 3104, Name: "CHAIN_INVALID_OPCODE", Category: CategoryExternal,
		Description: "Invalid opcode encountered", Retryable: false,
	})
	LavaErrorChainWriteProtection = registerError(&LavaError{
		Code: 3105, Name: "CHAIN_WRITE_PROTECTION", Category: CategoryExternal,
		Description: "Write in STATICCALL context", Retryable: false,
	})
	LavaErrorChainContractSizeExceeded = registerError(&LavaError{
		Code: 3106, Name: "CHAIN_CONTRACT_SIZE_EXCEEDED", Category: CategoryExternal,
		Description: "Contract bytecode exceeds 24KB EIP-170 limit (Geth: 'max code size exceeded')", Retryable: false,
	})
	LavaErrorChainAccountNotFound = registerError(&LavaError{
		Code: 3107, Name: "CHAIN_ACCOUNT_NOT_FOUND", Category: CategoryExternal,
		Description: "Account/contract does not exist", Retryable: false,
	})
	LavaErrorChainZkEVMOutOfCounters = registerError(&LavaError{
		Code: 3108, Name: "CHAIN_ZKEVM_OUT_OF_COUNTERS", Category: CategoryExternal,
		Description: "Polygon zkEVM prover exceeded circuit counter budget", Retryable: false,
	})

	// State/data errors (3200-3299)
	LavaErrorChainBlockNotFound = registerError(&LavaError{
		Code: 3201, Name: "CHAIN_BLOCK_NOT_FOUND", Category: CategoryExternal,
		Description: "Block not found", Retryable: true,
	})
	LavaErrorChainTxNotFound = registerError(&LavaError{
		Code: 3202, Name: "CHAIN_TX_NOT_FOUND", Category: CategoryExternal,
		Description: "Transaction not found", Retryable: true,
	})
	LavaErrorChainReceiptNotFound = registerError(&LavaError{
		Code: 3203, Name: "CHAIN_RECEIPT_NOT_FOUND", Category: CategoryExternal,
		Description: "Transaction receipt not found", Retryable: true,
	})
	LavaErrorChainStatePruned = registerError(&LavaError{
		Code: 3204, Name: "CHAIN_STATE_PRUNED", Category: CategoryExternal,
		Description: "State pruned/missing trie node", Retryable: true,
	})
	LavaErrorChainDataNotAvailable = registerError(&LavaError{
		Code: 3205, Name: "CHAIN_DATA_NOT_AVAILABLE", Category: CategoryExternal,
		Description: "Historical data not available", Retryable: true,
	})
	LavaErrorChainBlockTooOld = registerError(&LavaError{
		Code: 3206, Name: "CHAIN_BLOCK_TOO_OLD", Category: CategoryExternal,
		Description: "Block results only for recent blocks", Retryable: true,
	})
	LavaErrorChainLogResponseTooLarge = registerError(&LavaError{
		Code: 3207, Name: "CHAIN_LOG_RESPONSE_TOO_LARGE", Category: CategoryExternal,
		Description: "Log query returned too many results", Retryable: false,
	})

	// Solana-specific (3300-3319) — Tier 2
	// Source: Solana RPC custom error codes (agave rpc-client-api/src/custom_error.rs)
	LavaErrorChainSolanaMissingLongTerm = registerError(&LavaError{
		Code: 3302, Name: "CHAIN_SOLANA_MISSING_LONG_TERM", Category: CategoryExternal,
		Description: "Slot missing in long-term storage (-32009)", Retryable: false,
	})
	LavaErrorChainSolanaLedgerJump = registerError(&LavaError{
		Code: 3303, Name: "CHAIN_SOLANA_LEDGER_JUMP", Category: CategoryExternal,
		Description: "Missing due to ledger jump/snapshot (-32007)", Retryable: true,
	})
	LavaErrorChainSolanaBlockhashNotFound = registerError(&LavaError{
		Code: 3304, Name: "CHAIN_SOLANA_BLOCKHASH_NOT_FOUND", Category: CategoryExternal,
		Description: "Blockhash not found/expired", Retryable: false,
	})
	LavaErrorChainSolanaSimulationFailed = registerError(&LavaError{
		Code: 3305, Name: "CHAIN_SOLANA_SIMULATION_FAILED", Category: CategoryExternal,
		Description: "Transaction simulation failed (-32002)", Retryable: false,
	})
	LavaErrorChainSolanaSignatureVerifyFailed = registerError(&LavaError{
		Code: 3306, Name: "CHAIN_SOLANA_SIGNATURE_VERIFY_FAILED", Category: CategoryExternal,
		Description: "Signature verification failure (-32003)", Retryable: false,
	})
	LavaErrorChainSolanaExcludedFromIndex = registerError(&LavaError{
		Code: 3307, Name: "CHAIN_SOLANA_EXCLUDED_FROM_INDEX", Category: CategoryExternal,
		Description: "Excluded from account secondary indexes (-32010)", Retryable: false,
	})
	LavaErrorChainSolanaSignatureLengthMismatch = registerError(&LavaError{
		Code: 3308, Name: "CHAIN_SOLANA_SIGNATURE_LENGTH_MISMATCH", Category: CategoryExternal,
		Description: "Incorrectly formatted signature (-32013)", Retryable: false,
	})
	LavaErrorChainSolanaBlockStatusUnavailable = registerError(&LavaError{
		Code: 3309, Name: "CHAIN_SOLANA_BLOCK_STATUS_UNAVAILABLE", Category: CategoryExternal,
		Description: "Block status unavailable (-32014)", Retryable: true,
	})
	LavaErrorChainSolanaTxVersionUnsupported = registerError(&LavaError{
		Code: 3310, Name: "CHAIN_SOLANA_TX_VERSION_UNSUPPORTED", Category: CategoryExternal,
		Description: "Transaction version not supported (-32015)", Retryable: false,
	})
	LavaErrorChainSolanaMinContextSlotNotReached = registerError(&LavaError{
		Code: 3311, Name: "CHAIN_SOLANA_MIN_CONTEXT_SLOT_NOT_REACHED", Category: CategoryExternal,
		Description: "Minimum context slot not reached (-32016)", Retryable: true,
	})

	// Starknet-specific (3320-3349) — Tier 2
	// Source: Starknet JSON-RPC spec error codes
	LavaErrorChainStarknetFailedToReceiveTx = registerError(&LavaError{
		Code: 3320, Name: "CHAIN_STARKNET_FAILED_TO_RECEIVE_TX", Category: CategoryExternal,
		Description: "Sequencer rejected transaction (code 1)", Retryable: false,
	})
	LavaErrorChainStarknetClassNotFound = registerError(&LavaError{
		Code: 3321, Name: "CHAIN_STARKNET_CLASS_NOT_FOUND", Category: CategoryExternal,
		Description: "Class hash not found (code 28)", Retryable: false,
	})
	LavaErrorChainStarknetCompilationFailed = registerError(&LavaError{
		Code: 3322, Name: "CHAIN_STARKNET_COMPILATION_FAILED", Category: CategoryExternal,
		Description: "Sierra to CASM compilation failed (code 56)", Retryable: false,
	})
	LavaErrorChainStarknetClassAlreadyDeclared = registerError(&LavaError{
		Code: 3323, Name: "CHAIN_STARKNET_CLASS_ALREADY_DECLARED", Category: CategoryExternal,
		Description: "Class already declared (code 51)", Retryable: false,
	})
	LavaErrorChainStarknetContractError = registerError(&LavaError{
		Code: 3324, Name: "CHAIN_STARKNET_CONTRACT_ERROR", Category: CategoryExternal,
		Description: "Contract error during execution (code 40)", Retryable: false,
	})
	LavaErrorChainStarknetTxExecError = registerError(&LavaError{
		Code: 3325, Name: "CHAIN_STARKNET_TX_EXEC_ERROR", Category: CategoryExternal,
		Description: "Transaction execution error (code 41)", Retryable: false,
	})
	LavaErrorChainStarknetInvalidNonce = registerError(&LavaError{
		Code: 3326, Name: "CHAIN_STARKNET_INVALID_NONCE", Category: CategoryExternal,
		Description: "Invalid transaction nonce (code 52)", Retryable: false,
	})
	LavaErrorChainStarknetInsufficientFee = registerError(&LavaError{
		Code: 3327, Name: "CHAIN_STARKNET_INSUFFICIENT_FEE", Category: CategoryExternal,
		Description: "Insufficient max fee (code 53)", Retryable: false,
	})
	LavaErrorChainStarknetInsufficientBalance = registerError(&LavaError{
		Code: 3328, Name: "CHAIN_STARKNET_INSUFFICIENT_BALANCE", Category: CategoryExternal,
		Description: "Insufficient account balance (code 54)", Retryable: false,
	})
	LavaErrorChainStarknetValidationFailure = registerError(&LavaError{
		Code: 3329, Name: "CHAIN_STARKNET_VALIDATION_FAILURE", Category: CategoryExternal,
		Description: "Account validation failed (code 55)", Retryable: false,
	})
	LavaErrorChainStarknetContractNotFound = registerError(&LavaError{
		Code: 3330, Name: "CHAIN_STARKNET_CONTRACT_NOT_FOUND", Category: CategoryExternal,
		Description: "Contract address not found (code 20)", Retryable: false,
	})
	LavaErrorChainStarknetBlockNotFound = registerError(&LavaError{
		Code: 3331, Name: "CHAIN_STARKNET_BLOCK_NOT_FOUND", Category: CategoryExternal,
		Description: "Block not found (code 24)", Retryable: true,
	})
	LavaErrorChainStarknetTxHashNotFound = registerError(&LavaError{
		Code: 3332, Name: "CHAIN_STARKNET_TX_HASH_NOT_FOUND", Category: CategoryExternal,
		Description: "Transaction hash not found (code 29)", Retryable: true,
	})
	LavaErrorChainStarknetDuplicateTx = registerError(&LavaError{
		Code: 3333, Name: "CHAIN_STARKNET_DUPLICATE_TX", Category: CategoryExternal,
		Description: "Duplicate transaction in mempool (code 59)", Retryable: false,
	})
	LavaErrorChainStarknetTxVersionUnsupported = registerError(&LavaError{
		Code: 3334, Name: "CHAIN_STARKNET_TX_VERSION_UNSUPPORTED", Category: CategoryExternal,
		Description: "Unsupported transaction version (code 61)", Retryable: false,
	})
	LavaErrorChainStarknetUnexpectedError = registerError(&LavaError{
		Code: 3335, Name: "CHAIN_STARKNET_UNEXPECTED_ERROR", Category: CategoryExternal,
		Description: "Unexpected server error (code 63)", Retryable: true,
	})

	// Bitcoin/UTXO-specific (3340-3359) — Tier 2
	// Source: Bitcoin Core src/rpc/protocol.h
	LavaErrorChainBitcoinVerifyError = registerError(&LavaError{
		Code: 3341, Name: "CHAIN_BITCOIN_VERIFY_ERROR", Category: CategoryExternal,
		Description: "Transaction/block verification failed (RPC_VERIFY_ERROR, Bitcoin -25)", Retryable: false,
	})
	LavaErrorChainBitcoinVerifyRejected = registerError(&LavaError{
		Code: 3342, Name: "CHAIN_BITCOIN_VERIFY_REJECTED", Category: CategoryExternal,
		Description: "Transaction rejected by network rules (RPC_VERIFY_REJECTED, Bitcoin -26)", Retryable: false,
	})
	LavaErrorChainBitcoinAlreadyInChain = registerError(&LavaError{
		Code: 3343, Name: "CHAIN_BITCOIN_ALREADY_IN_CHAIN", Category: CategoryExternal,
		Description: "Transaction already confirmed (RPC_VERIFY_ALREADY_IN_CHAIN, Bitcoin -27)", Retryable: false,
	})
	LavaErrorChainBitcoinWalletInsufficientFunds = registerError(&LavaError{
		Code: 3344, Name: "CHAIN_BITCOIN_WALLET_INSUFFICIENT_FUNDS", Category: CategoryExternal,
		Description: "Wallet UTXO coin selection failed (RPC_WALLET_INSUFFICIENT_FUNDS, Bitcoin -6). Distinct from EVM CHAIN_INSUFFICIENT_FUNDS (3003) which is a tx submission failure.", Retryable: false,
	})

	// NEAR-specific (3360-3379) — Tier 2
	// Source: NEAR RPC docs (error names in JSON-RPC error.cause.name)
	LavaErrorChainNEARUnknownBlock = registerError(&LavaError{
		Code: 3360, Name: "CHAIN_NEAR_UNKNOWN_BLOCK", Category: CategoryExternal,
		Description: "Block not found or garbage-collected (UNKNOWN_BLOCK)", Retryable: true,
	})
	LavaErrorChainNEARUnknownChunk = registerError(&LavaError{
		Code: 3361, Name: "CHAIN_NEAR_UNKNOWN_CHUNK", Category: CategoryExternal,
		Description: "Chunk not found (UNKNOWN_CHUNK)", Retryable: true,
	})
	LavaErrorChainNEARInvalidShardID = registerError(&LavaError{
		Code: 3362, Name: "CHAIN_NEAR_INVALID_SHARD_ID", Category: CategoryExternal,
		Description: "Shard ID does not exist (INVALID_SHARD_ID)", Retryable: false,
	})
	LavaErrorChainNEARNotSyncedYet = registerError(&LavaError{
		Code: 3363, Name: "CHAIN_NEAR_NOT_SYNCED_YET", Category: CategoryExternal,
		Description: "Node still syncing (NOT_SYNCED_YET)", Retryable: true,
	})
)
View Source
var (
	LavaErrorUserParseError = registerError(&LavaError{
		Code: 4001, Name: "USER_PARSE_ERROR", Category: CategoryExternal,
		Description: "Invalid JSON in request", Retryable: false,
	})
	LavaErrorUserInvalidRequest = registerError(&LavaError{
		Code: 4002, Name: "USER_INVALID_REQUEST", Category: CategoryExternal,
		Description: "Request is not a valid JSON-RPC/REST/gRPC object", Retryable: false,
	})
	LavaErrorUserInvalidParams = registerError(&LavaError{
		Code: 4003, Name: "USER_INVALID_PARAMS", Category: CategoryExternal,
		Description: "Invalid method parameters", Retryable: false,
	})
	LavaErrorUserInvalidBlockFormat = registerError(&LavaError{
		Code: 4004, Name: "USER_INVALID_BLOCK_FORMAT", Category: CategoryExternal,
		Description: "Invalid block number format (e.g., non-hex)", Retryable: false,
	})
	LavaErrorUserInvalidAddress = registerError(&LavaError{
		Code: 4005, Name: "USER_INVALID_ADDRESS", Category: CategoryExternal,
		Description: "Invalid address format", Retryable: false,
	})
	LavaErrorUserRequestTooLarge = registerError(&LavaError{
		Code: 4006, Name: "USER_REQUEST_TOO_LARGE", Category: CategoryExternal,
		Description: "Request body exceeds size limit", Retryable: false,
	})
	LavaErrorUserInvalidHex = registerError(&LavaError{
		Code: 4007, Name: "USER_INVALID_HEX", Category: CategoryExternal,
		Description: "Invalid hex encoding", Retryable: false,
	})
)

Layer D errors are classified for metrics/observability but do NOT receive special CU treatment — providers still charge normal CU for processing invalid client requests (since responses are not cached and the provider does real work on every call).

View Source
var (
	ContextDeadlineExceededError = errors.New("context deadline exceeded")
	StatusCodeError504           = errors.New("Disallowed status code error (504)")
	StatusCodeError429           = errors.New("Disallowed status code error (429)")
	StatusCodeErrorStrict        = errors.New("Disallowed status code error (800)")
	APINotSupportedError         = errors.New("api not supported")
	SubscriptionNotFoundError    = errors.New("subscription not found")
)
View Source
var DefaultCrossValidationParams = CrossValidationParams{
	MaxParticipants:    1,
	AgreementThreshold: 1,
}

DefaultCrossValidationParams are used when cross-validation is not enabled (Selection != CrossValidation)

DefaultTimeout is the configurable default timeout for relay processing. It can be overridden via the --default-processing-timeout flag on consumer and smart router commands.

View Source
var JsonRpcBatchSizeExceededError = JsonRPCErrorMessage{
	JsonRPC: "2.0",
	Id:      1,
	Error: JsonRPCError{
		Code:    429,
		Message: "Batch request size exceeded",
	},
}
View Source
var JsonRpcMethodNotFoundError = JsonRPCErrorMessage{
	JsonRPC: "2.0",
	Id:      1,
	Error: JsonRPCError{
		Code:    -32601,
		Message: "Method not found",
	},
}
View Source
var JsonRpcParseError = JsonRPCErrorMessage{
	JsonRPC: "2.0",
	Id:      -1,
	Error: JsonRPCError{
		Code:    -32700,
		Message: "Parse error",
		Data:    "Failed to parse the request body as JSON",
	},
}
View Source
var JsonRpcRateLimitError = JsonRPCErrorMessage{
	JsonRPC: "2.0",
	Id:      1,
	Error: JsonRPCError{
		Code:    429,
		Message: "Too Many Requests",
	},
}
View Source
var JsonRpcSubscriptionNotFoundError = JsonRPCErrorMessage{
	JsonRPC: "2.0",
	Id:      1,
	Error: JsonRPCError{
		Code:    -32603,
		Message: "Internal error",
		Data:    "subscription not found",
	},
}
View Source
var LavaErrorUnknown = &LavaError{
	Code: 0, Name: "UNKNOWN_ERROR", Category: CategoryExternal,
	Description: "Unclassified error — no matcher matched", Retryable: true,
}

LavaErrorUnknown is the fallback for unclassified errors. Category is External because unmatched errors are node pass-throughs.

Retryable is intentionally TRUE: retrying unknowns is the deliberate fail-open policy. The rationale is that the registry cannot possibly enumerate every transient node/proxy error shape in the wild, so any unrecognised failure is *more likely* to be a one-off hiccup worth retrying on a different provider than a permanent condition. Failing closed (Retryable: false) would silently starve real transient errors — a brand-new 5xx variant from a CDN, an unrecognised proxy error body, etc. — the moment they started appearing in production.

The retry amplification concern (a struggling provider repeatedly hit by retries) is handled independently:

  • The relay retry limit caps per-request attempts (RelayRetryLimit).
  • classifyEndpointHealth marks providers unhealthy on CategoryInternal failures, which removes them from rotation.
  • The relay-race design sends one attempt per provider per retry, not a tight loop against a single struggling provider.

If a new unknown-error class starts dominating lava_errors_total in production, the right response is to add a matcher for it in error_classifier.go (demoting it from Unknown to a specific code with the appropriate Retryable flag), not to flip this default.

View Source
var MinimumTimePerRelayDelay = time.Second

MinimumTimePerRelayDelay is the minimum relay timeout floor used by GetTimePerCu. It can be overridden via the --min-relay-timeout flag on consumer and smart router commands.

View Source
var RestAptosMethodNotFoundError = RestAptosError{
	Message:     "not found",
	ErrorCode:   "web_framework_error",
	VmErrorCode: nil,
}
View Source
var RestMethodNotFoundError = RestError{
	Code:    12,
	Message: "Not Implemented",
	Details: []interface{}{},
}

Functions

func AddRollingLogConfig

func AddRollingLogConfig(cmd *cobra.Command)

default rolling logs behavior (if enabled) will store 3 files each 100MB for up to 1 day every time.

func BaseTimePerCU

func BaseTimePerCU(cu uint64) time.Duration

func CapContextTimeout

func CapContextTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc)

func ContextOutOfTime

func ContextOutOfTime(ctx context.Context) bool

func CreateRestMethodNotFoundError

func CreateRestMethodNotFoundError(fiberCtx *fiber.Ctx, chainId string) error

func EmitErrorMetric

func EmitErrorMetric(lavaError *LavaError, chainID string)

EmitErrorMetric fires the registered metrics callback for a classified error without emitting any log line. Prefer LogCodedError/LogCodedWarning for the common case; use this directly only when the caller has already logged (or is about to log) the same failure via a different path and needs to ensure the Prometheus counter is still incremented exactly once.

Uses an atomic pointer load — no locks on the hot classification path.

func ExtractJSONRPCErrorCode

func ExtractJSONRPCErrorCode(data []byte) int

ExtractJSONRPCErrorCode extracts the error code from a JSON-RPC error response body. Returns 0 if the body is not a valid JSON-RPC error.

func GetExtensionNames

func GetExtensionNames(extensionCollection []*spectypes.Extension) (extensions []string)

func GetIpFromGrpcContext

func GetIpFromGrpcContext(ctx context.Context) string

func GetRemainingTimeoutFromContext

func GetRemainingTimeoutFromContext(ctx context.Context) (timeRemaining time.Duration)

func GetTimePerCu

func GetTimePerCu(cu uint64) time.Duration

func GetTimeoutForProcessing

func GetTimeoutForProcessing(relayTimeout time.Duration, timeoutInfo TimeoutInfo) time.Duration

func IsClientCancellation

func IsClientCancellation(err error, ctx context.Context) bool

IsClientCancellation reports whether err represents a request that was cancelled by the client / relay orchestration, as opposed to an upstream (provider/endpoint) fault. Two scenarios reach this path:

  1. Relay race: multiple goroutines race in parallel. When one wins, the parent context's cancel() fires and the losing goroutines observe context.Canceled as their result — no provider is at fault.
  2. Client disconnect: the upstream caller closed the connection before we responded, producing context.Canceled on the in-flight request.

The rule is: the error must be context.Canceled AND the context itself must now carry an error. A standalone context.Canceled without ctx.Err() would be suspicious — it should never happen in practice, but the conjunction guards against misclassifying a provider-emitted "context canceled" string as a client cancellation.

Call this at endpoint-health / refusal-counter decision points instead of hand-rolling an errors.Is(err, context.Canceled) check — having one rule in one place avoids drift between the consumer session layer, the smart router health tracker, and the connection-refusal counter.

func IsExternal

func IsExternal(code uint32) bool

func IsInternal

func IsInternal(code uint32) bool

func IsNonRetryableNodeError

func IsNonRetryableNodeError(chainID string, statusCode int, message string) bool

IsNonRetryableNodeError returns true when the classified LavaError for the given node-error response has Retryable=false.

func IsNonRetryableNodeErrorWithContext

func IsNonRetryableNodeErrorWithContext(family ChainFamily, transport TransportType, statusCode int, message string) bool

IsNonRetryableNodeErrorWithContext is the variant of IsNonRetryableNodeError for call sites that already know the chain family and transport exactly.

func IsQuoted

func IsQuoted(s string) bool

func IsSolanaFamily

func IsSolanaFamily(chainID string) bool

IsSolanaFamily returns true if the chain ID belongs to the Solana/SVM family. These chains use slot-based block numbering where slots can be skipped or not yet propagated, requiring special handling in block fetching.

Delegates to the authoritative chainFamilyMap in error_registry.go so adding a new SVM chain only needs to update that single map — no parallel switch to keep in sync.

func IsSolanaNonRetryableError

func IsSolanaNonRetryableError(errorMessage string) bool

IsSolanaNonRetryableError checks if an error message indicates a Solana error that should not be retried. Currently this covers: - Error code -32009: "missing in long-term storage" (slot permanently unavailable)

Note: Error code -32007 (ledger jump to snapshot) IS retryable as another provider may have the data.

Returns true if the error message contains any known Solana non-retryable pattern.

func IsSolanaNonRetryableErrorBytes

func IsSolanaNonRetryableErrorBytes(errorMessage []byte) bool

IsSolanaNonRetryableErrorBytes checks if an error message (as bytes) indicates a Solana non-retryable error. This is more efficient than IsSolanaNonRetryableError when working with []byte data as it avoids string conversions and uses pre-computed byte patterns with a single-pass lowercase conversion.

func IsSquareBracketed

func IsSquareBracketed(s string) bool

func IsTestMode

func IsTestMode(ctx context.Context) bool

func IsTimeout

func IsTimeout(errArg error) bool

func IsUnsupportedMethodError

func IsUnsupportedMethodError(chainID string, statusCode int, message string) bool

IsUnsupportedMethodError returns true when the error identified by statusCode and message is classified as an unsupported method (the node does not recognise the method at all).

chainID is used to consult chain-specific Tier-2 matchers first, so chain-native messages like Solana's "Block is not available for slot N" don't accidentally match a broad Tier-1 substring rule (e.g. "is not available") and get pinned as unsupported-method — which would skip retries and zero out CU charging. Pass "" when the chain is genuinely unknown; Tier-2 is then skipped.

func IsUnsupportedMethodErrorMessageBytes

func IsUnsupportedMethodErrorMessageBytes(errorMessage []byte) bool

IsUnsupportedMethodErrorMessageBytes checks if an error message (as bytes) indicates an unsupported method. This is more efficient than IsUnsupportedMethodErrorMessage when working with []byte data as it avoids string conversions and uses pre-computed byte patterns with a single-pass lowercase conversion.

func IsUnsupportedMethodMessage

func IsUnsupportedMethodMessage(errorMessage string) bool

IsUnsupportedMethodMessage checks if an error message indicates an unsupported method. This is a convenience wrapper that delegates to IsUnsupportedMethodErrorMessageBytes for efficient pattern matching using pre-computed byte patterns.

For more comprehensive checks including HTTP status codes and gRPC status codes, use chainlib.IsUnsupportedMethodError which wraps this function with additional protocol-specific checks.

Returns true if the error message contains any known unsupported method pattern.

func LocalNodeTimePerCu

func LocalNodeTimePerCu(cu uint64) time.Duration

func LogCodedError

func LogCodedError(description string, err error, lavaError *LavaError, chainID string, chainErrorCode int, chainErrorMessage string, attributes ...utils.Attribute) error

LogCodedError logs an error at Error level with a classified LavaError, auto-populating structured fields and invoking the metrics callback if registered.

Parameters:

  • description: human-readable context (e.g., "relay to provider failed")
  • err: the original error
  • lavaError: the classified LavaError (nil defaults to LavaErrorUnknown)
  • chainID: the chain ID for metrics labels (may be empty)
  • chainErrorCode: the original error code from the node (0 if not applicable)
  • chainErrorMessage: the original error message from the node (may be empty)
  • attributes: additional structured log attributes

func LogCodedWarning

func LogCodedWarning(description string, err error, lavaError *LavaError, chainID string, chainErrorCode int, chainErrorMessage string, attributes ...utils.Attribute) error

LogCodedWarning logs an error at Warning level with a classified LavaError, auto-populating structured fields and invoking the metrics callback if registered.

Use this for expected/non-critical errors that should be tracked in metrics but should not appear as errors in logs (e.g., session-out-of-sync, invalid consumer requests, relay capacity limits that are normal in production).

func NewLavaError

func NewLavaError(lavaErr *LavaError, context string) error

NewLavaError creates an error that wraps a LavaError with optional context. Supports errors.Is(err, LavaErrorSomething) matching by code.

func OptimizedHttpClient

func OptimizedHttpClient() *http.Client

OptimizedHttpClient creates an HTTP client with optimized transport settings and a default 5-minute timeout suitable for blockchain node operations. The client uses the shared transport for maximum connection reuse.

Note: Multiple clients can safely share the same transport. The transport handles connection pooling internally.

Returns:

  • *http.Client: A client with optimized connection pooling and default timeout

func OptimizedHttpTransport

func OptimizedHttpTransport() *http.Transport

OptimizedHttpTransport creates an HTTP transport optimized for provider-to-node communication. This transport is configured to: 1. Reuse connections efficiently (high MaxIdleConnsPerHost) 2. Limit total connections per host (prevents overwhelming nodes) 3. Handle high concurrency scenarios (200+ simultaneous requests) 4. Close idle connections appropriately to avoid leaks 5. Cache TLS sessions for faster reconnections

Benefits: - Reduces TCP connection overhead - Prevents connection exhaustion on blockchain nodes - Improves latency through connection reuse - Handles heavy load without creating thousands of connections - TLS session resumption reduces CPU usage by ~10-15% on handshakes

Note: For most use cases, prefer SharedHttpTransport() to maximize connection reuse.

func ParseEndpointArgs

func ParseEndpointArgs(endpoint_strings, yaml_config_properties []string, endpointsConfigName string) (viper_endpoints *viper.Viper, err error)

func SetErrorMetricsCallback

func SetErrorMetricsCallback(cb ErrorMetricsCallback)

SetErrorMetricsCallback registers a callback for error metrics (e.g., Prometheus counter). Called once during application initialization from the metrics package. Passing nil clears the callback (used by tests).

func SetupRollingLogger

func SetupRollingLogger() func()

func SharedHttpTransport

func SharedHttpTransport() *http.Transport

SharedHttpTransport returns a singleton HTTP transport that is shared across all RPC clients in the application. This maximizes connection reuse and TLS session caching benefits.

Why sharing matters: - Each http.Transport maintains its own connection pool - With N separate transports, you get N separate pools with limited reuse - With 1 shared transport, all connections are pooled together - TLS session cache is also shared, benefiting all connections

This is safe for concurrent use as http.Transport is goroutine-safe.

func UnSquareBracket

func UnSquareBracket(s string) string

func ValidateAndCapMinRelayTimeout

func ValidateAndCapMinRelayTimeout()

ValidateAndCapMinRelayTimeout ensures both DefaultTimeout and MinimumTimePerRelayDelay are positive and that MinimumTimePerRelayDelay < DefaultTimeout. Called once at startup after flags are parsed.

func ValidateEndpoint

func ValidateEndpoint(endpoint, apiInterface string) error

Types

type AuthConfig

type AuthConfig struct {
	AuthHeaders   map[string]string `yaml:"auth-headers,omitempty" json:"auth-headers,omitempty" mapstructure:"auth-headers"`
	AuthQuery     string            `yaml:"auth-query,omitempty" json:"auth-query,omitempty" mapstructure:"auth-query"`
	UseTLS        bool              `yaml:"use-tls,omitempty" json:"use-tls,omitempty" mapstructure:"use-tls"`
	AllowInsecure bool              `yaml:"allow-insecure,omitempty" json:"allow-insecure,omitempty" mapstructure:"allow-insecure"`
	KeyPem        string            `yaml:"key-pem,omitempty" json:"key-pem,omitempty" mapstructure:"key-pem"`
	CertPem       string            `yaml:"cert-pem,omitempty" json:"cert-pem,omitempty" mapstructure:"cert-pem"`
	CaCert        string            `yaml:"cacert-pem,omitempty" json:"cacert-pem,omitempty" mapstructure:"cacert-pem"`
}

func (*AuthConfig) AddAuthPath

func (ac *AuthConfig) AddAuthPath(url string) string

func (*AuthConfig) GetCaCertificateParams

func (ac *AuthConfig) GetCaCertificateParams() string

File containing trusted root certificates for verifying the server.

func (*AuthConfig) GetLoadingCertificateParams

func (ac *AuthConfig) GetLoadingCertificateParams() (string, string)

File containing client certificate (public key), to present to the server. + File containing client private key, to present to the server.

func (*AuthConfig) GetUseTls

func (ac *AuthConfig) GetUseTls() bool

type ChainFamily

type ChainFamily int
const (
	ChainFamilyEVM ChainFamily = iota
	ChainFamilySolana
	ChainFamilyBitcoin
	ChainFamilyCosmosSDK
	ChainFamilyStarknet
	ChainFamilyAptos
	ChainFamilyNEAR
	ChainFamilyXRP
	ChainFamilyStellar
	ChainFamilyTON
	ChainFamilyPolygonZkEVM
	ChainFamilyCardano
	ChainFamilyTron
	ChainFamilySui
)
const ChainFamilyUnknown ChainFamily = -1

ChainFamilyUnknown is a sentinel returned for chains not registered in chainFamilyMap. Tier-2 lookups against this value intentionally miss so classification falls through to transport-scoped Tier-1 matchers instead of inheriting another family's semantics. Defined explicitly as -1 to avoid colliding with the iota-numbered real families below.

func GetChainFamily

func GetChainFamily(chainID string) (ChainFamily, bool)

GetChainFamily returns the chain family for a given chain ID. Returns ok=false for unknown chains; the caller is responsible for handling that case.

func GetChainFamilyOrDefault

func GetChainFamilyOrDefault(chainID string) ChainFamily

GetChainFamilyOrDefault returns the chain family for a given chain ID, or ChainFamilyUnknown if the chain is not registered. Defaulting to a concrete family (e.g. EVM) would silently inherit that family's Tier-2 matchers for unregistered chains — the sentinel ensures Tier-2 lookups miss and classification falls back to transport-scoped Tier-1 matchers instead.

func (ChainFamily) String

func (cf ChainFamily) String() string

type ChainMessageGetApiInterface

type ChainMessageGetApiInterface interface {
	GetApi() *spectypes.Api
}

type ConflictHandlerInterface

type ConflictHandlerInterface interface {
	ConflictAlreadyReported() bool
	StoreConflictReported()
}

type ConsumerCmdFlags

type ConsumerCmdFlags struct {
	HeadersFlag              string        // comma separated list of headers, or * for all, default simple cors specification headers
	CredentialsFlag          string        // access-control-allow-credentials, defaults to "true"
	OriginFlag               string        // comma separated list of origins, or * for all, default enabled completely
	MethodsFlag              string        // whether to allow access control headers *, most proxies have their own access control so its not required
	CDNCacheDuration         string        // how long to cache the preflight response defaults 24 hours (in seconds) "86400"
	RelaysHealthEnableFlag   bool          // enables relay health check
	RelaysHealthIntervalFlag time.Duration // interval for relay health check
	DebugRelays              bool          // enables debug mode for relays
	StaticSpecPaths          []string      // paths to spec sources (files, directories, or remote URLs). Later entries override earlier for same chain ID.
	GitHubToken              string        // GitHub personal access token for accessing private repositories
	GitLabToken              string        // GitLab personal access token for accessing private repositories
	EpochDuration            time.Duration // duration of each epoch for time-based epoch system (standalone mode)
	EnableSelectionStats     bool          // enables selection stats header for debugging provider selection
	DebugAddress             string        // address for the debug HTTP server, e.g. ":9999". Empty = disabled.
	ResponseCompression      string        // "gzip" (default), "brotli", or "off" — controls client-facing response compression
	ShutdownGracePeriod      time.Duration // graceful shutdown deadline; passed to chain listeners and upstream cleanup
}

helper struct to propagate flags deeper into the code in an organized manner

type CrossValidationParams

type CrossValidationParams struct {
	MaxParticipants    int // Maximum number of providers to query
	AgreementThreshold int // Number of matching responses needed for consensus
}

CrossValidationParams holds the cross-validation configuration parameters Note: Whether cross-validation is enabled is determined by the Selection type (CrossValidation), not by these parameters. These parameters only store the values when cross-validation is active.

type EligibilityAction

type EligibilityAction int

EligibilityAction represents the provider eligibility decision.

const (
	EligibilityMarkUnwanted EligibilityAction = iota
	EligibilityAllowRetry
)

type EligibilityResult

type EligibilityResult struct {
	Action EligibilityAction
}

EligibilityResult is returned by DecideEligibility.

func DecideEligibility

func DecideEligibility(isUnsupportedMethod bool, isSyncLoss bool, isFirstSyncLoss bool) EligibilityResult

DecideEligibility makes the provider eligibility decision. Pure function — no external dependencies. The caller computes the inputs.

  • isUnsupportedMethod: true if the error is an unsupported method (no provider will succeed)
  • isSyncLoss: true if the error is a session sync loss
  • isFirstSyncLoss: true if this provider hasn't had a sync loss before

type EpochTimer

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

EpochTimer manages epochs based on absolute wall clock time All processes using the same epochDuration will calculate the same epoch number and update at the same absolute time boundaries

func NewEpochTimer

func NewEpochTimer(epochDuration time.Duration) *EpochTimer

NewEpochTimer creates a new time-based epoch timer Epoch 0 starts at a fixed point in the past (January 1, 2024 00:00:00 UTC) This ensures epochs remain consistent even after long downtimes

func (*EpochTimer) CalculateCurrentEpoch

func (et *EpochTimer) CalculateCurrentEpoch() uint64

CalculateCurrentEpoch calculates epoch number from absolute time Formula: epoch = floor((currentTime - epochZeroTime) / epochDuration)

func (*EpochTimer) GetCurrentEpoch

func (et *EpochTimer) GetCurrentEpoch() uint64

GetCurrentEpoch returns current epoch (alias for clarity)

func (*EpochTimer) GetEpochBoundaryTime

func (et *EpochTimer) GetEpochBoundaryTime(epoch uint64) time.Time

GetEpochBoundaryTime returns the absolute time when an epoch starts

func (*EpochTimer) GetEpochDuration

func (et *EpochTimer) GetEpochDuration() time.Duration

GetEpochDuration returns the configured epoch duration

func (*EpochTimer) GetTimeUntilNextEpoch

func (et *EpochTimer) GetTimeUntilNextEpoch() time.Duration

GetTimeUntilNextEpoch calculates time until next epoch boundary

func (*EpochTimer) RegisterCallback

func (et *EpochTimer) RegisterCallback(callback func(uint64))

RegisterCallback registers a callback to be called on epoch updates

func (*EpochTimer) Start

func (et *EpochTimer) Start(ctx context.Context)

Start begins the epoch timer with synchronized triggers at absolute boundaries

func (*EpochTimer) Stop

func (et *EpochTimer) Stop()

Stop stops the epoch timer

type ErrorCategory

type ErrorCategory int

ErrorCategory — top-level grouping: internal (Lava-introduced) vs external (pass-through)

const (
	CategoryInternal ErrorCategory = iota // Errors introduced by Lava — user would never see these without Lava
	CategoryExternal                      // Pass-through errors — user would get the same error talking to the node directly
)

func (ErrorCategory) String

func (c ErrorCategory) String() string

type ErrorMatcher

type ErrorMatcher interface {
	Matches(errorCode int, errorMessage string) bool
}

ErrorMatcher classifies errors by matching error codes and/or messages.

func CodeEquals

func CodeEquals(code int) ErrorMatcher

func GRPCCodeEquals

func GRPCCodeEquals(code uint32) ErrorMatcher

func HTTPStatusContains

func HTTPStatusContains(status int) ErrorMatcher

func MessageContains

func MessageContains(substring string) ErrorMatcher

func MessageRegex

func MessageRegex(pattern string) ErrorMatcher

type ErrorMetricsCallback

type ErrorMetricsCallback func(errorCode uint32, errorName string, errorCategory string, retryable bool, chainID string)

ErrorMetricsCallback is a function that gets called on every classified error for metrics tracking. Registered via SetErrorMetricsCallback from the metrics package during initialization.

type ErrorSubCategory

type ErrorSubCategory int

ErrorSubCategory — finer classification within each category. Subcategories carry behavioral implications that the consumer hot path branches on (retries, CU charging, caching).

const (
	SubCategoryNone              ErrorSubCategory = iota
	SubCategoryUnsupportedMethod                  // zero retries, zero CU, cached response, no provider scoring
	SubCategoryRateLimit                          // rate-limit signal: endpoint is healthy but busy, apply backoff, do not mark unhealthy
)

func (ErrorSubCategory) IsRateLimit

func (sc ErrorSubCategory) IsRateLimit() bool

IsRateLimit reports whether this subcategory represents a "slow down" signal from the endpoint. Health-tracking callers should apply backoff but NOT mark the endpoint unhealthy — it's working, just busy.

func (ErrorSubCategory) IsUnsupportedMethod

func (sc ErrorSubCategory) IsUnsupportedMethod() bool

func (ErrorSubCategory) String

func (sc ErrorSubCategory) String() string

type GrpcConfig

type GrpcConfig struct {
	// DescriptorSource specifies how to obtain protobuf descriptors for dynamic message handling.
	// Options:
	//   - "reflection" (default): Use gRPC server reflection to auto-discover proto definitions
	//   - "file": Load from a pre-compiled FileDescriptorSet (.pb file)
	//   - "hybrid": Try reflection first, fallback to file if reflection is unavailable
	DescriptorSource string `yaml:"descriptor-source,omitempty" json:"descriptor-source,omitempty" mapstructure:"descriptor-source"`

	// DescriptorSetPath is the path to a FileDescriptorSet file (.pb or .prototxt).
	// Required when DescriptorSource is "file" or "hybrid".
	// Can be absolute path or relative to the working directory.
	DescriptorSetPath string `yaml:"descriptor-set-path,omitempty" json:"descriptor-set-path,omitempty" mapstructure:"descriptor-set-path"`

	// ReflectionTimeout is the timeout for gRPC reflection queries.
	// Only used when DescriptorSource is "reflection" or "hybrid".
	// Default: 5s
	ReflectionTimeout time.Duration `yaml:"reflection-timeout,omitempty" json:"reflection-timeout,omitempty" mapstructure:"reflection-timeout"`

	// AllowInsecure permits grpc:// (non-TLS) connections.
	// Should only be enabled for local development/testing.
	// Default: false (only grpcs:// allowed)
	AllowInsecure bool `yaml:"allow-insecure,omitempty" json:"allow-insecure,omitempty" mapstructure:"allow-insecure"`
}

GrpcConfig holds gRPC-specific configuration for direct gRPC connections. Used by the smart router for direct connections to gRPC endpoints (Cosmos SDK, Solana, etc.)

func (*GrpcConfig) GetDescriptorSource

func (gc *GrpcConfig) GetDescriptorSource() string

GetDescriptorSource returns the descriptor source, defaulting to "reflection"

func (*GrpcConfig) GetReflectionTimeout

func (gc *GrpcConfig) GetReflectionTimeout() time.Duration

GetReflectionTimeout returns the reflection timeout, defaulting to 5 seconds

func (*GrpcConfig) NeedsDescriptorFile

func (gc *GrpcConfig) NeedsDescriptorFile() bool

NeedsDescriptorFile returns true if descriptor source requires a file path

func (*GrpcConfig) Validate

func (gc *GrpcConfig) Validate() error

Validate checks the GrpcConfig for correctness

type JsonRPCError

type JsonRPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    string `json:"data"`
}

type JsonRPCErrorMessage

type JsonRPCErrorMessage struct {
	JsonRPC string       `json:"jsonrpc"`
	Id      int          `json:"id"`
	Error   JsonRPCError `json:"error"`
}

type LavaError

type LavaError struct {
	Code        uint32
	Name        string
	Category    ErrorCategory
	SubCategory ErrorSubCategory
	Description string
	Retryable   bool // retrying same relay with same params to a different provider has a chance of succeeding
}

LavaError is the central error definition — a classification struct, not a Go error. It is metadata *about* an error, used for logging, metrics, and retry decisions. The original error always passes through unchanged to the user (transparent hop).

func ClassifyError

func ClassifyError(connectionError *LavaError, chainFamily ChainFamily, transport TransportType, errorCode int, errorMessage string) *LavaError

ClassifyError classifies an error into a LavaError for internal use (logging, metrics, endpoint health). The original error always passes through unchanged to the user (transparent hop).

Parameters:

  • connectionError: pre-detected connection-level error (timeout, refused, etc.), or nil
  • chainFamily: the chain family for Tier 2 lookups, use -1 if unknown
  • transport: the transport type for Tier 1 generic matcher partitioning
  • errorCode: the numeric error code (e.g., JSON-RPC error code), or 0 if not applicable
  • errorMessage: the error message string for substring/regex matching

func ClassifyLegacyError

func ClassifyLegacyError(err error, transport TransportType) *LavaError

ClassifyLegacyError extracts the sdkerrors (codespace, code) tuple from a legacy error and returns the corresponding LavaError. Returns the transport-scoped ClassifyError result if no mapping exists.

transport is used for the message-based fallback when no sdkerrors codespace+code is found or the pair is not in our mapping. Use this for protocol-layer errors from the lavasession/protocolerrors packages that carry an ABCI code via the sdkerrors interface.

func ClassifyMessage

func ClassifyMessage(code int, message string) *LavaError

ClassifyMessage classifies an error from just a message string and an optional numeric code, trying all transport types in order (JsonRPC → REST → gRPC) and returning the first non-unknown classification.

Use this only when the transport AND chain are genuinely unknown. Tier-2 (chain-specific) matchers are unconditionally skipped here, so a chain-native message that happens to contain a broad Tier-1 substring can be misclassified. If the chain is known, call ClassifyError directly (or use a helper like IsUnsupportedMethodError that takes a chainID) to avoid false matches.

func DetectConnectionError

func DetectConnectionError(err error) *LavaError

DetectConnectionError inspects err for connection-level failures and returns the corresponding LavaError, or nil if the error is not connection-related. This is the single place for connection detection — callers pass the result as the connectionError argument to ClassifyError.

Detection happens in three ordered layers:

  1. Structured checks via errors.Is / errors.As (context, net.Error timeouts).
  2. String-fallback table (detectConnectionErrorFromString) for wrapped errors that lose their sentinel chain (e.g. fmt.Errorf without %w).
  3. net.OpError unwrap for raw syscall errno codes.

The string fallback is deliberately second, so structured detection wins when it can. Within the string fallback, the match order is explicit in the stringConnectionFallbacks data table to make precedence easy to audit.

func (*LavaError) ABCICode

func (le *LavaError) ABCICode() uint32

ABCICode returns the error code for gRPC wire protocol compatibility. This replaces the sdkerrors.ABCICode() method so LavaError can be used in status.Error(codes.Code(err.ABCICode()), ...) calls.

func (*LavaError) Error

func (le *LavaError) Error() string

Error implements the error interface so LavaError can be used directly as an error and checked with errors.Is().

func (*LavaError) Is

func (le *LavaError) Is(target error) bool

Is implements errors.Is matching by error code. This allows errors.Is(err, LavaErrorSomething) to work when err wraps a LavaError.

func (*LavaError) IsRateLimited

func (le *LavaError) IsRateLimited() bool

IsRateLimited reports whether this classification represents a rate-limit signal from any layer (protocol, node, or node-specific limit exceeded). Driven by SubCategoryRateLimit rather than a hardcoded code comparison so new rate-limit codes only need to be tagged at registration time.

func (*LavaError) String

func (le *LavaError) String() string

type LavaWrappedError

type LavaWrappedError struct {
	LavaErr *LavaError
	Context string
}

LavaWrappedError wraps a LavaError with context, supporting errors.Is matching.

func (*LavaWrappedError) Error

func (e *LavaWrappedError) Error() string

func (*LavaWrappedError) Is

func (e *LavaWrappedError) Is(target error) bool

func (*LavaWrappedError) Unwrap

func (e *LavaWrappedError) Unwrap() error

type NodeErrorClassification

type NodeErrorClassification struct {
	IsNonRetryable      bool
	IsUnsupportedMethod bool
}

NodeErrorClassification aggregates the policy flags derived from a single registry lookup on a node-error response:

  • IsNonRetryable: registry entry is Retryable=false (hard stop for retries).
  • IsUnsupportedMethod: SubCategory-based predicate used by the consumer to apply the zero-CU carve-out and response caching.

func ClassifyNodeErrorForRetry

func ClassifyNodeErrorForRetry(family ChainFamily, transport TransportType, errorCode int, message string) NodeErrorClassification

ClassifyNodeErrorForRetry runs ClassifyError exactly once and derives the policy flags consumed by the consumer's retry decision and CU/caching carve-outs.

type NodeUrl

type NodeUrl struct {
	Url               string        `yaml:"url,omitempty" json:"url,omitempty" mapstructure:"url"`
	InternalPath      string        `yaml:"internal-path,omitempty" json:"internal-path,omitempty" mapstructure:"internal-path"`
	AuthConfig        AuthConfig    `yaml:"auth-config,omitempty" json:"auth-config,omitempty" mapstructure:"auth-config"`
	IpForwarding      bool          `yaml:"ip-forwarding,omitempty" json:"ip-forwarding,omitempty" mapstructure:"ip-forwarding"`
	Timeout           time.Duration `yaml:"timeout,omitempty" json:"timeout,omitempty" mapstructure:"timeout"`
	Addons            []string      `yaml:"addons,omitempty" json:"addons,omitempty" mapstructure:"addons"`
	SkipVerifications []string      `yaml:"skip-verifications,omitempty" json:"skip-verifications,omitempty" mapstructure:"skip-verifications"`
	Methods           []string      `yaml:"methods,omitempty" json:"methods,omitempty" mapstructure:"methods"`
	// GrpcConfig holds gRPC-specific configuration for direct gRPC connections (smart router)
	GrpcConfig GrpcConfig `yaml:"grpc-config,omitempty" json:"grpc-config,omitempty" mapstructure:"grpc-config"`
}

func (*NodeUrl) GetAuthHeaders

func (url *NodeUrl) GetAuthHeaders() map[string]string

func (*NodeUrl) LowerContextTimeout

func (url *NodeUrl) LowerContextTimeout(ctx context.Context, processingTimeout time.Duration) (context.Context, context.CancelFunc)

func (*NodeUrl) LowerContextTimeoutWithDuration

func (url *NodeUrl) LowerContextTimeoutWithDuration(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc)

func (*NodeUrl) SetAuthHeaders

func (url *NodeUrl) SetAuthHeaders(ctx context.Context, headerSetter func(string, string))

func (*NodeUrl) SetIpForwardingIfNecessary

func (url *NodeUrl) SetIpForwardingIfNecessary(ctx context.Context, headerSetter func(string, string))

func (NodeUrl) String

func (nurl NodeUrl) String() string

func (*NodeUrl) UrlStr

func (nurl *NodeUrl) UrlStr() string

type ProviderInfo

type ProviderInfo struct {
	ProviderAddress           string
	ProviderReputationSummary float64 // the number represents the average qos for this provider session
	ProviderStake             int64
}

type RelayResult

type RelayResult struct {
	Request             *pairingtypes.RelayRequest
	Reply               *pairingtypes.RelayReply
	ProviderInfo        ProviderInfo
	ReplyServer         pairingtypes.Relayer_RelaySubscribeClient
	Finalized           bool
	ConflictHandler     ConflictHandlerInterface
	StatusCode          int
	CrossValidation     int
	ProviderTrailer     metadata.MD // the provider trailer attached to the request. used to transfer useful information (which is not signed so shouldn't be trusted completely).
	IsNodeError         bool
	ResponseHash        [32]byte // cached SHA256 hash of Reply.Data for cross-validation comparison, zero-value if not computed
	IsUnsupportedMethod bool     // Indicates this node error is an unsupported method (zero CU, cached)
	// IsNonRetryable is the umbrella flag the retry state machine consults:
	// it's true whenever the matched registry LavaError has Retryable=false,
	// which covers unsupported method, execution reverted, out of gas,
	// invalid signature, double spend, etc. Retrying on another provider
	// would just reproduce the same deterministic failure.
	// IsUnsupportedMethod is an independent subset flag derived from the
	// SubCategory and used to gate the zero-CU carve-out and caching policy.
	IsNonRetryable bool
}

func (*RelayResult) GetProvider

func (rr *RelayResult) GetProvider() string

func (*RelayResult) GetReply

func (rr *RelayResult) GetReply() *pairingtypes.RelayReply

func (*RelayResult) GetReplyServer

func (*RelayResult) GetStatusCode

func (rr *RelayResult) GetStatusCode() int

type RestAptosError

type RestAptosError struct {
	Message     string      `json:"message"`
	ErrorCode   string      `json:"error_code"`
	VmErrorCode interface{} `json:"vm_error_code"`
}

type RestError

type RestError struct {
	Code    int           `json:"code"`
	Message string        `json:"message"`
	Details []interface{} `json:"details"`
}

type SafeChannelSender

type SafeChannelSender[T any] struct {
	// contains filtered or unexported fields
}

func NewSafeChannelSender

func NewSafeChannelSender[T any](ctx context.Context, ch chan<- T) *SafeChannelSender[T]

func (*SafeChannelSender[T]) Close

func (scs *SafeChannelSender[T]) Close()

func (*SafeChannelSender[T]) LockAndSendAsynchronously

func (scs *SafeChannelSender[T]) LockAndSendAsynchronously(msg T)

Used when there is a need to validate locked, but you don't want to wait for the channel to return.

func (*SafeChannelSender[T]) MarkClosed

func (scs *SafeChannelSender[T]) MarkClosed()

MarkClosed marks the channel as closed without actually closing the underlying channel. This is useful when replacing a channel (e.g., during consumer reconnection) to signal that sends should fail gracefully without panicking on close.

func (*SafeChannelSender[T]) ReplaceChannel

func (scs *SafeChannelSender[T]) ReplaceChannel(ch chan<- T)

func (*SafeChannelSender[T]) Send

func (scs *SafeChannelSender[T]) Send(msg T)

Used when you need to wait for the other side to receive the message.

type SafeSyncMap

type SafeSyncMap[K, V any] struct {
	// contains filtered or unexported fields
}

func (*SafeSyncMap[K, V]) Load

func (ssm *SafeSyncMap[K, V]) Load(key K) (ret V, ok bool, err error)

func (*SafeSyncMap[K, V]) LoadOrStore

func (ssm *SafeSyncMap[K, V]) LoadOrStore(key K, value V) (ret V, loaded bool, err error)

LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored. The function returns the value that was loaded or stored.

func (*SafeSyncMap[K, V]) Range

func (ssm *SafeSyncMap[K, V]) Range(f func(key K, value V) bool)

func (*SafeSyncMap[K, V]) Store

func (ssm *SafeSyncMap[K, V]) Store(key K, toSet V)

type Test_mode_ctx_key

type Test_mode_ctx_key struct{}

type TimeoutInfo

type TimeoutInfo struct {
	CU       uint64
	Hanging  bool
	Stateful uint32
}

type TransportType

type TransportType int
const (
	TransportJsonRPC TransportType = iota // EVM, Solana, Bitcoin, etc. (includes WebSocket subscriptions)
	TransportREST                         // Aptos, Stellar, some Cosmos endpoints
	TransportGRPC                         // Cosmos SDK chains
)

func ApiInterfaceToTransport

func ApiInterfaceToTransport(apiInterface string) TransportType

ApiInterfaceToTransport maps a spec API interface string (jsonrpc, tendermintrpc, rest, grpc) to the TransportType used by the error registry.

func (TransportType) String

func (t TransportType) String() string

type UserData

type UserData struct {
	ConsumerIp string
	DappId     string
}

Jump to

Keyboard shortcuts

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