This repository has been archived by the owner on Nov 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
/
handler.go
82 lines (72 loc) · 2.04 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
package main
import (
"fmt"
"net/http"
"github.com/bandprotocol/bandchain/chain/app"
sdkctx "github.com/cosmos/cosmos-sdk/client/context"
ckeys "github.com/cosmos/cosmos-sdk/client/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/gin-gonic/gin"
)
type Request struct {
Address string `json:"address" binding:"required"`
}
type Response struct {
TxHash string `json:"txHash"`
}
var (
cdc = app.MakeCodec()
)
func handleRequest(gc *gin.Context, c *Context) {
key := <-c.keys
defer func() {
c.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
}
msg := bank.NewMsgSend(key.GetAddress(), to, c.amount)
if err := msg.ValidateBasic(); err != nil {
gc.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
cliCtx := sdkctx.CLIContext{Client: c.client}
acc, err := auth.NewAccountRetriever(cliCtx).GetAccount(key.GetAddress())
if err != nil {
gc.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
txBldr := auth.NewTxBuilder(
auth.DefaultTxEncoder(cdc), acc.GetAccountNumber(), acc.GetSequence(),
200000, 1, false, cfg.ChainID, "", sdk.NewCoins(), c.gasPrices,
)
out, err := txBldr.WithKeybase(keybase).BuildAndSign(key.GetName(), ckeys.DefaultKeyPass, []sdk.Msg{msg})
if err != nil {
gc.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
res, err := cliCtx.BroadcastTxCommit(out)
if err != nil {
gc.JSON(http.StatusInternalServerError, 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
}
gc.JSON(200, Response{
TxHash: res.TxHash,
})
}