-
Notifications
You must be signed in to change notification settings - Fork 924
/
state.go
62 lines (53 loc) · 1.47 KB
/
state.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
package gateway
import (
"encoding/json"
"errors"
"net/http"
"github.com/cosmos/cosmos-sdk/types"
"github.com/gorilla/mux"
"github.com/celestiaorg/celestia-node/state"
)
const (
balanceEndpoint = "/balance"
)
const addrKey = "address"
var ErrInvalidAddressFormat = errors.New("address must be a valid account or validator address")
func (h *Handler) handleBalanceRequest(w http.ResponseWriter, r *http.Request) {
var (
bal *state.Balance
err error
)
// read and parse request
vars := mux.Vars(r)
addrStr, exists := vars[addrKey]
if !exists {
writeError(w, http.StatusBadRequest, balanceEndpoint, errors.New("balance endpoint requires address"))
return
}
// convert address to Address type
var addr state.AccAddress
addr, err = types.AccAddressFromBech32(addrStr)
if err != nil {
// first check if it is a validator address and can be converted
valAddr, err := types.ValAddressFromBech32(addrStr)
if err != nil {
writeError(w, http.StatusBadRequest, balanceEndpoint, ErrInvalidAddressFormat)
return
}
addr = valAddr.Bytes()
}
bal, err = h.state.BalanceForAddress(r.Context(), state.Address{Address: addr})
if err != nil {
writeError(w, http.StatusInternalServerError, balanceEndpoint, err)
return
}
resp, err := json.Marshal(bal)
if err != nil {
writeError(w, http.StatusInternalServerError, balanceEndpoint, err)
return
}
_, err = w.Write(resp)
if err != nil {
log.Errorw("writing response", "endpoint", balanceEndpoint, "err", err)
}
}