Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(tm2): crypto.Address json Marshal #2756

Merged
merged 2 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@

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

"github.com/gnolang/gno/tm2/pkg/bech32"
Expand Down Expand Up @@ -53,11 +54,25 @@
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

Check warning on line 65 in tm2/pkg/crypto/crypto.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/crypto.go#L65

Added line #L65 was not covered by tests
}
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
Loading