-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
95 lines (76 loc) · 2.64 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
95
package common
import (
"fmt"
"strings"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/elysium-station/black/x/auction/types"
)
const (
defaultPage = 1
defaultLimit = 100
)
// QueryAuctionByID returns an auction from state if present or falls back to searching old blocks
func QueryAuctionByID(cliCtx client.Context, cdc *codec.Codec, queryRoute string, auctionID uint64) (types.Auction, int64, error) {
bz, err := cliCtx.LegacyAmino.MarshalJSON(types.NewQueryAuctionParams(auctionID))
if err != nil {
return nil, 0, err
}
res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryGetAuction), bz)
if err == nil {
var auction types.Auction
cliCtx.LegacyAmino.MustUnmarshalJSON(res, &auction)
return auction, height, nil
}
if err != nil && !strings.Contains(err.Error(), "auction not found") {
return nil, 0, err
}
res, height, err = cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryNextAuctionID), nil)
if err != nil {
return nil, 0, err
}
var nextAuctionID uint64
cliCtx.LegacyAmino.MustUnmarshalJSON(res, &nextAuctionID)
if auctionID >= nextAuctionID {
return nil, 0, errorsmod.Wrapf(types.ErrAuctionNotFound, "%d", auctionID)
}
events := []string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, "place_bid"),
fmt.Sprintf("%s.%s='%s'", types.EventTypeAuctionBid, types.AttributeKeyAuctionID, []byte(fmt.Sprintf("%d", auctionID))),
}
// if the auction is closed, query for previous bid transactions
// note, will only fetch a maximum of 100 bids, so if an auction had more than that this
// query may fail to retreive the final state of the auction
searchResult, err := authtx.QueryTxsByEvents(cliCtx, events, defaultPage, defaultLimit, "")
if err != nil {
return nil, 0, err
}
maxHeight := int64(0)
found := false
for _, info := range searchResult.Txs {
for _, msg := range info.GetTx().GetMsgs() {
_, ok := msg.(*types.MsgPlaceBid)
if ok {
found = true
if info.Height > maxHeight {
maxHeight = info.Height
}
}
}
}
if !found {
return nil, 0, errorsmod.Wrapf(types.ErrAuctionNotFound, "%d", auctionID)
}
queryCLIContext := cliCtx.WithHeight(maxHeight)
res, height, err = queryCLIContext.QueryWithData(fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryGetAuction), bz)
if err != nil {
return nil, 0, err
}
// Decode and print results
var auction types.Auction
cliCtx.LegacyAmino.MustUnmarshalJSON(res, &auction)
return auction, height, nil
}