/
client.go
331 lines (283 loc) · 8.2 KB
/
client.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package orbit
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/laxmicoinofficial/go/support/errors"
"github.com/laxmicoinofficial/go/xdr"
)
// HomeDomainForAccount returns the home domain for the provided strkey-encoded
// account id.
func (c *Client) HomeDomainForAccount(aid string) (string, error) {
a, err := c.LoadAccount(aid)
if err != nil {
return "", errors.Wrap(err, "load account failed")
}
return a.HomeDomain, nil
}
// fixURL removes trailing slash from Client.URL. This will prevent situation when
// http.Client does not follow redirects.
func (c *Client) fixURL() {
c.URL = strings.TrimRight(c.URL, "/")
}
// Root loads the root endpoint of orbit
func (c *Client) Root() (root Root, err error) {
c.fixURLOnce.Do(c.fixURL)
resp, err := c.HTTP.Get(c.URL)
if err != nil {
return
}
err = decodeResponse(resp, &root)
return
}
// LoadAccount loads the account state from orbit. err can be either error
// object or orbit.Error object.
func (c *Client) LoadAccount(accountID string) (account Account, err error) {
c.fixURLOnce.Do(c.fixURL)
resp, err := c.HTTP.Get(c.URL + "/accounts/" + accountID)
if err != nil {
return
}
err = decodeResponse(resp, &account)
return
}
// LoadAccountOffers loads the account offers from orbit. err can be either
// error object or orbit.Error object.
func (c *Client) LoadAccountOffers(accountID string, params ...interface{}) (offers OffersPage, err error) {
c.fixURLOnce.Do(c.fixURL)
endpoint := ""
query := url.Values{}
for _, param := range params {
switch param := param.(type) {
case At:
endpoint = string(param)
case Limit:
query.Add("limit", strconv.Itoa(int(param)))
case Order:
query.Add("order", string(param))
case Cursor:
query.Add("cursor", string(param))
default:
err = fmt.Errorf("Undefined parameter (%T): %+v", param, param)
return
}
}
if endpoint == "" {
endpoint = fmt.Sprintf(
"%s/accounts/%s/offers?%s",
c.URL,
accountID,
query.Encode(),
)
}
// ensure our endpoint is a real url
_, err = url.Parse(endpoint)
if err != nil {
err = errors.Wrap(err, "failed to parse endpoint")
return
}
resp, err := c.HTTP.Get(endpoint)
if err != nil {
err = errors.Wrap(err, "failed to load endpoint")
return
}
err = decodeResponse(resp, &offers)
return
}
// LoadMemo loads memo for a transaction in Payment
func (c *Client) LoadMemo(p *Payment) (err error) {
res, err := c.HTTP.Get(p.Links.Transaction.Href)
if err != nil {
return errors.Wrap(err, "load transaction failed")
}
defer res.Body.Close()
return json.NewDecoder(res.Body).Decode(&p.Memo)
}
// SequenceForAccount implements build.SequenceProvider
func (c *Client) SequenceForAccount(
accountID string,
) (xdr.SequenceNumber, error) {
a, err := c.LoadAccount(accountID)
if err != nil {
return 0, errors.Wrap(err, "load account failed")
}
seq, err := strconv.ParseUint(a.Sequence, 10, 64)
if err != nil {
return 0, errors.Wrap(err, "parse sequence failed")
}
return xdr.SequenceNumber(seq), nil
}
// LoadOrderBook loads order book for given selling and buying assets.
func (c *Client) LoadOrderBook(selling Asset, buying Asset, params ...interface{}) (orderBook OrderBookSummary, err error) {
c.fixURLOnce.Do(c.fixURL)
query := url.Values{}
query.Add("selling_asset_type", selling.Type)
query.Add("selling_asset_code", selling.Code)
query.Add("selling_asset_issuer", selling.Issuer)
query.Add("buying_asset_type", buying.Type)
query.Add("buying_asset_code", buying.Code)
query.Add("buying_asset_issuer", buying.Issuer)
for _, param := range params {
switch param := param.(type) {
case Limit:
query.Add("limit", strconv.Itoa(int(param)))
default:
err = fmt.Errorf("Undefined parameter (%T): %+v", param, param)
return
}
}
resp, err := c.HTTP.Get(c.URL + "/order_book?" + query.Encode())
if err != nil {
return
}
err = decodeResponse(resp, &orderBook)
return
}
func (c *Client) stream(ctx context.Context, baseURL string, cursor *Cursor, handler func(data []byte) error) error {
query := url.Values{}
if cursor != nil {
query.Set("cursor", string(*cursor))
}
for {
req, err := http.NewRequest("GET", fmt.Sprintf("%s?%s", baseURL, query.Encode()), nil)
if err != nil {
return err
}
req.Header.Set("Accept", "text/event-stream")
resp, err := c.HTTP.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
scanner.Split(splitSSE)
var objectBytes []byte
for scanner.Scan() {
// Check if ctx is not cancelled
select {
case <-ctx.Done():
return nil
default:
// Continue streaming
}
if len(scanner.Bytes()) == 0 {
continue
}
ev, err := parseEvent(scanner.Bytes())
if err != nil {
return err
}
if ev.Event != "message" {
continue
}
switch data := ev.Data.(type) {
case string:
err = handler([]byte(data))
objectBytes = []byte(data)
case []byte:
err = handler(data)
objectBytes = data
default:
err = errors.New("Invalid ev.Data type")
}
if err != nil {
return err
}
}
err = scanner.Err()
// Start streaming from the next object:
// - if there was no error OR
// - if connection was lost
if err == nil || err == io.ErrUnexpectedEOF {
object := struct {
PT string `json:"paging_token"`
}{}
err := json.Unmarshal(objectBytes, &object)
if err != nil {
return errors.Wrap(err, "Error unmarshaling objectBytes")
}
if object.PT != "" {
query.Set("cursor", object.PT)
} else {
return errors.New("no paging_token in object: cannot continue")
}
continue
}
if err != nil {
return err
}
}
}
// StreamLedgers streams incoming ledgers. Use context.WithCancel to stop streaming or
// context.Background() if you want to stream indefinitely.
func (c *Client) StreamLedgers(ctx context.Context, cursor *Cursor, handler LedgerHandler) (err error) {
c.fixURLOnce.Do(c.fixURL)
url := fmt.Sprintf("%s/ledgers", c.URL)
return c.stream(ctx, url, cursor, func(data []byte) error {
var ledger Ledger
err = json.Unmarshal(data, &ledger)
if err != nil {
return errors.Wrap(err, "Error unmarshaling data")
}
handler(ledger)
return nil
})
}
// StreamPayments streams incoming payments. Use context.WithCancel to stop streaming or
// context.Background() if you want to stream indefinitely.
func (c *Client) StreamPayments(ctx context.Context, accountID string, cursor *Cursor, handler PaymentHandler) (err error) {
c.fixURLOnce.Do(c.fixURL)
url := fmt.Sprintf("%s/accounts/%s/payments", c.URL, accountID)
return c.stream(ctx, url, cursor, func(data []byte) error {
var payment Payment
err = json.Unmarshal(data, &payment)
if err != nil {
return errors.Wrap(err, "Error unmarshaling data")
}
handler(payment)
return nil
})
}
// StreamTransactions streams incoming transactions. Use context.WithCancel to stop streaming or
// context.Background() if you want to stream indefinitely.
func (c *Client) StreamTransactions(ctx context.Context, accountID string, cursor *Cursor, handler TransactionHandler) (err error) {
c.fixURLOnce.Do(c.fixURL)
url := fmt.Sprintf("%s/accounts/%s/transactions", c.URL, accountID)
return c.stream(ctx, url, cursor, func(data []byte) error {
var transaction Transaction
err = json.Unmarshal(data, &transaction)
if err != nil {
return errors.Wrap(err, "Error unmarshaling data")
}
handler(transaction)
return nil
})
}
// SubmitTransaction submits a transaction to the network. err can be either error object or orbit.Error object.
func (c *Client) SubmitTransaction(transactionEnvelopeXdr string) (response TransactionSuccess, err error) {
c.fixURLOnce.Do(c.fixURL)
v := url.Values{}
v.Set("tx", transactionEnvelopeXdr)
resp, err := c.HTTP.PostForm(c.URL+"/transactions", v)
if err != nil {
err = errors.Wrap(err, "http post failed")
return
}
err = decodeResponse(resp, &response)
if err != nil {
return
}
// WARNING! Do not remove this code. If you include two trailing slashes (`//`) at the end of Client.URL
// and developers changed Client.HTTP to not follow redirects, this will return empty response and no error!
if resp.StatusCode != http.StatusOK {
err = errors.New("Invalid response code")
return
}
return
}