-
Notifications
You must be signed in to change notification settings - Fork 0
/
tx.go
77 lines (68 loc) · 2.54 KB
/
tx.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
package rest
import (
sdk "github.com/ci123chain/ci123chain/pkg/abci/types"
sdkerrors "github.com/ci123chain/ci123chain/pkg/abci/types/errors"
"github.com/ci123chain/ci123chain/pkg/abci/types/rest"
types2 "github.com/ci123chain/ci123chain/pkg/app/types"
"github.com/ci123chain/ci123chain/pkg/client/context"
"github.com/ci123chain/ci123chain/pkg/ibc/application/transfer/types"
clienttypes "github.com/ci123chain/ci123chain/pkg/ibc/core/clients/types"
"github.com/gorilla/mux"
"net/http"
"strconv"
"time"
)
var (
DefaultVersion uint64 = 0
)
func RegisterTxRoutes(cliCtx context.Context, r *mux.Router) {
r.HandleFunc("/ibc/transfer", rest.MiddleHandler(cliCtx, ibcTransferHandler, "")).Methods("POST")
}
func ibcTransferHandler(cliCtx context.Context, writer http.ResponseWriter, req *http.Request) {
sourcePort := req.FormValue("source_port")
sourceChannel := req.FormValue("source_channel")
token := req.FormValue("token")
coin, err := sdk.ParseCoinNormalized(token)
if err != nil {
rest.WriteErrorRes(writer, sdkerrors.Wrap(sdkerrors.ErrParams, err.Error()).Error())
return
}
receiver := req.FormValue("receiver")
timeoutHeight, err := strconv.ParseInt(req.FormValue("timeout_height"), 10, 64)
if err != nil {
rest.WriteErrorRes(writer, sdkerrors.Wrap(sdkerrors.ErrParams, err.Error()).Error())
return
}
timeoutTimestamp, err := strconv.ParseInt(req.FormValue("timeout_timestamp_offset"), 10, 64)
if err != nil {
rest.WriteErrorRes(writer, sdkerrors.Wrap(sdkerrors.ErrParams, err.Error()).Error())
return
}
if timeoutTimestamp != 0 {
timeoutTimestamp = time.Now().UTC().Add(time.Duration(timeoutTimestamp) * time.Second).UnixNano()
}
if coin.IsNegative() || coin.IsZero() {
rest.WriteErrorRes(writer, sdkerrors.Wrap(sdkerrors.ErrParams, "invalid coin").Error())
return
}
msg := types.NewMsgTransfer(
sourcePort,
sourceChannel,
coin,
cliCtx.FromAddr.String(), // 'MustGetAddress' must be called directly before calling 'NewMsg...'
receiver,
clienttypes.NewHeight(DefaultVersion, uint64(timeoutHeight)),
uint64(timeoutTimestamp),
)
if err := msg.ValidateBasic(); err != nil {
rest.WriteErrorRes(writer, sdkerrors.Wrap(sdkerrors.ErrParams, "invalid coin").Error())
return
}
txByte, err := types2.SignCommonTx(cliCtx.FromAddr, cliCtx.Nonce, cliCtx.Gas, []sdk.Msg{msg}, cliCtx.PrivateKey, cliCtx.Cdc)
res, err := cliCtx.BroadcastSignedTx(txByte)
if err != nil {
rest.WriteErrorRes(writer, sdkerrors.Wrap(sdkerrors.ErrInternal, "broadcast tx failed").Error())
return
}
rest.PostProcessResponseBare(writer, cliCtx, res)
}