-
Notifications
You must be signed in to change notification settings - Fork 0
/
broadcast.go
executable file
·60 lines (49 loc) · 1.58 KB
/
broadcast.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
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
"github.com/glitternetwork/glitter-sdk-go/tx"
"golang.org/x/net/context/ctxhttp"
)
// Broadcast transaction
func (lcd *LCDClient) Broadcast(ctx context.Context, txbuilder *tx.Builder) (*sdk.TxResponse, error) {
txBytes, err := txbuilder.GetTxBytes()
if err != nil {
return nil, err
}
broadcastReq := txtypes.BroadcastTxRequest{
TxBytes: txBytes,
Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC,
}
reqBytes, err := json.Marshal(broadcastReq)
if err != nil {
return nil, sdkerrors.Wrap(err, "failed to marshal")
}
resp, err := ctxhttp.Post(ctx, lcd.c, lcd.URL+"/cosmos/tx/v1beta1/txs", "application/json", bytes.NewBuffer(reqBytes))
if err != nil {
return nil, sdkerrors.Wrap(err, "failed to broadcast")
}
out, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, sdkerrors.Wrap(err, "failed to read response")
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("non-200 response code %d: %s", resp.StatusCode, string(out))
}
var broadcastTxResponse txtypes.BroadcastTxResponse
err = lcd.GetMarshaler().UnmarshalJSON(out, &broadcastTxResponse)
if err != nil {
return nil, sdkerrors.Wrap(err, "failed to unmarshal response")
}
txResponse := broadcastTxResponse.TxResponse
if txResponse.Code != 0 {
return txResponse, fmt.Errorf("tx failed with code %d: %s", txResponse.Code, txResponse.RawLog)
}
return txResponse, nil
}