forked from block-vision/sui-go-sdk
/
subscribe_api.go
90 lines (76 loc) · 2.25 KB
/
subscribe_api.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
package sui
import (
"context"
"encoding/json"
"log"
"github.com/tidwall/gjson"
"github.com/yasir7ca/sui-go-sdk/common/wsconn"
"github.com/yasir7ca/sui-go-sdk/models"
)
type ISubscribeAPI interface {
SubscribeEvent(ctx context.Context, req models.SuiXSubscribeEventsRequest, msgCh chan models.SuiEventResponse) error
SubscribeTransaction(ctx context.Context, req models.SuiXSubscribeTransactionsRequest, msgCh chan models.SuiEffects) error
}
type suiSubscribeImpl struct {
conn *wsconn.WsConn
}
// SubscribeEvent implements the method `suix_subscribeEvent`, subscribe to a stream of Sui event.
func (s *suiSubscribeImpl) SubscribeEvent(ctx context.Context, req models.SuiXSubscribeEventsRequest, msgCh chan models.SuiEventResponse) error {
rsp := make(chan []byte, 10)
err := s.conn.Call(ctx, wsconn.CallOp{
Method: "suix_subscribeEvent",
Params: []interface{}{
req.SuiEventFilter,
},
}, rsp)
if err != nil {
return err
}
go func() {
for {
select {
case messageData := <-rsp:
var result models.SuiEventResponse
if gjson.ParseBytes(messageData).Get("error").Exists() {
log.Fatal(gjson.ParseBytes(messageData).Get("error").String())
}
err := json.Unmarshal([]byte(gjson.ParseBytes(messageData).Get("params.result").String()), &result)
if err != nil {
log.Fatal(err)
}
msgCh <- result
}
}
}()
return nil
}
// SubscribeTransaction implements the method `suix_subscribeTransaction`, subscribe to a stream of Sui transaction effects.
func (s *suiSubscribeImpl) SubscribeTransaction(ctx context.Context, req models.SuiXSubscribeTransactionsRequest, msgCh chan models.SuiEffects) error {
rsp := make(chan []byte, 10)
err := s.conn.Call(ctx, wsconn.CallOp{
Method: "suix_subscribeTransaction",
Params: []interface{}{
req.TransactionFilter,
},
}, rsp)
if err != nil {
return err
}
go func() {
for {
select {
case messageData := <-rsp:
var result models.SuiEffects
if gjson.ParseBytes(messageData).Get("error").Exists() {
log.Fatal(gjson.ParseBytes(messageData).Get("error").String())
}
err := json.Unmarshal([]byte(gjson.ParseBytes(messageData).Get("params.result").String()), &result)
if err != nil {
log.Fatal(err)
}
msgCh <- result
}
}
}()
return nil
}