transport

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2024 License: MIT Imports: 18 Imported by: 2

Documentation

Index

Constants

View Source
const (
	// Standard errors:
	ErrCodeUnauthorized     = 1
	ErrCodeActionNotAllowed = 2
	ErrCodeExecutionError   = 3
	ErrCodeParseError       = -32700
	ErrCodeInvalidRequest   = -32600
	ErrCodeMethodNotFound   = -32601
	ErrCodeInvalidParams    = -32602
	ErrCodeInternalError    = -32603

	// Common non-standard errors:
	ErrCodeGeneral       = -32000
	ErrCodeLimitExceeded = -32005

	// Erigon errors:
	ErigonErrCodeGeneral         = -32000
	ErigonErrCodeNotFound        = -32601
	ErigonErrCodeUnsupportedFork = -38005

	// Nethermind errors:
	NethermindErrCodeMethodNotSupported  = -32004
	NethermindErrCodeLimitExceeded       = -32005
	NethermindErrCodeTransactionRejected = -32010
	NethermindErrCodeExecutionError      = -32015
	NethermindErrCodeTimeout             = -32016
	NethermindErrCodeModuleTimeout       = -32017
	NethermindErrCodeAccountLocked       = -32020
	NethermindErrCodeUnknownBlockError   = -39001

	// Infura errors:
	InfuraErrCodeInvalidInput               = -32000
	InfuraErrCodeResourceNotFound           = -32001
	InfuraErrCodeResourceUnavailable        = -32002
	InfuraErrCodeTransactionRejected        = -32003
	InfuraErrCodeMethodNotSupported         = -32004
	InfuraErrCodeLimitExceeded              = -32005
	InfuraErrCodeJSONRPCVersionNotSupported = -32006

	// Alchemy errors:
	AlchemyErrCodeLimitExceeded = 429

	// Blast errors:
	BlastErrCodeAuthenticationFailed = -32099
	BlastErrCodeCapacityExceeded     = -32098
	BlastErrRateLimitReached         = -32097
)

Variables

View Source
var (
	// RetryOnAnyError retries on any error except for the following:
	// 3: Execution error.
	// -32700: Parse error.
	// -32600: Invalid request.
	// -32601: Method not found.
	// -32602: Invalid params.
	// -32000: If error message starts with "execution reverted".
	RetryOnAnyError = func(err error) bool {

		switch errorCode(err) {
		case ErrCodeExecutionError:
			return false
		case ErrCodeParseError:
			return false
		case ErrCodeInvalidRequest:
			return false
		case ErrCodeMethodNotFound:
			return false
		case ErrCodeInvalidParams:
			return false
		case ErrCodeGeneral:
			rpcErr := &RPCError{}
			if errors.As(err, &rpcErr) {
				if strings.HasPrefix(rpcErr.Message, "execution reverted") {
					return false
				}
			}
		}

		return err != nil
	}

	// RetryOnLimitExceeded retries on the following errors:
	// -32005: Limit exceeded.
	// -32097: Rate limit reached (Blast).
	// 429: Too many requests
	RetryOnLimitExceeded = func(err error) bool {
		switch errorCode(err) {
		case ErrCodeLimitExceeded:
			return true
		case BlastErrRateLimitReached:
			return true
		case AlchemyErrCodeLimitExceeded:
			return true
		}
		return false
	}
)
View Source
var (
	// LinearBackoff returns a BackoffFunc that returns a constant delay.
	LinearBackoff = func(delay time.Duration) func(int) time.Duration {
		return func(_ int) time.Duration {
			return delay
		}
	}

	// ExponentialBackoff returns a BackoffFunc that returns an exponential delay.
	// The delay is calculated as BaseDelay * ExponentialFactor ^ retryCount.
	ExponentialBackoff = func(opts ExponentialBackoffOptions) func(int) time.Duration {
		return func(retryCount int) time.Duration {
			d := time.Duration(float64(opts.BaseDelay) * math.Pow(opts.ExponentialFactor, float64(retryCount)))
			if d > opts.MaxDelay {
				return opts.MaxDelay
			}
			return d
		}
	}
)
View Source
var ErrNotSubscriptionTransport = errors.New("transport does not implement SubscriptionTransport")

Functions

This section is empty.

Types

type Combined

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

Combined is transport that uses separate transports for regular calls and subscriptions.

It is recommended by some RPC providers to use HTTP for regular calls and WebSockets for subscriptions.

func NewCombined

func NewCombined(call Transport, subscriber SubscriptionTransport) *Combined

NewCombined creates a new Combined transport.

func (*Combined) Call

func (c *Combined) Call(ctx context.Context, result any, method string, args ...any) error

Call implements the Transport interface.

func (*Combined) Subscribe

func (c *Combined) Subscribe(ctx context.Context, method string, args ...any) (ch chan json.RawMessage, id string, err error)

Subscribe implements the SubscriptionTransport interface.

func (*Combined) Unsubscribe

func (c *Combined) Unsubscribe(ctx context.Context, id string) error

Unsubscribe implements the SubscriptionTransport interface.

type ExponentialBackoffOptions

type ExponentialBackoffOptions struct {
	// BaseDelay is the base delay before the first retry.
	BaseDelay time.Duration

	// MaxDelay is the maximum delay between retries.
	MaxDelay time.Duration

	// ExponentialFactor is the exponential factor to use for calculating the delay.
	// The delay is calculated as BaseDelay * ExponentialFactor ^ retryCount.
	ExponentialFactor float64
}

ExponentialBackoffOptions contains options for the ExponentialBackoff function.

type HTTP

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

HTTP is a Transport implementation that uses the HTTP protocol.

func NewHTTP

func NewHTTP(opts HTTPOptions) (*HTTP, error)

NewHTTP creates a new HTTP instance.

func (*HTTP) Call

func (h *HTTP) Call(ctx context.Context, result any, method string, args ...any) error

Call implements the Transport interface.

type HTTPError

type HTTPError struct {
	Code int   // Code is the HTTP status code.
	Err  error // Err is an optional underlying error.
}

HTTPError is an HTTP error.

func NewHTTPError added in v0.4.5

func NewHTTPError(code int, err error) *HTTPError

NewHTTPError creates a new HTTP error.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface.

func (*HTTPError) HTTPErrorCode added in v0.5.0

func (e *HTTPError) HTTPErrorCode() int

HTTPErrorCode implements the HTTPErrorCode interface.

type HTTPErrorCode added in v0.5.0

type HTTPErrorCode interface {
	// HTTPErrorCode returns the HTTP status code.
	HTTPErrorCode() int
}

type HTTPOptions

type HTTPOptions struct {
	// URL of the HTTP endpoint.
	URL string

	// HTTPClient is the HTTP client to use. If nil, http.DefaultClient is
	// used.
	HTTPClient *http.Client

	// HTTPHeader specifies the HTTP headers to send with each request.
	HTTPHeader http.Header
}

HTTPOptions contains options for the HTTP transport.

type IPC

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

IPC is a Transport implementation that uses the IPC protocol.

func NewIPC

func NewIPC(opts IPCOptions) (*IPC, error)

NewIPC creates a new IPC instance.

func (IPC) Call

func (s IPC) Call(ctx context.Context, result any, method string, args ...any) error

Call implements the Transport interface.

func (IPC) Subscribe

func (s IPC) Subscribe(ctx context.Context, method string, args ...any) (chan json.RawMessage, string, error)

Subscribe implements the SubscriptionTransport interface.

func (IPC) Unsubscribe

func (s IPC) Unsubscribe(ctx context.Context, id string) error

Unsubscribe implements the SubscriptionTransport interface.

type IPCOptions

type IPCOptions struct {
	// Context used to close the connection.
	Context context.Context

	// Path is the path to the IPC socket.
	Path string

	// Timeout is the timeout for the IPC requests. Default is 60s.
	Timout time.Duration

	// ErrorCh is an optional channel used to report errors.
	ErrorCh chan error
}

IPCOptions contains options for the IPC transport.

type RPCError

type RPCError struct {
	Code    int    // Code is the JSON-RPC error code.
	Message string // Message is the error message.
	Data    any    // Data associated with the error.
}

RPCError is an JSON-RPC error.

func NewRPCError added in v0.4.5

func NewRPCError(code int, message string, data any) *RPCError

NewRPCError creates a new RPC error.

If data is a hex-encoded string, it will be decoded.

func (*RPCError) Error

func (e *RPCError) Error() string

Error implements the error interface.

func (*RPCError) RPCErrorCode added in v0.5.0

func (e *RPCError) RPCErrorCode() int

RPCErrorCode implements the ErrorCode interface.

func (*RPCError) RPCErrorData added in v0.5.0

func (e *RPCError) RPCErrorData() any

RPCErrorData implements the ErrorData interface.

type RPCErrorCode added in v0.5.0

type RPCErrorCode interface {
	// RPCErrorCode returns the JSON-RPC error code.
	RPCErrorCode() int
}

type RPCErrorData added in v0.5.0

type RPCErrorData interface {
	// RPCErrorData returns the JSON-RPC error data.
	RPCErrorData() any
}

type Retry

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

Retry is a wrapper around another transport that retries requests.

func NewRetry

func NewRetry(opts RetryOptions) (*Retry, error)

NewRetry creates a new Retry instance.

func (*Retry) Call

func (c *Retry) Call(ctx context.Context, result any, method string, args ...any) (err error)

Call implements the Transport interface.

func (*Retry) Subscribe

func (c *Retry) Subscribe(ctx context.Context, method string, args ...any) (ch chan json.RawMessage, id string, err error)

Subscribe implements the SubscriptionTransport interface.

func (*Retry) Unsubscribe

func (c *Retry) Unsubscribe(ctx context.Context, id string) (err error)

Unsubscribe implements the SubscriptionTransport interface.

type RetryOptions

type RetryOptions struct {
	// Transport is the underlying transport to use.
	Transport Transport

	// RetryFunc is a function that returns true if the request should be
	// retried. The RetryOnAnyError and RetryOnLimitExceeded functions can be
	// used or a custom function can be provided.
	RetryFunc func(error) bool

	// BackoffFunc is a function that returns the delay before the next retry.
	// It takes the current retry count as an argument.
	BackoffFunc func(int) time.Duration

	// MaxRetries is the maximum number of retries. If negative, there is no limit.
	MaxRetries int
}

RetryOptions contains options for the Retry transport.

type SubscriptionTransport

type SubscriptionTransport interface {
	Transport

	// Subscribe starts a new subscription. It returns a channel that receives
	// subscription messages and a subscription ID.
	Subscribe(ctx context.Context, method string, args ...any) (ch chan json.RawMessage, id string, err error)

	// Unsubscribe cancels a subscription. The channel returned by Subscribe
	// will be closed.
	Unsubscribe(ctx context.Context, id string) error
}

SubscriptionTransport is transport that supports subscriptions.

type Transport

type Transport interface {
	// Call performs a JSON-RPC call.
	Call(ctx context.Context, result any, method string, args ...any) error
}

Transport handles the transport layer of the JSON-RPC protocol.

func New

func New(ctx context.Context, rpcURL string) (Transport, error)

New returns a new Transport instance based on the URL scheme. Supported schemes are: http, https, ws, wss. If scheme is empty, it will use IPC.

The context is used to close the underlying connection when the transport uses a websocket or IPC.

type Websocket

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

Websocket is a Transport implementation that uses the websocket protocol.

func NewWebsocket

func NewWebsocket(opts WebsocketOptions) (*Websocket, error)

NewWebsocket creates a new Websocket instance.

func (Websocket) Call

func (s Websocket) Call(ctx context.Context, result any, method string, args ...any) error

Call implements the Transport interface.

func (Websocket) Subscribe

func (s Websocket) Subscribe(ctx context.Context, method string, args ...any) (chan json.RawMessage, string, error)

Subscribe implements the SubscriptionTransport interface.

func (Websocket) Unsubscribe

func (s Websocket) Unsubscribe(ctx context.Context, id string) error

Unsubscribe implements the SubscriptionTransport interface.

type WebsocketOptions

type WebsocketOptions struct {
	// Context used to close the connection.
	Context context.Context

	// URL of the websocket endpoint.
	URL string

	// HTTPClient is the HTTP client to use. If nil, http.DefaultClient is
	// used.
	HTTPClient *http.Client

	// HTTPHeader specifies the HTTP headers to be included in the
	// websocket handshake request.
	HTTPHeader http.Header

	// Timeout is the timeout for the websocket requests. Default is 60s.
	Timout time.Duration

	// ErrorCh is an optional channel used to report errors.
	ErrorCh chan error
}

WebsocketOptions contains options for the websocket transport.

Jump to

Keyboard shortcuts

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