/
account_retriever.go
77 lines (63 loc) · 2.45 KB
/
account_retriever.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package compass
import (
"context"
"fmt"
"strconv"
"github.com/cosmos/cosmos-sdk/client"
sdk "github.com/cosmos/cosmos-sdk/types"
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
var _ client.AccountRetriever = &Client{}
// GetAccount queries for an account given an address and a block height. An
// error is returned if the query or decoding fails.
func (cc *Client) GetAccount(clientCtx client.Context, addr sdk.AccAddress) (client.Account, error) {
account, _, err := cc.GetAccountWithHeight(clientCtx, addr)
return account, err
}
// GetAccountWithHeight queries for an account given an address. Returns the
// height of the query with the account. An error is returned if the query
// or decoding fails.
func (cc *Client) GetAccountWithHeight(clientCtx client.Context, addr sdk.AccAddress) (client.Account, int64, error) {
var header metadata.MD
address, err := cc.EncodeBech32AccAddr(addr)
if err != nil {
return nil, 0, err
}
queryClient := authtypes.NewQueryClient(cc.GRPC)
res, err := queryClient.Account(context.Background(), &authtypes.QueryAccountRequest{Address: address}, grpc.Header(&header))
if err != nil {
return nil, 0, err
}
blockHeight := header.Get(grpctypes.GRPCBlockHeightHeader)
if l := len(blockHeight); l != 1 {
return nil, 0, fmt.Errorf("unexpected '%s' header length; got %d, expected: %d", grpctypes.GRPCBlockHeightHeader, l, 1)
}
nBlockHeight, err := strconv.Atoi(blockHeight[0])
if err != nil {
return nil, 0, fmt.Errorf("failed to parse block height: %w", err)
}
var acc sdk.AccountI
if err := cc.Codec.InterfaceRegistry.UnpackAny(res.Account, &acc); err != nil {
return nil, 0, err
}
return acc, int64(nBlockHeight), nil
}
// EnsureExists returns an error if no account exists for the given address else nil.
func (cc *Client) EnsureExists(clientCtx client.Context, addr sdk.AccAddress) error {
if _, err := cc.GetAccount(clientCtx, addr); err != nil {
return err
}
return nil
}
// GetAccountNumberSequence returns sequence and account number for the given address.
// It returns an error if the account couldn't be retrieved from the state.
func (cc *Client) GetAccountNumberSequence(clientCtx client.Context, addr sdk.AccAddress) (uint64, uint64, error) {
acc, err := cc.GetAccount(clientCtx, addr)
if err != nil {
return 0, 0, err
}
return acc.GetAccountNumber(), acc.GetSequence(), nil
}