-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbindings.go
More file actions
2844 lines (2381 loc) · 77.3 KB
/
bindings.go
File metadata and controls
2844 lines (2381 loc) · 77.3 KB
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package exports
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"log"
"reflect"
"strconv"
"strings"
"time"
"github.com/cockroachdb/apd/v3"
"github.com/golang-sql/civil"
"github.com/pkg/errors"
"github.com/trufnetwork/kwil-db/core/crypto"
"github.com/trufnetwork/kwil-db/core/crypto/auth"
kwilTypes "github.com/trufnetwork/kwil-db/core/types"
"github.com/trufnetwork/sdk-go/core/contractsapi"
"github.com/trufnetwork/sdk-go/core/tnclient"
"github.com/trufnetwork/sdk-go/core/types"
"github.com/trufnetwork/sdk-go/core/util"
"google.golang.org/genproto/googleapis/type/decimal"
)
// StreamType constants.
const (
StreamTypeComposed types.StreamType = types.StreamTypeComposed
StreamTypePrimitive types.StreamType = types.StreamTypePrimitive
VisibilityPublic util.VisibilityEnum = util.PublicVisibility
VisibilityPrivate util.VisibilityEnum = util.PrivateVisibility
)
type OptionalInt64 struct {
Value int64
IsSet bool
}
func toOptionalInt64(value *int64) OptionalInt64 {
if value == nil {
return OptionalInt64{
Value: 0,
IsSet: false,
}
}
return OptionalInt64{
Value: *value,
IsSet: value != nil,
}
}
// ProcedureArgs represents a slice of arguments for a procedure.
type ProcedureArgs []any
type Record struct {
Date int `json:"date"`
Value string `json:"value"`
}
type DataResponse struct {
Data []Record `json:"data"`
CacheHit bool `json:"cache_hit"`
Height OptionalInt64 `json:"height"`
}
// ArgsFromStrings converts a slice of strings to ProcedureArgs.
func ArgsFromStrings(values []string) ProcedureArgs {
var anySlice []any
for _, v := range values {
anySlice = append(anySlice, v)
}
return anySlice
}
// ArgsFromFloats converts a slice of floats to ProcedureArgs.
func ArgsFromFloats(values []float64) ProcedureArgs {
var anySlice []any
for _, v := range values {
anySlice = append(anySlice, v)
}
return anySlice
}
// using variadic to make it easier to consume from python
func ArgsFromStringsSlice(values ...[]string) ProcedureArgs {
var anySlice []any
for _, v := range values {
anySlice = append(anySlice, v)
}
return anySlice
}
// using variadic to make it easier to consume from python
func ArgsFromFloatsSlice(values ...[]float64) ProcedureArgs {
var anySlice []any
for _, v := range values {
anySlice = append(anySlice, v)
}
return anySlice
}
// ArgsFromJSON converts a JSON string to ProcedureArgs.
// This allows passing mixed-type arguments from Python.
func ArgsFromJSON(jsonStr string) (ProcedureArgs, error) {
var anySlice []any
err := json.Unmarshal([]byte(jsonStr), &anySlice)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal JSON args")
}
return anySlice, nil
}
// NewClient creates a new TN client with the given provider and private key.
func NewClient(provider string, privateKey string) (*tnclient.Client, error) {
ctx := context.Background()
signer, err := createSigner(privateKey)
if err != nil {
return nil, errors.Wrap(err, "error creating signer")
}
client, err := tnclient.NewClient(ctx, provider, tnclient.WithSigner(signer))
if err != nil {
return nil, errors.Wrap(err, "error creating client")
}
return client, nil
}
func GetCurrentAccount(client *tnclient.Client) (string, error) {
address := client.Address()
return address.Address(), nil
}
// createSigner creates an EthPersonalSigner from a private key.
func createSigner(privateKey string) (*auth.EthPersonalSigner, error) {
pk, err := crypto.Secp256k1PrivateKeyFromHex(privateKey)
if err != nil {
return nil, errors.Wrap(err, "failed to create signer")
}
signer := &auth.EthPersonalSigner{Key: *pk}
return signer, nil
}
// GenerateStreamId generates a stream ID from the given name.
func GenerateStreamId(name string) string {
streamId := util.GenerateStreamId(name)
return streamId.String()
}
// DeployStream deploys a stream with the given stream ID and stream type.
func DeployStream(client *tnclient.Client, streamId string, streamType types.StreamType) (string, error) {
ctx := context.Background()
streamIdTyped, err := util.NewStreamId(streamId)
if err != nil {
return "", errors.Wrap(err, "error creating stream id")
}
deployTxHash, err := client.DeployStream(ctx, *streamIdTyped, streamType)
if err != nil {
return "", errors.Wrap(err, "error deploying stream")
}
return deployTxHash.String(), nil
}
// DestroyStream destroys the stream with the given stream ID.
func DestroyStream(client *tnclient.Client, streamId string) (string, error) {
ctx := context.Background()
streamIdTyped, err := util.NewStreamId(streamId)
if err != nil {
return "", errors.Wrap(err, "error creating stream id")
}
destroyTxHash, err := client.DestroyStream(ctx, *streamIdTyped)
if err != nil {
return "", errors.Wrap(err, "error destroying stream")
}
return destroyTxHash.String(), nil
}
// InsertRecord inserts single record into the stream with the given stream ID.
func InsertRecord(client *tnclient.Client, input types.InsertRecordInput) (string, error) {
ctx := context.Background()
primitiveStream, err := client.LoadPrimitiveActions()
if err != nil {
return "", errors.Wrap(err, "error loading primitive stream")
}
txHash, err := primitiveStream.InsertRecord(ctx, input)
if err != nil {
return "", errors.Wrap(err, "error inserting record")
}
return txHash.String(), nil
}
// InsertRecords inserts records into the stream with the given stream ID.
func InsertRecords(client *tnclient.Client, inputs []types.InsertRecordInput) (string, error) {
ctx := context.Background()
primitiveStream, err := client.LoadPrimitiveActions()
if err != nil {
return "", errors.Wrap(err, "error loading primitive stream")
}
txHash, err := primitiveStream.InsertRecords(ctx, inputs)
if err != nil {
return "", errors.Wrap(err, "error inserting records")
}
return txHash.String(), nil
}
// NewInsertRecordInput creates a new InsertRecordInput struct
func NewInsertRecordInput(client *tnclient.Client, streamId string, date int, val float64) types.InsertRecordInput {
dataProvider, err := GetCurrentAccount(client)
if err != nil {
log.Printf("Warning: Failed to get data provider: %v\n", err)
return types.InsertRecordInput{}
}
return types.InsertRecordInput{
StreamId: streamId,
DataProvider: dataProvider,
EventTime: date,
Value: val,
}
}
// NewGetRecordInput creates a new GetRecordInput struct
func NewGetRecordInput(
client *tnclient.Client,
streamId string,
dataProvider string,
from int,
to int,
frozenAt int,
baseDate int,
prefix string,
useCache bool,
) types.GetRecordInput {
result := types.GetRecordInput{
StreamId: streamId,
DataProvider: dataProvider,
Prefix: &prefix,
UseCache: &useCache,
}
if dataProvider == "" {
currentAccount, err := GetCurrentAccount(client)
if err != nil {
return result
}
result.DataProvider = currentAccount
}
if from != -1 {
result.From = &from
}
if to != -1 {
result.To = &to
}
if frozenAt != -1 {
result.FrozenAt = &frozenAt
}
if baseDate != -1 {
result.BaseDate = &baseDate
}
return result
}
// GetRecords retrieves records from the stream with the given stream ID.
func GetRecords(client *tnclient.Client, input types.GetRecordInput) (DataResponse, error) {
ctx := context.Background()
stream, err := client.LoadPrimitiveActions()
if err != nil {
return DataResponse{}, err
}
// Call WithMetadata variant for cache support
response, err := stream.GetRecord(ctx, input)
if err != nil {
return DataResponse{}, err
}
// Convert records to map slice
records := make([]Record, len(response.Results))
for i, record := range response.Results {
records[i] = Record{
Date: record.EventTime,
Value: record.Value.String(),
}
}
// Build cache-aware response with metadata from sdk-go
result := DataResponse{
Data: records,
CacheHit: response.Metadata.CacheHit,
Height: toOptionalInt64(response.Metadata.CacheHeight),
}
return result, nil
}
// GetType retrieves type of a stream (primitive or composed)
func GetType(client *tnclient.Client, streamId string, dataProvider string) (types.StreamType, error) {
streamIdTyped, err := util.NewStreamId(streamId)
ctx := context.Background()
if err != nil {
return types.StreamTypePrimitive, fmt.Errorf("invalid stream id '%s': %w", streamId, err)
}
dataProviderTyped, err := parseDataProvider(client, dataProvider)
if err != nil {
return types.StreamTypePrimitive, fmt.Errorf("invalid data provider '%s': %w", dataProvider, err)
}
streamLocator := types.StreamLocator{
StreamId: *streamIdTyped,
DataProvider: dataProviderTyped,
}
stream, err := client.LoadActions()
if err != nil {
return types.StreamTypePrimitive, err
}
return stream.GetType(ctx, streamLocator)
}
// NewGetFirstRecordInput creates a new GetFirstRecordInput struct
func NewGetFirstRecordInput(
client *tnclient.Client,
streamId string,
dataProvider string,
after int,
frozenAt int,
useCache bool,
) types.GetFirstRecordInput {
result := types.GetFirstRecordInput{
StreamId: streamId,
DataProvider: dataProvider,
UseCache: &useCache,
}
if dataProvider == "" {
currentAccount, err := GetCurrentAccount(client)
if err != nil {
return result
}
result.DataProvider = currentAccount
}
if frozenAt != -1 {
result.FrozenAt = &frozenAt
}
if after != -1 {
result.After = &after
}
return result
}
// GetFirstRecord retrieves the first record of a stream after a given date
// we return a slice even if we expect only one record because we can't return nil in this interface
func GetFirstRecord(client *tnclient.Client, input types.GetFirstRecordInput) (DataResponse, error) {
ctx := context.Background()
stream, err := client.LoadPrimitiveActions()
if err != nil {
return DataResponse{}, err
}
// Call WithMetadata variant for cache support
record, err := stream.GetFirstRecord(ctx, input)
// Guard against empty results
if len(record.Results) == 0 {
return DataResponse{
Data: []Record{},
CacheHit: record.Metadata.CacheHit,
Height: toOptionalInt64(record.Metadata.CacheHeight),
}, nil
}
// Convert to Record struct
recordData := Record{
Date: record.Results[0].EventTime,
Value: record.Results[0].Value.String(),
}
// Build cache-aware response with metadata
result := DataResponse{
Data: []Record{recordData},
CacheHit: record.Metadata.CacheHit,
Height: toOptionalInt64(record.Metadata.CacheHeight),
}
return result, nil
}
// GetIndex retrieves index values from a stream
func GetIndex(client *tnclient.Client, input types.GetIndexInput) (DataResponse, error) {
ctx := context.Background()
stream, err := client.LoadPrimitiveActions()
if err != nil {
return DataResponse{}, err
}
// Call WithMetadata variant for cache support
response, err := stream.GetIndex(ctx, input)
if err != nil {
return DataResponse{}, err
}
// Convert indices to Record slice
records := make([]Record, len(response.Results))
for i, index := range response.Results {
records[i] = Record{
Date: index.EventTime,
Value: index.Value.String(),
}
}
// Build cache-aware response with metadata from sdk-go
result := DataResponse{
Data: records,
CacheHit: response.Metadata.CacheHit,
Height: toOptionalInt64(response.Metadata.CacheHeight),
}
return result, nil
}
// NewListStreamsInput creates a new ListStreamsInput struct
func NewListStreamsInput(limit int, offset int, dataProvider string, orderBy string, blockHeight int) types.ListStreamsInput {
result := types.ListStreamsInput{
BlockHeight: blockHeight,
}
if limit != -1 {
result.Limit = limit
}
if offset != -1 {
result.Offset = offset
}
if dataProvider != "" {
result.DataProvider = dataProvider
}
if orderBy != "" {
result.OrderBy = orderBy
}
return result
}
// ListStreams retrieves all streams associated with client
func ListStreams(client *tnclient.Client, input types.ListStreamsInput) ([]map[string]string, error) {
ctx := context.Background()
streams, err := client.ListStreams(ctx, input)
if err != nil {
return nil, err
}
return recordsToMapSlice(streams), nil
}
// NewTaxonomyItemInput creates a new TaxonomyItemInput struct
func NewTaxonomyItemInput(client *tnclient.Client, dataProvider string, stream_id string, weight float64) types.TaxonomyItem {
streamIdObj, err := util.NewStreamId(stream_id)
if err != nil {
return types.TaxonomyItem{}
}
if dataProvider == "" {
currentAccount, err := GetCurrentAccount(client)
if err != nil {
return types.TaxonomyItem{}
}
dataProvider = currentAccount
}
dataProviderTyped, err := parseDataProvider(client, dataProvider)
if err != nil {
return types.TaxonomyItem{}
}
return types.TaxonomyItem{
ChildStream: types.StreamLocator{
StreamId: *streamIdObj,
DataProvider: dataProviderTyped,
},
Weight: weight,
}
}
// NewTaxonomyInput creates a new TaxonomyInput struct
func NewTaxonomyInput(client *tnclient.Client, streamId string, childStreams []types.TaxonomyItem, startDate int, groupSequence int) types.Taxonomy {
result := types.Taxonomy{
TaxonomyItems: childStreams,
}
// Assign parent stream
streamIdObj, err := util.NewStreamId(streamId)
if err != nil {
return types.Taxonomy{}
}
result.ParentStream = client.OwnStreamLocator(*streamIdObj)
createdAt, err := parseDate(time.Now().Format("2006-01-02"))
if err != nil {
return types.Taxonomy{}
}
result.CreatedAt = *createdAt
if startDate != -1 {
result.StartDate = &startDate
}
if groupSequence != -1 {
result.GroupSequence = groupSequence
}
return result
}
// SetTaxonomy define the taxonomy structure of a composed stream
func SetTaxonomy(client *tnclient.Client, input types.Taxonomy) (string, error) {
ctx := context.Background()
stream, err := client.LoadComposedActions()
if err != nil {
return "", err
}
txHash, err := stream.InsertTaxonomy(ctx, input)
if err != nil {
return "", err
}
return txHash.String(), nil
}
// DescribeTaxonomy retrieves the taxonomy structure of a composed stream
func DescribeTaxonomy(client *tnclient.Client, streamId string, latestVersion bool) (map[string]string, error) {
ctx := context.Background()
stream, err := client.LoadComposedActions()
if err != nil {
return map[string]string{}, err
}
streamIdObj, err := util.NewStreamId(streamId)
if err != nil {
return map[string]string{}, nil
}
result, err := stream.DescribeTaxonomies(ctx, types.DescribeTaxonomiesParams{
Stream: client.OwnStreamLocator(*streamIdObj),
LatestVersion: latestVersion,
})
if err != nil {
return map[string]string{}, err
}
childStreams := make([]map[string]string, 0, len(result.TaxonomyItems))
for _, childStream := range result.TaxonomyItems {
childStreams = append(childStreams, map[string]string{
"stream_id": childStream.ChildStream.StreamId.String(),
"data_provider": childStream.ChildStream.DataProvider.Address(),
"weight": convertToString(childStream.Weight),
})
}
childStreamsJSON, err := json.Marshal(childStreams)
if err != nil {
return map[string]string{}, err
}
res := map[string]string{
"stream_id": streamId,
"child_streams": string(childStreamsJSON),
"start_date": convertToString(result.StartDate),
"created_at": convertToString(result.CreatedAt),
"group_sequence": convertToString(result.GroupSequence),
}
return res, nil
}
// AllowComposeStream allows stream to use this stream as child, if composing is private
func AllowComposeStream(client *tnclient.Client, streamId string) (string, error) {
ctx := context.Background()
stream, err := client.LoadPrimitiveActions()
if err != nil {
return "", err
}
streamIdObj, err := util.NewStreamId(streamId)
if err != nil {
return "", err
}
txHash, err := stream.AllowComposeStream(ctx, client.OwnStreamLocator(*streamIdObj))
if err != nil {
return "", err
}
return txHash.String(), nil
}
// DisableComposeStream disables streams from using this stream as child
func DisableComposeStream(client *tnclient.Client, streamId string) (string, error) {
ctx := context.Background()
stream, err := client.LoadPrimitiveActions()
if err != nil {
return "", err
}
streamIdObj, err := util.NewStreamId(streamId)
if err != nil {
return "", err
}
txHash, err := stream.DisableComposeStream(ctx, client.OwnStreamLocator(*streamIdObj))
if err != nil {
return "", err
}
return txHash.String(), nil
}
// NewReadWalletInput creates a new ReadWalletInput struct
func NewReadWalletInput(client *tnclient.Client, streamId string, wallet string) types.ReadWalletInput {
result := types.ReadWalletInput{}
streamIdObj, err := util.NewStreamId(streamId)
if err != nil {
return types.ReadWalletInput{}
}
result.Stream = client.OwnStreamLocator(*streamIdObj)
result.Wallet, err = util.NewEthereumAddressFromString(wallet)
if err != nil {
return types.ReadWalletInput{}
}
return result
}
// AllowReadWallet allows a wallet to read the stream, if reading is private
func AllowReadWallet(client *tnclient.Client, input types.ReadWalletInput) (string, error) {
ctx := context.Background()
stream, err := client.LoadActions()
if err != nil {
return "", err
}
txHash, err := stream.AllowReadWallet(ctx, input)
if err != nil {
return "", err
}
return txHash.String(), nil
}
// DisableReadWallet disables a wallet from reading the stream
func DisableReadWallet(client *tnclient.Client, input types.ReadWalletInput) (string, error) {
ctx := context.Background()
stream, err := client.LoadActions()
if err != nil {
return "", err
}
txHash, err := stream.DisableReadWallet(ctx, input)
if err != nil {
return "", err
}
return txHash.String(), nil
}
// NewVisibilityInput creates a new VisibilityInput struct
func NewVisibilityInput(client *tnclient.Client, streamId string, visibility int) types.VisibilityInput {
result := types.VisibilityInput{}
streamIdObj, err := util.NewStreamId(streamId)
if err != nil {
return types.VisibilityInput{}
}
result.Stream = client.OwnStreamLocator(*streamIdObj)
result.Visibility, err = util.NewVisibilityEnum(visibility)
if err != nil {
return types.VisibilityInput{}
}
return result
}
// SetReadVisibility sets the read visibility of the stream -- Private or Public
func SetReadVisibility(client *tnclient.Client, input types.VisibilityInput) (string, error) {
ctx := context.Background()
stream, err := client.LoadActions()
if err != nil {
return "", err
}
txHash, err := stream.SetReadVisibility(ctx, input)
if err != nil {
return "", err
}
return txHash.String(), nil
}
// GetReadVisibility gets the read visibility of the stream -- Private or Public
func GetReadVisibility(client *tnclient.Client, streamId string) (util.VisibilityEnum, error) {
ctx := context.Background()
stream, err := client.LoadActions()
if err != nil {
return 0, err
}
streamIdObj, err := util.NewStreamId(streamId)
if err != nil {
return 0, err
}
visibility, err := stream.GetReadVisibility(ctx, client.OwnStreamLocator(*streamIdObj))
if err != nil {
return 0, err
}
return *visibility, nil
}
// SetComposeVisibility sets the compose visibility of the stream -- Private or Public
func SetComposeVisibility(client *tnclient.Client, input types.VisibilityInput) (string, error) {
ctx := context.Background()
stream, err := client.LoadActions()
if err != nil {
return "", err
}
txHash, err := stream.SetComposeVisibility(ctx, input)
if err != nil {
return "", err
}
return txHash.String(), nil
}
// GetComposeVisibility gets the compose visibility of the stream -- Private or Public
func GetComposeVisibility(client *tnclient.Client, streamId string) (util.VisibilityEnum, error) {
ctx := context.Background()
stream, err := client.LoadActions()
if err != nil {
return 0, err
}
streamIdObj, err := util.NewStreamId(streamId)
if err != nil {
return 0, err
}
visibility, err := stream.GetComposeVisibility(ctx, client.OwnStreamLocator(*streamIdObj))
if err != nil {
return 0, err
}
return *visibility, nil
}
// GetAllowedReadWallets gets the wallets allowed to read the stream
func GetAllowedReadWallets(client *tnclient.Client, streamId string) ([]string, error) {
ctx := context.Background()
stream, err := client.LoadActions()
if err != nil {
return []string{}, err
}
streamIdObj, err := util.NewStreamId(streamId)
if err != nil {
return []string{}, err
}
result, err := stream.GetAllowedReadWallets(ctx, client.OwnStreamLocator(*streamIdObj))
if err != nil {
return []string{}, err
}
addresses := make([]string, 0, len(result))
for _, address := range result {
addresses = append(addresses, address.Address())
}
return addresses, nil
}
// GetAllowedComposeStreams gets the streams allowed to compose this stream
func GetAllowedComposeStreams(client *tnclient.Client, streamId string) ([]string, error) {
ctx := context.Background()
stream, err := client.LoadActions()
if err != nil {
return []string{}, err
}
streamIdObj, err := util.NewStreamId(streamId)
if err != nil {
return []string{}, err
}
result, err := stream.GetAllowedComposeStreams(ctx, client.OwnStreamLocator(*streamIdObj))
if err != nil {
return []string{}, err
}
streams := make([]string, 0, len(result))
for _, stream := range result {
streams = append(streams, stream.StreamId.String())
}
return streams, nil
}
// WaitForTx waits for the transaction with the given hash to be confirmed.
func WaitForTx(client *tnclient.Client, txHashHex string) error {
ctx := context.Background()
txHash, err := kwilTypes.NewHashFromString(txHashHex)
if err != nil {
return fmt.Errorf("invalid transaction hash '%s': %w", txHashHex, err)
}
tx, err := client.WaitForTx(ctx, txHash, 1*time.Second)
if err != nil {
return err
}
// Check if tx was successful
if tx.Result.Code != uint32(kwilTypes.CodeOk) {
return fmt.Errorf("transaction failed: %s", tx.Result.Log)
}
return nil
}
// /*****************************************
// * Helper Functions *
// *****************************************/
// parseDataProvider checks if dataProvider is empty; if so, returns client's own address.
func parseDataProvider(client *tnclient.Client, dataProvider string) (util.EthereumAddress, error) {
if dataProvider == "" {
return client.Address(), nil
}
return util.NewEthereumAddressFromString(dataProvider)
}
// parseDate parses a date string in YYYY-MM-DD format and returns a UNIX timestamp *int.
func parseDate(dateStr string) (*int, error) {
if dateStr == "" {
return nil, nil
}
date, err := civil.ParseDate(dateStr)
if err != nil {
return nil, fmt.Errorf("invalid date format '%s': %w", dateStr, err)
}
unixTime := int(date.In(time.UTC).Unix())
return &unixTime, nil
}
// intOrNil returns a pointer to value unless it's -1, in which case it returns nil.
func intOrNil(value int) *int {
if value == -1 {
return nil
}
return &value
}
// recordsToMapSlice converts a slice of records (structs) to a slice of map[string]string.
func recordsToMapSlice(records interface{}) []map[string]string {
v := reflect.ValueOf(records)
if v.Kind() != reflect.Slice {
return nil
}
length := v.Len()
out := make([]map[string]string, length)
for i := 0; i < length; i++ {
recordVal := v.Index(i)
out[i] = structToMapString(recordVal.Interface())
}
return out
}
// structToMapString converts a struct to a map[string]string by reflecting over its fields.
func structToMapString(record any) map[string]string {
result := make(map[string]string)
val := reflect.ValueOf(record)
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
field := typ.Field(i)
valAsStr := convertToString(val.Field(i).Interface())
result[field.Name] = valAsStr
}
return result
}
// convertToString converts various data types to a string representation.
func convertToString(val any) string {
switch v := val.(type) {
case nil:
return ""
case string:
return v
case int:
return strconv.Itoa(v)
case float64:
return strconv.FormatFloat(v, 'f', -1, 64)
case decimal.Decimal:
return v.String()
case apd.Decimal:
return v.String()
case civil.Date:
return v.String()
case util.EthereumAddress:
return v.Address()
case *util.EthereumAddress:
return v.Address()
case bool:
return strconv.FormatBool(v)
case fmt.Stringer:
return v.String()
default:
log.Printf("Warning: Failed to convert argument to string from type %T: %v\n", val, val)
return fmt.Sprintf("%v", val)
}
}
// convertBytesToHex converts byte slice to hex string for Python compatibility
func convertBytesToHex(data []byte) string {
if data == nil {
return ""
}
return fmt.Sprintf("%x", data) // Use hex encoding for simplicity and readability
}
// NewStreamDefinitionForBinding creates a new types.StreamDefinition for binding purposes.
// It takes string representations of streamId and streamType and converts them.
func NewStreamDefinitionForBinding(streamIdStr string, streamTypeStr string) (*types.StreamDefinition, error) {
sid, err := util.NewStreamId(streamIdStr)
if err != nil {
return nil, errors.Wrapf(err, "error creating stream id from string: %s", streamIdStr)
}
var st types.StreamType
if streamTypeStr == string(types.StreamTypeComposed) {
st = types.StreamTypeComposed
} else if streamTypeStr == string(types.StreamTypePrimitive) {
st = types.StreamTypePrimitive
} else {
return nil, fmt.Errorf("unsupported stream type string: %s, expected 'primitive' or 'composed'", streamTypeStr)
}
return &types.StreamDefinition{
StreamId: *sid,
StreamType: st,
}, nil
}
// NewStreamLocatorForBinding creates a new types.StreamLocator for binding purposes.
func NewStreamLocatorForBinding(streamIdStr string, dataProviderAddressStr string) (*types.StreamLocator, error) {
sid, err := util.NewStreamId(streamIdStr)
if err != nil {
return nil, errors.Wrapf(err, "error creating stream id from string: %s", streamIdStr)
}
dp, err := util.NewEthereumAddressFromString(dataProviderAddressStr)
if err != nil {
return nil, errors.Wrapf(err, "error creating ethereum address from string: %s", dataProviderAddressStr)
}
return &types.StreamLocator{
StreamId: *sid,
DataProvider: dp,
}, nil
}
// BatchDeployStreams deploys multiple streams.
// It expects a slice of types.StreamDefinition, which Python side should construct.
func BatchDeployStreams(client *tnclient.Client, definitions []types.StreamDefinition) (string, error) {
ctx := context.Background()
txHash, err := client.BatchDeployStreams(ctx, definitions)