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:
Dmitry Zenovich
2021-08-25 20:30:29 +03:00
committed by GitHub
parent 154b525ce8
commit 7c4cad064c
2 changed files with 47 additions and 0 deletions

View File

@ -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)
}