-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhandler.go
58 lines (52 loc) · 1.18 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
package iost
import (
"errors"
"time"
"github.com/iost-official/go-sdk/pb"
)
// Handler handle tx with polling
type Handler struct {
client *Client
tx *rpcpb.TransactionRequest
ChSuccess chan *rpcpb.TxReceipt
ChFailed chan error
ChPending chan *rpcpb.SendTransactionResponse
}
// NewHandler make a handler
func NewHandler(tx *rpcpb.TransactionRequest, client *Client) *Handler {
return &Handler{
client: client,
tx: tx,
ChSuccess: make(chan *rpcpb.TxReceipt),
ChFailed: make(chan error),
ChPending: make(chan *rpcpb.SendTransactionResponse),
}
}
// Send sync send and get the tx hash
func (h *Handler) Send() (string, error) {
res, err := h.client.SendTransaction(h.tx)
if err != nil {
return "", err
}
return res.Hash, nil
}
// SendAndListen polling result after send
func (h *Handler) SendAndListen(interval time.Duration, times int) {
res, err := h.client.SendTransaction(h.tx)
if err != nil {
h.ChFailed <- err
return
}
for i := 0; i < times; i++ {
tr, err := h.client.TxReceiptByTxHash(res.Hash)
if err != nil {
continue
}
if tr.StatusCode != 0 {
h.ChFailed <- errors.New(tr.Message)
return
}
h.ChSuccess <- tr
return
}
}