rpc

package
v0.0.0-...-4e2b750 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2026 License: Apache-2.0 Imports: 24 Imported by: 11

Documentation

Overview

Package json implements encoding and decoding of JSON as defined in RFC 7159. The mapping between JSON and Go values is described in the documentation for the Marshal and Unmarshal functions.

See "JSON and Go" for an introduction to this package: https://golang.org/doc/articles/json_and_go.html

Use https://github.com/golang/go/commits/master/src/encoding/json to track changes made upstream to `encoding/json/encode.go` file.

Sync up to commit 04edf418d285df410745118aae756f9e0a9a00f5 (see https://github.com/golang/go/blob/04edf418d285df410745118aae756f9e0a9a00f5/src/encoding/json/encode.go)

Use https://github.com/golang/go/commits/master/src/encoding/json to track changes made upstream to `encoding/json/indent.go` file.

Sync up to commit 04edf418d285df410745118aae756f9e0a9a00f5 (see https://github.com/golang/go/blob/04edf418d285df410745118aae756f9e0a9a00f5/src/encoding/json/indent.go)

Use https://github.com/golang/go/commits/master/src/encoding/json to track changes made upstream to `encoding/json/scanner.go` file.

Sync up to commit 04edf418d285df410745118aae756f9e0a9a00f5 (see https://github.com/golang/go/blob/04edf418d285df410745118aae756f9e0a9a00f5/src/encoding/json/scanner.go)

Use https://github.com/golang/go/commits/master/src/encoding/json to track changes made upstream to `encoding/json/stream.go` file.

The decoding part is commented to ease including new changes made upstream. We only use the "specialized" marshaler and not the unmarshaler.

Sync up to commit 04edf418d285df410745118aae756f9e0a9a00f5 (see https://github.com/golang/go/blob/04edf418d285df410745118aae756f9e0a9a00f5/src/encoding/json/stream.go)

Index

Constants

View Source
const GANACHE_REVERT_MESSAGE = "VM Exception while processing transaction: revert"
View Source
const GANACHE_VM_EXECUTION_ERROR = -32000
View Source
const JSON_RPC_INVALID_ARGUMENT_ERROR = -32602
View Source
const JSON_RPC_INVALID_REQUEST_ERROR = -32600
View Source
const PARITY_BAD_INSTRUCTION_FD = "Bad instruction fd"
View Source
const PARITY_BAD_INSTRUCTION_FE = "Bad instruction fe"
View Source
const PARITY_BAD_JUMP_PREFIX = "Bad jump"
View Source
const PARITY_OUT_OF_BOUND = "return data out of bounds"
View Source
const PARITY_OUT_OF_GAS = "Out of gas"
View Source
const PARITY_REVERT_PREFIX = "Reverted 0x"
View Source
const PARITY_STACK_LIMIT_PREFIX = "Out of stack"
View Source
const PARITY_VM_EXECUTION_ERROR = -32015

Variables

View Source
var EarliestBlock = &BlockRef{tag: "earliest"}
View Source
var ErrFalseResp = errors.New("false response")
View Source
var FinalizedBlock = &BlockRef{tag: "finalized"}
View Source
var GETH_DETERMINISTIC_ERRORS = []string{
	"revert",
	"invalid jump destination",
	"invalid opcode",
	"stack limit reached 1024",
	"stack underflow (",
	"gas uint64 overflow",

	"out of gas",
	"evm error: invalidfeopcode",
}
View Source
var LatestBlock = &BlockRef{tag: "latest"}
View Source
var PendingBlock = &BlockRef{tag: "pending"}
View Source
var RETH_DETERMINISTIC_ERRORS = []string{
	"revert",
	"invalidjump",
	"opcodenotfound",
	"stackoverflow",
	"outofgas",
	"invalidfeopcode",
}

Functions

func Compact

func Compact(dst *bytes.Buffer, src []byte) error

Compact appends to dst the JSON-encoded src with insignificant space characters elided.

func Do

func Do[T any](c *Client, ctx context.Context, method string, params []interface{}) (out T, err error)

Do performs an RPC request and unmarshals the response into the type T. It wraps DoRequest and handles JSON unmarshalling automatically.

When T is string, the result is returned directly without JSON unmarshalling since DoRequest already returns the unquoted string value from the JSON response.

func HTMLEscape

func HTMLEscape(dst *bytes.Buffer, src []byte)

HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 so that the JSON will be safe to embed inside HTML <script> tags. For historical reasons, web browsers don't honor standard HTML escaping within <script> tags, so an alternative JSON encoding must be used.

func Indent

func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error

Indent appends to dst an indented form of the JSON-encoded src. Each element in a JSON object or array begins on a new, indented line beginning with prefix followed by one or more copies of indent according to the indentation nesting. The data appended to dst does not begin with the prefix nor any indentation, to make it easier to embed inside other formatted JSON data. Although leading space characters (space, tab, carriage return, newline) at the beginning of src are dropped, trailing space characters at the end of src are preserved and copied to dst. For example, if src has no trailing spaces, neither will dst; if src ends in a trailing newline, so will dst.

func IsDeterministicError

func IsDeterministicError(err *ErrResponse) bool

IsDeterministicError determines if an error is deterministic or not according to some heuristic based on the error's message.

The rules used here are the one used by `graph-node` software to determine if the error is determinsitic or not.

See https://github.com/graphprotocol/graph-node/blob/581ff5cf2978af66c49c91d4bf819b6647173776/chain/ethereum/src/ethereum_adapter.rs#L486

func IsGanacheDeterministicError

func IsGanacheDeterministicError(err *ErrResponse) bool

func IsGenericDeterministicError

func IsGenericDeterministicError(err *ErrResponse) bool

func IsGethDeterministicError

func IsGethDeterministicError(err *ErrResponse) bool

func IsParityDeterministicError

func IsParityDeterministicError(err *ErrResponse) bool

func IsRethDeterministicError

func IsRethDeterministicError(err *ErrResponse) bool

func MarshalJSONRPC

func MarshalJSONRPC(v interface{}) ([]byte, error)

MarshalJSONRPC returns the JSON encoding of v. It acts exactly like `json.Marshal` call excepts for a few variations: - It encodes byte array as hex encoding with "0x" prefix - The method MarshalJSONRPC has precedence over standard `MarshalJSON` - It supports JSON-RPC big.Int type out of the box - The escapeHTML option is to supported.

Marshal traverses the value v recursively. If an encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce JSON. If no MarshalJSON method is present but the value implements encoding.TextMarshaler instead, Marshal calls its MarshalText method and encodes the result as a JSON string. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of UnmarshalJSON.

Otherwise, Marshal uses the following type-dependent default encodings:

Boolean values encode as JSON booleans.

Floating point, integer, and Number values encode as JSON numbers.

String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. So that the JSON will be safe to embed inside HTML <script> tags, the string is encoded using HTMLEscape, which replaces "<", ">", "&", U+2028, and U+2029 are escaped to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". This replacement can be disabled when using an Encoder, by calling SetEscapeHTML(false).

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.

The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

As a special case, if the field tag is "-", the field is always omitted. Note that a field with name "-" can still be generated using the tag "-,".

Examples of struct field tags and their meanings:

// Field appears in JSON as key "myName".
Field int `json:"myName"`

// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`

// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`

// Field is ignored by this package.
Field int `json:"-"`

// Field appears in JSON as key "-".
Field int `json:"-,"`

The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

Int64String int64 `json:",string"`

The key name will be used if it's a non-empty string consisting of only Unicode letters, digits, and ASCII punctuation except quotation marks, backslash, and comma.

Anonymous struct fields are usually marshaled as if their inner exported fields were fields in the outer struct, subject to the usual Go visibility rules amended as described in the next paragraph. An anonymous struct field with a name given in its JSON tag is treated as having that name, rather than being anonymous. An anonymous struct field of interface type is treated the same as having that type as its name, rather than being anonymous.

The Go visibility rules for struct fields are amended for JSON when deciding which field to marshal or unmarshal. If there are multiple fields at the same level, and that level is the least nested (and would therefore be the nesting level selected by the usual Go rules), the following extra rules apply:

1) Of those fields, if any are JSON-tagged, only tagged fields are considered, even if there are multiple untagged fields that would otherwise conflict.

2) If there is exactly one field (tagged or not according to the first rule), that is selected.

3) Otherwise there are multiple fields, and all are ignored; no error occurs.

Handling of anonymous struct fields is new in Go 1.1. Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of an anonymous struct field in both current and earlier versions, give the field a JSON tag of "-".

Map values encode as JSON objects. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler. The map keys are sorted and used as JSON object keys by applying the following rules, subject to the UTF-8 coercion described for string values above:

  • keys of any string type are used directly
  • encoding.TextMarshalers are marshaled
  • integer keys are converted to strings

Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON value.

Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON value.

Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.

JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an error.

func MarshalJSONRPCIndent

func MarshalJSONRPCIndent(v interface{}, prefix, indent string) ([]byte, error)

func MarshalJSONRPCWithOpts

func MarshalJSONRPCWithOpts(v interface{}, useNumericID bool) ([]byte, error)

func Valid

func Valid(data []byte) bool

Valid reports whether data is a valid JSON encoding.

Types

type AccessList

type AccessList []AccessTuple

type AccessTuple

type AccessTuple struct {
	Address     eth.Address `json:"address"`
	StorageKeys []eth.Hash  `json:"storageKeys"`
}

type Block

type Block struct {
	Number           eth.Uint64         `json:"number"`
	Hash             eth.Hash           `json:"hash"`
	ParentHash       eth.Hash           `json:"parentHash"`
	Timestamp        eth.Timestamp      `json:"timestamp"`
	StateRoot        eth.Hash           `json:"stateRoot"`
	TransactionsRoot eth.Hash           `json:"transactionsRoot"`
	ReceiptsRoot     eth.Hash           `json:"receiptsRoot"`
	MixHash          eth.Hash           `json:"mixHash"`
	GasLimit         eth.Uint64         `json:"gasLimit"`
	GasUsed          eth.Uint64         `json:"gasUsed"`
	Difficulty       *eth.Uint256       `json:"difficulty"`
	TotalDifficulty  *eth.Uint256       `json:"totalDifficulty"`
	Miner            eth.Address        `json:"miner"`
	Nonce            eth.FixedUint64    `json:"nonce,omitempty"`
	LogsBloom        eth.Hex            `json:"logsBloom"`
	ExtraData        eth.Hex            `json:"extraData"`
	BaseFeePerGas    *eth.Uint256       `json:"baseFeePerGas,omitempty"`
	BlockSize        eth.Uint64         `json:"size,omitempty"`
	Transactions     *BlockTransactions `json:"transactions,omitempty"`
	UnclesSHA3       eth.Hash           `json:"sha3Uncles,omitempty"`
	Uncles           []eth.Hash         `json:"uncles,omitempty"`

	BlobGasUsed           *eth.Uint64  `json:"blobGasUsed,omitempty"`           // EIP-4844
	ExcessBlobGas         *eth.Uint64  `json:"excessBlobGas,omitempty"`         // EIP-4844
	ParentBeaconBlockRoot *eth.Hash    `json:"parentBeaconBlockRoot,omitempty"` // EIP-4844
	WithdrawalsHash       *eth.Hash    `json:"withdrawalsRoot,omitempty"`       // EIP-4895
	Withdrawals           []Withdrawal `json:"withdrawals,omitempty"`           // EIP-4895
	RequestsHash          *eth.Hash    `json:"requestsHash,omitempty"`          // EIP-7685
}

type BlockRef

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

func BlockHash

func BlockHash(hash string) *BlockRef

BlockHash is supported on some providers like Alchemy and is based on [EIP-1898](https://eips.ethereum.org/EIPS/eip-1898) rules.

@panics If hash == ""

func BlockNumber

func BlockNumber(number uint64) *BlockRef

func MaybeBlockHash

func MaybeBlockHash(in string) (*BlockRef, error)

MaybeBlockHash is exactly like BlockHash but it does not panic and returns the error instead.

func (*BlockRef) BlockHash

func (b *BlockRef) BlockHash() (hash eth.Hash, ok bool)

func (*BlockRef) BlockNumber

func (b *BlockRef) BlockNumber() (number uint64, ok bool)

func (*BlockRef) IsEarliest

func (b *BlockRef) IsEarliest() bool

func (*BlockRef) IsFinalized

func (b *BlockRef) IsFinalized() bool

func (*BlockRef) IsLatest

func (b *BlockRef) IsLatest() bool

func (*BlockRef) IsPending

func (b *BlockRef) IsPending() bool

func (*BlockRef) MarshalJSONRPC

func (b *BlockRef) MarshalJSONRPC() ([]byte, error)

func (*BlockRef) MarshalText

func (b *BlockRef) MarshalText() (string, error)

func (*BlockRef) SetShortBlockNumberNotation

func (b *BlockRef) SetShortBlockNumberNotation()

SetShortBlockNumberNotation sets the BlockRef to always be marshalled as a short string (ex: "0x123" or "latest") and never as long format like `{"blockNumber": ...}`

func (*BlockRef) String

func (b *BlockRef) String() string

func (*BlockRef) UnmarshalJSON

func (b *BlockRef) UnmarshalJSON(text []byte) error

func (*BlockRef) UnmarshalText

func (b *BlockRef) UnmarshalText(text []byte) error

type BlockTransactions

type BlockTransactions struct {
	Transactions []Transaction
	// contains filtered or unexported fields
}

BlockTransactions is a dynamic types and can be either a list of transactions hashes, retrievable via `Hashes()` getter when `GetBlockBy{Hash|Number}` is called without full transaction and it a list of transaction receipts if it's called with full transaction (option `rpc.WithGetBlockFullTransaction`).

func NewBlockTransactions

func NewBlockTransactions() *BlockTransactions

func (*BlockTransactions) Hashes

func (txs *BlockTransactions) Hashes() (out []eth.Hash)

func (*BlockTransactions) MarshalJSON

func (txs *BlockTransactions) MarshalJSON() ([]byte, error)

func (*BlockTransactions) MarshalJSONRPC

func (txs *BlockTransactions) MarshalJSONRPC() ([]byte, error)

func (*BlockTransactions) Receipts

func (txs *BlockTransactions) Receipts() (out []Transaction, found bool)

func (*BlockTransactions) UnmarshalJSON

func (txs *BlockTransactions) UnmarshalJSON(data []byte) error

type CallParams

type CallParams struct {
	// From the address the transaction is sent from (optional).
	From eth.Address `json:"from,omitempty"`
	// To the address the transaction is directed to (required).
	To eth.Address `json:"to,omitempty"`
	// GasLimit Integer of the gas provided for the transaction execution. eth_call consumes zero gas, but this parameter may be needed by some executions (optional).
	GasLimit uint64 `json:"gas,omitempty"`
	// GasPrice big integer of the gasPrice used for each paid gas (optional).
	GasPrice *big.Int `json:"gasPrice,omitempty"`
	// Value big integer of the value sent with this transaction (optional).
	Value *big.Int `json:"value,omitempty"`
	// Hash of the method signature and encoded parameters or any object that implements `MarshalJSONRPC` and serialize to a byte array, for details see Ethereum Contract ABI in the Solidity documentation (optional).
	Data interface{} `json:"data,omitempty"`
}

type Client

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

TODO: refactor to use mux rpc

func NewClient

func NewClient(endpointURL string, opts ...Option) *Client

func (*Client) Call

func (c *Client) Call(ctx context.Context, params CallParams) (string, error)

func (*Client) CallAtBlock

func (c *Client) CallAtBlock(ctx context.Context, params CallParams, blockAt *BlockRef) (string, error)

func (*Client) ChainID

func (c *Client) ChainID(ctx context.Context) (*big.Int, error)

func (*Client) DoRequest

func (c *Client) DoRequest(ctx context.Context, method string, params []interface{}) (string, error)

func (*Client) DoRequests

func (c *Client) DoRequests(ctx context.Context, reqs []*RPCRequest) ([]*RPCResponse, error)

func (*Client) EstimateGas

func (c *Client) EstimateGas(ctx context.Context, params CallParams) (string, error)

func (*Client) FinalizeBlockNum

func (c *Client) FinalizeBlockNum(ctx context.Context) (uint64, error)

func (*Client) GasPrice

func (c *Client) GasPrice(ctx context.Context) (*big.Int, error)

func (*Client) GetBalance

func (c *Client) GetBalance(ctx context.Context, accountAddr eth.Address, at *BlockRef) (*eth.TokenAmount, error)

func (*Client) GetBlockByHash

func (c *Client) GetBlockByHash(ctx context.Context, hash eth.Hash, opts ...GetBlockOption) (*Block, error)

GetBlockByHash fetches the block by its hash and optionally include full transaction receipts if you supply the `rpc.withGetBlockFullTransaction` option.

Uses RPC call `eth_getBlockByHash`.

func (*Client) GetBlockByNumber

func (c *Client) GetBlockByNumber(ctx context.Context, ref *BlockRef, opts ...GetBlockOption) (*Block, error)

GetBlockByNumber fetches the block by its number and optionally include full transaction receipts if you supply the `rpc.withGetBlockFullTransaction` option.

Uses RPC call `eth_getBlockByNumber`

func (*Client) GetCode

func (c *Client) GetCode(ctx context.Context, accountAddr eth.Address, at *BlockRef) (eth.Bytes, error)

func (*Client) GetTransactionCount

func (c *Client) GetTransactionCount(ctx context.Context, accountAddr eth.Address, at *BlockRef) (uint64, error)

func (*Client) LatestBlockNum

func (c *Client) LatestBlockNum(ctx context.Context) (uint64, error)

func (*Client) Logs

func (c *Client) Logs(ctx context.Context, params LogsParams) ([]*LogEntry, error)

func (*Client) Nonce

func (c *Client) Nonce(ctx context.Context, accountAddr eth.Address, at *BlockRef) (uint64, error)

func (*Client) ProtocolVersion

func (c *Client) ProtocolVersion(ctx context.Context) (string, error)

func (*Client) SendRaw

func (c *Client) SendRaw(ctx context.Context, rawData []byte) (string, error)

Depreacted: Use SendRawTransaction instead

func (*Client) SendRawTransaction

func (c *Client) SendRawTransaction(ctx context.Context, rawData []byte) (string, error)

func (*Client) String

func (c *Client) String() string

func (*Client) Syncing

func (c *Client) Syncing(ctx context.Context) (*SyncingResp, error)

func (*Client) TransactionReceipt

func (c *Client) TransactionReceipt(ctx context.Context, hash eth.Hash) (*TransactionReceipt, error)

TransactionReceipt fetches the receipt associated with the transaction's hash received. If the transaction is not found by the queried node, `nil, nil` is returned. If it's found, the receipt is decoded and `receipt, nil` is returned. Otherwise, the RPC error is returned if something went wrong.

type ETHCall

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

func NewETHCall

func NewETHCall(to eth.Address, methodDef *eth.MethodDef, options ...ETHCallOption) *ETHCall

func NewRawETHCall

func NewRawETHCall(callParams CallParams, atBlock *BlockRef) *ETHCall

NewRawETHCall can be used to construct an ETHCall when caller has already encoded the call data

func (*ETHCall) ToRequest

func (c *ETHCall) ToRequest() *RPCRequest

type ETHCallOption

type ETHCallOption func(*ETHCall)

func AtBlockNum

func AtBlockNum(num uint64) ETHCallOption

type Encoder

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

An Encoder writes JSON values to an output stream.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

func (*Encoder) Encode

func (enc *Encoder) Encode(v interface{}) error

Encode writes the JSON encoding of v to the stream, followed by a newline character.

See the documentation for Marshal for details about the conversion of Go values to JSON.

func (*Encoder) SetEscapeHTML

func (enc *Encoder) SetEscapeHTML(on bool)

SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.

In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior.

func (*Encoder) SetIndent

func (enc *Encoder) SetIndent(prefix, indent string)

SetIndent instructs the encoder to format each subsequent encoded value as if indented by the package-level function Indent(dst, src, prefix, indent). Calling SetIndent("", "") disables indentation.

type ErrResponse

type ErrResponse struct {
	Code    ErrorCode   `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

func (*ErrResponse) Error

func (e *ErrResponse) Error() string

type ErrorCode

type ErrorCode int

func (ErrorCode) MarshalJSONRPC

func (c ErrorCode) MarshalJSONRPC() ([]byte, error)

type GetBlockOption

type GetBlockOption interface {
	// contains filtered or unexported methods
}

func WithGetBlockFullTransaction

func WithGetBlockFullTransaction() GetBlockOption

type InvalidUTF8Error deprecated

type InvalidUTF8Error struct {
	S string // the whole string value that caused the error
}

Before Go 1.2, an InvalidUTF8Error was returned by Marshal when attempting to encode a string value with invalid UTF-8 sequences. As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by replacing invalid bytes with the Unicode replacement rune U+FFFD.

Deprecated: No longer used; kept for compatibility.

func (*InvalidUTF8Error) Error

func (e *InvalidUTF8Error) Error() string

type LogEntry

type LogEntry struct {
	Address          eth.Address `json:"address"`
	Topics           []eth.Hash  `json:"topics"`
	Data             eth.Hex     `json:"data"`
	BlockNumber      eth.Uint64  `json:"blockNumber"`
	TransactionHash  eth.Hash    `json:"transactionHash"`
	TransactionIndex eth.Uint64  `json:"transactionIndex"`
	BlockHash        eth.Hash    `json:"blockHash"`
	LogIndex         eth.Uint64  `json:"logIndex"`
	Removed          bool        `json:"removed"`
}

func (*LogEntry) ToLog

func (e *LogEntry) ToLog() (out eth.Log)

type LogsParams

type LogsParams struct {
	// FromBlock is either block number encoded as a hexadecimal or tagged value which is one of
	// "latest" (`rpc.LatestBlock`), "pending" (`rpc.PendingBlock`) or "earliest" tags (`rpc.EarliestBlock`) (optional).
	FromBlock *BlockRef `json:"fromBlock,omitempty"`

	// ToBlock is either block number encoded as a hexadecimal or tagged value which is one of
	// "latest" (`LatestBlock`), "pending" (`rpc.PendingBlock`) or "earliest" tags (`EarliestBlock`) (optional).
	ToBlock *BlockRef `json:"toBlock,omitempty"`

	// Address is the contract address or a list of addresses from which logs should originate (optional).
	Address eth.Address `json:"address,omitempty"`

	// Topics are order-dependent, each topic can also be an array of DATA with "or" options (optional).
	Topics *TopicFilter `json:"topics,omitempty"`

	// BlockHash is the block hash encoded as a hex string with prefix '0x'
	BlockHash eth.Bytes `json:"blockHash,omitempty"`
}

type Marshaler

type Marshaler interface {
	MarshalJSON() ([]byte, error)
}

Marshaler is the interface implemented by types that can marshal themselves into valid JSON.

type MarshalerError

type MarshalerError struct {
	Type reflect.Type
	Err  error
	// contains filtered or unexported fields
}

A MarshalerError represents an error from calling a MarshalJSON or MarshalText method.

func (*MarshalerError) Error

func (e *MarshalerError) Error() string

func (*MarshalerError) Unwrap

func (e *MarshalerError) Unwrap() error

Unwrap returns the underlying error.

type MarshalerRPC

type MarshalerRPC interface {
	MarshalJSONRPC() ([]byte, error)
}

MarshalerRPC is the interface implemented by types that can marshal themselves into valid JSON-RPC format.

It has precedence over MarshalJSON

type Option

type Option func(*Client)

func WithHttpClient

func WithHttpClient(httpClient *http.Client) Option

func WithHttpHeader

func WithHttpHeader(key, val string) Option

func WithNumericID

func WithNumericID(useNumericID bool) Option

type RPCRequest

type RPCRequest struct {
	Params []interface{} `json:"params"`
	Method string        `json:"method"`

	JSONRPC string  `json:"jsonrpc"`
	ID      eth.Int `json:"id"`
	// contains filtered or unexported fields
}

type RPCResponse

type RPCResponse struct {
	Content string
	ID      int
	Err     error
	// contains filtered or unexported fields
}

func (*RPCResponse) CopyDecoder

func (res *RPCResponse) CopyDecoder(req *RPCRequest)

func (*RPCResponse) Decode

func (res *RPCResponse) Decode() ([]interface{}, error)

func (*RPCResponse) Deterministic

func (res *RPCResponse) Deterministic() bool

func (*RPCResponse) Empty

func (res *RPCResponse) Empty() bool

func (*RPCResponse) UnmarshalJSON

func (r *RPCResponse) UnmarshalJSON(in []byte) error

type RawMessage

type RawMessage []byte

RawMessage is a raw encoded JSON value. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.

func (RawMessage) MarshalJSON

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

MarshalJSON returns m as the JSON encoding of m.

func (*RawMessage) UnmarshalJSON

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

UnmarshalJSON sets *m to a copy of data.

type ResponseDecoder

type ResponseDecoder func([]byte) ([]interface{}, error)

type SyncingResp

type SyncingResp struct {
	StartingBlockNum eth.Uint64 `json:"starting_block_num"`
	CurrentBlockNum  eth.Uint64 `json:"current_block_num"`
	HighestBlockNum  eth.Uint64 `json:"highest_block_num"`
}

type SyntaxError

type SyntaxError struct {
	Offset int64 // error occurred after reading Offset bytes
	// contains filtered or unexported fields
}

A SyntaxError is a description of a JSON syntax error.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

type TopicFilter

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

func NewTopicFilter

func NewTopicFilter(exprs ...interface{}) (out *TopicFilter)

func (*TopicFilter) Append

func (f *TopicFilter) Append(in interface{})

func (*TopicFilter) MarshalJSONRPC

func (f *TopicFilter) MarshalJSONRPC() ([]byte, error)

func (*TopicFilter) String

func (f *TopicFilter) String() string

type TopicFilterExpr

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

func AnyTopic

func AnyTopic() TopicFilterExpr

func ExactTopic

func ExactTopic(in interface{}) TopicFilterExpr

func OneOfTopic

func OneOfTopic(topics ...interface{}) (out TopicFilterExpr)

func (TopicFilterExpr) MarshalJSONRPC

func (f TopicFilterExpr) MarshalJSONRPC() ([]byte, error)

func (TopicFilterExpr) String

func (f TopicFilterExpr) String() string

type Transaction

type Transaction struct {
	// Hash is the hash of the transaction.
	Hash eth.Hash `json:"hash"`

	Nonce eth.Uint64 `json:"nonce,omitempty"`

	// BlockHash is the hash of the block where this transaction was in, none when pending.
	BlockHash eth.Hash `json:"blockHash"`

	// BlockNumber is the block number where this transaction was in, none when pending.
	BlockNumber eth.Uint64 `json:"blockNumber"`

	// TransactionIndex is the transactions index position in the block, none when pending.
	TransactionIndex eth.Uint64 `json:"transactionIndex"`

	// From is the address of the sender.
	From eth.Address `json:"from"`

	// To is the address of the receiver, `null` when the transaction is a contract creation transaction.
	To *eth.Address `json:"to"`

	// Value is the ETH transfered value to the recipient/
	Value *eth.Uint256 `json:"value"`

	// GasPrice is the ETH value of the gas sender is willing to pay, it's the effective gas price when London fork is active and transaction type is 0x02 (DynamicFee).
	GasPrice *eth.Uint256 `json:"gasPrice"`

	// Gas is the the amount of gas sender is willing to allocate for this transaction, might not be fully consumed.
	Gas eth.Uint64 `json:"gas"`

	// Input data the transaction will receive for execution of EVM.
	Input eth.Hex `json:"input,omitempty"`

	// V is the ECDSA recovery id of the transaction's signature.
	V eth.Uint64 `json:"v,omitempty"`

	// R is the ECDSA signature R point of transaction's signature.
	R *eth.Uint256 `json:"r,omitempty"`

	// S is the ECDSA signature S point of transaction's signature.
	S *eth.Uint256 `json:"s,omitempty"`

	// AccessList is the defined access list tuples when the transaction is of AccessList type (0x01), none when transaction of other types.
	AccessList AccessList `json:"accessList,omitempty"`

	// ChainID is the identifier chain the transaction was executed in, none if London fork is **not** activated
	ChainID eth.Uint64 `json:"chainId,omitempty"`

	// MaxFeePerGas is the identifier chain the transaction was executed in, none if London fork is **not** activated
	MaxFeePerGas *eth.Uint256 `json:"maxFeePerGas,omitempty"`

	// MaxPriorityFeePerGas is the identifier chain the transaction was executed in, none if London fork is **not** activated
	MaxPriorityFeePerGas *eth.Uint256 `json:"maxPriorityFeePerGas,omitempty"`

	// Type is the transaction's type
	Type eth.TransactionType `json:"type"`
}

Transaction retrieve from `eth_getBlockByXXX` methods.

type TransactionReceipt

type TransactionReceipt struct {
	// TransactionHash is the hash of the transaction.
	TransactionHash eth.Hash `json:"transactionHash"`
	// TransactionIndex is the transactions index position in the block.
	TransactionIndex eth.Uint64 `json:"transactionIndex"`
	// BlockHash is the hash of the block where this transaction was in.
	BlockHash eth.Hash `json:"blockHash"`
	// BlockNumber is the block number where this transaction was in.
	BlockNumber eth.Uint64 `json:"blockNumber"`
	// From is the address of the sender.
	From eth.Address `json:"from"`
	// To is the address of the receiver, `null` when the transaction is a contract creation transaction.
	To *eth.Address `json:"to,omitempty"`
	// CumulativeGasUsed is the the total amount of gas used when this transaction was executed in the block.
	CumulativeGasUsed eth.Uint64 `json:"cumulativeGasUsed"`
	// EffectiveGasPrice is the sum of the base fee and tip paid per unit of gas.
	EffectiveGasPrice eth.Uint64 `json:"effectiveGasPrice"`
	// GasUsed is the the amount of gas used by this specific transaction alone.
	GasUsed eth.Uint64 `json:"gasUsed"`
	// ContractAddress is the the contract address created, if the transaction was a contract creation, otherwise - null.
	ContractAddress *eth.Address `json:"contractAddress,omitempty"`
	// Logs is the Array of log objects, which this transaction generated.
	Logs []*LogEntry `json:"logs"`
	// LogsBloom is the Bloom filter for light clients to quickly retrieve related logs.
	LogsBloom eth.Hex `json:"logsBloom"`
	// Type is the transaction type, 0x0 for legacy transactions, 0x1 for access list types, 0x2 for dynamic fees
	Type eth.Uint64 `json:"type"`

	// Root: 32 bytes of post-transaction stateroot (pre Byzantium)
	Root eth.Hash `json:"root"`
	// Status is either 1 (success) or 0 (failure) (post Byzantium)
	Status *eth.Uint64 `json:"status"`
}

type UnsupportedTypeError

type UnsupportedTypeError struct {
	Type reflect.Type
}

An UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.

func (*UnsupportedTypeError) Error

func (e *UnsupportedTypeError) Error() string

type UnsupportedValueError

type UnsupportedValueError struct {
	Value reflect.Value
	Str   string
}

An UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.

func (*UnsupportedValueError) Error

func (e *UnsupportedValueError) Error() string

type Withdrawal

type Withdrawal struct {
	Index     eth.Uint64  `json:"index"`          // monotonically increasing identifier issued by consensus layer
	Validator eth.Uint64  `json:"validatorIndex"` // index of validator associated with withdrawal
	Address   eth.Address `json:"address"`        // target address for withdrawn ether
	Amount    eth.Uint64  `json:"amount"`         // value of withdrawal in Gwei
}

Jump to

Keyboard shortcuts

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