ethrpc

package module
v0.2.11 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2026 License: MIT Imports: 14 Imported by: 2

README

GoDoc

ethrpc

A lightweight Go library for making JSON-RPC calls to Ethereum-compatible nodes.

Install

go get github.com/KarpelesLab/ethrpc

Quick start

rpc := ethrpc.New("https://cloudflare-eth.com")
blockNo, err := ethrpc.ReadUint64(rpc.Do("eth_blockNumber"))

Features

Positional and named arguments
// Positional arguments
balance, err := ethrpc.ReadBigInt(rpc.Do("eth_getBalance", "0xAddress", "latest"))

// Named arguments
result, err := rpc.DoNamed("eth_call", map[string]any{
    "to":   "0xContract",
    "data": "0xCalldata",
})
Decode helpers

Response decoders can be chained directly with Do calls:

blockNo, err := ethrpc.ReadUint64(rpc.Do("eth_blockNumber"))
balance, err := ethrpc.ReadBigInt(rpc.Do("eth_getBalance", addr, "latest"))
hash, err := ethrpc.ReadString(rpc.Do("eth_sendRawTransaction", signedTx))

// Decode into a struct
var block MyBlockType
err := ethrpc.ReadTo(&block)(rpc.Do("eth_getBlockByNumber", "0x1b4", true))

// Generic decoder
block, err := ethrpc.ReadAs[MyBlockType](rpc.Do("eth_getBlockByNumber", "0x1b4", true))
Unmarshal into a target
var peers []any
err := rpc.To(&peers, "net_peerCount")
Context support

All methods have context-aware variants:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

blockNo, err := ethrpc.ReadUint64(rpc.DoCtx(ctx, "eth_blockNumber"))
Basic authentication
rpc := ethrpc.New("https://my-node.example.com")
rpc.SetBasicAuth("user", "password")
Method overrides

Intercept RPC methods locally without hitting the remote node:

rpc.Override("eth_chainId", func(ctx context.Context) (string, error) {
    return "0x1", nil
})
Server evaluation

Select the fastest endpoint from a list by racing eth_blockNumber calls:

handler, err := ethrpc.Evaluate(ctx,
    "https://node1.example.com",
    "https://node2.example.com",
    "https://node3.example.com",
)
// handler implements ethrpc.Handler with the best responding servers
HTTP response forwarding

Proxy JSON-RPC responses directly to an http.ResponseWriter:

rpc.Forward(ctx, w, req, &ethrpc.ForwardOptions{
    Pretty: true,
    Cache:  30 * time.Second,
})
Chain metadata

The chains subpackage provides static metadata for known EVM-compatible chains:

import "github.com/KarpelesLab/ethrpc/chains"

eth := chains.Get(1) // Ethereum Mainnet
fmt.Println(eth.Name)                          // "Ethereum Mainnet"
fmt.Println(eth.NativeCurrency.Symbol)         // "ETH"
fmt.Println(eth.HasFeature("EIP1559"))         // true
fmt.Println(eth.TransactionUrl("0xabc..."))    // "https://etherscan.io/tx/0xabc..."
fmt.Println(eth.ExplorerURL())                 // "https://etherscan.io"

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNoAvailableServer = errors.New("no available server")

ErrNoAvailableServer is returned by Evaluate when no servers are provided or reachable.

Functions

func ReadAs

func ReadAs[T any](v json.RawMessage, e error) (T, error)

ReadAs decodes the return value into the specified generic type T.

func ReadBigInt

func ReadBigInt(v json.RawMessage, e error) (*big.Int, error)

ReadBigInt can decode a json-encoded bigint in various ways, including if it is a number literal or a string.

func ReadString

func ReadString(v json.RawMessage, e error) (string, error)

ReadString decodes the return value as a string and returns it

func ReadTo

func ReadTo(target any) func(v json.RawMessage, e error) error

ReadTo returns a setter function that will return an error if an error happens. This is a bit convoluted because of limitation in Go's syntax, but this could be used as:

err = ReadTo(&block)(target.Do("eth_getBlockByNumber", "0x1b4", true))

func ReadUint64

func ReadUint64(v json.RawMessage, e error) (uint64, error)

ReadUint64 decodes the return value and passes it as a uint64.

This can be used as: res, err := ReadUint64(target.Do("eth_blockNumber"))

Types

type Api

type Api struct {
	Handler
}

Api wraps a Handler and provides convenience methods for common Ethereum RPC calls.

func (*Api) BlockNumber

func (a *Api) BlockNumber(ctx context.Context) (uint64, error)

BlockNumber returns the current block number from the connected node.

func (*Api) ChainId

func (a *Api) ChainId(ctx context.Context) (uint64, error)

ChainId returns the chain ID of the connected network.

func (*Api) Do

func (a *Api) Do(method string, args ...any) (json.RawMessage, error)

Do performs a JSON-RPC call using a background context.

func (*Api) To

func (a *Api) To(target any, method string, args ...any) error

To performs a JSON-RPC call and unmarshals the result into target.

func (*Api) ToCtx

func (a *Api) ToCtx(ctx context.Context, target any, method string, args ...any) error

ToCtx performs a JSON-RPC call with context and unmarshals the result into target.

type ErrorObject

type ErrorObject struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

ErrorObject represents a JSON-RPC 2.0 error returned by the server.

func (*ErrorObject) Error

func (e *ErrorObject) Error() string

type ForwardOptions

type ForwardOptions struct {
	Pretty bool
	Cache  time.Duration
}

ForwardOptions configures how RPC.Forward writes the response.

type Handler

type Handler interface {
	DoCtx(ctx context.Context, method string, args ...any) (json.RawMessage, error)
}

Handler is the interface for any backend capable of executing JSON-RPC calls.

func Evaluate

func Evaluate(ctx context.Context, servers ...string) (Handler, error)

Evaluate will call the various servers in the list and return a list of servers that work (if any)

This will send a eth_blockNumber request to all the servers and measure the response time

type RPC

type RPC struct {
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

RPC represents a connection to an Ethereum JSON-RPC endpoint. It supports HTTP transport with optional basic authentication and method overrides.

func New

func New(h string) *RPC

New returns a new instance of RPC to perform requests to the given RPC endpoint

func (*RPC) Do

func (r *RPC) Do(method string, args ...any) (json.RawMessage, error)

Do performs a RPC request

func (*RPC) DoCtx

func (r *RPC) DoCtx(ctx context.Context, method string, args ...any) (json.RawMessage, error)

DoCtx performs a RPC request, taking an optional context that can be cancelled to stop the request

func (*RPC) DoNamed

func (r *RPC) DoNamed(method string, args map[string]any) (json.RawMessage, error)

DoNamed performs a RPC request using named arguments

func (*RPC) DoNamedCtx

func (r *RPC) DoNamedCtx(ctx context.Context, method string, args map[string]any) (json.RawMessage, error)

DoNamedCtx performs a RPC request using named arguments, taking an optional context that can be cancelled to stop the request

func (*RPC) Forward

func (r *RPC) Forward(ctx context.Context, rw http.ResponseWriter, req *Request, opts *ForwardOptions)

Forward will write the RPC response to the given http.ResponseWriter.

func (*RPC) GetHost

func (r *RPC) GetHost() string

GetHost returns the host as configured

func (*RPC) Override

func (r *RPC) Override(method string, fnc any)

Override allows redirecting calls to a RPC method to a standard go function

func (*RPC) Send

func (r *RPC) Send(req *Request) (json.RawMessage, error)

Send sends a raw request for processing

func (*RPC) SendCtx

func (r *RPC) SendCtx(ctx context.Context, req *Request) (json.RawMessage, error)

SendCtx sends a raw Request to the RPC endpoint using the provided context.

func (*RPC) SetBasicAuth

func (r *RPC) SetBasicAuth(username, password string)

SetBasicAuth sets basic auth params for all subsequent RPC requests

func (*RPC) SetHost

func (r *RPC) SetHost(host string)

SetHost sets the host requests are sent to for subsequent RPC requests

func (*RPC) To

func (r *RPC) To(target any, method string, args ...any) error

To performs the request and puts the result into target

type RPCList

type RPCList []*RPC

RPCList is a list of RPC endpoints that implements Handler.

func (RPCList) DoCtx

func (r RPCList) DoCtx(ctx context.Context, method string, args ...any) (json.RawMessage, error)

DoCtx performs a JSON-RPC call using the first server in the list.

type Request

type Request struct {
	JsonRpc string `json:"jsonrpc"` // 2.0
	Method  string `json:"method"`
	Params  any    `json:"params"`
	Id      any    `json:"id"`
}

Request represents a JSON-RPC 2.0 request object.

func NewRequest

func NewRequest(method string, params ...any) *Request

NewRequest makes a new Request fit to use with methods like Send.

func NewRequestMap

func NewRequestMap(method string, params map[string]any) *Request

NewRequestMap makes a new Request fit to use with methods like Send, using named parameters.

func (*Request) HTTPRequest

func (req *Request) HTTPRequest(ctx context.Context, host string) (*http.Request, error)

HTTPRequest returns a http.Request for the given json-rpc request.

type Response

type Response struct {
	JsonRpc string          `json:"jsonrpc"` // 2.0
	Result  json.RawMessage `json:"result"`
	Error   *ErrorObject    `json:"error,omitempty"`
	Id      any             `json:"id"`
}

Response represents a JSON-RPC 2.0 response with a raw JSON result.

type ResponseIntf

type ResponseIntf struct {
	JsonRpc string       `json:"jsonrpc"` // 2.0
	Result  any          `json:"result"`
	Error   *ErrorObject `json:"error,omitempty"`
	Id      any          `json:"id"`
}

ResponseIntf is a JSON-RPC 2.0 response where Result is an arbitrary type rather than json.RawMessage, allowing direct encoding of Go values.

Directories

Path Synopsis
Package chains provides static metadata for known EVM-compatible chains.
Package chains provides static metadata for known EVM-compatible chains.

Jump to

Keyboard shortcuts

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