-
Notifications
You must be signed in to change notification settings - Fork 4
/
handler.go
86 lines (74 loc) · 1.88 KB
/
handler.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
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
GasAmount = 200000
GasAdjustment = 1
)
// Request defines request of faucet withdrawal.
type Request struct {
Denom string `json:"denom" binding:"required"`
Address string `json:"address" binding:"required"`
}
// Response defines response of faucet withdrawal.
type Response struct {
TxHash string `json:"txHash"`
}
// HandleRequest handles faucet withdrawal.
func (l *Limiter) HandleRequest(gc *gin.Context) {
key := <-l.keys
defer func() {
l.keys <- key
}()
var req Request
if err := gc.ShouldBindJSON(&req); err != nil {
gc.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
to, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
gc.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := sdk.ValidateDenom(req.Denom); err != nil {
gc.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if limitStatus, ok := l.allowed(req.Address, req.Denom); !ok {
gc.JSON(
http.StatusForbidden,
gin.H{
"error": "cannot withdraw more coins",
"time": (faucet.config.Period - time.Now().Sub(limitStatus.LastWithdrawals[req.Denom])).Seconds(),
},
)
return
}
coinsToWithdraw := sdk.NewCoins(sdk.NewCoin(req.Denom, l.ctx.coins.AmountOf(req.Denom)))
res, err := l.transferCoinsToClaimer(key, to, coinsToWithdraw)
if err != nil {
gc.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if res.Code != 0 {
gc.JSON(
http.StatusInternalServerError,
gin.H{
"error": fmt.Sprintf(
":exploding_head: Tx returned nonzero code %d with log %s, tx hash: %s",
res.Code,
res.RawLog,
res.TxHash,
),
},
)
return
}
l.updateLimitation(req.Address, req.Denom, coinsToWithdraw)
gc.JSON(http.StatusOK, Response{TxHash: res.TxHash})
}