Skip to content

Commit

Permalink
feat: get withdraw records by status
Browse files Browse the repository at this point in the history
  • Loading branch information
YuexingZeng committed Feb 5, 2024
1 parent d334592 commit 123b94b
Show file tree
Hide file tree
Showing 11 changed files with 868 additions and 66 deletions.
20 changes: 20 additions & 0 deletions proto/ethermint/bridge/v1/query.proto
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ service Query {
rpc WithdrawAll(QueryAllWithdrawRequest) returns (QueryAllWithdrawResponse) {
option (google.api.http).get = "/ethermint/bridge/v1/withdraw";
}
// WithdrawsByStatus queries withdraw records by status.
rpc WithdrawsByStatus(QueryWithdrawsByStatusRequest) returns (QueryWithdrawsByStatusResponse) {
option (google.api.http).get = "/ethermint/bridge/v1/withdraws_by_status/{status}";
}
// CallerGroup queries a caller group by group name.
rpc CallerGroup(QueryGetCallerGroupRequest) returns (QueryGetCallerGroupResponse) {
option (google.api.http).get = "/ethermint/bridge/v1/caller_group/{name}";
Expand Down Expand Up @@ -113,6 +117,22 @@ message QueryAllWithdrawResponse {
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}

// QueryWithdrawsByStatusRequest is request type for the Query/WithdrawsByStatus RPC method.
message QueryWithdrawsByStatusRequest {
// status is the status of the withdrawals to query.
WithdrawStatus status = 1;
// pagination defines an pagination for the request.
cosmos.base.query.v1beta1.PageRequest pagination = 2;
}

// QueryWithdrawsByStatusResponse is response type for the Query/WithdrawsByStatus RPC method.
message QueryWithdrawsByStatusResponse {
// withdraw is all withdraw records.
repeated Withdraw withdraw = 1 [(gogoproto.nullable) = false];
// pagination defines an pagination for the request.
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}

// QueryGetCallerGroupRequest is request type for the Query/CallerGroup RPC method.
message QueryGetCallerGroupRequest {
// name is the unique name of the caller group.
Expand Down
1 change: 1 addition & 0 deletions x/bridge/client/cli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func GetQueryCmd(_ string) *cobra.Command {
cmd.AddCommand(CmdListDeposit())
cmd.AddCommand(CmdShowDeposit())
cmd.AddCommand(CmdListWithdraw())
cmd.AddCommand(CmdListWithdrawByStatus())
cmd.AddCommand(CmdShowWithdraw())
// this line is used by starport scaffolding # 1

Expand Down
38 changes: 38 additions & 0 deletions x/bridge/client/cli/query_withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,44 @@ func CmdListWithdraw() *cobra.Command {
return cmd
}

func CmdListWithdrawByStatus() *cobra.Command {
cmd := &cobra.Command{
Use: "list-withdraw-by-status [status]",
Short: "list withdraws by status",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)

pageReq, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}

queryClient := types.NewQueryClient(clientCtx)
argStatus, err := types.WithdrawStatusFromString(args[0])
if err != nil {
return err
}
params := &types.QueryWithdrawsByStatusRequest{
Status: argStatus,
Pagination: pageReq,
}

res, err := queryClient.WithdrawsByStatus(context.Background(), params)
if err != nil {
return err
}

return clientCtx.PrintProto(res)
},
}

flags.AddPaginationFlagsToCmd(cmd, cmd.Use)
flags.AddQueryFlagsToCmd(cmd)

return cmd
}

func CmdShowWithdraw() *cobra.Command {
cmd := &cobra.Command{
Use: "show-withdraw [tx-hash]",
Expand Down
2 changes: 1 addition & 1 deletion x/bridge/keeper/deposit.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package keeper //nolint:dupl
package keeper

import (
"github.com/cosmos/cosmos-sdk/store/prefix"
Expand Down
8 changes: 8 additions & 0 deletions x/bridge/keeper/msg_server_withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ func (k msgServer) CreateWithdraw(goCtx context.Context, msg *types.MsgCreateWit
withdraw,
)

k.SetStatusIndex(ctx, withdraw.Status.String(), withdraw.TxHash)

if err := ctx.EventManager().EmitTypedEvent(&types.EventCreateWithdraw{TxHash: msg.TxHash}); err != nil {
return nil, err
}
Expand Down Expand Up @@ -82,6 +84,8 @@ func (k msgServer) UpdateWithdraw(goCtx context.Context, msg *types.MsgUpdateWit
}

k.SetWithdraw(ctx, withdraw)
k.RemoveStatusIndex(ctx, valFound.GetStatus().String(), valFound.TxHash)
k.SetStatusIndex(ctx, withdraw.Status.String(), withdraw.TxHash)

if err := ctx.EventManager().EmitTypedEvent(&types.EventUpdateWithdraw{TxHash: msg.TxHash}); err != nil {
return nil, err
Expand Down Expand Up @@ -151,6 +155,8 @@ func (k msgServer) SignWithdraw(goCtx context.Context, msg *types.MsgSignWithdra
if err := ctx.EventManager().EmitTypedEvent(&types.EventSignWithdraw{TxHash: msg.TxHash}); err != nil {
return nil, err
}
k.RemoveStatusIndex(ctx, valFound.GetStatus().String(), valFound.TxHash)
k.SetStatusIndex(ctx, withdraw.Status.String(), withdraw.TxHash)
}
return &types.MsgSignWithdrawResponse{}, nil
}
Expand All @@ -177,6 +183,8 @@ func (k msgServer) DeleteWithdraw(goCtx context.Context, msg *types.MsgDeleteWit
msg.TxHash,
)

k.RemoveStatusIndex(ctx, valFound.GetStatus().String(), valFound.TxHash)

if err := ctx.EventManager().EmitTypedEvent(&types.EventDeleteWithdraw{TxHash: msg.TxHash}); err != nil {
return nil, err
}
Expand Down
2 changes: 2 additions & 0 deletions x/bridge/keeper/msg_server_withdraw_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ func TestWithdrawMsgServerCreate(t *testing.T) {
require.True(t, found)
require.Equal(t, expected.Creator, rst.Creator)
}
list := k.GetAllWithdrawByStatus(ctx, types.WithdrawStatus_WITHDRAW_STATUS_PENDING.String())
require.Equal(t, 5, len(list))
}

func TestWithdrawMsgServerUpdate(t *testing.T) {
Expand Down
52 changes: 51 additions & 1 deletion x/bridge/keeper/query_withdraw.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package keeper //nolint:dupl
package keeper

import (
"context"
"fmt"

"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -54,3 +55,52 @@ func (k Keeper) Withdraw(goCtx context.Context, req *types.QueryGetWithdrawReque

return &types.QueryGetWithdrawResponse{Withdraw: val}, nil
}

func (k Keeper) WithdrawsByStatus(goCtx context.Context, req *types.QueryWithdrawsByStatusRequest) (*types.QueryWithdrawsByStatusResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "invalid request")
}

ctx := sdk.UnwrapSDKContext(goCtx)

withdraws := k.GetAllWithdrawByStatus(ctx, req.Status.String())
paginatedWithdraws, pageRes, err := PaginateWithdraws(withdraws, req.Pagination)
if err != nil {
return nil, err
}

return &types.QueryWithdrawsByStatusResponse{
Withdraw: paginatedWithdraws,
Pagination: pageRes,
}, nil
}

// PaginateWithdraws is a helper function to do pagination of withdraws.
func PaginateWithdraws(withdraws []types.Withdraw, pageReq *query.PageRequest) ([]types.Withdraw, *query.PageResponse, error) {
if pageReq == nil {
pageReq = &query.PageRequest{
Limit: 100, // 设定一个默认值或者根据具体情况处理
Offset: 0,
}
}

start, end := int(pageReq.Offset), int(pageReq.Offset+pageReq.Limit)

Check failure

Code scanning / gosec

Potential integer overflow by integer type conversion Error

Potential integer overflow by integer type conversion

Check failure

Code scanning / gosec

Potential integer overflow by integer type conversion Error

Potential integer overflow by integer type conversion
if end > len(withdraws) || end < 0 { // -ve end means that the end has overflown
end = len(withdraws)
}
if start > len(withdraws) || start < 0 {
return []types.Withdraw{}, nil, status.Errorf(codes.InvalidArgument, "invalid request")
}

paginatedWithdraws := withdraws[start:end]

var nextPageToken []byte
if end < len(withdraws) {
nextPageToken = []byte(fmt.Sprintf("%v", end)) // Serialize the end cursor
}

return paginatedWithdraws, &query.PageResponse{
NextKey: nextPageToken,
Total: uint64(len(withdraws)),
}, nil
}
43 changes: 42 additions & 1 deletion x/bridge/keeper/withdraw.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package keeper //nolint:dupl
package keeper

import (
"github.com/cosmos/cosmos-sdk/store/prefix"
Expand Down Expand Up @@ -59,3 +59,44 @@ func (k Keeper) GetAllWithdraw(ctx sdk.Context) (list []types.Withdraw) {

return
}

// SetStatusIndex use status and txHash composite key
func (k Keeper) SetStatusIndex(ctx sdk.Context, status string, txHash string) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.WithdrawStatusKeyPrefix))
store.Set(types.WithdrawStatusKey(
status,
txHash,
), []byte(txHash))
}

// RemoveStatusIndex removes a status index
func (k Keeper) RemoveStatusIndex(
ctx sdk.Context,
status string,
txHash string,
) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.WithdrawStatusKeyPrefix))
store.Delete(types.WithdrawStatusKey(
status,
txHash,
))
}

// GetAllWithdrawByStatus returns all withdraw which have the same status
func (k Keeper) GetAllWithdrawByStatus(ctx sdk.Context, status string) (list []types.Withdraw) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.WithdrawStatusKeyPrefix))
iterator := sdk.KVStorePrefixIterator(store, []byte(status))

defer iterator.Close()

for ; iterator.Valid(); iterator.Next() {
txHash := string(iterator.Value())
val, found := k.GetWithdraw(ctx, txHash)
if !found {
continue
}
list = append(list, val)
}

return
}
12 changes: 12 additions & 0 deletions x/bridge/types/key_withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ var _ binary.ByteOrder
const (
// WithdrawKeyPrefix is the prefix to retrieve all Withdraw
WithdrawKeyPrefix = "Withdraw/value/"
// WithdrawStatusKeyPrefix is the prefix to retrieve all Withdraw by status
WithdrawStatusKeyPrefix = "Withdraw/status/"
)

// WithdrawKey returns the store key to retrieve a Withdraw from the index fields
Expand All @@ -21,3 +23,13 @@ func WithdrawKey(

return key
}

// WithdrawStatusKey returns the store key to retrieve a Withdraw from it's status and txHash
func WithdrawStatusKey(status string, txHash string) []byte {
var key []byte
key = append(key, []byte(status)...)
key = append(key, []byte("/")...)
key = append(key, []byte(txHash)...)
key = append(key, []byte("/")...)
return key
}
Loading

0 comments on commit 123b94b

Please sign in to comment.