-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaction.ts
More file actions
1033 lines (928 loc) · 29.6 KB
/
action.ts
File metadata and controls
1033 lines (928 loc) · 29.6 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
import {KwilSigner, NodeKwil, WebKwil, Types} from "@trufnetwork/kwil-js";
import { Either } from "monads-io";
import { DateString } from "../types/other";
import { StreamLocator } from "../types/stream";
import { CacheAwareResponse, GetRecordOptions, GetIndexOptions, GetIndexChangeOptions, GetFirstRecordOptions } from "../types/cache";
import { EthereumAddress } from "../util/EthereumAddress";
import { head } from "../util/head";
import { StreamId } from "../util/StreamId";
import { toVisibilityEnum, VisibilityEnum } from "../util/visibility";
import { CacheMetadataParser } from "../util/cacheMetadataParser";
import { CacheValidation } from "../util/cacheValidation";
import {
MetadataKey,
MetadataKeyValueMap,
MetadataTableKey,
MetadataValueTypeForKey,
StreamType,
} from "./contractValues";
// ValueType is available as Types.ValueType
export interface GetRecordInput {
stream: StreamLocator;
from?: number;
to?: number;
frozenAt?: number;
baseTime?: DateString | number;
prefix?: string;
}
export interface GetFirstRecordInput {
stream: StreamLocator;
after?: number;
frozenAt?: number;
}
export interface StreamRecord {
eventTime: number;
value: string;
}
export interface GetIndexChangeInput extends GetRecordInput {
timeInterval: number;
}
export interface ListMetadataByHeightParams {
/** Key reference filter. Default: empty string */
key?: string;
/** Value reference filter. Default: null */
value?: string;
/** Start height (inclusive). If null, uses earliest available. */
fromHeight?: number;
/** End height (inclusive). If null, uses current height. */
toHeight?: number;
/** Maximum number of results to return. Default: 1000 */
limit?: number;
/** Number of results to skip for pagination. Default: 0 */
offset?: number;
}
export interface MetadataQueryResult {
streamId: string;
dataProvider: string;
rowId: string;
valueInt: number | null;
valueFloat: string | null;
valueBoolean: boolean | null;
valueString: string | null;
valueRef: string | null;
createdAt: number;
}
export class Action {
protected kwilClient: WebKwil | NodeKwil;
protected kwilSigner: KwilSigner;
/** Track if deprecation warnings were already emitted */
private static _legacyWarnEmitted: Record<string, boolean> = {
getRecord: false,
getIndex: false,
getFirstRecord: false,
getIndexChange: false,
};
constructor(
kwilClient: WebKwil | NodeKwil,
kwilSigner: KwilSigner,
) {
this.kwilClient = kwilClient;
this.kwilSigner = kwilSigner;
}
/**
* Executes a method on the stream
*/
protected async executeWithNamedParams(
method: string,
inputs: Types.NamedParams[],
): Promise<Types.GenericResponse<Types.TxReceipt>> {
return this.kwilClient.execute({
namespace: "main",
name: method,
inputs,
description: `TN SDK - Executing method on stream: ${method}`,
},
this.kwilSigner,
);
}
/**
* Executes a method on the stream
*/
protected async executeWithActionBody(
inputs: Types.ActionBody,
synchronous: boolean = false,
): Promise<Types.GenericResponse<Types.TxReceipt>> {
return this.kwilClient.execute(inputs, this.kwilSigner, synchronous);
}
/**
* Calls a method on the stream
*/
protected async call<T>(
method: string,
inputs: Types.NamedParams,
): Promise<Either<number, T>> {
const result = await this.kwilClient.call(
{
namespace: "main",
name: method,
inputs: inputs,
},
this.kwilSigner,
);
if (result.status !== 200) {
return Either.left(result.status);
}
return Either.right(result.data?.result as T);
}
/**
* @deprecated Use getRecord(stream, options?) to leverage cache support and future-proof parameter handling.
*/
public async getRecord(input: GetRecordInput): Promise<StreamRecord[]>;
public async getRecord(stream: StreamLocator, options?: GetRecordOptions): Promise<CacheAwareResponse<StreamRecord[]>>;
public async getRecord(
inputOrStream: GetRecordInput | StreamLocator,
options?: GetRecordOptions
): Promise<StreamRecord[] | CacheAwareResponse<StreamRecord[]>> {
// Handle backward compatibility
if ('stream' in inputOrStream) {
// Legacy call format
const input = inputOrStream as GetRecordInput;
// emit deprecation warning once
if (!Action._legacyWarnEmitted.getRecord) {
Action._legacyWarnEmitted.getRecord = true;
if (typeof console !== 'undefined' && console.warn) {
console.warn('[TN SDK] Deprecated signature: getRecord(input). Use getRecord(stream, options?) instead.');
}
}
const prefix = input.prefix ? input.prefix : ""
const result = await this.call<{ event_time: number; value: string }[]>(
prefix + "get_record",
{
$data_provider: input.stream.dataProvider.getAddress(),
$stream_id: input.stream.streamId.getId(),
$from: input.from,
$to: input.to,
$frozen_at: input.frozenAt,
}
);
return result
.mapRight((result) =>
result.map((row) => ({
eventTime: row.event_time,
value: row.value,
})),
)
.throw();
}
// New cache-aware call format
const stream = inputOrStream as StreamLocator;
// Validate options if provided
if (options) {
CacheValidation.validateGetRecordOptions(options);
CacheValidation.validateTimeRange(options.from, options.to);
}
const prefix = options?.prefix ? options.prefix : ""
const params: any = {
$data_provider: stream.dataProvider.getAddress(),
$stream_id: stream.streamId.getId(),
$from: options?.from,
$to: options?.to,
$frozen_at: options?.frozenAt,
};
if (options?.useCache !== undefined) {
params.$use_cache = options.useCache;
}
const result = await this.kwilClient.call(
{
namespace: "main",
name: prefix + "get_record",
inputs: params,
},
this.kwilSigner,
);
if (result.status !== 200) {
throw new Error(`Failed to get record: ${result.status}`);
}
const data = (result.data?.result as { event_time: number; value: string }[]).map((row) => ({
eventTime: row.event_time,
value: row.value,
}));
let cache = CacheMetadataParser.extractFromResponse(result);
// Enhance cache metadata with SDK-provided context
if (cache) {
cache = {
...cache,
streamId: stream.streamId.getId(),
dataProvider: stream.dataProvider.getAddress(),
from: options?.from,
to: options?.to,
frozenAt: options?.frozenAt,
rowsServed: data.length
};
}
return {
data,
cache: cache || undefined,
logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined,
};
}
/**
* Returns the index of the stream within the given date range
* @deprecated Use getIndex(stream, options?) to leverage cache support and future-proof parameter handling.
*/
public async getIndex(input: GetRecordInput): Promise<StreamRecord[]>;
public async getIndex(stream: StreamLocator, options?: GetIndexOptions): Promise<CacheAwareResponse<StreamRecord[]>>;
public async getIndex(
inputOrStream: GetRecordInput | StreamLocator,
options?: GetIndexOptions
): Promise<StreamRecord[] | CacheAwareResponse<StreamRecord[]>> {
// Handle backward compatibility
if ('stream' in inputOrStream) {
// Legacy call format
const input = inputOrStream as GetRecordInput;
if (!Action._legacyWarnEmitted.getIndex) {
Action._legacyWarnEmitted.getIndex = true;
if (typeof console !== 'undefined' && console.warn) {
console.warn('[TN SDK] Deprecated signature: getIndex(input). Use getIndex(stream, options?) instead.');
}
}
const prefix = input.prefix ? input.prefix : ""
const result = await this.call<{ event_time: number; value: string }[]>(
prefix + "get_index",
{
$data_provider: input.stream.dataProvider.getAddress(),
$stream_id: input.stream.streamId.getId(),
$from: input.from,
$to: input.to,
$frozen_at: input.frozenAt,
$base_time: input.baseTime,
}
);
return result
.mapRight((result) =>
result.map((row) => ({
eventTime: row.event_time,
value: row.value,
})),
)
.throw();
}
// New cache-aware call format
const stream = inputOrStream as StreamLocator;
// Validate options if provided
if (options) {
CacheValidation.validateGetIndexOptions(options);
CacheValidation.validateTimeRange(options.from, options.to);
}
const prefix = options?.prefix ? options.prefix : ""
const params: any = {
$data_provider: stream.dataProvider.getAddress(),
$stream_id: stream.streamId.getId(),
$from: options?.from,
$to: options?.to,
$frozen_at: options?.frozenAt,
$base_time: options?.baseTime,
};
if (options?.useCache !== undefined) {
params.$use_cache = options.useCache;
}
const result = await this.kwilClient.call(
{
namespace: "main",
name: prefix + "get_index",
inputs: params,
},
this.kwilSigner,
);
if (result.status !== 200) {
throw new Error(`Failed to get index: ${result.status}`);
}
const data = (result.data?.result as { event_time: number; value: string }[]).map((row) => ({
eventTime: row.event_time,
value: row.value,
}));
let cache = CacheMetadataParser.extractFromResponse(result);
// Enhance cache metadata with SDK-provided context
if (cache) {
cache = {
...cache,
streamId: stream.streamId.getId(),
dataProvider: stream.dataProvider.getAddress(),
from: options?.from,
to: options?.to,
frozenAt: options?.frozenAt,
rowsServed: data.length
};
}
return {
data,
cache: cache || undefined,
logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined
};
}
/**
* Returns the type of the stream
*/
public async getType(
stream: StreamLocator,
): Promise<StreamType> {
const result = await this.getMetadata(
stream,
MetadataKey.TypeKey);
if (!result) {
throw new Error("Failed to get stream type");
}
const type = head(result).unwrapOrElse(() => {
throw new Error(
"Failed to get stream type. Check if the stream is initialized.",
);
});
const validTypes = [StreamType.Primitive, StreamType.Composed];
if (!validTypes.includes(type.value as StreamType)) {
throw new Error(`Invalid stream type: ${type.value}`);
}
return type.value as StreamType;
}
/**
* Returns the first record of the stream
* @deprecated Use getFirstRecord(stream, options?) to leverage cache support and future-proof parameter handling.
*/
public async getFirstRecord(
input: GetFirstRecordInput,
): Promise<StreamRecord | null>;
public async getFirstRecord(
stream: StreamLocator,
options?: GetFirstRecordOptions
): Promise<CacheAwareResponse<StreamRecord | null>>;
public async getFirstRecord(
inputOrStream: GetFirstRecordInput | StreamLocator,
options?: GetFirstRecordOptions
): Promise<StreamRecord | null | CacheAwareResponse<StreamRecord | null>> {
// Handle backward compatibility
if ('stream' in inputOrStream) {
// Legacy call format
const input = inputOrStream as GetFirstRecordInput;
if (!Action._legacyWarnEmitted.getFirstRecord) {
Action._legacyWarnEmitted.getFirstRecord = true;
if (typeof console !== 'undefined' && console.warn) {
console.warn('[TN SDK] Deprecated signature: getFirstRecord(input). Use getFirstRecord(stream, options?) instead.');
}
}
const result = await this.call<{ event_time: number; value: string }[]>(
"get_first_record",
{
$data_provider: input.stream.dataProvider.getAddress(),
$stream_id: input.stream.streamId.getId(),
$after: input.after,
$frozen_at: input.frozenAt,
}
);
return result
.mapRight(head)
.mapRight((result) =>
result
.map((result) => ({
eventTime: result.event_time,
value: result.value,
}))
.unwrapOr(null),
)
.throw();
}
// New cache-aware call format
const stream = inputOrStream as StreamLocator;
// Validate options if provided
if (options) {
CacheValidation.validateGetFirstRecordOptions(options);
}
const params: any = {
$data_provider: stream.dataProvider.getAddress(),
$stream_id: stream.streamId.getId(),
$after: options?.after,
$frozen_at: options?.frozenAt,
};
if (options?.useCache !== undefined) {
params.$use_cache = options.useCache;
}
const result = await this.kwilClient.call(
{
namespace: "main",
name: "get_first_record",
inputs: params,
},
this.kwilSigner,
);
if (result.status !== 200) {
throw new Error(`Failed to get first record: ${result.status}`);
}
const rawData = result.data?.result as { event_time: number; value: string }[];
const data = rawData && rawData.length > 0 ? {
eventTime: rawData[0].event_time,
value: rawData[0].value,
} : null;
let cache = CacheMetadataParser.extractFromResponse(result);
// Enhance cache metadata with SDK-provided context
if (cache) {
cache = {
...cache,
streamId: stream.streamId.getId(),
dataProvider: stream.dataProvider.getAddress(),
frozenAt: options?.frozenAt,
rowsServed: data ? 1 : 0
};
}
return {
data,
cache: cache || undefined,
logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined
};
}
protected async setMetadata<K extends MetadataKey>(
stream: StreamLocator,
key: K,
value: MetadataValueTypeForKey<K>,
): Promise<Types.GenericResponse<Types.TxReceipt>> {
return await this.executeWithNamedParams("insert_metadata", [{
$data_provider: stream.dataProvider.getAddress(),
$stream_id: stream.streamId.getId(),
$key: key,
$value: value,
$val_type: MetadataKeyValueMap[key],
},
]);
}
protected async getMetadata<K extends MetadataKey>(
stream: StreamLocator,
key: K,
// onlyLatest: boolean = true,
filteredRef?: string,
limit?: number,
offset?: number,
orderBy?: string,
): Promise<
{ rowId: string; value: MetadataValueTypeForKey<K>; createdAt: number }[]
> {
const result = await this.call<
{
row_id: string;
value_i: number;
value_f: string;
value_b: boolean;
value_s: string;
value_ref: string;
created_at: number;
}[]
>("get_metadata", {
$data_provider: stream.dataProvider.getAddress(),
$stream_id: stream.streamId.getId(),
$key: key,
$ref: filteredRef,
$limit: limit,
$offset: offset,
$order_by: orderBy,
},
);
return result
.mapRight((result) =>
result.map((row) => ({
rowId: row.row_id,
value: row[
MetadataTableKey[MetadataKeyValueMap[key as MetadataKey]]
] as MetadataValueTypeForKey<K>,
createdAt: row.created_at,
})),
)
.throw();
}
public async listMetadataByHeight<K extends MetadataKey>(
params: ListMetadataByHeightParams = {},
): Promise<MetadataQueryResult[]> {
type MetadataRawResult = {
stream_id: string;
data_provider: string;
row_id: string;
value_i: number | null;
value_f: string | null;
value_b: boolean | null;
value_s: string | null;
value_ref: string | null;
created_at: number;
}[];
const result = await this.call<MetadataRawResult>(
"list_metadata_by_height",
{
$key: params.key ?? "",
$ref: params.value ?? null,
$from_height: params.fromHeight ?? null,
$to_height: params.toHeight ?? null,
$limit: params.limit ?? null,
$offset: params.offset ?? null,
},
);
return result
.mapRight((records) =>
records.map(record => ({
streamId: record.stream_id,
dataProvider: record.data_provider,
rowId: record.row_id,
valueInt: record.value_i,
valueFloat: record.value_f,
valueBoolean: record.value_b,
valueString: record.value_s,
valueRef: record.value_ref,
createdAt: record.created_at,
}))
)
.throw();
}
/**
* Sets the read visibility of the stream
*/
public async setReadVisibility(
stream: StreamLocator,
visibility: VisibilityEnum,
): Promise<Types.GenericResponse<Types.TxReceipt>> {
return await this.setMetadata(
stream,
MetadataKey.ReadVisibilityKey,
visibility.toString(),
);
}
/**
* Returns the read visibility of the stream
*/
public async getReadVisibility(
stream: StreamLocator,
): Promise<VisibilityEnum | null> {
const result = await this.getMetadata(
stream,
MetadataKey.ReadVisibilityKey);
return head(result)
.map((row) => toVisibilityEnum(row.value))
.unwrapOr(null);
}
/**
* Sets the compose visibility of the stream
*/
public async setComposeVisibility(
stream: StreamLocator,
visibility: VisibilityEnum,
): Promise<Types.GenericResponse<Types.TxReceipt>> {
return await this.setMetadata(
stream,
MetadataKey.ComposeVisibilityKey,
visibility.toString(),
);
}
/**
* Returns the compose visibility of the stream
*/
public async getComposeVisibility(
stream: StreamLocator,
): Promise<VisibilityEnum | null> {
const result = await this.getMetadata(
stream,
MetadataKey.ComposeVisibilityKey);
return head(result)
.map((row) => toVisibilityEnum(row.value))
.unwrapOr(null);
}
/**
* Allows a wallet to read the stream
*/
public async allowReadWallet(
stream: StreamLocator,
wallet: EthereumAddress,
): Promise<Types.GenericResponse<Types.TxReceipt>> {
return await this.setMetadata(
stream,
MetadataKey.AllowReadWalletKey,
wallet.getAddress(),
);
}
/**
* Disables a wallet from reading the stream
*/
public async disableReadWallet(
stream: StreamLocator,
wallet: EthereumAddress,
): Promise<Types.GenericResponse<Types.TxReceipt>> {
const result = await this.getMetadata(
stream,
MetadataKey.AllowReadWalletKey,
wallet.getAddress(),
);
const row_id = head(result)
.map((row) => row.rowId)
.unwrapOr(null);
if (!row_id) {
throw new Error("Wallet not found in allowed list");
}
return await this.disableMetadata(stream, row_id);
}
/**
* Allows a stream to use this stream as child
*/
public async allowComposeStream(
stream: StreamLocator,
wallet: StreamLocator,
): Promise<Types.GenericResponse<Types.TxReceipt>> {
return await this.setMetadata(
stream,
MetadataKey.AllowComposeStreamKey,
wallet.streamId.getId(),
);
}
/**
* Disables a stream from using this stream as child
*/
public async disableComposeStream(
stream: StreamLocator,
wallet: StreamLocator,
): Promise<Types.GenericResponse<Types.TxReceipt>> {
const result = await this.getMetadata(
stream,
MetadataKey.AllowComposeStreamKey,
wallet.toString(),
);
const row_id = head(result)
.map((row) => row.rowId)
.unwrapOr(null);
if (!row_id) {
throw new Error("Stream not found in allowed list");
}
return await this.disableMetadata(stream, row_id);
}
protected async disableMetadata(
stream: StreamLocator,
rowId: string,
): Promise<Types.GenericResponse<Types.TxReceipt>> {
return await this.executeWithNamedParams("disable_metadata", [{
$data_provider: stream.dataProvider.getAddress(),
$stream_id: stream.streamId.getId(),
$row_id: rowId,
}]);
}
/**
* Returns the wallets allowed to read the stream
*/
public async getAllowedReadWallets(
stream: StreamLocator,
): Promise<EthereumAddress[]> {
const result = await this.getMetadata(
stream,
MetadataKey.AllowReadWalletKey);
return result
.filter((row) => row.value)
.map((row) => new EthereumAddress(row.value));
}
/**
* Returns the streams allowed to compose the stream
*/
public async getAllowedComposeStreams(
stream: StreamLocator,
): Promise<StreamLocator[]> {
const result = await this.getMetadata(
stream,
MetadataKey.AllowComposeStreamKey);
return result
.filter((row) => row.value)
.map((row) => {
const [streamId, dataProvider] = row.value.split(":");
return {
streamId: StreamId.fromString(streamId).throw(),
dataProvider: new EthereumAddress(dataProvider),
};
});
}
/**
* Returns the index change of the stream within the given date range
* @deprecated Use getIndexChange(stream, options) to leverage cache support and future-proof parameter handling.
*/
public async getIndexChange(
input: GetIndexChangeInput,
): Promise<StreamRecord[]>;
public async getIndexChange(
stream: StreamLocator,
options: GetIndexChangeOptions
): Promise<CacheAwareResponse<StreamRecord[]>>;
public async getIndexChange(
inputOrStream: GetIndexChangeInput | StreamLocator,
options?: GetIndexChangeOptions
): Promise<StreamRecord[] | CacheAwareResponse<StreamRecord[]>> {
// Handle backward compatibility
if ('stream' in inputOrStream) {
// Legacy call format
const input = inputOrStream as GetIndexChangeInput;
if (!Action._legacyWarnEmitted.getIndexChange) {
Action._legacyWarnEmitted.getIndexChange = true;
if (typeof console !== 'undefined' && console.warn) {
console.warn('[TN SDK] Deprecated signature: getIndexChange(input). Use getIndexChange(stream, options?) instead.');
}
}
const result = await this.call<{ event_time: number; value: string }[]>(
"get_index_change",
{
$data_provider: input.stream.dataProvider.getAddress(),
$stream_id: input.stream.streamId.getId(),
$from: input.from,
$to: input.to,
$frozen_at: input.frozenAt,
$base_time: input.baseTime,
$time_interval: input.timeInterval,
}
);
return result
.mapRight((result) =>
result.map((row) => ({
eventTime: row.event_time,
value: row.value,
})),
)
.throw();
}
// New cache-aware call format
const stream = inputOrStream as StreamLocator;
if (!options) {
throw new Error('Options parameter is required for cache-aware getIndexChange');
}
// Validate options
CacheValidation.validateGetIndexChangeOptions(options);
CacheValidation.validateTimeRange(options.from, options.to);
const params: any = {
$data_provider: stream.dataProvider.getAddress(),
$stream_id: stream.streamId.getId(),
$from: options.from,
$to: options.to,
$frozen_at: options.frozenAt,
$base_time: options.baseTime,
$time_interval: options.timeInterval,
};
if (options.useCache !== undefined) {
params.$use_cache = options.useCache;
}
const result = await this.kwilClient.call(
{
namespace: "main",
name: "get_index_change",
inputs: params,
},
this.kwilSigner,
);
if (result.status !== 200) {
throw new Error(`Failed to get index change: ${result.status}`);
}
const data = (result.data?.result as { event_time: number; value: string }[]).map((row) => ({
eventTime: row.event_time,
value: row.value,
}));
let cache = CacheMetadataParser.extractFromResponse(result);
// Enhance cache metadata with SDK-provided context
if (cache) {
cache = {
...cache,
streamId: stream.streamId.getId(),
dataProvider: stream.dataProvider.getAddress(),
from: options.from,
to: options.to,
frozenAt: options.frozenAt,
rowsServed: data.length
};
}
return {
data,
cache: cache || undefined,
logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined
};
}
/**
* A custom method that accepts the procedure name and the input of GetRecordInput
* Returns the result of the procedure in the same format as StreamRecord
* I.e. a custom procedure named "get_price" that returns a list of date_value and value
* can be called with customGetProcedure("get_price", { dateFrom: "2021-01-01", dateTo: "2021-01-31" })
*/
public async customGetProcedure(
procedure: string,
input: GetRecordInput,
): Promise<StreamRecord[]> {
const result = await this.call<{ event_time: number; value: string }[]>(
procedure,
{
$data_provider: input.stream.dataProvider.getAddress(),
$stream_id: input.stream.streamId.getId(),
$from: input.from,
$to: input.to,
$frozen_at: input.frozenAt
}
);
return result
.mapRight((result) =>
result.map((row) => ({
eventTime: row.event_time,
value: row.value,
})),
)
.throw();
}
/**
* A custom method that accepts the procedure name and custom input of type Record<string, any>
* Returns the result of the procedure in the same format as StreamRecord
* I.e. a custom procedure named "get_custom_index" that returns a list of date_value and value
* can be called with customProcedureWithArgs("get_custom_index", { $customArg1: "value1", $customArg2: "value2" })
* where $customArg1 and $customArg2 are the arguments of the procedure
* @param procedure
* @param args
*/
public async customProcedureWithArgs(
procedure: string,
args: Record<string, Types.ValueType | Types.ValueType[]>,
){
const result = await this.call<{ event_time: number; value: string }[]>(
procedure,
args
);
return result
.mapRight((result) =>
result.map((row) => ({
eventTime: row.event_time,
value: row.value,
})),
)
.throw();
}
/**
* Returns the size of database
*/
public async getDatabaseSize(): Promise<BigInt> {
const result = await this.call<{ database_size: BigInt }[]>("get_database_size", {})
return result
.map((rows) => {
const raw = rows[0].database_size;
const asBigInt = BigInt(raw.toString());
return asBigInt;
}).throw();
}
/**
* Gets the wallet balance on any supported blockchain network
* @param chain The chain identifier (e.g., "sepolia", "mainnet", "polygon", etc.)
* @param walletAddress The wallet address to check balance for
* @returns Promise that resolves to the balance as a string, or throws on error
*/
public async getWalletBalance(
chain: string,
walletAddress: string
): Promise<string> {
const result = await this.call<{ balance?: string; }[]>(
`${chain}_wallet_balance`,
{
$wallet_address: walletAddress,
}
);
return result
.mapRight((rows) => {
if (rows.length === 0) {
throw new Error("You don't have necessary permissions to execute this query");
}
const row = rows[0];
if (row.balance === undefined) {
throw new Error("No balance returned from wallet balance query");
}
return row.balance;
})
.throw();
}
/**
* Calls the whoami action to get the caller's wallet address
* This is useful for verifying wallet authentication with TN
* @returns Promise that resolves to the caller's wallet address
*/
public async whoami(): Promise<string> {
const result = await this.call<{ caller: string }[]>(
"whoami",
{}
);
return result
.mapRight((rows) => {
if (rows.length === 0) {
throw new Error("No response from whoami action");
}
const row = rows[0];