Skip to content

Commit

Permalink
Eth JSON-RPC: support passing uint64 in JSON-RPC arguments for EthUint64
Browse files Browse the repository at this point in the history
  • Loading branch information
ychiaoli18 committed Jan 20, 2023
1 parent 1ea5774 commit 01d4693
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
26 changes: 18 additions & 8 deletions chain/types/ethtypes/eth_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,28 @@ 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 {
if !strings.HasPrefix(s, "0x") {
return fmt.Errorf("input string %s should start with 0x", s)
}
parsedInt, err := strconv.ParseUint(strings.Replace(s, "0x", "", -1), 16, 64)
if err != nil {
return err
}
eint := EthUint64(parsedInt)
*e = eint
return nil
}
parsedInt, err := strconv.ParseUint(strings.Replace(s, "0x", "", -1), 16, 64)
if err != nil {
return err
if eint, err := strconv.ParseUint(string(b), 10, 64); err == nil {
*e = EthUint64(eint)
return nil
}
eint := EthUint64(parsedInt)
*e = eint
return nil
return fmt.Errorf("cannot parse %s into EthUint64", string(b))
}

func EthUint64FromHex(s string) (EthUint64, error) {
Expand Down
5 changes: 4 additions & 1 deletion chain/types/ethtypes/eth_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down

0 comments on commit 01d4693

Please sign in to comment.