-
Notifications
You must be signed in to change notification settings - Fork 109
/
tx.go
65 lines (56 loc) · 1.37 KB
/
tx.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
package presenter
import (
"bytes"
"encoding/json"
"strconv"
"sync"
"github.com/strangelove-ventures/interchaintest/v6/internal/blockdb"
)
var bufPool = sync.Pool{New: func() any { return new(bytes.Buffer) }}
type Tx struct {
Result blockdb.TxResult
}
func (tx Tx) Height() string { return strconv.FormatInt(tx.Result.Height, 10) }
// Data attempts to pretty print JSON. If not valid JSON, returns tx data as-is which may not be human-readable.
func (tx Tx) Data() string {
buf := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf)
defer buf.Reset()
if err := json.Indent(buf, tx.Result.Tx, "", " "); err != nil {
return string(tx.Result.Tx)
}
return buf.String()
}
type Txs []blockdb.TxResult
// ToJSON always renders valid JSON given the blockdb.TxResult.
// If the tx data is not valid JSON, the tx data is represented as a base64 encoded string.
func (txs Txs) ToJSON() []byte {
type jsonObj struct {
Height int64
Tx json.RawMessage
}
type jsonBytes struct {
Height int64
Tx []byte
}
objs := make([]any, len(txs))
for i, tx := range txs {
if !json.Valid(tx.Tx) {
objs[i] = jsonBytes{
Height: tx.Height,
Tx: tx.Tx,
}
continue
}
objs[i] = jsonObj{
Height: tx.Height,
Tx: tx.Tx,
}
}
b, err := json.Marshal(objs)
if err != nil {
// json.Valid check above should prevent an error here.
panic(err)
}
return b
}