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
- Variables
- func Compact(dst *bytes.Buffer, src []byte) error
- func HTMLEscape(dst *bytes.Buffer, src []byte)
- func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
- func IsDeterministicError(err *ErrResponse) bool
- func IsGanacheDeterministicError(err *ErrResponse) bool
- func IsGethDeterministicError(err *ErrResponse) bool
- func IsParityDeterministicError(err *ErrResponse) bool
- func MarshalJSONRPC(v interface{}) ([]byte, error)
- func MarshalJSONRPCIndent(v interface{}, prefix, indent string) ([]byte, error)
- func Valid(data []byte) bool
- type Block
- type BlockRef
- func (b *BlockRef) BlockNumber() (number uint64, ok bool)
- func (b *BlockRef) IsEarliest() bool
- func (b *BlockRef) IsLatest() bool
- func (b *BlockRef) IsPending() bool
- func (b BlockRef) MarshalJSONRPC() ([]byte, error)
- func (b BlockRef) String() string
- func (b *BlockRef) UnmarshalText(text []byte) error
- type Cache
- type CallParams
- type Client
- func (c *Client) Call(ctx context.Context, params CallParams) (string, error)
- func (c *Client) CallAtBlock(ctx context.Context, params CallParams, blockAt *BlockRef) (string, error)
- func (c *Client) ChainID(ctx context.Context) (*big.Int, error)
- func (c *Client) DoRequest(ctx context.Context, method string, params []interface{}) (string, error)
- func (c *Client) DoRequests(ctx context.Context, reqs []*RPCRequest) ([]*RPCResponse, error)
- func (c *Client) EstimateGas(ctx context.Context, params CallParams) (string, error)
- func (c *Client) GasPrice(ctx context.Context) (*big.Int, error)
- func (c *Client) GetBalance(ctx context.Context, accountAddr eth.Address) (*eth.TokenAmount, error)
- func (c *Client) GetBlockByNumber(ctx context.Context, blockNum uint64) (*Block, error)
- func (c *Client) GetTransactionCount(ctx context.Context, accountAddr eth.Address) (uint64, error)
- func (c *Client) LatestBlockNum(ctx context.Context) (uint64, error)
- func (c *Client) Logs(ctx context.Context, params LogsParams) ([]*LogEntry, error)
- func (c *Client) Nonce(ctx context.Context, accountAddr eth.Address) (uint64, error)
- func (c *Client) ProtocolVersion(ctx context.Context) (string, error)
- func (c *Client) SendRaw(ctx context.Context, rawData []byte) (string, error)
- func (c *Client) SendRawTransaction(ctx context.Context, rawData []byte) (string, error)
- func (c *Client) Syncing(ctx context.Context) (*SyncingResp, error)
- func (c *Client) TransactionReceipt(ctx context.Context, hash eth.Hash) (out *TransactionReceipt, err error)
- type ETHCall
- type ETHCallOption
- type Encoder
- type ErrResponse
- type InvalidUTF8Errordeprecated
- type LogEntry
- type LogsParams
- type Marshaler
- type MarshalerError
- type MarshalerRPC
- type Option
- type RPCRequest
- type RPCResponse
- type RawMessage
- type ResponseDecoder
- type SyncingResp
- type SyntaxError
- type TopicFilter
- type TopicFilterExpr
- type TransactionReceipt
- type UnsupportedTypeError
- type UnsupportedValueError
Constants ¶
const GANACHE_REVERT_MESSAGE = "VM Exception while processing transaction: revert"
const GANACHE_VM_EXECUTION_ERROR = -32000
const PARITY_BAD_INSTRUCTION_FD = "Bad instruction fd"
const PARITY_BAD_INSTRUCTION_FE = "Bad instruction fe"
const PARITY_BAD_JUMP_PREFIX = "Bad jump"
const PARITY_REVERT_PREFIX = "Reverted 0x"
const PARITY_STACK_LIMIT_PREFIX = "Out of stack"
const PARITY_VM_EXECUTION_ERROR = -32015
Variables ¶
var EarliestBlock = &BlockRef{tag: "earliest"}
var ErrFalseResp = errors.New("false response")
var GETH_DETERMINISTIC_ERRORS = []string{
"revert",
"invalid jump destination",
"invalid opcode",
"stack limit reached 1024",
"stack underflow (",
"gas uint64 overflow",
"out of gas",
}
var LatestBlock = &BlockRef{tag: "latest"}
var PendingBlock = &BlockRef{tag: "pending"}
Functions ¶
func Compact ¶
Compact appends to dst the JSON-encoded src with insignificant space characters elided.
func HTMLEscape ¶
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 ¶
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
func IsGanacheDeterministicError ¶
func IsGanacheDeterministicError(err *ErrResponse) bool
func IsGethDeterministicError ¶
func IsGethDeterministicError(err *ErrResponse) bool
func IsParityDeterministicError ¶
func IsParityDeterministicError(err *ErrResponse) bool
func MarshalJSONRPC ¶
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 ¶
Types ¶
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"` // Left out for now because we need to actually pull in https://github.com/holiman/uint256 // and get a eth.Uint256 wrapper in that is able to properly read those value from a JSON // string like "0x8792c6f47f70f". // Difficulty *big.Int `json:"difficulty"` // TotalDifficult *big.Int `json:"totalDifficulty"` Miner eth.Address `json:"miner"` Nonce eth.Hex `json:"nonce,omitempty"` LogsBloom eth.Hex `json:"logsBloom"` ExtraData eth.Hex `json:"extraData"` BaseFeePerGas eth.Uint64 `json:"baseFeePerGas,omitempty"` BlockSize eth.Uint64 `json:"size,omitempty"` // Left out for now because this is a dynamic type. It's a []eth.Hash value when hydrating // params is sets to `false` and it's a `rpc.TransactionReceipt` when sets to `true`. // Transactions interface{} `json:"transactions,omitempty"` UnclesSHA3 eth.Hash `json:"sha3Uncles,omitempty"` Uncles []eth.Hash `json:"uncles,omitempty"` }
type BlockRef ¶
type BlockRef struct {
// contains filtered or unexported fields
}
func BlockNumber ¶
func (*BlockRef) BlockNumber ¶
func (*BlockRef) IsEarliest ¶
func (BlockRef) MarshalJSONRPC ¶
func (*BlockRef) UnmarshalText ¶
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 { URL string // contains filtered or unexported fields }
TODO: refactor to use mux rpc
func (*Client) CallAtBlock ¶
func (*Client) DoRequests ¶
func (c *Client) DoRequests(ctx context.Context, reqs []*RPCRequest) ([]*RPCResponse, error)
func (*Client) EstimateGas ¶
func (*Client) GetBalance ¶
func (*Client) GetBlockByNumber ¶
func (*Client) GetTransactionCount ¶
func (*Client) LatestBlockNum ¶
func (*Client) ProtocolVersion ¶
func (*Client) SendRawTransaction ¶
func (*Client) TransactionReceipt ¶
func (c *Client) TransactionReceipt(ctx context.Context, hash eth.Hash) (out *TransactionReceipt, err 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 (*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 ¶
NewEncoder returns a new encoder that writes to w.
func (*Encoder) Encode ¶
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 ¶
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.
type ErrResponse ¶
type ErrResponse struct { Code int `json:"code"` Message string `json:"message"` Data interface{} `json:"data,omitempty"` }
func (*ErrResponse) Error ¶
func (e *ErrResponse) Error() string
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"` }
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.EarliestBlockRef`) (optional). FromBlock *BlockRef `json:"fromBlock,omitempty"` // ToBlock is either block number encoded as a hexadecimal or tagged value which is one of // "latest" (`LatestBlockRef()`), "pending" (`PendingBlockRef()`) or "earliest" tags (`EarliestBlockRef()`) (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"` }
type Marshaler ¶
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 ¶
MarshalerRPC is the interface implemented by types that can marshal themselves into valid JSON-RPC format.
It has precedence over MarshalJSON
type RPCRequest ¶
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
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 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 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"` // 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 UnsupportedTypeError ¶
An UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.
func (*UnsupportedTypeError) Error ¶
func (e *UnsupportedTypeError) Error() string
type UnsupportedValueError ¶
An UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.
func (*UnsupportedValueError) Error ¶
func (e *UnsupportedValueError) Error() string