/
wavesapi.go
129 lines (107 loc) · 2.58 KB
/
wavesapi.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package helpers
import (
"bytes"
"encoding/json"
"errors"
"github.com/Gravity-Hub-Org/proof-of-concept/gh-node/helpers/state"
"io/ioutil"
"net/http"
"time"
)
const (
GetTxPath = "/transactions/info"
GetUnconfirmedTxByPath = "/transactions/unconfirmed/info"
GetStateByAddressPath = "/addresses/data"
WaitCount = 10
)
type Node struct {
nodeUrl string
apiKey string
}
func New(nodeUrl string, apiKey string) Node {
return Node{nodeUrl: nodeUrl, apiKey: apiKey}
}
func (node *Node) GetStateByAddressAndKey(address string, key string) (*state.State, error) {
rsBody, _, err := sendRequest("GET", node.nodeUrl+GetStateByAddressPath+"/"+address+"?key="+key, nil, "")
if err != nil {
return nil, err
}
var states []state.State
if err := json.Unmarshal(rsBody, &states); err != nil {
return nil, err
}
if len(states) == 0 {
return nil, nil
}
return &states[0], nil
}
func (node *Node) GetTxById(id string) (Transaction, error) {
rsBody, _, err := sendRequest("GET", node.nodeUrl+GetTxPath+"/"+id, nil, "")
if err != nil {
return Transaction{}, err
}
return Unmarshal(rsBody)
}
func (node *Node) IsUnconfirmedTx(id string) (bool, error) {
_, code, err := sendRequest("GET", node.nodeUrl+GetUnconfirmedTxByPath+"/"+id, nil, "")
if err != nil && code != 404 {
return true, err
}
return code == 200, nil
}
func (node *Node) WaitTx(id string) <-chan error {
out := make(chan error)
go func() {
defer close(out)
for i := 0; i < WaitCount; i++ {
un, err := node.IsUnconfirmedTx(id)
if err != nil {
out <- err
break
}
if un == false {
tx, err := node.GetTxById(id)
if err != nil {
out <- err
}
if tx.ID == "" {
out <- errors.New("transaction not found")
} else {
out <- nil
}
break
}
if i == (WaitCount - 1) {
out <- errors.New("transaction not found")
break
}
time.Sleep(time.Second)
}
}()
return out
}
func sendRequest(method string, url string, rqBody []byte, apiKey string) ([]byte, int, error) {
req, err := http.NewRequest(method, url, bytes.NewBuffer(rqBody))
req.Header.Add("content-type", "application/json")
if apiKey != "" {
req.Header.Add("X-API-Key", apiKey)
}
if err != nil {
return nil, 0, err
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
if resp != nil {
return nil, resp.StatusCode, err
} else {
return nil, 520, err
}
}
defer resp.Body.Close()
rsBody, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
return rsBody, resp.StatusCode, errors.New(string(rsBody))
}
return rsBody, resp.StatusCode, nil
}