Skip to content

Commit

Permalink
minor improvement regarding JSON marshal (vechain#737)
Browse files Browse the repository at this point in the history
* minor improvement regarding JSON marshal

* Update thor/bytes32.go

Co-authored-by: Pedro Gomes <[email protected]>

---------

Co-authored-by: Pedro Gomes <[email protected]>
  • Loading branch information
libotony and otherview authored May 14, 2024
1 parent de6037f commit 95aed69
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
2 changes: 1 addition & 1 deletion genesis/customnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,5 +260,5 @@ func (i HexOrDecimal256) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
return []byte("\"" + string(text) + "\""), nil
return json.Marshal(string(text))
}
6 changes: 2 additions & 4 deletions thor/bytes32.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"strings"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
)

// Bytes32 array of 32 bytes.
Expand Down Expand Up @@ -46,9 +45,8 @@ func (b Bytes32) IsZero() bool {

// MarshalJSON implements json.Marshaler.
func (b Bytes32) MarshalJSON() ([]byte, error) {
// Convert Bytes32 to a hexadecimal string.
// if []byte = [00000...] then we return 0x000000 instead of nil
return json.Marshal(hexutil.Encode(b[:]))
// Bytes32 are represented as a hexadecimal string.
return json.Marshal(b.String())
}

// UnmarshalJSON implements json.Unmarshaler.
Expand Down
8 changes: 7 additions & 1 deletion thor/bytes32_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/assert"
)

func TestMarshalUnmarshall(t *testing.T) {
func TestMarshalUnmarshal(t *testing.T) {
// Example hex string representing the value 100
originalHex := `"0x00000000000000000000000000000000000000000000000000006d6173746572"` // Note the enclosing double quotes for valid JSON string

Expand Down Expand Up @@ -43,4 +43,10 @@ func TestMarshalUnmarshall(t *testing.T) {
marshalPtr, err := json.Marshal(&unmarshaledValue)
assert.NoError(t, err, "Marshaling should not produce an error")
assert.Equal(t, originalHex, string(marshalPtr))

// Marshal a zero value
var b Bytes32
j, err := b.MarshalJSON()
assert.NoError(t, err, "Marshaling should not produce an error")
assert.Equal(t, `"0x0000000000000000000000000000000000000000000000000000000000000000"`, string(j))
}

0 comments on commit 95aed69

Please sign in to comment.