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