Skip to content

Commit 369847c

Browse files
authored
feat(x/accounts): use router service from env (#20003)
1 parent f499bbf commit 369847c

10 files changed

Lines changed: 74 additions & 151 deletions

File tree

simapp/app.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -287,10 +287,8 @@ func NewSimApp(
287287
// add keepers
288288
accountsKeeper, err := accounts.NewKeeper(
289289
appCodec,
290-
runtime.NewEnvironment(runtime.NewKVStoreService(keys[accounts.StoreKey]), logger),
290+
runtime.NewEnvironment(runtime.NewKVStoreService(keys[accounts.StoreKey]), logger, runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())),
291291
signingCtx.AddressCodec(),
292-
app.MsgServiceRouter(),
293-
app.GRPCQueryRouter(),
294292
appCodec.InterfaceRegistry(),
295293
// TESTING: do not add
296294
accountstd.AddAccount("counter", counter.NewAccount),

tests/integration/auth/keeper/msg_server_test.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package keeper_test
22

33
import (
44
"context"
5+
"fmt"
56
"strings"
67
"testing"
78

@@ -84,10 +85,8 @@ func initFixture(t *testing.T) *fixture {
8485
account := baseaccount.NewAccount("base", signing.NewHandlerMap(handler))
8586
accountsKeeper, err := accounts.NewKeeper(
8687
cdc,
87-
runtime.NewEnvironment(runtime.NewKVStoreService(keys[accounts.StoreKey]), log.NewNopLogger()),
88+
runtime.NewEnvironment(runtime.NewKVStoreService(keys[accounts.StoreKey]), log.NewNopLogger(), runtime.EnvWithRouterService(queryRouter, router)),
8889
addresscodec.NewBech32Codec("cosmos"),
89-
router,
90-
queryRouter,
9190
cdc.InterfaceRegistry(),
9291
account,
9392
)
@@ -158,7 +157,7 @@ func TestAsyncExec(t *testing.T) {
158157
addrs := simtestutil.CreateIncrementalAccounts(2)
159158
coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10)))
160159

161-
assert.NilError(t, testutil.FundAccount(f.ctx, f.bankKeeper, addrs[0], sdk.NewCoins(sdk.NewInt64Coin("stake", 50))))
160+
assert.NilError(t, testutil.FundAccount(f.ctx, f.bankKeeper, addrs[0], sdk.NewCoins(sdk.NewInt64Coin("stake", 500))))
162161

163162
msg := &banktypes.MsgSend{
164163
FromAddress: addrs[0].String(),
@@ -276,7 +275,7 @@ func TestAsyncExec(t *testing.T) {
276275
if tc.expErrMsg != "" {
277276
for _, res := range result.Results {
278277
if res.Error != "" {
279-
assert.Assert(t, strings.Contains(res.Error, tc.expErrMsg))
278+
assert.Assert(t, strings.Contains(res.Error, tc.expErrMsg), fmt.Sprintf("res.Error %s does not contain %s", res.Error, tc.expErrMsg))
280279
}
281280
continue
282281
}

x/accounts/depinject.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,10 @@ type ModuleInputs struct {
3434
Cdc codec.Codec
3535
Environment appmodule.Environment
3636
AddressCodec address.Codec
37-
ExecRouter MsgRouter
38-
QueryRouter QueryRouter
3937
Registry cdctypes.InterfaceRegistry
38+
39+
// TODO: Add a way to inject custom accounts.
40+
// Currently only the base account is supported.
4041
}
4142

4243
type ModuleOutputs struct {
@@ -61,10 +62,7 @@ func (s directHandler) GetSignBytes(_ context.Context, _ signing.SignerData, _ s
6162
func ProvideModule(in ModuleInputs) ModuleOutputs {
6263
handler := directHandler{}
6364
account := baseaccount.NewAccount("base", signing.NewHandlerMap(handler))
64-
accountskeeper, err := NewKeeper(
65-
in.Cdc, in.Environment, in.AddressCodec,
66-
in.ExecRouter, in.QueryRouter, in.Registry, account,
67-
)
65+
accountskeeper, err := NewKeeper(in.Cdc, in.Environment, in.AddressCodec, in.Registry, account)
6866
if err != nil {
6967
panic(err)
7068
}

x/accounts/genesis_test.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package accounts
22

33
import (
4-
"context"
54
"testing"
65

76
"github.com/cosmos/gogoproto/types"
@@ -16,7 +15,6 @@ func TestGenesis(t *testing.T) {
1615
acc, err := NewTestAccount(deps)
1716
return "test", acc, err
1817
})
19-
k.queryRouter = mockQuery(func(ctx context.Context, req, resp implementation.ProtoMsg) error { return nil })
2018
// we init two accounts of the same type
2119

2220
// we set counter to 10

x/accounts/keeper.go

Lines changed: 5 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,6 @@ var (
3535
AccountByNumber = collections.NewPrefix(2)
3636
)
3737

38-
// QueryRouter represents a router which can be used to route queries to the correct module.
39-
// It returns the handler given the message name, if multiple handlers are returned, then
40-
// it is up to the caller to choose which one to call.
41-
type QueryRouter interface {
42-
HybridHandlerByRequestName(name string) []func(ctx context.Context, req, resp implementation.ProtoMsg) error
43-
}
44-
45-
// MsgRouter represents a router which can be used to route messages to the correct module.
46-
type MsgRouter interface {
47-
HybridHandlerByMsgName(msgName string) func(ctx context.Context, req, resp implementation.ProtoMsg) error
48-
ResponseNameByMsgName(name string) string
49-
}
50-
5138
type InterfaceRegistry interface {
5239
RegisterInterface(name string, iface any, impls ...protoiface.MessageV1)
5340
RegisterImplementations(iface any, impls ...protoiface.MessageV1)
@@ -57,18 +44,14 @@ func NewKeeper(
5744
cdc codec.Codec,
5845
env appmodule.Environment,
5946
addressCodec address.Codec,
60-
execRouter MsgRouter,
61-
queryRouter QueryRouter,
6247
ir InterfaceRegistry,
6348
accounts ...accountstd.AccountCreatorFunc,
6449
) (Keeper, error) {
6550
sb := collections.NewSchemaBuilder(env.KVStoreService)
6651
keeper := Keeper{
6752
environment: env,
68-
addressCodec: addressCodec,
69-
msgRouter: execRouter,
7053
codec: cdc,
71-
queryRouter: queryRouter,
54+
addressCodec: addressCodec,
7255
makeSendCoinsMsg: defaultCoinsTransferMsgFunc(addressCodec),
7356
Schema: collections.Schema{},
7457
AccountNumber: collections.NewSequence(sb, AccountNumberKey, "account_number"),
@@ -95,8 +78,6 @@ type Keeper struct {
9578
environment appmodule.Environment
9679
addressCodec address.Codec
9780
codec codec.Codec
98-
msgRouter MsgRouter // todo use env
99-
queryRouter QueryRouter // todo use env
10081
makeSendCoinsMsg coinsTransferMsgFunc
10182

10283
accounts map[string]implementation.Implementation
@@ -343,17 +324,11 @@ func (k Keeper) sendAnyMessages(ctx context.Context, sender []byte, anyMessages
343324
// SendModuleMessageUntyped can be used to send a message towards a module.
344325
// It should be used when the response type is not known by the caller.
345326
func (k Keeper) SendModuleMessageUntyped(ctx context.Context, sender []byte, msg implementation.ProtoMsg) (implementation.ProtoMsg, error) {
346-
// we need to fetch the response type from the request message type.
347-
// this is because the response type is not known.
348-
respName := k.msgRouter.ResponseNameByMsgName(implementation.MessageName(msg))
349-
if respName == "" {
350-
return nil, fmt.Errorf("could not find response type for message %T", msg)
351-
}
352-
// get response type
353-
resp, err := implementation.FindMessageByName(respName)
327+
resp, err := k.environment.RouterService.MessageRouterService().InvokeUntyped(ctx, msg)
354328
if err != nil {
355329
return nil, err
356330
}
331+
357332
// send the message
358333
return resp, k.sendModuleMessage(ctx, sender, msg, resp)
359334
}
@@ -373,27 +348,14 @@ func (k Keeper) sendModuleMessage(ctx context.Context, sender []byte, msg, msgRe
373348
if !bytes.Equal(sender, wantSenders[0]) {
374349
return fmt.Errorf("%w: sender does not match expected sender", ErrUnauthorized)
375350
}
376-
messageName := implementation.MessageName(msg)
377-
handler := k.msgRouter.HybridHandlerByMsgName(messageName)
378-
if handler == nil {
379-
return fmt.Errorf("unknown message: %s", messageName)
380-
}
381-
return handler(ctx, msg, msgResp)
351+
return k.environment.RouterService.MessageRouterService().InvokeTyped(ctx, msg, msgResp)
382352
}
383353

384354
// queryModule is the entrypoint for an account to query a module.
385355
// It will try to find the query handler for the given query and execute it.
386356
// If multiple query handlers are found, it will return an error.
387357
func (k Keeper) queryModule(ctx context.Context, queryReq, queryResp implementation.ProtoMsg) error {
388-
queryName := implementation.MessageName(queryReq)
389-
handlers := k.queryRouter.HybridHandlerByRequestName(queryName)
390-
if len(handlers) == 0 {
391-
return fmt.Errorf("unknown query: %s", queryName)
392-
}
393-
if len(handlers) > 1 {
394-
return fmt.Errorf("multiple handlers for query: %s", queryName)
395-
}
396-
return handlers[0](ctx, queryReq, queryResp)
358+
return k.environment.RouterService.QueryRouterService().InvokeTyped(ctx, queryReq, queryResp)
397359
}
398360

399361
// maybeSendFunds will send the provided coins between the provided addresses, if amt

x/accounts/keeper_test.go

Lines changed: 3 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,18 @@
11
package accounts
22

33
import (
4-
"context"
54
"testing"
65

76
"github.com/cosmos/gogoproto/types"
87
"github.com/stretchr/testify/require"
9-
"google.golang.org/protobuf/proto"
108

11-
bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1"
12-
basev1beta1 "cosmossdk.io/api/cosmos/base/v1beta1"
139
"cosmossdk.io/collections"
1410
"cosmossdk.io/x/accounts/accountstd"
1511
"cosmossdk.io/x/accounts/internal/implementation"
1612
)
1713

1814
func TestKeeper_Init(t *testing.T) {
1915
m, ctx := newKeeper(t, accountstd.AddAccount("test", NewTestAccount))
20-
m.queryRouter = mockQuery(func(ctx context.Context, req, resp implementation.ProtoMsg) error {
21-
_, ok := req.(*bankv1beta1.QueryBalanceRequest)
22-
require.True(t, ok)
23-
_, ok = resp.(*bankv1beta1.QueryBalanceResponse)
24-
require.True(t, ok)
25-
return nil
26-
})
2716

2817
t.Run("ok", func(t *testing.T) {
2918
sender := []byte("sender")
@@ -52,7 +41,6 @@ func TestKeeper_Init(t *testing.T) {
5241

5342
func TestKeeper_Execute(t *testing.T) {
5443
m, ctx := newKeeper(t, accountstd.AddAccount("test", NewTestAccount))
55-
m.queryRouter = mockQuery(func(ctx context.Context, req, resp implementation.ProtoMsg) error { return nil })
5644

5745
// create account
5846
sender := []byte("sender")
@@ -71,35 +59,14 @@ func TestKeeper_Execute(t *testing.T) {
7159
})
7260

7361
t.Run("exec module", func(t *testing.T) {
74-
m.msgRouter = mockExec(func(ctx context.Context, msg, msgResp implementation.ProtoMsg) error {
75-
concrete, ok := msg.(*bankv1beta1.MsgSend)
76-
require.True(t, ok)
77-
require.Equal(t, concrete.ToAddress, "recipient")
78-
_, ok = msgResp.(*bankv1beta1.MsgSendResponse)
79-
require.True(t, ok)
80-
return nil
81-
})
82-
83-
m.msgRouter = mockExec(func(ctx context.Context, msg, msgResp implementation.ProtoMsg) error {
84-
concrete, ok := msg.(*bankv1beta1.MsgSend)
85-
require.True(t, ok)
86-
require.Equal(t, concrete.FromAddress, string(accAddr))
87-
_, ok = msgResp.(*bankv1beta1.MsgSendResponse)
88-
require.True(t, ok)
89-
90-
resp, err := m.Execute(ctx, accAddr, sender, &types.Int64Value{Value: 1000}, nil)
91-
require.NoError(t, err)
92-
require.True(t, implementation.Equal(&types.Empty{}, resp))
93-
return nil
94-
})
62+
resp, err := m.Execute(ctx, accAddr, sender, &types.Int64Value{Value: 1000}, nil)
63+
require.NoError(t, err)
64+
require.True(t, implementation.Equal(&types.Empty{}, resp))
9565
})
9666
}
9767

9868
func TestKeeper_Query(t *testing.T) {
9969
m, ctx := newKeeper(t, accountstd.AddAccount("test", NewTestAccount))
100-
m.queryRouter = mockQuery(func(ctx context.Context, req, resp implementation.ProtoMsg) error {
101-
return nil
102-
})
10370

10471
// create account
10572
sender := []byte("sender")
@@ -118,21 +85,6 @@ func TestKeeper_Query(t *testing.T) {
11885
})
11986

12087
t.Run("query module", func(t *testing.T) {
121-
// we inject the module query function, which accepts only a specific type of message
122-
// we force the response
123-
m.queryRouter = mockQuery(func(ctx context.Context, req, resp implementation.ProtoMsg) error {
124-
concrete, ok := req.(*bankv1beta1.QueryBalanceRequest)
125-
require.True(t, ok)
126-
require.Equal(t, string(accAddr), concrete.Address)
127-
require.Equal(t, concrete.Denom, "atom")
128-
copyResp := &bankv1beta1.QueryBalanceResponse{Balance: &basev1beta1.Coin{
129-
Denom: "atom",
130-
Amount: "1000",
131-
}}
132-
proto.Merge(resp.(proto.Message), copyResp)
133-
return nil
134-
})
135-
13688
resp, err := m.Query(ctx, accAddr, &types.StringValue{Value: "atom"})
13789
require.NoError(t, err)
13890
require.True(t, implementation.Equal(&types.Int64Value{Value: 1000}, resp))

x/accounts/msg_server_test.go

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,19 @@
11
package accounts
22

33
import (
4-
"context"
54
"testing"
65

76
"github.com/stretchr/testify/require"
8-
"google.golang.org/protobuf/proto"
97
"google.golang.org/protobuf/types/known/emptypb"
108
"google.golang.org/protobuf/types/known/wrapperspb"
119

12-
bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1"
1310
"cosmossdk.io/x/accounts/accountstd"
1411
"cosmossdk.io/x/accounts/internal/implementation"
1512
v1 "cosmossdk.io/x/accounts/v1"
1613
)
1714

1815
func TestMsgServer(t *testing.T) {
1916
k, ctx := newKeeper(t, accountstd.AddAccount("test", NewTestAccount))
20-
k.queryRouter = mockQuery(func(ctx context.Context, req, resp implementation.ProtoMsg) error {
21-
_, ok := req.(*bankv1beta1.QueryBalanceRequest)
22-
require.True(t, ok)
23-
proto.Merge(resp.(proto.Message), &bankv1beta1.QueryBalanceResponse{})
24-
return nil
25-
})
26-
2717
s := NewMsgServer(k)
2818

2919
// create

x/accounts/query_server_test.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package accounts
22

33
import (
4-
"context"
54
"testing"
65

76
"github.com/cosmos/gogoproto/types"
@@ -16,9 +15,6 @@ import (
1615

1716
func TestQueryServer(t *testing.T) {
1817
k, ctx := newKeeper(t, accountstd.AddAccount("test", NewTestAccount))
19-
k.queryRouter = mockQuery(func(ctx context.Context, req, resp implementation.ProtoMsg) error {
20-
return nil
21-
})
2218

2319
ms := NewMsgServer(k)
2420
qs := NewQueryServer(k)

0 commit comments

Comments
 (0)