rpc: add BlockNumber.MarshalText (#23324)
Currently rpc.BlockNumber is marshalled to JSON as a numeric value, which is wrong because BlockNumber.UnmarshalJSON() wants it to either be hex-encoded or string "earliest"/"latest"/"pending". As a result, the call chain rpc.BlockNumberOrHashWithNumber(123) -> json.Marshal() -> json.Unmarshal() fails with error "cannot unmarshal object into Go value of type string".
This commit is contained in:
16
rpc/types.go
16
rpc/types.go
@ -98,6 +98,22 @@ func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler. It marshals:
|
||||
// - "latest", "earliest" or "pending" as strings
|
||||
// - other numbers as hex
|
||||
func (bn BlockNumber) MarshalText() ([]byte, error) {
|
||||
switch bn {
|
||||
case EarliestBlockNumber:
|
||||
return []byte("earliest"), nil
|
||||
case LatestBlockNumber:
|
||||
return []byte("latest"), nil
|
||||
case PendingBlockNumber:
|
||||
return []byte("pending"), nil
|
||||
default:
|
||||
return hexutil.Uint64(bn).MarshalText()
|
||||
}
|
||||
}
|
||||
|
||||
func (bn BlockNumber) Int64() int64 {
|
||||
return (int64)(bn)
|
||||
}
|
||||
|
Reference in New Issue
Block a user