Skip to content

Commit

Permalink
Fix negative number hex formatting and add JSON number formatting option
Browse files Browse the repository at this point in the history
Signed-off-by: Peter Broadhurst <[email protected]>
  • Loading branch information
peterbroadhurst committed Oct 20, 2024
1 parent 41530b2 commit 2aaf316
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
11 changes: 10 additions & 1 deletion pkg/abi/outputserialization.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,16 @@ func Base10StringIntSerializer(i *big.Int) interface{} {
}

func HexIntSerializer0xPrefix(i *big.Int) interface{} {
return "0x" + i.Text(16)
absHi := new(big.Int).Abs(i)
sign := ""
if i.Sign() < 0 {
sign = "-"
}
return fmt.Sprintf("%s0x%s", sign, absHi.Text(16))
}

func JSONNumberIntSerializer(i *big.Int) interface{} {
return json.Number(i.String())
}

func Base10StringFloatSerializer(f *big.Float) interface{} {
Expand Down
34 changes: 34 additions & 0 deletions pkg/abi/outputserialization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,40 @@ func TestJSONSerializationFormatsTuple(t *testing.T) {
]`, string(j3))
}

func TestJSONSerializationNumbers(t *testing.T) {

abi := testABI(t, sampleABI1)
assert.NotNil(t, abi)

v, err := (ParameterArray{{Type: "uint"}, {Type: "int"}}).ParseJSON([]byte(`[
"123000000000000000000000112233",
"-0x18d6f3720c92d9d437801b669"
]`))
assert.NoError(t, err)

j, err := v.JSON()
assert.NoError(t, err)
assert.JSONEq(t, `{
"0": "123000000000000000000000112233",
"1": "-123000000000000000000000112233"
}`, string(j))

j, err = NewSerializer().SetIntSerializer(HexIntSerializer0xPrefix).SerializeJSON(v)
assert.NoError(t, err)
assert.JSONEq(t, `{
"0": "0x18d6f3720c92d9d437801b669",
"1": "-0x18d6f3720c92d9d437801b669"
}`, string(j))

j, err = NewSerializer().SetIntSerializer(JSONNumberIntSerializer).SerializeJSON(v)
assert.NoError(t, err)
assert.JSONEq(t, `{
"0": 123000000000000000000000112233,
"1": -123000000000000000000000112233
}`, string(j))

}

func TestJSONSerializationForTypes(t *testing.T) {

abi := testABI(t, sampleABI2)
Expand Down

0 comments on commit 2aaf316

Please sign in to comment.