Skip to content

Commit

Permalink
Merge PR #4454: Implement MarshalJSON for Coins Type
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderbez authored May 31, 2019
1 parent d204afb commit 6ec9b26
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .pending/improvements/sdk/4259-Coins-that-are-
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#4259 `Coins` that are `nil` are now JSON encoded as an empty array `[]`.
Decoding remains unchanged and behavior is left intact.
13 changes: 13 additions & 0 deletions types/coin.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package types

import (
"encoding/json"
"fmt"
"regexp"
"sort"
Expand Down Expand Up @@ -151,6 +152,18 @@ func NewCoins(coins ...Coin) Coins {
return newCoins
}

type coinsJSON Coins

// MarshalJSON implements a custom JSON marshaller for the Coins type to allow
// nil Coins to be encoded as an empty array.
func (coins Coins) MarshalJSON() ([]byte, error) {
if coins == nil {
return json.Marshal(coinsJSON(Coins{}))
}

return json.Marshal(coinsJSON(coins))
}

func (coins Coins) String() string {
if len(coins) == 0 {
return ""
Expand Down
33 changes: 33 additions & 0 deletions types/coin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"strings"
"testing"

"github.com/cosmos/cosmos-sdk/codec"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -621,3 +622,35 @@ func TestFindDup(t *testing.T) {
})
}
}

func TestMarshalJSONCoins(t *testing.T) {
cdc := codec.New()
RegisterCodec(cdc)

testCases := []struct {
name string
input Coins
strOutput string
}{
{"nil coins", nil, `[]`},
{"empty coins", Coins{}, `[]`},
{"non-empty coins", NewCoins(NewInt64Coin("foo", 50)), `[{"denom":"foo","amount":"50"}]`},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
bz, err := cdc.MarshalJSON(tc.input)
require.NoError(t, err)
require.Equal(t, tc.strOutput, string(bz))

var newCoins Coins
require.NoError(t, cdc.UnmarshalJSON(bz, &newCoins))

if tc.input.Empty() {
require.Nil(t, newCoins)
} else {
require.Equal(t, tc.input, newCoins)
}
})
}
}

0 comments on commit 6ec9b26

Please sign in to comment.