Skip to content

Commit 05d9906

Browse files
authored
refactor(type): use uint64 for id and encode it in the store in big endian (ignite#848)
* Change id to uint64 * Fixes * Fixes * Refactor for legacy * Fix legacy * Last fixes * Fix sprintf * starport/templates/typed/stargate_legacy/x/{{moduleName}}/handler_{{typeName}}.go.plush
1 parent 5b2e84d commit 05d9906

20 files changed

+170
-83
lines changed

starport/templates/typed/genesis.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ func (t *typedStargate) genesisTypesModify(opts *Options) genny.RunFn {
6464

6565
templateTypesValidate := `%[1]v
6666
// Check for duplicated ID in %[2]v
67-
%[2]vIdMap := make(map[string]bool)
67+
%[2]vIdMap := make(map[uint64]bool)
6868
6969
for _, elem := range gs.%[3]vList {
7070
if _, ok := %[2]vIdMap[elem.Id]; ok {
@@ -100,7 +100,7 @@ for _, elem := range genState.%[3]vList {
100100
}
101101
102102
// Set %[2]v count
103-
k.Set%[3]vCount(ctx, int64(len(genState.%[3]vList)))
103+
k.Set%[3]vCount(ctx, uint64(len(genState.%[3]vList)))
104104
`
105105
replacementModuleInit := fmt.Sprintf(
106106
templateModuleInit,

starport/templates/typed/new_stargate.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ func NewStargate(opts *Options) (*genny.Generator, error) {
4040
g.RunFn(t.keeperQueryModify(opts))
4141
g.RunFn(t.clientRestRestModify(opts))
4242
g.RunFn(t.frontendSrcStoreAppModify(opts))
43+
4344
t.genesisModify(opts, g)
4445

4546
if opts.Legacy {
@@ -145,19 +146,19 @@ message MsgCreate%[2]v {
145146
%[3]v}
146147
147148
message MsgCreate%[2]vResponse {
148-
string id = 1;
149+
uint64 id = 1;
149150
}
150151
151152
message MsgUpdate%[2]v {
152153
string creator = 1;
153-
string id = 2;
154+
uint64 id = 2;
154155
%[4]v}
155156
156157
message MsgUpdate%[2]vResponse { }
157158
158159
message MsgDelete%[2]v {
159160
string creator = 1;
160-
string id = 2;
161+
uint64 id = 2;
161162
}
162163
163164
message MsgDelete%[2]vResponse { }
@@ -230,7 +231,7 @@ func (t *typedStargate) protoRPCMessageModify(opts *Options) genny.RunFn {
230231
}
231232
template := `%[1]v
232233
message QueryGet%[2]vRequest {
233-
string id = 1;
234+
uint64 id = 1;
234235
}
235236
236237
message QueryGet%[2]vResponse {

starport/templates/typed/stargate/proto/{{moduleName}}/{{typeName}}.proto.plush

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@ import "gogoproto/gogo.proto";
77

88
message <%= title(TypeName) %> {
99
string creator = 1;
10-
string id = 2;<%= for (i, field) in Fields { %>
10+
uint64 id = 2;<%= for (i, field) in Fields { %>
1111
<%= field.Datatype %> <%= field.Name %> = <%= i+3 %>; <% } %>
1212
}

starport/templates/typed/stargate/x/{{moduleName}}/client/cli/query{{TypeName}}.go.plush

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package cli
22

33
import (
44
"context"
5+
"strconv"
56

67
"github.com/cosmos/cosmos-sdk/client"
78
"github.com/cosmos/cosmos-sdk/client/flags"
@@ -51,8 +52,13 @@ func CmdShow<%= title(TypeName) %>() *cobra.Command {
5152

5253
queryClient := types.NewQueryClient(clientCtx)
5354

55+
id, err := strconv.ParseUint(args[0], 10, 64)
56+
if err != nil {
57+
return err
58+
}
59+
5460
params := &types.QueryGet<%= title(TypeName) %>Request{
55-
Id: args[0],
61+
Id: id,
5662
}
5763

5864
res, err := queryClient.<%= title(TypeName) %>(context.Background(), params)

starport/templates/typed/stargate/x/{{moduleName}}/client/cli/tx{{TypeName}}.go.plush

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package cli
22

33
import (
4-
<%= if (strconv()) { %>"strconv"<% } %>
4+
"strconv"
55
"github.com/spf13/cobra"
66

77
"github.com/cosmos/cosmos-sdk/client"
@@ -42,7 +42,11 @@ func CmdUpdate<%= title(TypeName) %>() *cobra.Command {
4242
Short: "Update a <%= TypeName %>",
4343
Args: cobra.ExactArgs(<%= len(Fields) + 1 %>),
4444
RunE: func(cmd *cobra.Command, args []string) error {
45-
id := args[0]
45+
id, err := strconv.ParseUint(args[0], 10, 64)
46+
if err != nil {
47+
return err
48+
}
49+
4650
<%= for (i, field) in Fields { %>args<%= title(field.Name) %><%= if (field.DatatypeName != "string") {%>, _<%}%> := <%= if (field.DatatypeName == "string") {%>string<%} else {%>strconv.Parse<%= title(field.DatatypeName) %><%}%>(args[<%= i + 1 %>]<%= if (field.DatatypeName == "int") {%>, 10, 64<%}%>)
4751
<% } %>
4852
clientCtx, err := client.GetClientTxContext(cmd)
@@ -69,7 +73,10 @@ func CmdDelete<%= title(TypeName) %>() *cobra.Command {
6973
Short: "Delete a <%= TypeName %> by id",
7074
Args: cobra.ExactArgs(1),
7175
RunE: func(cmd *cobra.Command, args []string) error {
72-
id := args[0]
76+
id, err := strconv.ParseUint(args[0], 10, 64)
77+
if err != nil {
78+
return err
79+
}
7380

7481
clientCtx, err := client.GetClientTxContext(cmd)
7582
if err != nil {

starport/templates/typed/stargate/x/{{moduleName}}/client/rest/tx{{TypeName}}.go.plush

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@ import (
1212
"github.com/gorilla/mux"
1313
)
1414

15-
// Used to not have an error if strconv is unused
16-
var _ = strconv.Itoa(42)
17-
1815
type create<%= title(TypeName) %>Request struct {
1916
BaseReq rest.BaseReq `json:"base_req"`
2017
Creator string `json:"creator"`
@@ -78,7 +75,10 @@ type update<%= title(TypeName) %>Request struct {
7875

7976
func update<%= title(TypeName) %>Handler(clientCtx client.Context) http.HandlerFunc {
8077
return func(w http.ResponseWriter, r *http.Request) {
81-
id := mux.Vars(r)["id"]
78+
id, err := strconv.ParseUint(mux.Vars(r)["id"], 10, 64)
79+
if err != nil {
80+
return
81+
}
8282

8383
var req update<%= title(TypeName) %>Request
8484
if !rest.ReadRESTReq(w, r, clientCtx.LegacyAmino, &req) {
@@ -91,7 +91,7 @@ func update<%= title(TypeName) %>Handler(clientCtx client.Context) http.HandlerF
9191
return
9292
}
9393

94-
_, err := sdk.AccAddressFromBech32(req.Creator)
94+
_, err = sdk.AccAddressFromBech32(req.Creator)
9595
if err != nil {
9696
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
9797
return
@@ -132,7 +132,10 @@ type delete<%= title(TypeName) %>Request struct {
132132

133133
func delete<%= title(TypeName) %>Handler(clientCtx client.Context) http.HandlerFunc {
134134
return func(w http.ResponseWriter, r *http.Request) {
135-
id := mux.Vars(r)["id"]
135+
id, err := strconv.ParseUint(mux.Vars(r)["id"], 10, 64)
136+
if err != nil {
137+
return
138+
}
136139

137140
var req delete<%= title(TypeName) %>Request
138141
if !rest.ReadRESTReq(w, r, clientCtx.LegacyAmino, &req) {
@@ -145,7 +148,7 @@ func delete<%= title(TypeName) %>Handler(clientCtx client.Context) http.HandlerF
145148
return
146149
}
147150

148-
_, err := sdk.AccAddressFromBech32(req.Creator)
151+
_, err = sdk.AccAddressFromBech32(req.Creator)
149152
if err != nil {
150153
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
151154
return

starport/templates/typed/stargate/x/{{moduleName}}/keeper/grpc_query_{{typeName}}.go.plush

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55

66
"github.com/cosmos/cosmos-sdk/store/prefix"
77
sdk "github.com/cosmos/cosmos-sdk/types"
8+
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
89
"github.com/cosmos/cosmos-sdk/types/query"
910
"<%= ModulePath %>/x/<%= ModuleName %>/types"
1011
"google.golang.org/grpc/codes"
@@ -47,8 +48,12 @@ func (k Keeper) <%= title(TypeName) %>(c context.Context, req *types.QueryGet<%=
4748
var <%= TypeName %> types.<%= title(TypeName) %>
4849
ctx := sdk.UnwrapSDKContext(c)
4950

51+
if !k.Has<%= title(TypeName) %>(ctx, req.Id) {
52+
return nil, sdkerrors.ErrKeyNotFound
53+
}
54+
5055
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.<%= title(TypeName) %>Key))
51-
k.cdc.MustUnmarshalBinaryBare(store.Get(types.KeyPrefix(types.<%= title(TypeName) %>Key + req.Id)), &<%= TypeName %>)
56+
k.cdc.MustUnmarshalBinaryBare(store.Get(Get<%= title(TypeName) %>IDBytes(req.Id)), &<%= TypeName %>)
5257

5358
return &types.QueryGet<%= title(TypeName) %>Response{<%= title(TypeName) %>: &<%= TypeName %>}, nil
5459
}

starport/templates/typed/stargate/x/{{moduleName}}/keeper/msg_server_{{typeName}}.go.plush

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ func (k msgServer) Update<%= title(TypeName) %>(goCtx context.Context, msg *typ
3535

3636
// Checks that the element exists
3737
if !k.Has<%= title(TypeName) %>(ctx, msg.Id) {
38-
return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %s doesn't exist", msg.Id))
38+
return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %d doesn't exist", msg.Id))
3939
}
4040

4141
// Checks if the the msg sender is the same as the current owner
@@ -52,7 +52,7 @@ func (k msgServer) Delete<%= title(TypeName) %>(goCtx context.Context, msg *typ
5252
ctx := sdk.UnwrapSDKContext(goCtx)
5353

5454
if !k.Has<%= title(TypeName) %>(ctx, msg.Id) {
55-
return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %s doesn't exist", msg.Id))
55+
return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %d doesn't exist", msg.Id))
5656
}
5757
if msg.Creator != k.Get<%= title(TypeName) %>Owner(ctx, msg.Id) {
5858
return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "incorrect owner")

starport/templates/typed/stargate/x/{{moduleName}}/keeper/query_{{typeName}}.go.plush

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package keeper
22

33
import (
4+
"strconv"
45
"github.com/cosmos/cosmos-sdk/codec"
56
sdk "github.com/cosmos/cosmos-sdk/types"
67
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
@@ -17,7 +18,16 @@ func list<%= title(TypeName) %>(ctx sdk.Context, keeper Keeper, legacyQuerierCdc
1718
return bz, nil
1819
}
1920

20-
func get<%= title(TypeName) %>(ctx sdk.Context, id string, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) {
21+
func get<%= title(TypeName) %>(ctx sdk.Context, key string, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) {
22+
id, err := strconv.ParseUint(key, 10, 64)
23+
if err != nil {
24+
return nil, err
25+
}
26+
27+
if !keeper.Has<%= title(TypeName) %>(ctx, id) {
28+
return nil, sdkerrors.ErrKeyNotFound
29+
}
30+
2131
msg := keeper.Get<%= title(TypeName) %>(ctx, id)
2232

2333
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, msg)
Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
package keeper
22

33
import (
4+
"encoding/binary"
45
sdk "github.com/cosmos/cosmos-sdk/types"
56
"<%= ModulePath %>/x/<%= ModuleName %>/types"
67
"github.com/cosmos/cosmos-sdk/store/prefix"
78
"strconv"
89
)
910

1011
// Get<%= title(TypeName) %>Count get the total number of <%= TypeName %>
11-
func (k Keeper) Get<%= title(TypeName) %>Count(ctx sdk.Context) int64 {
12+
func (k Keeper) Get<%= title(TypeName) %>Count(ctx sdk.Context) uint64 {
1213
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.<%= title(TypeName) %>CountKey))
1314
byteKey := types.KeyPrefix(types.<%= title(TypeName) %>CountKey)
1415
bz := store.Get(byteKey)
@@ -19,20 +20,20 @@ func (k Keeper) Get<%= title(TypeName) %>Count(ctx sdk.Context) int64 {
1920
}
2021

2122
// Parse bytes
22-
count, err := strconv.ParseInt(string(bz), 10, 64)
23+
count, err := strconv.ParseUint(string(bz), 10, 64)
2324
if err != nil {
24-
// Panic because the count should be always formattable to int64
25+
// Panic because the count should be always formattable to iint64
2526
panic("cannot decode count")
2627
}
2728

2829
return count
2930
}
3031

3132
// Set<%= title(TypeName) %>Count set the total number of <%= TypeName %>
32-
func (k Keeper) Set<%= title(TypeName) %>Count(ctx sdk.Context, count int64) {
33+
func (k Keeper) Set<%= title(TypeName) %>Count(ctx sdk.Context, count uint64) {
3334
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.<%= title(TypeName) %>CountKey))
3435
byteKey := types.KeyPrefix(types.<%= title(TypeName) %>CountKey)
35-
bz := []byte(strconv.FormatInt(count, 10))
36+
bz := []byte(strconv.FormatUint(count, 10))
3637
store.Set(byteKey, bz)
3738
}
3839

@@ -41,63 +42,61 @@ func (k Keeper) Append<%= title(TypeName) %>(
4142
ctx sdk.Context,
4243
creator string,<%= for (field) in Fields { %>
4344
<%= field.Name %> <%= field.Datatype %>,<% } %>
44-
) string {
45+
) uint64 {
4546
// Create the <%= TypeName %>
4647
count := k.Get<%= title(TypeName) %>Count(ctx)
47-
id := strconv.FormatInt(count, 10)
4848
var <%= TypeName %> = types.<%= title(TypeName) %>{
4949
Creator: creator,
50-
Id: id,<%= for (field) in Fields { %>
50+
Id: count,<%= for (field) in Fields { %>
5151
<%= title(field.Name) %>: <%= field.Name %>,<% } %>
5252
}
5353

5454
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.<%= title(TypeName) %>Key))
55-
key := types.KeyPrefix(types.<%= title(TypeName) %>Key + <%= TypeName %>.Id)
5655
value := k.cdc.MustMarshalBinaryBare(&<%= TypeName %>)
57-
store.Set(key, value)
56+
store.Set(Get<%= title(TypeName) %>IDBytes(<%= TypeName %>.Id), value)
5857

5958
// Update <%= TypeName %> count
6059
k.Set<%= title(TypeName) %>Count(ctx, count+1)
6160

62-
return id
61+
return count
6362
}
6463

6564
// Set<%= title(TypeName) %> set a specific <%= TypeName %> in the store
6665
func (k Keeper) Set<%= title(TypeName) %>(ctx sdk.Context, <%= TypeName %> types.<%= title(TypeName) %>) {
6766
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.<%= title(TypeName) %>Key))
6867
b := k.cdc.MustMarshalBinaryBare(&<%= TypeName %>)
69-
store.Set(types.KeyPrefix(types.<%= title(TypeName) %>Key + <%= TypeName %>.Id), b)
68+
store.Set(Get<%= title(TypeName) %>IDBytes(<%= TypeName %>.Id), b)
7069
}
7170

7271
// Get<%= title(TypeName) %> returns a <%= TypeName %> from its id
73-
func (k Keeper) Get<%= title(TypeName) %>(ctx sdk.Context, key string) types.<%= title(TypeName) %> {
72+
func (k Keeper) Get<%= title(TypeName) %>(ctx sdk.Context, id uint64) types.<%= title(TypeName) %> {
7473
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.<%= title(TypeName) %>Key))
7574
var <%= TypeName %> types.<%= title(TypeName) %>
76-
k.cdc.MustUnmarshalBinaryBare(store.Get(types.KeyPrefix(types.<%= title(TypeName) %>Key + key)), &<%= TypeName %>)
75+
k.cdc.MustUnmarshalBinaryBare(store.Get(Get<%= title(TypeName) %>IDBytes(id)), &<%= TypeName %>)
7776
return <%= TypeName %>
7877
}
7978

8079
// Has<%= title(TypeName) %> checks if the <%= TypeName %> exists in the store
81-
func (k Keeper) Has<%= title(TypeName) %>(ctx sdk.Context, id string) bool {
80+
func (k Keeper) Has<%= title(TypeName) %>(ctx sdk.Context, id uint64) bool {
8281
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.<%= title(TypeName) %>Key))
83-
return store.Has(types.KeyPrefix(types.<%= title(TypeName) %>Key + id))
82+
return store.Has(Get<%= title(TypeName) %>IDBytes(id))
8483
}
8584

8685
// Get<%= title(TypeName) %>Owner returns the creator of the <%= TypeName %>
87-
func (k Keeper) Get<%= title(TypeName) %>Owner(ctx sdk.Context, key string) string {
88-
return k.Get<%= title(TypeName) %>(ctx, key).Creator
86+
func (k Keeper) Get<%= title(TypeName) %>Owner(ctx sdk.Context, id uint64) string {
87+
return k.Get<%= title(TypeName) %>(ctx, id).Creator
8988
}
9089

91-
// Delete<%= title(TypeName) %> removes a <%= TypeName %> from the store
92-
func (k Keeper) Remove<%= title(TypeName) %>(ctx sdk.Context, key string) {
90+
// Remove<%= title(TypeName) %> removes a <%= TypeName %> from the store
91+
func (k Keeper) Remove<%= title(TypeName) %>(ctx sdk.Context, id uint64) {
9392
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.<%= title(TypeName) %>Key))
94-
store.Delete(types.KeyPrefix(types.<%= title(TypeName) %>Key + key))
93+
store.Delete(Get<%= title(TypeName) %>IDBytes(id))
9594
}
9695

9796
// GetAll<%= title(TypeName) %> returns all <%= TypeName %>
9897
func (k Keeper) GetAll<%= title(TypeName) %>(ctx sdk.Context) (list []types.<%= title(TypeName) %>) {
9998
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.<%= title(TypeName) %>Key))
100-
iterator := sdk.KVStorePrefixIterator(store, types.KeyPrefix(types.<%= title(TypeName) %>Key))
99+
iterator := sdk.KVStorePrefixIterator(store, []byte{})
101100

102101
defer iterator.Close()
103102

@@ -109,3 +108,15 @@ func (k Keeper) GetAll<%= title(TypeName) %>(ctx sdk.Context) (list []types.<%=
109108

110109
return
111110
}
111+
112+
// Get<%= title(TypeName) %>IDBytes returns the byte representation of the ID
113+
func Get<%= title(TypeName) %>IDBytes(id uint64) []byte {
114+
bz := make([]byte, 8)
115+
binary.BigEndian.PutUint64(bz, id)
116+
return bz
117+
}
118+
119+
// Get<%= title(TypeName) %>IDFromBytes returns ID in uint64 format from a byte array
120+
func Get<%= title(TypeName) %>IDFromBytes(bz []byte) uint64 {
121+
return binary.BigEndian.Uint64(bz)
122+
}

0 commit comments

Comments
 (0)