-
Notifications
You must be signed in to change notification settings - Fork 12
/
mixinnet.go
80 lines (65 loc) · 1.79 KB
/
mixinnet.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
package mixin
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/go-resty/resty/v2"
)
var mixinNetClient = resty.New().
SetHeader("Content-Type", "application/json").
SetHostURL(DefaultMixinNetHost).
SetTimeout(10 * time.Second)
func SendRawTransaction(ctx context.Context, raw string) (*Transaction, error) {
var tx Transaction
if err := callMixinNetRPC(ctx, map[string]interface{}{
"method": "sendrawtransaction",
"params": []interface{}{raw},
}, &tx); err != nil {
return nil, err
}
return &tx, nil
}
func GetTransaction(ctx context.Context, hash string) (*Transaction, error) {
var tx Transaction
if err := callMixinNetRPC(ctx, map[string]interface{}{
"method": "gettransaction",
"params": []interface{}{hash},
}, &tx); err != nil {
return nil, err
}
return &tx, nil
}
func callMixinNetRPC(ctx context.Context, params interface{}, resp interface{}) error {
r, err := mixinNetClient.R().SetContext(ctx).SetBody(params).Post("")
if err != nil {
return err
}
return UnmarshalMixinNetResponse(r, resp)
}
func DecodeMixinNetResponse(resp *resty.Response) ([]byte, error) {
var body struct {
Error interface{} `json:"error,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
}
if err := json.Unmarshal(resp.Body(), &body); err != nil {
if resp.IsError() {
return nil, createError(resp.StatusCode(), resp.StatusCode(), resp.Status())
}
return nil, createError(resp.StatusCode(), resp.StatusCode(), err.Error())
}
if body.Error != nil {
return nil, fmt.Errorf("MIXIN NET RPC ERROR %s", body.Error)
}
return body.Data, nil
}
func UnmarshalMixinNetResponse(resp *resty.Response, v interface{}) error {
data, err := DecodeMixinNetResponse(resp)
if err != nil {
return err
}
if v != nil {
return json.Unmarshal(data, v)
}
return nil
}