-
Notifications
You must be signed in to change notification settings - Fork 40
/
getswapsbyrecipient.go
97 lines (83 loc) · 2.41 KB
/
getswapsbyrecipient.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
96
97
package rest
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/cosmos/cosmos-sdk/client/context"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/gorilla/mux"
"github.com/bnb-chain/node/plugins/tokens/swap"
"github.com/bnb-chain/node/wire"
)
// QuerySwapIDsByRecipientReqHandler creates an http request handler to query swapID list by recipient address
func QuerySwapIDsByRecipientReqHandler(
cdc *wire.Codec, ctx context.CLIContext) http.HandlerFunc {
responseType := "application/json"
throw := func(w http.ResponseWriter, status int, err error) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(status)
_, _ = w.Write([]byte(err.Error()))
}
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
recipientAddr, err := sdk.AccAddressFromBech32(vars["recipientAddr"])
if err != nil {
throw(w, http.StatusBadRequest, err)
return
}
limitStr := r.FormValue("limit")
offsetStr := r.FormValue("offset")
limit, err := strconv.Atoi(limitStr)
if err != nil {
throw(w, http.StatusBadRequest, fmt.Errorf("invalid limit"))
return
}
if limit <= 0 || limit > 100 {
throw(w, http.StatusBadRequest, fmt.Errorf("limit should be in (0, 100]"))
return
}
offset, err := strconv.Atoi(offsetStr)
if err != nil {
throw(w, http.StatusBadRequest, fmt.Errorf("invalid offset"))
return
}
if offset < 0 {
throw(w, http.StatusBadRequest, fmt.Errorf("offset must be positiv"))
return
}
params := swap.QuerySwapByRecipientParams{
Recipient: recipientAddr,
Limit: int64(limit),
Offset: int64(offset),
}
paramsBytes, err := cdc.MarshalJSON(params)
if err != nil {
throw(w, http.StatusInternalServerError, err)
return
}
bz, err := ctx.QueryWithData(fmt.Sprintf("custom/%s/%s", swap.AtomicSwapRoute, swap.QuerySwapRecipient), paramsBytes)
if err != nil {
throw(w, http.StatusInternalServerError, err)
return
}
var swapIDs []swap.SwapBytes
err = cdc.UnmarshalJSON(bz, &swapIDs)
if err != nil {
throw(w, http.StatusInternalServerError, err)
return
}
if len(swapIDs) == 0 {
throw(w, http.StatusNotFound, fmt.Errorf("no match swapID"))
return
}
output, err := json.MarshalIndent(swapIDs, "", " ")
if err != nil {
throw(w, http.StatusInternalServerError, err)
return
}
w.Header().Set("Content-Type", responseType)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(output)
}
}