diff --git a/chain/types/ethtypes/eth_types.go b/chain/types/ethtypes/eth_types.go index eb0e12891..af27ec58c 100644 --- a/chain/types/ethtypes/eth_types.go +++ b/chain/types/ethtypes/eth_types.go @@ -39,18 +39,24 @@ func (e EthUint64) MarshalJSON() ([]byte, error) { return json.Marshal(e.Hex()) } +// UnmarshalJSON should be able to parse two types of input: +// 1. a JSON string containing a hex-encoded uint64 starting with 0x +// 2. a valid string containing a uint64 in decimal func (e *EthUint64) UnmarshalJSON(b []byte) error { var s string - if err := json.Unmarshal(b, &s); err != nil { - return err + if err := json.Unmarshal(b, &s); err == nil { + parsedInt, err := strconv.ParseUint(strings.Replace(s, "0x", "", -1), 16, 64) + if err != nil { + return err + } + eint := EthUint64(parsedInt) + *e = eint + return nil + } else if eint, err := strconv.ParseUint(string(b), 10, 64); err == nil { + *e = EthUint64(eint) + return nil } - parsedInt, err := strconv.ParseUint(strings.Replace(s, "0x", "", -1), 16, 64) - if err != nil { - return err - } - eint := EthUint64(parsedInt) - *e = eint - return nil + return fmt.Errorf("cannot parse %s into EthUint64", string(b)) } func EthUint64FromHex(s string) (EthUint64, error) { diff --git a/chain/types/ethtypes/eth_types_test.go b/chain/types/ethtypes/eth_types_test.go index 89c38ba29..b05557b07 100644 --- a/chain/types/ethtypes/eth_types_test.go +++ b/chain/types/ethtypes/eth_types_test.go @@ -36,13 +36,16 @@ func TestEthIntUnmarshalJSON(t *testing.T) { {[]byte("\"0x0\""), EthUint64(0)}, {[]byte("\"0x41\""), EthUint64(65)}, {[]byte("\"0x400\""), EthUint64(1024)}, + {[]byte("0"), EthUint64(0)}, + {[]byte("100"), EthUint64(100)}, + {[]byte("1024"), EthUint64(1024)}, } for _, tc := range testcases { var i EthUint64 err := i.UnmarshalJSON(tc.Input.([]byte)) require.Nil(t, err) - require.Equal(t, i, tc.Output) + require.Equal(t, tc.Output, i) } }