Skip to content

Commit

Permalink
feat(tm2): implement custom encoding/json marshaler on crypto.Address (
Browse files Browse the repository at this point in the history
…#2756)

Currently, on any `sdk.Message`, when doing a json.Marshal, the result
look like:

```json
{"amount": [{"denom": "ugnot", "amount": 10000000}], "to_address": [109, 116, 186, 231, 239, 107, 120, 148, 194, 146, 166, 150, 161, 244, 93, 201, 25, 61, 216, 223], "from_address": [70, 139, 48, 165, 116, 79, 88, 170, 84, 108, 231, 73, 227, 127, 127, 98, 252, 214, 167, 152]}
```

Now it's returning

```json
{"from_address":"g1g69npft5fav254rvuay7xlmlvt7ddfucgvx8xf","to_address":"g1d46t4el0dduffs5j56t2razaeyvnmkxlduduuw","amount":[{"denom":"ugnot","amount":10000000}]}
```

This is already done for amino Marshalling, it's not for json.

---------

Co-authored-by: Morgan Bazalgette <morgan@morganbaz.com>
  • Loading branch information
albttx and thehowl authored Sep 6, 2024
1 parent d5015ab commit 9396400
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions tm2/pkg/crypto/bech32_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package crypto_test

import (
"encoding/json"
"math/rand"
"testing"

Expand Down Expand Up @@ -59,6 +60,7 @@ func TestRandBech32AddrConsistency(t *testing.T) {
addr := crypto.AddressFromBytes(pub.Address().Bytes())
testMarshal(t, addr, amino.Marshal, amino.Unmarshal)
testMarshal(t, addr, amino.MarshalJSON, amino.UnmarshalJSON)
testMarshal(t, addr, json.Marshal, json.Unmarshal)

str := addr.String()
res, err := crypto.AddressFromBech32(str)
Expand Down
15 changes: 15 additions & 0 deletions tm2/pkg/crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package crypto

import (
"bytes"
"encoding/json"
"fmt"

"github.com/gnolang/gno/tm2/pkg/bech32"
Expand Down Expand Up @@ -53,11 +54,25 @@ func AddressFromBytes(bz []byte) (ret Address) {
return
}

func (addr Address) MarshalJSON() ([]byte, error) {
b := AddressToBech32(addr)
return []byte(`"` + b + `"`), nil
}

func (addr *Address) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
return addr.UnmarshalAmino(s)
}

func (addr Address) MarshalAmino() (string, error) {
return AddressToBech32(addr), nil
}

func (addr *Address) UnmarshalAmino(b32str string) (err error) {
// NOTE: also used to unmarshal normal JSON, through UnmarshalJSON.
if b32str == "" {
return nil // leave addr as zero.
}
Expand Down

0 comments on commit 9396400

Please sign in to comment.