jsonrpc

package
v0.0.0-...-4827941 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2023 License: MIT Imports: 9 Imported by: 2

Documentation

Overview

jsonrpc contains the common JSON RPC structures Infura products use.

Index

Examples

Constants

View Source
const (
	ErrCodeParseError          = -32700
	ErrCodeInvalidRequest      = -32600
	ErrCodeMethodNotFound      = -32601
	ErrCodeInvalidParams       = -32602
	ErrCodeInternalError       = -32603
	ErrCodeInvalidInput        = -32000
	ErrCodeResourceNotFound    = -32001
	ErrCodeResourceUnavailable = -32002
	ErrCodeTransactionRejected = -32003
	ErrCodeMethodNotSupported  = -32004
	ErrCodeLimitExceeded       = -32005
)
View Source
const VSN = "2.0"

Variables

This section is empty.

Functions

func RequestHandlerFunc

func RequestHandlerFunc(fn requestHandlerFunc) *requestHandlerFunc

RequestHandlerFunc is a helper for handling JSONRPC Requests over HTTP It can be used by microservices to handle JSONRPC methods. For example:

http.Handle("/", RequestHandlerFunc(func(ctx context.Context, r *Request) (interface{}, *Error) {
		if r.Method != "eth_blockNumber" {
			return nil, MethodNotSupported(fmt.Sprintf("unsupported method %s", r.Method))
		}

		return "0x123456", nil
	}))
Example
http.Handle("/", RequestHandlerFunc(func(ctx RequestContext, r *Request) (interface{}, *Error) {
	if r.Method != "eth_blockNumber" {
		return nil, MethodNotSupported(r)
	}

	// if the underlying HTTP Request object is required, it is accessible from the context
	url := ctx.HTTPRequest().URL
	if url.Host != "mainnet.infura.io" {
		return nil, InvalidInput("wrong host")
	}

	return "0x123456", nil
}))
Output:

func Unmarshal

func Unmarshal(data []byte) (interface{}, error)

func WriteResponse

func WriteResponse(w http.ResponseWriter, request *Request, result interface{}, e *Error)

Types

type BatchRequest

type BatchRequest []*Request

type BatchResponse

type BatchResponse []*Response

type Error

type Error struct {
	Code    ErrorCode       `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

func InternalError

func InternalError(message string, data ...map[string]interface{}) *Error

func InvalidInput

func InvalidInput(message string, data ...map[string]interface{}) *Error

func InvalidParams

func InvalidParams(message string, data ...map[string]interface{}) *Error

func InvalidRequest

func InvalidRequest(message string, data ...map[string]interface{}) *Error

func LimitExceeded

func LimitExceeded(message string, data ...map[string]interface{}) *Error

func MethodNotFound

func MethodNotFound(request *Request, data ...map[string]interface{}) *Error

func MethodNotSupported

func MethodNotSupported(request *Request, data ...map[string]interface{}) *Error

func NewError

func NewError(code ErrorCode, message string, data ...map[string]interface{}) *Error

func ParseError

func ParseError(message string) *Error

func ResourceNotFound

func ResourceNotFound(message string, data ...map[string]interface{}) *Error

func ResourceUnavailable

func ResourceUnavailable(message string, data ...map[string]interface{}) *Error

func TransactionRejected

func TransactionRejected(message string, data ...map[string]interface{}) *Error

func (*Error) Error

func (e *Error) Error() string

type ErrorCode

type ErrorCode int

type ID

type ID struct {
	// At most one of Num or Str may be nonzero. If both are zero
	// valued, then IsNum specifies which field's value is to be used
	// as the ID.
	Num uint64
	Str string

	// IsString controls whether the Num or Str field's value should be
	// used as the ID, when both are zero valued. It must always be
	// set to true if the request ID is a string.
	IsString bool
}

ID represents a JSON-RPC 2.0 request ID, which may be either a string or number (or null, which is unsupported).

func IntID

func IntID(i uint64) ID

func StringID

func StringID(s string) ID

func (ID) MarshalJSON

func (id ID) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (ID) String

func (id ID) String() string

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Notification

type Notification struct {
	JSONRPC string             `json:"jsonrpc"`
	Method  string             `json:"method"`
	Params  NotificationParams `json:"params"`
}

func (Notification) MarshalJSON

func (n Notification) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0" property.

func (*Notification) UnmarshalJSON

func (n *Notification) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Notification) UnmarshalParamsInto

func (n *Notification) UnmarshalParamsInto(receiver interface{}) error

UnmarshalParamsInto will decode Notification.Params into the passed in value, which must be a pointer receiver. The type of the passed in value is used to Unmarshal the data. UnmarshalInto will fail if the parameters cannot be converted to the passed-in types.

Example:

var newHead eth.NewHeads
err := notification.UnmarshalParamsInto(&newHead)

IMPORTANT: While Go will compile with non-pointer receivers, the Unmarshal attempt will *always* fail with an error.

type NotificationParams

type NotificationParams = json.RawMessage

Currently NotificationParams are always a JSON object, but this may change, in which case the code around NotificationParams will need to be updated.

type Param

type Param json.RawMessage

Params is an ARRAY of json.RawMessages. This is because *Ethereum* RPCs always use arrays is their input parameter; this differs from the official JSONRPC spec, which allows parameters of any type. But, this assumption makes handling Params in our Ethereum API use-cases *so* much easier.

func (Param) MarshalJSON

func (m Param) MarshalJSON() ([]byte, error)

MarshalJSON returns m as the JSON encoding of m.

func (*Param) UnmarshalJSON

func (m *Param) UnmarshalJSON(data []byte) error

UnmarshalJSON sets *m to a copy of data.

type Params

type Params []Param

func MakeParams

func MakeParams(params ...interface{}) (Params, error)

MakeParams generates JSONRPC parameters from its inputs, and should be used for complex dynamic data which may fail to marshal, in which case the error is propagated to the caller.

Examples:

params, err := jsonrpc.MakeParams(someComplexObject, "string", true)

func MustParams

func MustParams(params ...interface{}) Params

MakeParams can be used to generate JSONRPC Params field from well-known data, which should not fail.

Examples:

request.Params = jsonrpc.MustParams("latest", true)

func (Params) UnmarshalInto

func (p Params) UnmarshalInto(receivers ...interface{}) error

UnmarshalInto will decode Params into the passed in values, which must be pointer receivers. The type of the passed in value is used to Unmarshal the data. UnmarshalInto will fail if the parameters cannot be converted to the passed-in types.

Example:

var blockNum string
var fullBlock bool
err := request.Params.UnmarshalInto(&blockNum, &fullBlock)

IMPORTANT: While Go will compile with non-pointer receivers, the Unmarshal attempt will *always* fail with an error.

func (Params) UnmarshalSingleParam

func (p Params) UnmarshalSingleParam(pos int, receiver interface{}) error

UnmarshalSingleParam can be used in the (rare) case where only one of the Request.Params is needed. For example we use this in Smart Routing to extract the blockNum value from RPCs without decoding the entire Params array.

Example:

err := request.Params.UnmarshalSingleParam(pos, &blockNum)

type RawResponse

type RawResponse struct {
	JSONRPC string           `json:"jsonrpc"`
	ID      ID               `json:"id"`
	Result  json.RawMessage  `json:"result,omitempty"`
	Error   *json.RawMessage `json:"error,omitempty"`
}

RawResponse keeps Result and Error as unparsed JSON It is meant to be used to deserialize JSONPRC responses from downstream components while Response is meant to be used to craft our own responses to clients.

func NewErrorResponse

func NewErrorResponse(error *Error, id ID) *RawResponse

func NewInternalError

func NewInternalError(id ID) *RawResponse

func NewInvalidInput

func NewInvalidInput(message string, id ID) *RawResponse

func NewInvalidParams

func NewInvalidParams(id ID) *RawResponse

func NewInvalidParamsWithMessage

func NewInvalidParamsWithMessage(message string, id ID) *RawResponse

func NewMissingParams

func NewMissingParams(id ID, index int) *RawResponse

func NewNullResponse

func NewNullResponse(id ID) *RawResponse

func NewParseError

func NewParseError(id ID) *RawResponse

func NewResourceUnavailable

func NewResourceUnavailable(message string, id ID) *RawResponse

func NewResultRawResponse

func NewResultRawResponse(result []byte, id ID) *RawResponse

func (RawResponse) MarshalJSON

func (r RawResponse) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0" property.

func (*RawResponse) UnmarshalJSON

func (r *RawResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Request

type Request struct {
	JSONRPC string `json:"jsonrpc"`
	Method  string `json:"method"`
	ID      ID     `json:"id"`
	Params  Params `json:"params"`
}

func MakeRequest

func MakeRequest(id int, method string, params ...interface{}) (*Request, error)

MakeRequest builds a Request from all its parts, but returns an error if the params cannot be marshalled.

func MustRequest

func MustRequest(id int, method string, params ...interface{}) *Request

MustRequest builds a request from all its parts but panics if the params cannot be marshaled, so should only be used with well-known parameter data.

func NewRequest

func NewRequest() *Request

func (Request) MarshalJSON

func (r Request) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0" property.

func (*Request) UnmarshalJSON

func (r *Request) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type RequestContext

type RequestContext struct {
	context.Context
}

func (*RequestContext) HTTPRequest

func (rc *RequestContext) HTTPRequest() *http.Request

func (*RequestContext) HTTPResponseWriter

func (rc *RequestContext) HTTPResponseWriter() http.ResponseWriter

func (*RequestContext) RawJSON

func (rc *RequestContext) RawJSON() json.RawMessage

type RequestWithNetwork

type RequestWithNetwork struct {
	*Request
	Network string `json:"network"`
}

func (RequestWithNetwork) MarshalJSON

func (r RequestWithNetwork) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0" property.

func (*RequestWithNetwork) UnmarshalJSON

func (r *RequestWithNetwork) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Response

type Response struct {
	JSONRPC string      `json:"jsonrpc"`
	ID      ID          `json:"id"`
	Result  interface{} `json:"result,omitempty"`
	Error   interface{} `json:"error,omitempty"`
}

func NewResponse

func NewResponse() *Response

func NewResultResponse

func NewResultResponse(result interface{}, id ID) *Response

func (Response) MarshalJSON

func (r Response) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0" property.

func (*Response) UnmarshalJSON

func (r *Response) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

Jump to

Keyboard shortcuts

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