/
client.ts
803 lines (726 loc) · 22 KB
/
client.ts
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
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
import { fromB58, toB64, toHEX } from '@mysten/bcs';
import type { Signer } from '../cryptography/index.js';
import type { TransactionBlock } from '../transactions/index.js';
import { isTransactionBlock } from '../transactions/index.js';
import {
isValidSuiAddress,
isValidSuiObjectId,
isValidTransactionDigest,
normalizeSuiAddress,
normalizeSuiObjectId,
} from '../utils/sui-types.js';
import { SuiHTTPTransport } from './http-transport.js';
import type { SuiTransport } from './http-transport.js';
import type {
AddressMetrics,
AllEpochsAddressMetrics,
Checkpoint,
CheckpointPage,
CoinBalance,
CoinMetadata,
CoinSupply,
CommitteeInfo,
DelegatedStake,
DevInspectResults,
DevInspectTransactionBlockParams,
DryRunTransactionBlockParams,
DryRunTransactionBlockResponse,
DynamicFieldPage,
EpochInfo,
EpochMetricsPage,
EpochPage,
ExecuteTransactionBlockParams,
GetAllBalancesParams,
GetAllCoinsParams,
GetBalanceParams,
GetCheckpointParams,
GetCheckpointsParams,
GetCoinMetadataParams,
GetCoinsParams,
GetCommitteeInfoParams,
GetDynamicFieldObjectParams,
GetDynamicFieldsParams,
GetMoveFunctionArgTypesParams,
GetNormalizedMoveFunctionParams,
GetNormalizedMoveModuleParams,
GetNormalizedMoveModulesByPackageParams,
GetNormalizedMoveStructParams,
GetObjectParams,
GetOwnedObjectsParams,
GetProtocolConfigParams,
GetStakesByIdsParams,
GetStakesParams,
GetTotalSupplyParams,
GetTransactionBlockParams,
MoveCallMetrics,
MultiGetObjectsParams,
MultiGetTransactionBlocksParams,
NetworkMetrics,
ObjectRead,
Order,
PaginatedCoins,
PaginatedEvents,
PaginatedObjectsResponse,
PaginatedTransactionResponse,
ProtocolConfig,
QueryEventsParams,
QueryTransactionBlocksParams,
ResolvedNameServiceNames,
ResolveNameServiceAddressParams,
ResolveNameServiceNamesParams,
SubscribeEventParams,
SubscribeTransactionParams,
SuiEvent,
SuiMoveFunctionArgType,
SuiMoveNormalizedFunction,
SuiMoveNormalizedModule,
SuiMoveNormalizedModules,
SuiMoveNormalizedStruct,
SuiObjectResponse,
SuiObjectResponseQuery,
SuiSystemStateSummary,
SuiTransactionBlockResponse,
SuiTransactionBlockResponseQuery,
TransactionEffects,
TryGetPastObjectParams,
Unsubscribe,
ValidatorsApy,
} from './types/index.js';
export interface PaginationArguments<Cursor> {
/** Optional paging cursor */
cursor?: Cursor;
/** Maximum item returned per page */
limit?: number | null;
}
export interface OrderArguments {
order?: Order | null;
}
/**
* Configuration options for the SuiClient
* You must provide either a `url` or a `transport`
*/
export type SuiClientOptions = NetworkOrTransport;
export type NetworkOrTransport =
| {
url: string;
transport?: never;
}
| {
transport: SuiTransport;
url?: never;
};
export const SUI_CLIENT_BRAND = Symbol.for('@mysten/SuiClient');
export function isSuiClient(client: unknown): client is SuiClient {
return (
typeof client === 'object' &&
client !== null &&
(client as { [SUI_CLIENT_BRAND]: unknown })[SUI_CLIENT_BRAND] === true
);
}
export class SuiClient {
protected transport: SuiTransport;
get [SUI_CLIENT_BRAND]() {
return true;
}
/**
* Establish a connection to a Sui RPC endpoint
*
* @param options configuration options for the API Client
*/
constructor(options: SuiClientOptions) {
this.transport = options.transport ?? new SuiHTTPTransport({ url: options.url });
}
async getRpcApiVersion(): Promise<string | undefined> {
const resp = await this.transport.request<{ info: { version: string } }>({
method: 'rpc.discover',
params: [],
});
return resp.info.version;
}
/**
* Get all Coin<`coin_type`> objects owned by an address.
*/
async getCoins(input: GetCoinsParams): Promise<PaginatedCoins> {
if (!input.owner || !isValidSuiAddress(normalizeSuiAddress(input.owner))) {
throw new Error('Invalid Sui address');
}
return await this.transport.request({
method: 'suix_getCoins',
params: [input.owner, input.coinType, input.cursor, input.limit],
});
}
/**
* Get all Coin objects owned by an address.
*/
async getAllCoins(input: GetAllCoinsParams): Promise<PaginatedCoins> {
if (!input.owner || !isValidSuiAddress(normalizeSuiAddress(input.owner))) {
throw new Error('Invalid Sui address');
}
return await this.transport.request({
method: 'suix_getAllCoins',
params: [input.owner, input.cursor, input.limit],
});
}
/**
* Get the total coin balance for one coin type, owned by the address owner.
*/
async getBalance(input: GetBalanceParams): Promise<CoinBalance> {
if (!input.owner || !isValidSuiAddress(normalizeSuiAddress(input.owner))) {
throw new Error('Invalid Sui address');
}
return await this.transport.request({
method: 'suix_getBalance',
params: [input.owner, input.coinType],
});
}
/**
* Get the total coin balance for all coin types, owned by the address owner.
*/
async getAllBalances(input: GetAllBalancesParams): Promise<CoinBalance[]> {
if (!input.owner || !isValidSuiAddress(normalizeSuiAddress(input.owner))) {
throw new Error('Invalid Sui address');
}
return await this.transport.request({ method: 'suix_getAllBalances', params: [input.owner] });
}
/**
* Fetch CoinMetadata for a given coin type
*/
async getCoinMetadata(input: GetCoinMetadataParams): Promise<CoinMetadata | null> {
return await this.transport.request({
method: 'suix_getCoinMetadata',
params: [input.coinType],
});
}
/**
* Fetch total supply for a coin
*/
async getTotalSupply(input: GetTotalSupplyParams): Promise<CoinSupply> {
return await this.transport.request({
method: 'suix_getTotalSupply',
params: [input.coinType],
});
}
/**
* Invoke any RPC method
* @param method the method to be invoked
* @param args the arguments to be passed to the RPC request
*/
async call<T = unknown>(method: string, params: unknown[]): Promise<T> {
return await this.transport.request({ method, params });
}
/**
* Get Move function argument types like read, write and full access
*/
async getMoveFunctionArgTypes(
input: GetMoveFunctionArgTypesParams,
): Promise<SuiMoveFunctionArgType[]> {
return await this.transport.request({
method: 'sui_getMoveFunctionArgTypes',
params: [input.package, input.module, input.function],
});
}
/**
* Get a map from module name to
* structured representations of Move modules
*/
async getNormalizedMoveModulesByPackage(
input: GetNormalizedMoveModulesByPackageParams,
): Promise<SuiMoveNormalizedModules> {
return await this.transport.request({
method: 'sui_getNormalizedMoveModulesByPackage',
params: [input.package],
});
}
/**
* Get a structured representation of Move module
*/
async getNormalizedMoveModule(
input: GetNormalizedMoveModuleParams,
): Promise<SuiMoveNormalizedModule> {
return await this.transport.request({
method: 'sui_getNormalizedMoveModule',
params: [input.package, input.module],
});
}
/**
* Get a structured representation of Move function
*/
async getNormalizedMoveFunction(
input: GetNormalizedMoveFunctionParams,
): Promise<SuiMoveNormalizedFunction> {
return await this.transport.request({
method: 'sui_getNormalizedMoveFunction',
params: [input.package, input.module, input.function],
});
}
/**
* Get a structured representation of Move struct
*/
async getNormalizedMoveStruct(
input: GetNormalizedMoveStructParams,
): Promise<SuiMoveNormalizedStruct> {
return await this.transport.request({
method: 'sui_getNormalizedMoveStruct',
params: [input.package, input.module, input.struct],
});
}
/**
* Get all objects owned by an address
*/
async getOwnedObjects(input: GetOwnedObjectsParams): Promise<PaginatedObjectsResponse> {
if (!input.owner || !isValidSuiAddress(normalizeSuiAddress(input.owner))) {
throw new Error('Invalid Sui address');
}
return await this.transport.request({
method: 'suix_getOwnedObjects',
params: [
input.owner,
{
filter: input.filter,
options: input.options,
} as SuiObjectResponseQuery,
input.cursor,
input.limit,
],
});
}
/**
* Get details about an object
*/
async getObject(input: GetObjectParams): Promise<SuiObjectResponse> {
if (!input.id || !isValidSuiObjectId(normalizeSuiObjectId(input.id))) {
throw new Error('Invalid Sui Object id');
}
return await this.transport.request({
method: 'sui_getObject',
params: [input.id, input.options],
});
}
async tryGetPastObject(input: TryGetPastObjectParams): Promise<ObjectRead> {
return await this.transport.request({
method: 'sui_tryGetPastObject',
params: [input.id, input.version, input.options],
});
}
/**
* Batch get details about a list of objects. If any of the object ids are duplicates the call will fail
*/
async multiGetObjects(input: MultiGetObjectsParams): Promise<SuiObjectResponse[]> {
input.ids.forEach((id) => {
if (!id || !isValidSuiObjectId(normalizeSuiObjectId(id))) {
throw new Error(`Invalid Sui Object id ${id}`);
}
});
const hasDuplicates = input.ids.length !== new Set(input.ids).size;
if (hasDuplicates) {
throw new Error(`Duplicate object ids in batch call ${input.ids}`);
}
return await this.transport.request({
method: 'sui_multiGetObjects',
params: [input.ids, input.options],
});
}
/**
* Get transaction blocks for a given query criteria
*/
async queryTransactionBlocks(
input: QueryTransactionBlocksParams,
): Promise<PaginatedTransactionResponse> {
return await this.transport.request({
method: 'suix_queryTransactionBlocks',
params: [
{
filter: input.filter,
options: input.options,
} as SuiTransactionBlockResponseQuery,
input.cursor,
input.limit,
(input.order || 'descending') === 'descending',
],
});
}
async getTransactionBlock(
input: GetTransactionBlockParams,
): Promise<SuiTransactionBlockResponse> {
if (!isValidTransactionDigest(input.digest)) {
throw new Error('Invalid Transaction digest');
}
return await this.transport.request({
method: 'sui_getTransactionBlock',
params: [input.digest, input.options],
});
}
async multiGetTransactionBlocks(
input: MultiGetTransactionBlocksParams,
): Promise<SuiTransactionBlockResponse[]> {
input.digests.forEach((d) => {
if (!isValidTransactionDigest(d)) {
throw new Error(`Invalid Transaction digest ${d}`);
}
});
const hasDuplicates = input.digests.length !== new Set(input.digests).size;
if (hasDuplicates) {
throw new Error(`Duplicate digests in batch call ${input.digests}`);
}
return await this.transport.request({
method: 'sui_multiGetTransactionBlocks',
params: [input.digests, input.options],
});
}
async executeTransactionBlock(
input: ExecuteTransactionBlockParams,
): Promise<SuiTransactionBlockResponse> {
return await this.transport.request({
method: 'sui_executeTransactionBlock',
params: [
typeof input.transactionBlock === 'string'
? input.transactionBlock
: toB64(input.transactionBlock),
Array.isArray(input.signature) ? input.signature : [input.signature],
input.options,
input.requestType,
],
});
}
async signAndExecuteTransactionBlock({
transactionBlock,
signer,
...input
}: {
transactionBlock: Uint8Array | TransactionBlock;
signer: Signer;
} & Omit<
ExecuteTransactionBlockParams,
'transactionBlock' | 'signature'
>): Promise<SuiTransactionBlockResponse> {
let transactionBytes;
if (transactionBlock instanceof Uint8Array) {
transactionBytes = transactionBlock;
} else {
transactionBlock.setSenderIfNotSet(signer.toSuiAddress());
transactionBytes = await transactionBlock.build({ client: this });
}
const { signature, bytes } = await signer.signTransactionBlock(transactionBytes);
return this.executeTransactionBlock({
transactionBlock: bytes,
signature,
...input,
});
}
/**
* Get total number of transactions
*/
async getTotalTransactionBlocks(): Promise<bigint> {
const resp = await this.transport.request<string>({
method: 'sui_getTotalTransactionBlocks',
params: [],
});
return BigInt(resp);
}
/**
* Getting the reference gas price for the network
*/
async getReferenceGasPrice(): Promise<bigint> {
const resp = await this.transport.request<string>({
method: 'suix_getReferenceGasPrice',
params: [],
});
return BigInt(resp);
}
/**
* Return the delegated stakes for an address
*/
async getStakes(input: GetStakesParams): Promise<DelegatedStake[]> {
if (!input.owner || !isValidSuiAddress(normalizeSuiAddress(input.owner))) {
throw new Error('Invalid Sui address');
}
return await this.transport.request({ method: 'suix_getStakes', params: [input.owner] });
}
/**
* Return the delegated stakes queried by id.
*/
async getStakesByIds(input: GetStakesByIdsParams): Promise<DelegatedStake[]> {
input.stakedSuiIds.forEach((id) => {
if (!id || !isValidSuiObjectId(normalizeSuiObjectId(id))) {
throw new Error(`Invalid Sui Stake id ${id}`);
}
});
return await this.transport.request({
method: 'suix_getStakesByIds',
params: [input.stakedSuiIds],
});
}
/**
* Return the latest system state content.
*/
async getLatestSuiSystemState(): Promise<SuiSystemStateSummary> {
return await this.transport.request({ method: 'suix_getLatestSuiSystemState', params: [] });
}
/**
* Get events for a given query criteria
*/
async queryEvents(input: QueryEventsParams): Promise<PaginatedEvents> {
return await this.transport.request({
method: 'suix_queryEvents',
params: [
input.query,
input.cursor,
input.limit,
(input.order || 'descending') === 'descending',
],
});
}
/**
* Subscribe to get notifications whenever an event matching the filter occurs
*/
async subscribeEvent(
input: SubscribeEventParams & {
/** function to run when we receive a notification of a new event matching the filter */
onMessage: (event: SuiEvent) => void;
},
): Promise<Unsubscribe> {
return this.transport.subscribe({
method: 'suix_subscribeEvent',
unsubscribe: 'suix_unsubscribeEvent',
params: [input.filter],
onMessage: input.onMessage,
});
}
async subscribeTransaction(
input: SubscribeTransactionParams & {
/** function to run when we receive a notification of a new event matching the filter */
onMessage: (event: TransactionEffects) => void;
},
): Promise<Unsubscribe> {
return this.transport.subscribe({
method: 'suix_subscribeTransaction',
unsubscribe: 'suix_unsubscribeTransaction',
params: [input.filter],
onMessage: input.onMessage,
});
}
/**
* Runs the transaction block in dev-inspect mode. Which allows for nearly any
* transaction (or Move call) with any arguments. Detailed results are
* provided, including both the transaction effects and any return values.
*/
async devInspectTransactionBlock(
input: DevInspectTransactionBlockParams,
): Promise<DevInspectResults> {
let devInspectTxBytes;
if (isTransactionBlock(input.transactionBlock)) {
input.transactionBlock.setSenderIfNotSet(input.sender);
devInspectTxBytes = toB64(
await input.transactionBlock.build({
client: this,
onlyTransactionKind: true,
}),
);
} else if (typeof input.transactionBlock === 'string') {
devInspectTxBytes = input.transactionBlock;
} else if (input.transactionBlock instanceof Uint8Array) {
devInspectTxBytes = toB64(input.transactionBlock);
} else {
throw new Error('Unknown transaction block format.');
}
return await this.transport.request({
method: 'sui_devInspectTransactionBlock',
params: [input.sender, devInspectTxBytes, input.gasPrice?.toString(), input.epoch],
});
}
/**
* Dry run a transaction block and return the result.
*/
async dryRunTransactionBlock(
input: DryRunTransactionBlockParams,
): Promise<DryRunTransactionBlockResponse> {
return await this.transport.request({
method: 'sui_dryRunTransactionBlock',
params: [
typeof input.transactionBlock === 'string'
? input.transactionBlock
: toB64(input.transactionBlock),
],
});
}
/**
* Return the list of dynamic field objects owned by an object
*/
async getDynamicFields(input: GetDynamicFieldsParams): Promise<DynamicFieldPage> {
if (!input.parentId || !isValidSuiObjectId(normalizeSuiObjectId(input.parentId))) {
throw new Error('Invalid Sui Object id');
}
return await this.transport.request({
method: 'suix_getDynamicFields',
params: [input.parentId, input.cursor, input.limit],
});
}
/**
* Return the dynamic field object information for a specified object
*/
async getDynamicFieldObject(input: GetDynamicFieldObjectParams): Promise<SuiObjectResponse> {
return await this.transport.request({
method: 'suix_getDynamicFieldObject',
params: [input.parentId, input.name],
});
}
/**
* Get the sequence number of the latest checkpoint that has been executed
*/
async getLatestCheckpointSequenceNumber(): Promise<string> {
const resp = await this.transport.request({
method: 'sui_getLatestCheckpointSequenceNumber',
params: [],
});
return String(resp);
}
/**
* Returns information about a given checkpoint
*/
async getCheckpoint(input: GetCheckpointParams): Promise<Checkpoint> {
return await this.transport.request({ method: 'sui_getCheckpoint', params: [input.id] });
}
/**
* Returns historical checkpoints paginated
*/
async getCheckpoints(
input: PaginationArguments<CheckpointPage['nextCursor']> & GetCheckpointsParams,
): Promise<CheckpointPage> {
return await this.transport.request({
method: 'sui_getCheckpoints',
params: [input.cursor, input?.limit, input.descendingOrder],
});
}
/**
* Return the committee information for the asked epoch
*/
async getCommitteeInfo(input?: GetCommitteeInfoParams): Promise<CommitteeInfo> {
return await this.transport.request({
method: 'suix_getCommitteeInfo',
params: [input?.epoch],
});
}
async getNetworkMetrics(): Promise<NetworkMetrics> {
return await this.transport.request({ method: 'suix_getNetworkMetrics', params: [] });
}
async getAddressMetrics(): Promise<AddressMetrics> {
return await this.transport.request({ method: 'suix_getLatestAddressMetrics', params: [] });
}
async getEpochMetrics(
input?: { descendingOrder?: boolean } & PaginationArguments<EpochMetricsPage['nextCursor']>,
): Promise<EpochMetricsPage> {
return await this.transport.request({
method: 'suix_getEpochMetrics',
params: [input?.cursor, input?.limit, input?.descendingOrder],
});
}
async getAllEpochAddressMetrics(input?: {
descendingOrder?: boolean;
}): Promise<AllEpochsAddressMetrics> {
return await this.transport.request({
method: 'suix_getAllEpochAddressMetrics',
params: [input?.descendingOrder],
});
}
/**
* Return the committee information for the asked epoch
*/
async getEpochs(
input?: {
descendingOrder?: boolean;
} & PaginationArguments<EpochPage['nextCursor']>,
): Promise<EpochPage> {
return await this.transport.request({
method: 'suix_getEpochs',
params: [input?.cursor, input?.limit, input?.descendingOrder],
});
}
/**
* Returns list of top move calls by usage
*/
async getMoveCallMetrics(): Promise<MoveCallMetrics> {
return await this.transport.request({ method: 'suix_getMoveCallMetrics', params: [] });
}
/**
* Return the committee information for the asked epoch
*/
async getCurrentEpoch(): Promise<EpochInfo> {
return await this.transport.request({ method: 'suix_getCurrentEpoch', params: [] });
}
/**
* Return the Validators APYs
*/
async getValidatorsApy(): Promise<ValidatorsApy> {
return await this.transport.request({ method: 'suix_getValidatorsApy', params: [] });
}
// TODO: Migrate this to `sui_getChainIdentifier` once it is widely available.
async getChainIdentifier(): Promise<string> {
const checkpoint = await this.getCheckpoint({ id: '0' });
const bytes = fromB58(checkpoint.digest);
return toHEX(bytes.slice(0, 4));
}
async resolveNameServiceAddress(input: ResolveNameServiceAddressParams): Promise<string | null> {
return await this.transport.request({
method: 'suix_resolveNameServiceAddress',
params: [input.name],
});
}
async resolveNameServiceNames(
input: ResolveNameServiceNamesParams,
): Promise<ResolvedNameServiceNames> {
return await this.transport.request({
method: 'suix_resolveNameServiceNames',
params: [input.address, input.cursor, input.limit],
});
}
async getProtocolConfig(input?: GetProtocolConfigParams): Promise<ProtocolConfig> {
return await this.transport.request({
method: 'sui_getProtocolConfig',
params: [input?.version],
});
}
/**
* Wait for a transaction block result to be available over the API.
* This can be used in conjunction with `executeTransactionBlock` to wait for the transaction to
* be available via the API.
* This currently polls the `getTransactionBlock` API to check for the transaction.
*/
async waitForTransactionBlock({
signal,
timeout = 60 * 1000,
pollInterval = 2 * 1000,
...input
}: {
/** An optional abort signal that can be used to cancel */
signal?: AbortSignal;
/** The amount of time to wait for a transaction block. Defaults to one minute. */
timeout?: number;
/** The amount of time to wait between checks for the transaction block. Defaults to 2 seconds. */
pollInterval?: number;
} & Parameters<SuiClient['getTransactionBlock']>[0]): Promise<SuiTransactionBlockResponse> {
const timeoutSignal = AbortSignal.timeout(timeout);
const timeoutPromise = new Promise((_, reject) => {
timeoutSignal.addEventListener('abort', () => reject(timeoutSignal.reason));
});
timeoutPromise.catch(() => {
// Swallow unhandled rejections that might be thrown after early return
});
while (!timeoutSignal.aborted) {
signal?.throwIfAborted();
try {
return await this.getTransactionBlock(input);
} catch (e) {
// Wait for either the next poll interval, or the timeout.
await Promise.race([
new Promise((resolve) => setTimeout(resolve, pollInterval)),
timeoutPromise,
]);
}
}
timeoutSignal.throwIfAborted();
// This should never happen, because the above case should always throw, but just adding it in the event that something goes horribly wrong.
throw new Error('Unexpected error while waiting for transaction block.');
}
}