-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
94 lines (85 loc) · 2.42 KB
/
query.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package grpc
import (
"context"
"encoding/hex"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdktx "github.com/cosmos/cosmos-sdk/types/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/pkg/errors"
)
func GetLatestBlockNumber(ctx context.Context, clientCtx ClientContext) (uint64, error) {
res, err := clientCtx.Client().Status(ctx)
if err != nil {
return 0, err
}
return uint64(res.SyncInfo.LatestBlockHeight), nil
}
func GetChainID(ctx context.Context, clientCtx ClientContext) (string, error) {
status, err := clientCtx.Client().Status(ctx)
if err != nil {
return "", err
}
res, err := clientCtx.Client().Block(ctx, &status.SyncInfo.LatestBlockHeight)
if err != nil {
return "", err
}
return res.Block.Header.ChainID, nil
}
func GetTransactionByHash(ctx context.Context, clientCtx ClientContext, txHash string) (*sdk.TxResponse, error) {
txHashBytes, err := hex.DecodeString(txHash)
if err != nil {
return nil, errors.Wrap(err, "tx hash is not a valid hex")
}
txres, err := clientCtx.Client().Tx(ctx, txHashBytes, false)
if err != nil {
return nil, errors.WithStack(err)
}
var tx sdktx.Tx
err = protoCodec.Unmarshal(txres.Tx, &tx)
if err != nil {
return nil, errors.WithStack(err)
}
anyTx, err := codectypes.NewAnyWithValue(&tx)
if err != nil {
return nil, errors.WithStack(err)
}
return sdk.NewResponseResultTx(txres, anyTx, ""), nil
}
func GetDenomBalance(
ctx context.Context,
clientCtx ClientContext,
address, denom string,
) (sdk.Int, error) {
bankClient := banktypes.NewQueryClient(clientCtx)
res, err := bankClient.Balance(ctx, &banktypes.QueryBalanceRequest{
Address: address,
Denom: denom,
})
if err != nil {
return sdk.ZeroInt(), errors.WithStack(err)
}
return res.Balance.Amount, nil
}
// GetAccountInfo returns account number and account sequence for provided address
func GetAccountInfo(
ctx context.Context,
clientCtx ClientContext,
address string,
) (authtypes.AccountI, error) {
authClient := authtypes.NewQueryClient(clientCtx)
res, err := authClient.Account(ctx,
&authtypes.QueryAccountRequest{
Address: address,
},
)
if err != nil {
return nil, errors.WithStack(err)
}
var acc authtypes.AccountI
if err := clientCtx.InterfaceRegistry().UnpackAny(res.Account, &acc); err != nil {
return nil, errors.WithStack(err)
}
return acc, nil
}