Skip to content

Commit a2d29ea

Browse files
authored
Merge branch 'main' into am/group-amino-2
2 parents 1b816c5 + 10ac33e commit a2d29ea

File tree

17 files changed

+463
-311
lines changed

17 files changed

+463
-311
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ Ref: https://keepachangelog.com/en/1.0.0/
3939

4040
### Features
4141

42+
* (core) [#13306](https://github.com/cosmos/cosmos-sdk/pull/13306) Add a `FormatCoins` function to in `core/coins` to format sdk Coins following the Value Renderers spec.
43+
* (math) [#13306](https://github.com/cosmos/cosmos-sdk/pull/13306) Add `FormatInt` and `FormatDec` functiosn in `math` to format integers and decimals following the Value Renderers spec.
4244
* (grpc) [#13485](https://github.com/cosmos/cosmos-sdk/pull/13485) Implement a new gRPC query, `/cosmos/base/node/v1beta1/config`, which provides operator configuration.
4345
* (x/staking) [#13122](https://github.com/cosmos/cosmos-sdk/pull/13122) Add `UnbondingCanComplete` and `PutUnbondingOnHold` to `x/staking` module.
4446
* [#13437](https://github.com/cosmos/cosmos-sdk/pull/13437) Add new flag `--modules-to-export` in `simd export` command to export only selected modules.

core/coins/format.go

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package coins
2+
3+
import (
4+
"fmt"
5+
"sort"
6+
"strings"
7+
8+
bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1"
9+
basev1beta1 "cosmossdk.io/api/cosmos/base/v1beta1"
10+
"cosmossdk.io/math"
11+
)
12+
13+
// formatCoin formats a sdk.Coin into a value-rendered string, using the
14+
// given metadata about the denom. It returns the formatted coin string, the
15+
// display denom, and an optional error.
16+
func formatCoin(coin *basev1beta1.Coin, metadata *bankv1beta1.Metadata) (string, error) {
17+
coinDenom := coin.Denom
18+
19+
// Return early if no display denom or display denom is the current coin denom.
20+
if metadata == nil || metadata.Display == "" || coinDenom == metadata.Display {
21+
vr, err := math.FormatDec(coin.Amount)
22+
return vr + " " + coin.Denom, err
23+
}
24+
25+
dispDenom := metadata.Display
26+
27+
// Find exponents of both denoms.
28+
var coinExp, dispExp uint32
29+
foundCoinExp, foundDispExp := false, false
30+
for _, unit := range metadata.DenomUnits {
31+
if coinDenom == unit.Denom {
32+
coinExp = unit.Exponent
33+
foundCoinExp = true
34+
}
35+
if dispDenom == unit.Denom {
36+
dispExp = unit.Exponent
37+
foundDispExp = true
38+
}
39+
}
40+
41+
// If we didn't find either exponent, then we return early.
42+
if !foundCoinExp || !foundDispExp {
43+
vr, err := math.FormatInt(coin.Amount)
44+
return vr + " " + coin.Denom, err
45+
}
46+
47+
exponentDiff := int64(coinExp) - int64(dispExp)
48+
49+
dispAmount, err := math.LegacyNewDecFromStr(coin.Amount)
50+
if err != nil {
51+
return "", err
52+
}
53+
54+
if exponentDiff > 0 {
55+
dispAmount = dispAmount.Mul(math.LegacyNewDec(10).Power(uint64(exponentDiff)))
56+
} else {
57+
dispAmount = dispAmount.Quo(math.LegacyNewDec(10).Power(uint64(-exponentDiff)))
58+
}
59+
60+
vr, err := math.FormatDec(dispAmount.String())
61+
return vr + " " + dispDenom, err
62+
}
63+
64+
// formatCoins formats Coins into a value-rendered string, which uses
65+
// `formatCoin` separated by ", " (a comma and a space), and sorted
66+
// alphabetically by value-rendered denoms. It expects an array of metadata
67+
// (optionally nil), where each metadata at index `i` MUST match the coin denom
68+
// at the same index.
69+
func FormatCoins(coins []*basev1beta1.Coin, metadata []*bankv1beta1.Metadata) (string, error) {
70+
if len(coins) != len(metadata) {
71+
return "", fmt.Errorf("formatCoins expect one metadata for each coin; expected %d, got %d", len(coins), len(metadata))
72+
}
73+
74+
formatted := make([]string, len(coins))
75+
for i, coin := range coins {
76+
var err error
77+
formatted[i], err = formatCoin(coin, metadata[i])
78+
if err != nil {
79+
return "", err
80+
}
81+
}
82+
83+
// Sort the formatted coins by display denom.
84+
sort.SliceStable(formatted, func(i, j int) bool {
85+
denomI := strings.Split(formatted[i], " ")[1]
86+
denomJ := strings.Split(formatted[j], " ")[1]
87+
88+
return denomI < denomJ
89+
})
90+
91+
return strings.Join(formatted, ", "), nil
92+
}

core/coins/format_test.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package coins_test
2+
3+
import (
4+
"encoding/json"
5+
"os"
6+
"testing"
7+
8+
bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1"
9+
basev1beta1 "cosmossdk.io/api/cosmos/base/v1beta1"
10+
"cosmossdk.io/core/coins"
11+
"github.com/stretchr/testify/require"
12+
)
13+
14+
// coinsJsonTest is the type of test cases in the coin.json file.
15+
type coinJsonTest struct {
16+
Proto *basev1beta1.Coin
17+
Metadata *bankv1beta1.Metadata
18+
Text string
19+
Error bool
20+
}
21+
22+
// coinsJsonTest is the type of test cases in the coins.json file.
23+
type coinsJsonTest struct {
24+
Proto []*basev1beta1.Coin
25+
Metadata map[string]*bankv1beta1.Metadata
26+
Text string
27+
Error bool
28+
}
29+
30+
func TestFormatCoin(t *testing.T) {
31+
var testcases []coinJsonTest
32+
raw, err := os.ReadFile("../../tx/textual/internal/testdata/coin.json")
33+
require.NoError(t, err)
34+
err = json.Unmarshal(raw, &testcases)
35+
require.NoError(t, err)
36+
37+
for _, tc := range testcases {
38+
t.Run(tc.Text, func(t *testing.T) {
39+
if tc.Proto != nil {
40+
out, err := coins.FormatCoins([]*basev1beta1.Coin{tc.Proto}, []*bankv1beta1.Metadata{tc.Metadata})
41+
42+
if tc.Error {
43+
require.Error(t, err)
44+
return
45+
}
46+
47+
require.NoError(t, err)
48+
require.Equal(t, tc.Text, out)
49+
}
50+
})
51+
}
52+
}
53+
54+
func TestFormatCoins(t *testing.T) {
55+
var testcases []coinsJsonTest
56+
raw, err := os.ReadFile("../../tx/textual/internal/testdata/coins.json")
57+
require.NoError(t, err)
58+
err = json.Unmarshal(raw, &testcases)
59+
require.NoError(t, err)
60+
61+
for _, tc := range testcases {
62+
t.Run(tc.Text, func(t *testing.T) {
63+
if tc.Proto != nil {
64+
metadata := make([]*bankv1beta1.Metadata, len(tc.Proto))
65+
for i, coin := range tc.Proto {
66+
metadata[i] = tc.Metadata[coin.Denom]
67+
}
68+
69+
out, err := coins.FormatCoins(tc.Proto, metadata)
70+
71+
if tc.Error {
72+
require.Error(t, err)
73+
return
74+
}
75+
76+
require.NoError(t, err)
77+
require.Equal(t, tc.Text, out)
78+
}
79+
})
80+
}
81+
}

core/go.mod

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,31 @@ go 1.19
55
require (
66
cosmossdk.io/api v0.2.1
77
cosmossdk.io/depinject v1.0.0-alpha.3
8+
cosmossdk.io/math v1.0.0-beta.3
89
github.com/cosmos/cosmos-proto v1.0.0-alpha8
10+
github.com/stretchr/testify v1.8.0
911
google.golang.org/protobuf v1.28.1
1012
gotest.tools/v3 v3.4.0
1113
sigs.k8s.io/yaml v1.3.0
1214
)
1315

1416
require (
17+
github.com/cosmos/gogoproto v1.4.1 // indirect
18+
github.com/davecgh/go-spew v1.1.1 // indirect
1519
github.com/golang/protobuf v1.5.2 // indirect
1620
github.com/google/go-cmp v0.5.9 // indirect
1721
github.com/kr/text v0.2.0 // indirect
1822
github.com/pkg/errors v0.9.1 // indirect
23+
github.com/pmezard/go-difflib v1.0.0 // indirect
1924
golang.org/x/exp v0.0.0-20220827204233-334a2380cb91 // indirect
2025
golang.org/x/net v0.0.0-20221017152216-f25eb7ecb193 // indirect
2126
golang.org/x/sys v0.0.0-20221013171732-95e765b1cc43 // indirect
2227
golang.org/x/text v0.3.8 // indirect
2328
google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a // indirect
2429
google.golang.org/grpc v1.50.1 // indirect
2530
gopkg.in/yaml.v2 v2.4.0 // indirect
31+
gopkg.in/yaml.v3 v3.0.1 // indirect
2632
)
33+
34+
// temporary until we tag a new go module
35+
replace cosmossdk.io/math => ../math

core/go.sum

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,12 @@ github.com/alecthomas/participle/v2 v2.0.0-alpha7 h1:cK4vjj0VSgb3lN1nuKA5F7dw+1s
66
github.com/cockroachdb/apd/v3 v3.1.0 h1:MK3Ow7LH0W8zkd5GMKA1PvS9qG3bWFI95WaVNfyZJ/w=
77
github.com/cosmos/cosmos-proto v1.0.0-alpha8 h1:d3pCRuMYYvGA5bM0ZbbjKn+AoQD4A7dyNG2wzwWalUw=
88
github.com/cosmos/cosmos-proto v1.0.0-alpha8/go.mod h1:6/p+Bc4O8JKeZqe0VqUGTX31eoYqemTT4C1hLCWsO7I=
9+
github.com/cosmos/gogoproto v1.4.1 h1:WoyH+0/jbCTzpKNvyav5FL1ZTWsp1im1MxEpJEzKUB8=
10+
github.com/cosmos/gogoproto v1.4.1/go.mod h1:Ac9lzL4vFpBMcptJROQ6dQ4M3pOEK5Z/l0Q9p+LoCr4=
911
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
1012
github.com/cucumber/common/gherkin/go/v22 v22.0.0 h1:4K8NqptbvdOrjL9DEea6HFjSpbdT9+Q5kgLpmmsHYl0=
1113
github.com/cucumber/common/messages/go/v17 v17.1.1 h1:RNqopvIFyLWnKv0LfATh34SWBhXeoFTJnSrgm9cT/Ts=
14+
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
1215
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
1316
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
1417
github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0=
@@ -24,9 +27,14 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
2427
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
2528
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
2629
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
30+
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
2731
github.com/regen-network/gocuke v0.6.2 h1:pHviZ0kKAq2U2hN2q3smKNxct6hS0mGByFMHGnWA97M=
2832
github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg=
33+
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
34+
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
35+
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
2936
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
37+
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
3038
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
3139
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
3240
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
@@ -70,7 +78,9 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
7078
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
7179
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
7280
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
81+
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
7382
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
83+
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
7484
gotest.tools/v3 v3.4.0 h1:ZazjZUfuVeZGLAmlKKuyv3IKP5orXcwtOwDQH6YVr6o=
7585
gotest.tools/v3 v3.4.0/go.mod h1:CtbdzLSsqVhDgMtKsx03ird5YTGB3ar27v0u/yKBW5g=
7686
pgregory.net/rapid v0.5.3 h1:163N50IHFqr1phZens4FQOdPgfJscR7a562mjQqeo4M=

math/dec.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -894,3 +894,35 @@ func LegacyDecApproxEq(t *testing.T, d1 LegacyDec, d2 LegacyDec, tol LegacyDec)
894894
diff := d1.Sub(d2).Abs()
895895
return t, diff.LTE(tol), "expected |d1 - d2| <:\t%v\ngot |d1 - d2| = \t\t%v", tol.String(), diff.String()
896896
}
897+
898+
// FormatDec formats a decimal (as encoded in protobuf) into a value-rendered
899+
// string following ADR-050. This function operates with string manipulation
900+
// (instead of manipulating the sdk.Dec object).
901+
func FormatDec(v string) (string, error) {
902+
parts := strings.Split(v, ".")
903+
if len(parts) > 2 {
904+
return "", fmt.Errorf("invalid decimal: too many points in %s", v)
905+
}
906+
907+
intPart, err := FormatInt(parts[0])
908+
if err != nil {
909+
return "", err
910+
}
911+
912+
if len(parts) == 1 {
913+
return intPart, nil
914+
}
915+
916+
decPart := strings.TrimRight(parts[1], "0")
917+
if len(decPart) == 0 {
918+
return intPart, nil
919+
}
920+
921+
// Ensure that the decimal part has only digits.
922+
// https://github.com/cosmos/cosmos-sdk/issues/12811
923+
if !hasOnlyDigits(decPart) {
924+
return "", fmt.Errorf("non-digits detected after decimal point in: %q", decPart)
925+
}
926+
927+
return intPart + "." + decPart, nil
928+
}

math/dec_test.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"encoding/json"
66
"fmt"
77
"math/big"
8+
"os"
89
"strings"
910
"testing"
1011

@@ -666,3 +667,50 @@ func BenchmarkLegacyQuoRoundupMut(b *testing.B) {
666667
}
667668
sink = (interface{})(nil)
668669
}
670+
671+
func TestFormatDec(t *testing.T) {
672+
type decimalTest []string
673+
var testcases []decimalTest
674+
raw, err := os.ReadFile("../tx/textual/internal/testdata/decimals.json")
675+
require.NoError(t, err)
676+
err = json.Unmarshal(raw, &testcases)
677+
require.NoError(t, err)
678+
679+
for _, tc := range testcases {
680+
tc := tc
681+
t.Run(tc[0], func(t *testing.T) {
682+
out, err := math.FormatDec(tc[0])
683+
require.NoError(t, err)
684+
require.Equal(t, tc[1], out)
685+
})
686+
}
687+
}
688+
689+
func TestFormatDecNonDigits(t *testing.T) {
690+
badCases := []string{
691+
"10.a",
692+
"1a.10",
693+
"p1a10.",
694+
"0.10p",
695+
"--10",
696+
"12.😎😎",
697+
"11111111111133333333333333333333333333333a",
698+
"11111111111133333333333333333333333333333 192892",
699+
}
700+
701+
for _, value := range badCases {
702+
value := value
703+
t.Run(value, func(t *testing.T) {
704+
s, err := math.FormatDec(value)
705+
if err == nil {
706+
t.Fatal("Expected an error")
707+
}
708+
if g, w := err.Error(), "non-digits"; !strings.Contains(g, w) {
709+
t.Errorf("Error mismatch\nGot: %q\nWant substring: %q", g, w)
710+
}
711+
if s != "" {
712+
t.Fatalf("Got a non-empty string: %q", s)
713+
}
714+
})
715+
}
716+
}

0 commit comments

Comments
 (0)