@thru/sdk 0.2.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.abi.md +112 -0
  2. package/README.md +342 -0
  3. package/dist/abi/index.cjs +946 -0
  4. package/dist/abi/index.cjs.map +1 -0
  5. package/dist/abi/index.d.cts +331 -0
  6. package/dist/abi/index.d.ts +331 -0
  7. package/dist/abi/index.js +892 -0
  8. package/dist/abi/index.js.map +1 -0
  9. package/dist/abi/wasm/bundler/abi_reflect_wasm.d.ts +65 -0
  10. package/dist/abi/wasm/bundler/abi_reflect_wasm.js +5 -0
  11. package/dist/abi/wasm/bundler/abi_reflect_wasm_bg.js +412 -0
  12. package/dist/abi/wasm/bundler/abi_reflect_wasm_bg.wasm +0 -0
  13. package/dist/abi/wasm/bundler/abi_reflect_wasm_bg.wasm.d.ts +24 -0
  14. package/dist/abi/wasm/bundler/package.json +17 -0
  15. package/dist/abi/wasm/node/abi_reflect_wasm.d.ts +65 -0
  16. package/dist/abi/wasm/node/abi_reflect_wasm.js +425 -0
  17. package/dist/abi/wasm/node/abi_reflect_wasm_bg.wasm +0 -0
  18. package/dist/abi/wasm/node/abi_reflect_wasm_bg.wasm.d.ts +24 -0
  19. package/dist/abi/wasm/node/package.json +11 -0
  20. package/dist/abi/wasm/web/abi_reflect_wasm.d.ts +114 -0
  21. package/dist/abi/wasm/web/abi_reflect_wasm.js +499 -0
  22. package/dist/abi/wasm/web/abi_reflect_wasm_bg.wasm +0 -0
  23. package/dist/abi/wasm/web/abi_reflect_wasm_bg.wasm.d.ts +24 -0
  24. package/dist/abi/wasm/web/package.json +15 -0
  25. package/dist/chunk-CVBQ4UPL.js +3614 -0
  26. package/dist/chunk-CVBQ4UPL.js.map +1 -0
  27. package/dist/chunk-NSBPE2FW.js +15 -0
  28. package/dist/chunk-NSBPE2FW.js.map +1 -0
  29. package/dist/chunk-RL3Q6FDE.js +105 -0
  30. package/dist/chunk-RL3Q6FDE.js.map +1 -0
  31. package/dist/chunk-UDIXYJXC.js +260 -0
  32. package/dist/chunk-UDIXYJXC.js.map +1 -0
  33. package/dist/chunk-YQDWOMNO.js +271 -0
  34. package/dist/chunk-YQDWOMNO.js.map +1 -0
  35. package/dist/client-Cfi7zRLm.d.cts +1247 -0
  36. package/dist/client-worIo0a3.d.ts +1247 -0
  37. package/dist/client.cjs +3791 -0
  38. package/dist/client.cjs.map +1 -0
  39. package/dist/client.d.cts +7 -0
  40. package/dist/client.d.ts +7 -0
  41. package/dist/client.js +7 -0
  42. package/dist/client.js.map +1 -0
  43. package/dist/crypto/index.cjs +170 -0
  44. package/dist/crypto/index.cjs.map +1 -0
  45. package/dist/crypto/index.d.cts +60 -0
  46. package/dist/crypto/index.d.ts +60 -0
  47. package/dist/crypto/index.js +5 -0
  48. package/dist/crypto/index.js.map +1 -0
  49. package/dist/helpers/index.cjs +270 -0
  50. package/dist/helpers/index.cjs.map +1 -0
  51. package/dist/helpers/index.d.cts +15 -0
  52. package/dist/helpers/index.d.ts +15 -0
  53. package/dist/helpers/index.js +4 -0
  54. package/dist/helpers/index.js.map +1 -0
  55. package/dist/metafile-cjs.json +1 -0
  56. package/dist/metafile-esm.json +1 -0
  57. package/dist/proto/index.cjs +433 -0
  58. package/dist/proto/index.cjs.map +1 -0
  59. package/dist/proto/index.d.cts +435 -0
  60. package/dist/proto/index.d.ts +435 -0
  61. package/dist/proto/index.js +4 -0
  62. package/dist/proto/index.js.map +1 -0
  63. package/dist/sdk.cjs +4137 -0
  64. package/dist/sdk.cjs.map +1 -0
  65. package/dist/sdk.d.cts +36 -0
  66. package/dist/sdk.d.ts +36 -0
  67. package/dist/sdk.js +7 -0
  68. package/dist/sdk.js.map +1 -0
  69. package/dist/streaming_service_pb-DvCdJiCr.d.cts +4877 -0
  70. package/dist/streaming_service_pb-DvCdJiCr.d.ts +4877 -0
  71. package/dist/webcrypto-LTajLAad.d.cts +3 -0
  72. package/dist/webcrypto-LTajLAad.d.ts +3 -0
  73. package/package.json +88 -0
@@ -0,0 +1,3614 @@
1
+ import { VersionContextSchema, CurrentVersionSchema, StateProofRequestSchema, GenerateStateProofRequestSchema, GetStateRootsRequestSchema, GetAccountRequestSchema, GetRawAccountRequestSchema, ListAccountsRequestSchema, GetBlockRequestSchema, GetRawBlockRequestSchema, ListBlocksRequestSchema, CurrentOrHistoricalVersionSchema, GetEventRequestSchema, ListEventsRequestSchema, GetHeightRequestSchema, GetChainInfoRequestSchema, GetNodeStatusRequestSchema, GetNodePubkeyRequestSchema, GetNodeRecordsRequestSchema, StreamBlocksRequestSchema, StreamAccountUpdatesRequestSchema, StreamTransactionsRequestSchema, StreamEventsRequestSchema, TrackTransactionRequestSchema, StreamHeightRequestSchema, StreamSlotMetricsRequestSchema, StreamNodeRecordsRequestSchema, GetSlotMetricsRequestSchema, ListSlotMetricsRequestSchema, GetTransactionRequestSchema, GetRawTransactionRequestSchema, GetTransactionStatusRequestSchema, ListTransactionsForAccountRequestSchema, ListTransactionsRequestSchema, BatchSendTransactionsRequestSchema, SendAndTrackTxnRequestSchema, SendTransactionRequestSchema, PubkeySchema, TaPubkeySchema, PageResponseSchema, BlockHashSchema, ConsensusStatus, FilterSchema, FilterParamValueSchema, SignatureSchema, TsSignatureSchema, PageRequestSchema, StreamingService, CommandService, QueryService, GetVersionRequestSchema } from './chunk-YQDWOMNO.js';
2
+ import { ThruHDWallet } from './chunk-RL3Q6FDE.js';
3
+ import { getWebCrypto, encodeSignature, encodeAddress, decodeAddress, isHexString, hexToBytes, ensureBytes, decodeSignature } from './chunk-UDIXYJXC.js';
4
+ import { __export } from './chunk-NSBPE2FW.js';
5
+ import { create } from '@bufbuild/protobuf';
6
+ import { createClient } from '@connectrpc/connect';
7
+ import { createGrpcWebTransport } from '@connectrpc/connect-web';
8
+ import { hashes, getPublicKeyAsync, utils, Point, etc } from '@noble/ed25519';
9
+ import { sha512, sha256 } from '@noble/hashes/sha2.js';
10
+
11
+ // thru-ts-client-sdk/domain/primitives/byte-utils.ts
12
+ function copyBytes(source) {
13
+ const bytes = new Uint8Array(source.length);
14
+ bytes.set(source);
15
+ return bytes;
16
+ }
17
+ function ensureExactLength(bytes, expected) {
18
+ if (bytes.length !== expected) {
19
+ throw new Error(`Must contain ${expected} bytes`);
20
+ }
21
+ return copyBytes(bytes);
22
+ }
23
+ function bytesEqual(a, b) {
24
+ if (a.length !== b.length) {
25
+ return false;
26
+ }
27
+ for (let i = 0; i < a.length; i++) {
28
+ if (a[i] !== b[i]) {
29
+ return false;
30
+ }
31
+ }
32
+ return true;
33
+ }
34
+ function bytesToHex(bytes) {
35
+ const hex = new Array(bytes.length);
36
+ for (let i = 0; i < bytes.length; i++) {
37
+ hex[i] = bytes[i].toString(16).padStart(2, "0");
38
+ }
39
+ return hex.join("");
40
+ }
41
+
42
+ // thru-ts-client-sdk/domain/primitives/constants.ts
43
+ var PUBKEY_LENGTH = 32;
44
+ var SIGNATURE_LENGTH = 64;
45
+ var TA_ADDRESS_LENGTH = 46;
46
+ var TS_SIGNATURE_LENGTH = 90;
47
+
48
+ // thru-ts-client-sdk/domain/primitives/Pubkey.ts
49
+ var Pubkey = class _Pubkey {
50
+ constructor(bytes) {
51
+ this.bytes = bytes;
52
+ }
53
+ static from(value) {
54
+ if (value instanceof _Pubkey) {
55
+ return value;
56
+ }
57
+ if (value instanceof Uint8Array) {
58
+ return new _Pubkey(ensureExactLength(value, PUBKEY_LENGTH));
59
+ }
60
+ if (typeof value === "string") {
61
+ return new _Pubkey(_Pubkey.bytesFromString(value));
62
+ }
63
+ throw new Error(
64
+ `Must be provided as Uint8Array, hex string, or ta-address`
65
+ );
66
+ }
67
+ static isThruFmt(value) {
68
+ return value.startsWith("ta") && value.length === TA_ADDRESS_LENGTH;
69
+ }
70
+ toBytes() {
71
+ return copyBytes(this.bytes);
72
+ }
73
+ toBytesUnsafe() {
74
+ return this.bytes;
75
+ }
76
+ toThruFmt() {
77
+ return encodeAddress(this.bytes);
78
+ }
79
+ toHex() {
80
+ return bytesToHex(this.bytes);
81
+ }
82
+ equals(other) {
83
+ const candidate = _Pubkey.from(other);
84
+ return bytesEqual(this.bytes, candidate.bytes);
85
+ }
86
+ toProtoPubkey() {
87
+ return create(PubkeySchema, { value: this.toBytes() });
88
+ }
89
+ toProtoTaPubkey() {
90
+ return create(TaPubkeySchema, { value: this.toThruFmt() });
91
+ }
92
+ static fromProtoPubkey(proto) {
93
+ if (!proto?.value) {
94
+ throw new Error(`Proto is missing value`);
95
+ }
96
+ return new _Pubkey(ensureExactLength(proto.value, PUBKEY_LENGTH));
97
+ }
98
+ static fromProtoTaPubkey(proto) {
99
+ if (!proto?.value) {
100
+ throw new Error(`Proto is missing value`);
101
+ }
102
+ return new _Pubkey(ensureExactLength(decodeAddress(proto.value), PUBKEY_LENGTH));
103
+ }
104
+ static bytesFromString(value) {
105
+ if (_Pubkey.isThruFmt(value)) {
106
+ return ensureExactLength(decodeAddress(value), PUBKEY_LENGTH);
107
+ }
108
+ if (isHexString(value)) {
109
+ return ensureExactLength(hexToBytes(value), PUBKEY_LENGTH);
110
+ }
111
+ throw new Error(`Must be provided as hex string or ta-address`);
112
+ }
113
+ };
114
+ var Signature = class _Signature {
115
+ constructor(bytes) {
116
+ this.bytes = bytes;
117
+ }
118
+ static from(value) {
119
+ if (value instanceof _Signature) {
120
+ return value;
121
+ }
122
+ if (value instanceof Uint8Array) {
123
+ return new _Signature(ensureExactLength(value, SIGNATURE_LENGTH));
124
+ }
125
+ if (typeof value === "string") {
126
+ return new _Signature(_Signature.bytesFromString(value));
127
+ }
128
+ throw new Error(
129
+ `Must be provided as Uint8Array, ts-encoded string, hex string, or base64 string`
130
+ );
131
+ }
132
+ static fromProto(proto) {
133
+ if (!proto?.value) {
134
+ throw new Error(`Proto is missing value`);
135
+ }
136
+ return new _Signature(ensureExactLength(proto.value, SIGNATURE_LENGTH));
137
+ }
138
+ static isThruFmt(value) {
139
+ return value.startsWith("ts") && value.length === TS_SIGNATURE_LENGTH;
140
+ }
141
+ toBytes() {
142
+ return copyBytes(this.bytes);
143
+ }
144
+ toBytesUnsafe() {
145
+ return this.bytes;
146
+ }
147
+ toThruFmt() {
148
+ return encodeSignature(this.bytes);
149
+ }
150
+ toHex() {
151
+ return bytesToHex(this.bytes);
152
+ }
153
+ equals(other) {
154
+ const candidate = _Signature.from(other);
155
+ return bytesEqual(this.bytes, candidate.bytes);
156
+ }
157
+ toProtoSignature() {
158
+ return create(SignatureSchema, { value: this.toBytes() });
159
+ }
160
+ toProtoTsSignature() {
161
+ return create(TsSignatureSchema, { value: this.toThruFmt() });
162
+ }
163
+ static fromProtoTsSignature(proto) {
164
+ if (!proto?.value) {
165
+ throw new Error(`Proto is missing value`);
166
+ }
167
+ return new _Signature(ensureExactLength(decodeSignature(proto.value), SIGNATURE_LENGTH));
168
+ }
169
+ static fromProtoSignature(proto) {
170
+ if (!proto?.value) {
171
+ throw new Error(`Proto is missing value`);
172
+ }
173
+ return new _Signature(ensureExactLength(proto.value, SIGNATURE_LENGTH));
174
+ }
175
+ static bytesFromString(value) {
176
+ if (_Signature.isThruFmt(value)) {
177
+ return ensureExactLength(decodeSignature(value), SIGNATURE_LENGTH);
178
+ }
179
+ if (isHexString(value)) {
180
+ return ensureExactLength(hexToBytes(value), SIGNATURE_LENGTH);
181
+ }
182
+ throw new Error(`Must be provided as ts-encoded string or hex string`);
183
+ }
184
+ };
185
+
186
+ // thru-ts-client-sdk/modules/accounts.ts
187
+ var accounts_exports = {};
188
+ __export(accounts_exports, {
189
+ createAccount: () => createAccount,
190
+ getAccount: () => getAccount,
191
+ getRawAccount: () => getRawAccount,
192
+ listAccounts: () => listAccounts
193
+ });
194
+ var DEFAULT_HOST = "https://grpc-web.alphanet.thruput.org";
195
+ var DEFAULT_ACCOUNT_VIEW = 4 /* FULL */;
196
+ var DEFAULT_BLOCK_VIEW = 4 /* FULL */;
197
+ var DEFAULT_TRANSACTION_VIEW = 4 /* FULL */;
198
+ var DEFAULT_MIN_CONSENSUS = 0 /* UNSPECIFIED */;
199
+ var DEFAULT_VERSION_CONTEXT = create(VersionContextSchema, {
200
+ version: {
201
+ case: "current",
202
+ value: create(CurrentVersionSchema, {})
203
+ }
204
+ });
205
+ var DEFAULT_FEE = 1n;
206
+ var DEFAULT_COMPUTE_UNITS = 3e8;
207
+ var DEFAULT_STATE_UNITS = 1e4;
208
+ var DEFAULT_MEMORY_UNITS = 1e4;
209
+ var DEFAULT_EXPIRY_AFTER = 100;
210
+
211
+ // thru-ts-client-sdk/core/client.ts
212
+ function createThruClientContext(config = {}) {
213
+ const transportOptions = config.transportOptions ?? {};
214
+ const { baseUrl: optionsBaseUrl, interceptors: optionInterceptors, ...restTransportOptions } = transportOptions;
215
+ const baseUrl = config.baseUrl ?? optionsBaseUrl ?? DEFAULT_HOST;
216
+ const mergedInterceptors = [
217
+ ...optionInterceptors ?? [],
218
+ ...config.interceptors ?? []
219
+ ];
220
+ const transport = config.transport ?? createGrpcWebTransport({
221
+ baseUrl,
222
+ ...restTransportOptions,
223
+ interceptors: mergedInterceptors.length > 0 ? mergedInterceptors : void 0
224
+ });
225
+ return {
226
+ baseUrl,
227
+ transport,
228
+ query: createClient(QueryService, transport),
229
+ command: createClient(CommandService, transport),
230
+ streaming: createClient(StreamingService, transport),
231
+ callOptions: config.callOptions
232
+ };
233
+ }
234
+ function withCallOptions(ctx, overrides) {
235
+ return mergeCallOptions(ctx.callOptions, overrides);
236
+ }
237
+ function mergeCallOptions(defaults, overrides) {
238
+ if (!defaults) {
239
+ return overrides;
240
+ }
241
+ if (!overrides) {
242
+ return defaults;
243
+ }
244
+ return {
245
+ ...defaults,
246
+ ...overrides,
247
+ headers: mergeHeaders(defaults.headers, overrides.headers),
248
+ contextValues: overrides.contextValues ?? defaults.contextValues,
249
+ onHeader: overrides.onHeader ?? defaults.onHeader,
250
+ onTrailer: overrides.onTrailer ?? defaults.onTrailer
251
+ };
252
+ }
253
+ function mergeHeaders(a, b) {
254
+ const entries = [];
255
+ const add = (init) => {
256
+ if (!init) {
257
+ return;
258
+ }
259
+ if (init instanceof Headers) {
260
+ init.forEach((value, key) => {
261
+ entries.push([key, value]);
262
+ });
263
+ return;
264
+ }
265
+ if (Array.isArray(init)) {
266
+ for (const [key, value] of init) {
267
+ entries.push([key, value]);
268
+ }
269
+ return;
270
+ }
271
+ for (const [key, value] of Object.entries(init)) {
272
+ if (value !== void 0) {
273
+ entries.push([key, String(value)]);
274
+ }
275
+ }
276
+ };
277
+ add(a);
278
+ add(b);
279
+ if (entries.length === 0) {
280
+ return void 0;
281
+ }
282
+ return entries;
283
+ }
284
+
285
+ // thru-ts-client-sdk/utils/utils.ts
286
+ function isSlotSelector(selector) {
287
+ return "slot" in selector;
288
+ }
289
+ function mergeTransactionHeader(defaults, overrides) {
290
+ if (!overrides) {
291
+ return defaults;
292
+ }
293
+ const sanitized = Object.fromEntries(
294
+ Object.entries(overrides).filter(([, value]) => value !== void 0)
295
+ );
296
+ return {
297
+ ...defaults,
298
+ ...sanitized
299
+ };
300
+ }
301
+ function timestampToNanoseconds(timestamp) {
302
+ if (!timestamp) {
303
+ return 0n;
304
+ }
305
+ const seconds = BigInt(timestamp.seconds ?? 0);
306
+ const nanos = BigInt(timestamp.nanos ?? 0);
307
+ return seconds * 1000000000n + nanos;
308
+ }
309
+ function nanosecondsToTimestamp(ns) {
310
+ const seconds = ns / 1000000000n;
311
+ const nanos = Number(ns % 1000000000n);
312
+ return { seconds, nanos };
313
+ }
314
+ function consensusStatusToString(status) {
315
+ const lookup = ConsensusStatus;
316
+ return lookup[status] ?? `UNKNOWN(${status})`;
317
+ }
318
+
319
+ // thru-ts-client-sdk/domain/accounts/Account.ts
320
+ var AccountFlags = class _AccountFlags {
321
+ constructor(flags) {
322
+ this.isProgram = flags?.isProgram ?? false;
323
+ this.isPrivileged = flags?.isPrivileged ?? false;
324
+ this.isUncompressable = flags?.isUncompressable ?? false;
325
+ this.isEphemeral = flags?.isEphemeral ?? false;
326
+ this.isDeleted = flags?.isDeleted ?? false;
327
+ this.isNew = flags?.isNew ?? false;
328
+ this.isCompressed = flags?.isCompressed ?? false;
329
+ }
330
+ static fromProto(flags) {
331
+ if (!flags) {
332
+ return new _AccountFlags();
333
+ }
334
+ return new _AccountFlags({
335
+ isProgram: flags.isProgram,
336
+ isPrivileged: flags.isPrivileged,
337
+ isUncompressable: flags.isUncompressable,
338
+ isEphemeral: flags.isEphemeral,
339
+ isDeleted: flags.isDeleted,
340
+ isNew: flags.isNew,
341
+ isCompressed: flags.isCompressed
342
+ });
343
+ }
344
+ };
345
+ var AccountMeta = class _AccountMeta {
346
+ constructor(params) {
347
+ this.version = params.version;
348
+ this.flags = params.flags ?? new AccountFlags();
349
+ this.dataSize = params.dataSize;
350
+ this.seq = params.seq;
351
+ this.owner = params.owner;
352
+ this.balance = params.balance;
353
+ this.nonce = params.nonce;
354
+ }
355
+ static fromProto(meta) {
356
+ if (!meta) {
357
+ return void 0;
358
+ }
359
+ return new _AccountMeta({
360
+ version: meta.version,
361
+ flags: AccountFlags.fromProto(meta.flags),
362
+ dataSize: meta.dataSize,
363
+ seq: meta.seq ?? 0n,
364
+ owner: meta.owner ? Pubkey.fromProtoPubkey(meta.owner) : void 0,
365
+ balance: meta.balance ?? 0n,
366
+ nonce: meta.nonce
367
+ });
368
+ }
369
+ };
370
+ var AccountData = class _AccountData {
371
+ constructor(params) {
372
+ this.data = params.data ? new Uint8Array(params.data) : void 0;
373
+ this.compressed = params.compressed ?? false;
374
+ this.compressionAlgorithm = params.compressionAlgorithm;
375
+ }
376
+ static fromProto(data) {
377
+ if (!data) {
378
+ return void 0;
379
+ }
380
+ return new _AccountData({
381
+ data: data.data ? new Uint8Array(data.data) : void 0,
382
+ compressed: data.compressed ?? false,
383
+ compressionAlgorithm: data.compressionAlgorithm
384
+ });
385
+ }
386
+ };
387
+ var Account = class _Account {
388
+ constructor(params) {
389
+ this.address = params.address;
390
+ this.meta = params.meta;
391
+ this.data = params.data;
392
+ this.versionContext = params.versionContext;
393
+ this.consensusStatus = params.consensusStatus;
394
+ }
395
+ static fromProto(proto) {
396
+ if (!proto.address) {
397
+ throw new Error("Account proto missing address");
398
+ }
399
+ return new _Account({
400
+ address: Pubkey.fromProtoPubkey(proto.address),
401
+ meta: AccountMeta.fromProto(proto.meta),
402
+ data: AccountData.fromProto(proto.data ?? void 0),
403
+ versionContext: convertVersionContext(proto.versionContext),
404
+ consensusStatus: proto.consensusStatus
405
+ });
406
+ }
407
+ };
408
+ function convertVersionContext(meta) {
409
+ if (!meta) {
410
+ return void 0;
411
+ }
412
+ return {
413
+ slot: meta.slot,
414
+ blockTimestampNs: timestampToNanoseconds(meta.blockTimestamp)
415
+ };
416
+ }
417
+
418
+ // thru-ts-client-sdk/domain/accounts/streaming.ts
419
+ function toStreamAccountUpdate(response) {
420
+ if (!response.message) {
421
+ return void 0;
422
+ }
423
+ if (response.message.case === "snapshot") {
424
+ return {
425
+ kind: "snapshot",
426
+ snapshot: { account: Account.fromProto(response.message.value) }
427
+ };
428
+ }
429
+ if (response.message.case === "update") {
430
+ return {
431
+ kind: "update",
432
+ update: fromProtoUpdate(response.message.value)
433
+ };
434
+ }
435
+ return void 0;
436
+ }
437
+ function fromProtoUpdate(update) {
438
+ return {
439
+ slot: update.slot,
440
+ meta: AccountMeta.fromProto(update.meta),
441
+ page: update.page ? fromProtoPage(update.page) : void 0,
442
+ deleted: update.delete ?? false
443
+ };
444
+ }
445
+ function fromProtoPage(page) {
446
+ return {
447
+ pageIndex: page.pageIdx,
448
+ pageSize: page.pageSize,
449
+ data: new Uint8Array(page.pageData),
450
+ compressed: page.compressed ?? void 0,
451
+ compressionAlgorithm: page.compressionAlgorithm
452
+ };
453
+ }
454
+ var PageRequest = class _PageRequest {
455
+ constructor(params = {}) {
456
+ if (params.pageSize !== void 0) {
457
+ if (!Number.isInteger(params.pageSize) || params.pageSize < 0) {
458
+ throw new Error("PageRequest.pageSize must be a non-negative integer");
459
+ }
460
+ }
461
+ this.pageSize = params.pageSize;
462
+ this.pageToken = params.pageToken;
463
+ this.orderBy = params.orderBy;
464
+ }
465
+ static fromProto(proto) {
466
+ if (!proto) {
467
+ return void 0;
468
+ }
469
+ return new _PageRequest({
470
+ pageSize: proto.pageSize,
471
+ pageToken: proto.pageToken,
472
+ orderBy: proto.orderBy
473
+ });
474
+ }
475
+ toProto() {
476
+ return create(PageRequestSchema, {
477
+ pageSize: this.pageSize,
478
+ pageToken: this.pageToken,
479
+ orderBy: this.orderBy
480
+ });
481
+ }
482
+ withParams(params) {
483
+ return new _PageRequest({
484
+ pageSize: params.pageSize ?? this.pageSize,
485
+ pageToken: params.pageToken ?? this.pageToken,
486
+ orderBy: params.orderBy ?? this.orderBy
487
+ });
488
+ }
489
+ };
490
+ var PageResponse = class _PageResponse {
491
+ constructor(params = {}) {
492
+ this.nextPageToken = params.nextPageToken;
493
+ this.totalSize = params.totalSize;
494
+ }
495
+ static fromProto(proto) {
496
+ if (!proto) {
497
+ return void 0;
498
+ }
499
+ return new _PageResponse({
500
+ nextPageToken: proto.nextPageToken,
501
+ totalSize: proto.totalSize
502
+ });
503
+ }
504
+ toProto() {
505
+ return create(PageResponseSchema, {
506
+ nextPageToken: this.nextPageToken,
507
+ totalSize: this.totalSize
508
+ });
509
+ }
510
+ hasNextPage() {
511
+ return !!this.nextPageToken;
512
+ }
513
+ };
514
+ hashes.sha512 = sha512;
515
+ var SignatureDomain = /* @__PURE__ */ ((SignatureDomain2) => {
516
+ SignatureDomain2[SignatureDomain2["TXN"] = 0] = "TXN";
517
+ SignatureDomain2[SignatureDomain2["BLOCK_HEADER"] = 1] = "BLOCK_HEADER";
518
+ SignatureDomain2[SignatureDomain2["BLOCK"] = 2] = "BLOCK";
519
+ SignatureDomain2[SignatureDomain2["GOSSIP"] = 3] = "GOSSIP";
520
+ return SignatureDomain2;
521
+ })(SignatureDomain || {});
522
+ var DOMAIN_TAGS = {
523
+ [0 /* TXN */]: 1n,
524
+ [1 /* BLOCK_HEADER */]: 2n,
525
+ [2 /* BLOCK */]: 3n,
526
+ [3 /* GOSSIP */]: 4n
527
+ };
528
+ var DOMAIN_BLOCK_SIZE = 128;
529
+ var SIGNATURE_SIZE = 64;
530
+ var PUBKEY_SIZE = 32;
531
+ function createDomainBlock(domain) {
532
+ const block = new Uint8Array(DOMAIN_BLOCK_SIZE);
533
+ block.fill(0);
534
+ const tag = DOMAIN_TAGS[domain];
535
+ if (tag === void 0) {
536
+ throw new Error(`Invalid signature domain: ${domain}`);
537
+ }
538
+ const view = new DataView(block.buffer, block.byteOffset, block.byteLength);
539
+ view.setBigUint64(0, tag, false);
540
+ return block;
541
+ }
542
+ function copyBytes2(bytes) {
543
+ const out = new Uint8Array(bytes.length);
544
+ out.set(bytes);
545
+ return out;
546
+ }
547
+ function concatBytes(...arrays) {
548
+ return etc.concatBytes(...arrays);
549
+ }
550
+ function sha512Bytes(bytes) {
551
+ return new Uint8Array(sha512(bytes));
552
+ }
553
+ function bytesToNumberLE(bytes) {
554
+ let value = 0n;
555
+ for (let i = 0; i < bytes.length; i++) {
556
+ value += BigInt(bytes[i]) << 8n * BigInt(i);
557
+ }
558
+ return value;
559
+ }
560
+ function modOrder(value) {
561
+ const modulus = Point.CURVE().n;
562
+ const result = value % modulus;
563
+ return result >= 0n ? result : result + modulus;
564
+ }
565
+ function numberToBytesLE(value, length) {
566
+ const out = new Uint8Array(length);
567
+ let current = value;
568
+ for (let i = 0; i < length; i++) {
569
+ out[i] = Number(current & 0xffn);
570
+ current >>= 8n;
571
+ }
572
+ return out;
573
+ }
574
+ async function signWithDomain(message, privateKey, publicKey, domain = 0 /* TXN */) {
575
+ if (privateKey.length !== PUBKEY_SIZE) {
576
+ throw new Error("Private key must contain 32 bytes");
577
+ }
578
+ const domainBlock = createDomainBlock(domain);
579
+ const messageBytes = copyBytes2(message);
580
+ const extended = utils.getExtendedPublicKey(privateKey);
581
+ const publicKeyBytes = publicKey ? copyBytes2(publicKey) : extended.pointBytes;
582
+ if (publicKeyBytes.length !== PUBKEY_SIZE) {
583
+ throw new Error("Public key must contain 32 bytes");
584
+ }
585
+ const rInput = concatBytes(domainBlock, extended.prefix, messageBytes);
586
+ const r = modOrder(bytesToNumberLE(sha512Bytes(rInput)));
587
+ const R = Point.BASE.multiply(r).toBytes();
588
+ const kInput = concatBytes(domainBlock, R, publicKeyBytes, messageBytes);
589
+ const k = modOrder(bytesToNumberLE(sha512Bytes(kInput)));
590
+ const s = modOrder(r + k * extended.scalar);
591
+ const signature = new Uint8Array(SIGNATURE_SIZE);
592
+ signature.set(R, 0);
593
+ signature.set(numberToBytesLE(s, PUBKEY_SIZE), PUBKEY_SIZE);
594
+ return signature;
595
+ }
596
+ async function verifyWithDomain(signature, message, publicKey, domain = 0 /* TXN */) {
597
+ if (signature.length !== SIGNATURE_SIZE || publicKey.length !== PUBKEY_SIZE) {
598
+ return false;
599
+ }
600
+ const domainBlock = createDomainBlock(domain);
601
+ const messageBytes = copyBytes2(message);
602
+ const rBytes = signature.subarray(0, PUBKEY_SIZE);
603
+ const s = bytesToNumberLE(signature.subarray(PUBKEY_SIZE));
604
+ if (s >= Point.CURVE().n) {
605
+ return false;
606
+ }
607
+ let R;
608
+ let A;
609
+ try {
610
+ R = Point.fromBytes(rBytes);
611
+ A = Point.fromBytes(publicKey);
612
+ } catch {
613
+ return false;
614
+ }
615
+ const kInput = concatBytes(domainBlock, rBytes, publicKey, messageBytes);
616
+ const k = modOrder(bytesToNumberLE(sha512Bytes(kInput)));
617
+ const lhs = Point.BASE.multiply(s);
618
+ const rhs = R.add(A.multiply(k));
619
+ return lhs.add(rhs.negate()).clearCofactor().is0();
620
+ }
621
+
622
+ // thru-ts-client-sdk/wire-format.ts
623
+ var SIGNATURE_SIZE2 = 64;
624
+ var PUBKEY_SIZE2 = 32;
625
+ var HASH_SIZE = 32;
626
+ var BLOCK_HEADER_SIZE = 168;
627
+ var BLOCK_HEADER_SIZE_LEGACY = 160;
628
+ var BLOCK_FOOTER_SIZE = 104;
629
+ var BLOCK_VERSION_V1 = 1;
630
+ var TXN_HEADER_BODY_SIZE = 112;
631
+ var TXN_VERSION_V1 = 1;
632
+ var TXN_MAX_ACCOUNTS = 1024;
633
+ var STATE_PROOF_HEADER_SIZE = 40;
634
+ var ACCOUNT_META_FOOTPRINT = 64;
635
+ var TXN_FLAG_HAS_FEE_PAYER_PROOF = 1 << 0;
636
+ var STATE_PROOF_TYPE_EXISTING = 0;
637
+ var STATE_PROOF_TYPE_UPDATING = 1;
638
+ var STATE_PROOF_TYPE_CREATION = 2;
639
+
640
+ // thru-ts-client-sdk/domain/transactions/Transaction.ts
641
+ var DEFAULT_FLAGS = 0;
642
+ var MAX_INSTRUCTION_DATA_LENGTH = 65535;
643
+ var BYTE_POPCOUNT = new Uint8Array(256).map((_value, index) => {
644
+ let v = index;
645
+ let count = 0;
646
+ while (v !== 0) {
647
+ count += v & 1;
648
+ v >>= 1;
649
+ }
650
+ return count;
651
+ });
652
+ var Transaction = class _Transaction {
653
+ constructor(params) {
654
+ this.version = params.version ?? TXN_VERSION_V1;
655
+ this.feePayer = Pubkey.from(params.feePayer);
656
+ this.program = Pubkey.from(params.program);
657
+ this.fee = params.header.fee;
658
+ this.nonce = params.header.nonce;
659
+ this.startSlot = params.header.startSlot;
660
+ this.expiryAfter = params.header.expiryAfter ?? 0;
661
+ this.chainId = params.header.chainId ?? 1;
662
+ this.requestedComputeUnits = params.header.computeUnits ?? 0;
663
+ this.requestedStateUnits = params.header.stateUnits ?? 0;
664
+ this.requestedMemoryUnits = params.header.memoryUnits ?? 0;
665
+ this.flags = params.header.flags ?? DEFAULT_FLAGS;
666
+ this.readWriteAccounts = params.accounts?.readWriteAccounts ? params.accounts.readWriteAccounts.map(Pubkey.from) : [];
667
+ this.readOnlyAccounts = params.accounts?.readOnlyAccounts ? params.accounts.readOnlyAccounts.map(Pubkey.from) : [];
668
+ this.instructionData = params.instructionData ? new Uint8Array(params.instructionData) : void 0;
669
+ if (this.instructionData && this.instructionData.length > MAX_INSTRUCTION_DATA_LENGTH) {
670
+ throw new Error(`Instruction data exceeds maximum length (${MAX_INSTRUCTION_DATA_LENGTH} bytes)`);
671
+ }
672
+ this.instructionDataSize = params.instructionDataSize;
673
+ this.feePayerStateProof = params.proofs?.feePayerStateProof ? new Uint8Array(params.proofs.feePayerStateProof) : void 0;
674
+ this.feePayerAccountMetaRaw = params.proofs?.feePayerAccountMetaRaw ? new Uint8Array(params.proofs.feePayerAccountMetaRaw) : void 0;
675
+ }
676
+ static fromWire(data) {
677
+ const { transaction, size } = _Transaction.parseWire(data, { strict: true });
678
+ if (size !== data.length) {
679
+ throw new Error(
680
+ `Transaction body has trailing bytes: expected ${size} bytes but found ${data.length}`
681
+ );
682
+ }
683
+ return transaction;
684
+ }
685
+ static parseWire(data, options = {}) {
686
+ const strict = options.strict ?? false;
687
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
688
+ if (data.length < TXN_HEADER_BODY_SIZE) {
689
+ throw new Error(`Transaction data too short: ${data.length} bytes (minimum ${TXN_HEADER_BODY_SIZE})`);
690
+ }
691
+ let offset = 0;
692
+ const version = view.getUint8(offset);
693
+ offset += 1;
694
+ if (strict && version !== TXN_VERSION_V1) {
695
+ throw new Error(`Unsupported transaction version: ${version}`);
696
+ }
697
+ const flags = view.getUint8(offset);
698
+ offset += 1;
699
+ const invalidFlags = flags & -4;
700
+ if (strict && invalidFlags !== 0) {
701
+ throw new Error(`Unsupported transaction flags: 0x${invalidFlags.toString(16).padStart(2, "0")}`);
702
+ }
703
+ const readwriteAccountsCount = view.getUint16(offset, true);
704
+ offset += 2;
705
+ const readonlyAccountsCount = view.getUint16(offset, true);
706
+ offset += 2;
707
+ const instructionDataSize = view.getUint16(offset, true);
708
+ offset += 2;
709
+ const requestedComputeUnits = view.getUint32(offset, true);
710
+ offset += 4;
711
+ const requestedStateUnits = view.getUint16(offset, true);
712
+ offset += 2;
713
+ const requestedMemoryUnits = view.getUint16(offset, true);
714
+ offset += 2;
715
+ const fee = view.getBigUint64(offset, true);
716
+ offset += 8;
717
+ const nonce = view.getBigUint64(offset, true);
718
+ offset += 8;
719
+ const startSlot = view.getBigUint64(offset, true);
720
+ offset += 8;
721
+ const expiryAfter = view.getUint32(offset, true);
722
+ offset += 4;
723
+ const chainId = view.getUint16(offset, true);
724
+ offset += 2;
725
+ offset += 2;
726
+ _Transaction.ensureAvailable(data.length, offset, PUBKEY_SIZE2, "fee payer account");
727
+ const feePayer = data.slice(offset, offset + PUBKEY_SIZE2);
728
+ offset += PUBKEY_SIZE2;
729
+ _Transaction.ensureAvailable(data.length, offset, PUBKEY_SIZE2, "program account");
730
+ const program = data.slice(offset, offset + PUBKEY_SIZE2);
731
+ offset += PUBKEY_SIZE2;
732
+ if (offset !== TXN_HEADER_BODY_SIZE) {
733
+ throw new Error(`Transaction header parsing mismatch (expected offset ${TXN_HEADER_BODY_SIZE}, got ${offset})`);
734
+ }
735
+ const totalAccountCount = Number(readwriteAccountsCount + readonlyAccountsCount);
736
+ if (strict && totalAccountCount > TXN_MAX_ACCOUNTS) {
737
+ throw new Error(
738
+ `Transaction references ${totalAccountCount} accounts (maximum allowed ${TXN_MAX_ACCOUNTS})`
739
+ );
740
+ }
741
+ const accountsSize = totalAccountCount * PUBKEY_SIZE2;
742
+ let expectedBodySize = accountsSize + instructionDataSize;
743
+ if ((flags & TXN_FLAG_HAS_FEE_PAYER_PROOF) !== 0) {
744
+ const proofOffset = TXN_HEADER_BODY_SIZE + accountsSize + instructionDataSize;
745
+ _Transaction.ensureAvailable(data.length, proofOffset, STATE_PROOF_HEADER_SIZE, "state proof header");
746
+ const proofView = new DataView(data.buffer, data.byteOffset + proofOffset, STATE_PROOF_HEADER_SIZE);
747
+ const typeSlot = proofView.getBigUint64(0, true);
748
+ const proofType = Number(typeSlot >> 62n & 0x3n);
749
+ const pathBitset = data.subarray(proofOffset + 8, proofOffset + 40);
750
+ const siblingCount = countSetBits(pathBitset);
751
+ const bodyCount = proofType + siblingCount;
752
+ const proofFootprint = STATE_PROOF_HEADER_SIZE + bodyCount * HASH_SIZE;
753
+ expectedBodySize += proofFootprint;
754
+ if (proofType === STATE_PROOF_TYPE_EXISTING) {
755
+ expectedBodySize += ACCOUNT_META_FOOTPRINT;
756
+ }
757
+ }
758
+ const txnSize = TXN_HEADER_BODY_SIZE + expectedBodySize + SIGNATURE_SIZE2;
759
+ _Transaction.ensureAvailable(data.length, 0, txnSize, "full transaction");
760
+ const sigStart = TXN_HEADER_BODY_SIZE + expectedBodySize;
761
+ const readWriteAccounts = [];
762
+ for (let i = 0; i < readwriteAccountsCount; i++) {
763
+ _Transaction.ensureAvailable(sigStart, offset, PUBKEY_SIZE2, "read-write accounts");
764
+ readWriteAccounts.push(data.slice(offset, offset + PUBKEY_SIZE2));
765
+ offset += PUBKEY_SIZE2;
766
+ }
767
+ const readOnlyAccounts = [];
768
+ for (let i = 0; i < readonlyAccountsCount; i++) {
769
+ _Transaction.ensureAvailable(sigStart, offset, PUBKEY_SIZE2, "read-only accounts");
770
+ readOnlyAccounts.push(data.slice(offset, offset + PUBKEY_SIZE2));
771
+ offset += PUBKEY_SIZE2;
772
+ }
773
+ let instructionData;
774
+ if (instructionDataSize > 0) {
775
+ _Transaction.ensureAvailable(sigStart, offset, instructionDataSize, "instruction data");
776
+ instructionData = data.slice(offset, offset + instructionDataSize);
777
+ offset += instructionDataSize;
778
+ }
779
+ let feePayerStateProof;
780
+ let feePayerAccountMetaRaw;
781
+ if ((flags & TXN_FLAG_HAS_FEE_PAYER_PROOF) !== 0) {
782
+ const { proofBytes, footprint, proofType } = _Transaction.parseStateProof(data.subarray(offset, sigStart));
783
+ feePayerStateProof = proofBytes;
784
+ offset += footprint;
785
+ if (proofType === STATE_PROOF_TYPE_EXISTING) {
786
+ _Transaction.ensureAvailable(sigStart, offset, ACCOUNT_META_FOOTPRINT, "fee payer account metadata");
787
+ feePayerAccountMetaRaw = data.slice(offset, offset + ACCOUNT_META_FOOTPRINT);
788
+ offset += ACCOUNT_META_FOOTPRINT;
789
+ }
790
+ }
791
+ if (offset !== sigStart) {
792
+ throw new Error(
793
+ `Transaction body has trailing bytes: expected ${sigStart} bytes consumed but found ${offset}`
794
+ );
795
+ }
796
+ const signatureBytes = data.slice(sigStart, sigStart + SIGNATURE_SIZE2);
797
+ const hasSignature = hasNonZeroBytes(signatureBytes);
798
+ const transaction = new _Transaction({
799
+ version,
800
+ feePayer: Pubkey.from(feePayer),
801
+ program: Pubkey.from(program),
802
+ header: {
803
+ fee,
804
+ nonce,
805
+ startSlot,
806
+ expiryAfter,
807
+ chainId,
808
+ computeUnits: requestedComputeUnits,
809
+ stateUnits: requestedStateUnits,
810
+ memoryUnits: requestedMemoryUnits,
811
+ flags
812
+ },
813
+ accounts: {
814
+ readWriteAccounts,
815
+ readOnlyAccounts
816
+ },
817
+ instructionData,
818
+ instructionDataSize,
819
+ proofs: feePayerStateProof || feePayerAccountMetaRaw ? {
820
+ feePayerStateProof,
821
+ feePayerAccountMetaRaw
822
+ } : void 0
823
+ });
824
+ if (hasSignature) {
825
+ transaction.setSignature(Signature.from(signatureBytes));
826
+ }
827
+ return { transaction, size: txnSize };
828
+ }
829
+ static fromProto(proto) {
830
+ if (!proto.header) {
831
+ throw new Error("Transaction proto missing header");
832
+ }
833
+ const header = proto.header;
834
+ const body = proto.body ? new Uint8Array(proto.body) : void 0;
835
+ let transaction;
836
+ if (body && body.length > 0) {
837
+ try {
838
+ const { transaction: parsed } = this.parseWire(body, { strict: false });
839
+ transaction = parsed;
840
+ } catch (err) {
841
+ transaction = void 0;
842
+ }
843
+ }
844
+ if (!transaction) {
845
+ let parsed;
846
+ if (body && body.length > 0) {
847
+ try {
848
+ parsed = this.parseBodySections(
849
+ body,
850
+ header.readwriteAccountsCount ?? 0,
851
+ header.readonlyAccountsCount ?? 0,
852
+ header.instructionDataSize ?? 0,
853
+ header.flags ?? DEFAULT_FLAGS
854
+ );
855
+ } catch (sectionErr) {
856
+ if (body.length >= TXN_HEADER_BODY_SIZE) {
857
+ parsed = this.parseBodySections(
858
+ body.slice(TXN_HEADER_BODY_SIZE),
859
+ header.readwriteAccountsCount ?? 0,
860
+ header.readonlyAccountsCount ?? 0,
861
+ header.instructionDataSize ?? 0,
862
+ header.flags ?? DEFAULT_FLAGS
863
+ );
864
+ } else {
865
+ throw sectionErr;
866
+ }
867
+ }
868
+ }
869
+ if (!parsed) {
870
+ parsed = {
871
+ readWriteAccounts: [],
872
+ readOnlyAccounts: [],
873
+ instructionData: void 0,
874
+ feePayerStateProof: void 0,
875
+ feePayerAccountMetaRaw: void 0
876
+ };
877
+ }
878
+ transaction = new _Transaction({
879
+ version: header.version ?? TXN_VERSION_V1,
880
+ feePayer: Pubkey.fromProtoPubkey(header.feePayerPubkey),
881
+ program: Pubkey.fromProtoPubkey(header.programPubkey),
882
+ header: {
883
+ fee: header.fee ?? 0n,
884
+ nonce: header.nonce ?? 0n,
885
+ startSlot: header.startSlot ?? 0n,
886
+ expiryAfter: header.expiryAfter ?? 0,
887
+ chainId: header.chainId ?? 1,
888
+ computeUnits: header.requestedComputeUnits ?? 0,
889
+ stateUnits: header.requestedStateUnits ?? 0,
890
+ memoryUnits: header.requestedMemoryUnits ?? 0,
891
+ flags: header.flags ?? DEFAULT_FLAGS
892
+ },
893
+ accounts: {
894
+ readWriteAccounts: parsed.readWriteAccounts,
895
+ readOnlyAccounts: parsed.readOnlyAccounts
896
+ },
897
+ instructionData: parsed.instructionData,
898
+ instructionDataSize: header.instructionDataSize,
899
+ proofs: parsed.feePayerStateProof || parsed.feePayerAccountMetaRaw ? {
900
+ feePayerStateProof: parsed.feePayerStateProof,
901
+ feePayerAccountMetaRaw: parsed.feePayerAccountMetaRaw
902
+ } : void 0
903
+ });
904
+ }
905
+ const signatureBytes = proto.signature?.value ?? header.feePayerSignature?.value ?? void 0;
906
+ if (signatureBytes && signatureBytes.length === SIGNATURE_SIZE2 && hasNonZeroBytes(signatureBytes)) {
907
+ transaction.setSignature(Signature.from(signatureBytes));
908
+ }
909
+ if (proto.executionResult) {
910
+ transaction.executionResult = _Transaction.executionResultFromProto(proto.executionResult);
911
+ }
912
+ if (proto.slot !== void 0) {
913
+ transaction.slot = proto.slot;
914
+ }
915
+ if (proto.blockOffset !== void 0) {
916
+ transaction.blockOffset = proto.blockOffset;
917
+ }
918
+ return transaction;
919
+ }
920
+ getSignature() {
921
+ return this.signature;
922
+ }
923
+ setSignature(signature) {
924
+ this.signature = signature;
925
+ }
926
+ async sign(privateKey) {
927
+ if (privateKey.length !== 32) {
928
+ throw new Error("Fee payer private key must contain 32 bytes");
929
+ }
930
+ const payload = this.toWireForSigning();
931
+ const publicKey = this.feePayer.toBytes();
932
+ const signature = await signWithDomain(
933
+ payload,
934
+ privateKey,
935
+ publicKey,
936
+ 0 /* TXN */
937
+ );
938
+ if (signature.length !== SIGNATURE_SIZE2) {
939
+ throw new Error("ed25519 signing produced an invalid signature");
940
+ }
941
+ this.signature = Signature.from(signature);
942
+ return this.signature;
943
+ }
944
+ toWireForSigning() {
945
+ const header = this.createHeader();
946
+ return this.buildWirePayload(new Uint8Array(header), false);
947
+ }
948
+ toWire() {
949
+ const header = this.createHeader();
950
+ return this.buildWirePayload(new Uint8Array(header), true);
951
+ }
952
+ createHeader() {
953
+ const buffer = new ArrayBuffer(TXN_HEADER_BODY_SIZE);
954
+ const headerBytes = new Uint8Array(buffer);
955
+ const view = new DataView(buffer);
956
+ let offset = 0;
957
+ view.setUint8(offset, this.version & 255);
958
+ offset += 1;
959
+ view.setUint8(offset, this.flags & 255);
960
+ offset += 1;
961
+ view.setUint16(offset, this.readWriteAccounts.length, true);
962
+ offset += 2;
963
+ view.setUint16(offset, this.readOnlyAccounts.length, true);
964
+ offset += 2;
965
+ const instructionDataLength = this.instructionData?.length ?? 0;
966
+ if (instructionDataLength > MAX_INSTRUCTION_DATA_LENGTH) {
967
+ throw new Error(`Instruction data exceeds maximum length (${MAX_INSTRUCTION_DATA_LENGTH} bytes)`);
968
+ }
969
+ view.setUint16(offset, instructionDataLength, true);
970
+ offset += 2;
971
+ view.setUint32(offset, ensureUint32(this.requestedComputeUnits), true);
972
+ offset += 4;
973
+ view.setUint16(offset, ensureUint16(this.requestedStateUnits), true);
974
+ offset += 2;
975
+ view.setUint16(offset, ensureUint16(this.requestedMemoryUnits), true);
976
+ offset += 2;
977
+ view.setBigUint64(offset, ensureBigUint64(this.fee), true);
978
+ offset += 8;
979
+ view.setBigUint64(offset, ensureBigUint64(this.nonce), true);
980
+ offset += 8;
981
+ view.setBigUint64(offset, ensureBigUint64(this.startSlot), true);
982
+ offset += 8;
983
+ view.setUint32(offset, ensureUint32(this.expiryAfter), true);
984
+ offset += 4;
985
+ view.setUint16(offset, ensureUint16(this.chainId), true);
986
+ offset += 2;
987
+ offset += 2;
988
+ headerBytes.set(this.feePayer.toBytes(), offset);
989
+ offset += PUBKEY_SIZE2;
990
+ headerBytes.set(this.program.toBytes(), offset);
991
+ return buffer;
992
+ }
993
+ buildWirePayload(headerBytes, includeSignature) {
994
+ const dynamicLength = this.readWriteAccounts.length * PUBKEY_SIZE2 + this.readOnlyAccounts.length * PUBKEY_SIZE2 + (this.instructionData?.length ?? 0) + (this.feePayerStateProof?.length ?? 0) + (this.feePayerAccountMetaRaw?.length ?? 0);
995
+ const signatureLength = includeSignature ? SIGNATURE_SIZE2 : 0;
996
+ const result = new Uint8Array(headerBytes.length + dynamicLength + signatureLength);
997
+ result.set(headerBytes, 0);
998
+ let offset = headerBytes.length;
999
+ offset = appendAccountList(result, offset, this.readWriteAccounts.map((account) => account.toBytes()));
1000
+ offset = appendAccountList(result, offset, this.readOnlyAccounts.map((account) => account.toBytes()));
1001
+ if (this.instructionData) {
1002
+ result.set(this.instructionData, offset);
1003
+ offset += this.instructionData.length;
1004
+ }
1005
+ if (this.feePayerStateProof) {
1006
+ result.set(this.feePayerStateProof, offset);
1007
+ offset += this.feePayerStateProof.length;
1008
+ }
1009
+ if (this.feePayerAccountMetaRaw) {
1010
+ result.set(this.feePayerAccountMetaRaw, offset);
1011
+ offset += this.feePayerAccountMetaRaw.length;
1012
+ }
1013
+ if (includeSignature) {
1014
+ if (this.signature) {
1015
+ result.set(this.signature.toBytes(), offset);
1016
+ }
1017
+ }
1018
+ return result;
1019
+ }
1020
+ static parseBodySections(body, readwriteCount, readonlyCount, instructionDataSize, flags) {
1021
+ let offset = 0;
1022
+ const readWriteAccounts = [];
1023
+ for (let i = 0; i < readwriteCount; i++) {
1024
+ this.ensureAvailable(body.length, offset, PUBKEY_SIZE2, "read-write accounts");
1025
+ readWriteAccounts.push(body.slice(offset, offset + PUBKEY_SIZE2));
1026
+ offset += PUBKEY_SIZE2;
1027
+ }
1028
+ const readOnlyAccounts = [];
1029
+ for (let i = 0; i < readonlyCount; i++) {
1030
+ this.ensureAvailable(body.length, offset, PUBKEY_SIZE2, "read-only accounts");
1031
+ readOnlyAccounts.push(body.slice(offset, offset + PUBKEY_SIZE2));
1032
+ offset += PUBKEY_SIZE2;
1033
+ }
1034
+ let instructionData;
1035
+ if (instructionDataSize > 0) {
1036
+ this.ensureAvailable(body.length, offset, instructionDataSize, "instruction data");
1037
+ instructionData = body.slice(offset, offset + instructionDataSize);
1038
+ offset += instructionDataSize;
1039
+ }
1040
+ let feePayerStateProof;
1041
+ let feePayerAccountMetaRaw;
1042
+ if ((flags & TXN_FLAG_HAS_FEE_PAYER_PROOF) !== 0) {
1043
+ const { proofBytes, footprint, proofType } = this.parseStateProof(body.subarray(offset));
1044
+ feePayerStateProof = proofBytes;
1045
+ offset += footprint;
1046
+ if (proofType === STATE_PROOF_TYPE_EXISTING) {
1047
+ this.ensureAvailable(body.length, offset, ACCOUNT_META_FOOTPRINT, "fee payer account metadata");
1048
+ feePayerAccountMetaRaw = body.slice(offset, offset + ACCOUNT_META_FOOTPRINT);
1049
+ offset += ACCOUNT_META_FOOTPRINT;
1050
+ }
1051
+ }
1052
+ if (offset !== body.length) {
1053
+ throw new Error(
1054
+ `Transaction body has trailing bytes: expected ${offset} bytes but found ${body.length}`
1055
+ );
1056
+ }
1057
+ return {
1058
+ readWriteAccounts,
1059
+ readOnlyAccounts,
1060
+ instructionData,
1061
+ feePayerStateProof,
1062
+ feePayerAccountMetaRaw
1063
+ };
1064
+ }
1065
+ static ensureAvailable(totalLength, offset, required, context) {
1066
+ if (offset + required > totalLength) {
1067
+ throw new Error(`Transaction data truncated while parsing ${context}`);
1068
+ }
1069
+ }
1070
+ static parseStateProof(data) {
1071
+ if (data.length < STATE_PROOF_HEADER_SIZE) {
1072
+ throw new Error("Transaction data truncated while parsing state proof header");
1073
+ }
1074
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
1075
+ const typeSlot = view.getBigUint64(0, true);
1076
+ const proofType = Number(typeSlot >> 62n & 0x3n);
1077
+ if (proofType !== STATE_PROOF_TYPE_EXISTING && proofType !== STATE_PROOF_TYPE_UPDATING && proofType !== STATE_PROOF_TYPE_CREATION) {
1078
+ throw new Error(`Transaction state proof has unknown type: ${proofType}`);
1079
+ }
1080
+ const pathBitset = data.subarray(8, 40);
1081
+ const siblingCount = countSetBits(pathBitset);
1082
+ const bodyCount = proofType + siblingCount;
1083
+ const totalSize = STATE_PROOF_HEADER_SIZE + bodyCount * HASH_SIZE;
1084
+ if (proofType === STATE_PROOF_TYPE_CREATION && bodyCount < 2) {
1085
+ throw new Error("Transaction state proof creation entry is truncated");
1086
+ }
1087
+ if (proofType === STATE_PROOF_TYPE_UPDATING && bodyCount < 1) {
1088
+ throw new Error("Transaction state proof updating entry is truncated");
1089
+ }
1090
+ if (data.length < totalSize) {
1091
+ throw new Error("Transaction data truncated while parsing state proof body");
1092
+ }
1093
+ return {
1094
+ proofBytes: data.slice(0, totalSize),
1095
+ footprint: totalSize,
1096
+ proofType
1097
+ };
1098
+ }
1099
+ static executionResultFromProto(proto) {
1100
+ return {
1101
+ consumedComputeUnits: proto.consumedComputeUnits ?? 0,
1102
+ consumedMemoryUnits: proto.consumedMemoryUnits ?? 0,
1103
+ consumedStateUnits: proto.consumedStateUnits ?? 0,
1104
+ userErrorCode: proto.userErrorCode ?? 0n,
1105
+ vmError: proto.vmError ?? 0 /* TRANSACTION_VM_EXECUTE_SUCCESS */,
1106
+ executionResult: proto.executionResult ?? 0n,
1107
+ pagesUsed: proto.pagesUsed ?? 0,
1108
+ eventsCount: proto.eventsCount ?? 0,
1109
+ eventsSize: proto.eventsSize ?? 0,
1110
+ readwriteAccounts: proto.readwriteAccounts.map((account) => Pubkey.fromProtoPubkey(account)),
1111
+ readonlyAccounts: proto.readonlyAccounts.map((account) => Pubkey.fromProtoPubkey(account)),
1112
+ events: proto.events.length ? proto.events.map((event) => ({
1113
+ eventId: event.eventId,
1114
+ callIdx: event.callIdx,
1115
+ programIdx: event.programIdx,
1116
+ program: event.program ? Pubkey.fromProtoPubkey(event.program) : void 0,
1117
+ payload: new Uint8Array(event.payload ?? new Uint8Array(0))
1118
+ })) : void 0,
1119
+ errorProgramAccIdx: proto.errorProgramAccIdx ?? 0
1120
+ };
1121
+ }
1122
+ };
1123
+ function appendAccountList(target, start, accounts) {
1124
+ let offset = start;
1125
+ for (const account of accounts) {
1126
+ target.set(account, offset);
1127
+ offset += PUBKEY_SIZE2;
1128
+ }
1129
+ return offset;
1130
+ }
1131
+ function ensureUint16(value) {
1132
+ if (!Number.isInteger(value) || value < 0 || value > 65535) {
1133
+ throw new Error("Value must fit within uint16 range");
1134
+ }
1135
+ return value;
1136
+ }
1137
+ function ensureUint32(value) {
1138
+ if (!Number.isInteger(value) || value < 0 || value > 4294967295) {
1139
+ throw new Error("Value must fit within uint32 range");
1140
+ }
1141
+ return value;
1142
+ }
1143
+ function ensureBigUint64(value) {
1144
+ if (value < 0n || value > 0xffffffffffffffffn) {
1145
+ throw new Error("Value must fit within uint64 range");
1146
+ }
1147
+ return value;
1148
+ }
1149
+ function countSetBits(bytes) {
1150
+ let total = 0;
1151
+ for (let i = 0; i < bytes.length; i++) {
1152
+ total += BYTE_POPCOUNT[bytes[i]];
1153
+ }
1154
+ return total;
1155
+ }
1156
+ function hasNonZeroBytes(value) {
1157
+ for (let i = 0; i < value.length; i++) {
1158
+ if (value[i] !== 0) {
1159
+ return true;
1160
+ }
1161
+ }
1162
+ return false;
1163
+ }
1164
+
1165
+ // thru-ts-client-sdk/domain/transactions/utils.ts
1166
+ var ACCOUNT_LIMIT = 1024;
1167
+ function normalizeAccountList(accounts) {
1168
+ if (accounts.length === 0) {
1169
+ return [];
1170
+ }
1171
+ if (accounts.length > ACCOUNT_LIMIT) {
1172
+ throw new Error(`Too many accounts provided: ${accounts.length} (max ${ACCOUNT_LIMIT})`);
1173
+ }
1174
+ const deduped = dedupeAccountList(accounts);
1175
+ return deduped;
1176
+ }
1177
+ function dedupeAccountList(accounts) {
1178
+ const pubkeys = accounts.map(Pubkey.from).map((pubkey) => pubkey.toBytes());
1179
+ const seen = /* @__PURE__ */ new Map();
1180
+ for (const pubkey of pubkeys) {
1181
+ if (pubkey.length !== 32) {
1182
+ throw new Error("Account addresses must contain 32 bytes");
1183
+ }
1184
+ const key = toHex(pubkey);
1185
+ if (!seen.has(key)) {
1186
+ seen.set(key, pubkey);
1187
+ }
1188
+ }
1189
+ return Array.from(seen.values()).sort(compareAccounts);
1190
+ }
1191
+ function compareAccounts(a, b) {
1192
+ for (let i = 0; i < 32; i++) {
1193
+ if (a[i] !== b[i]) {
1194
+ return a[i] - b[i];
1195
+ }
1196
+ }
1197
+ return 0;
1198
+ }
1199
+ function toHex(bytes) {
1200
+ let result = "";
1201
+ for (let i = 0; i < bytes.length; i++) {
1202
+ const hex = bytes[i].toString(16).padStart(2, "0");
1203
+ result += hex;
1204
+ }
1205
+ return result;
1206
+ }
1207
+ function parseInstructionData(value) {
1208
+ if (value === void 0) {
1209
+ return void 0;
1210
+ }
1211
+ if (value instanceof Uint8Array) {
1212
+ return new Uint8Array(value);
1213
+ }
1214
+ if (typeof value === "string") {
1215
+ if (value.length === 0) {
1216
+ return new Uint8Array();
1217
+ }
1218
+ if (isHexString(value)) {
1219
+ return hexToBytes(value);
1220
+ }
1221
+ }
1222
+ throw new Error("Instruction data must be provided as hex string or Uint8Array");
1223
+ }
1224
+ function createInstructionContext(feePayer, program, sortedReadWrite, sortedReadOnly) {
1225
+ const accounts = [
1226
+ feePayer,
1227
+ program,
1228
+ ...sortedReadWrite.map((bytes) => Pubkey.from(bytes)),
1229
+ ...sortedReadOnly.map((bytes) => Pubkey.from(bytes))
1230
+ ];
1231
+ const indexMap = /* @__PURE__ */ new Map();
1232
+ for (let i = 0; i < accounts.length; i++) {
1233
+ const key = toHex(accounts[i].toBytes());
1234
+ if (!indexMap.has(key)) {
1235
+ indexMap.set(key, i);
1236
+ }
1237
+ }
1238
+ return {
1239
+ accounts,
1240
+ getAccountIndex: (pubkey) => {
1241
+ const bytes = Pubkey.from(pubkey).toBytes();
1242
+ const key = toHex(bytes);
1243
+ const index = indexMap.get(key);
1244
+ if (index === void 0) {
1245
+ throw new Error(`Account ${key} not found in transaction accounts`);
1246
+ }
1247
+ return index;
1248
+ }
1249
+ };
1250
+ }
1251
+
1252
+ // thru-ts-client-sdk/domain/transactions/TransactionBuilder.ts
1253
+ var FLAG_HAS_FEE_PAYER_PROOF = 1 << 0;
1254
+ var TransactionBuilder = class {
1255
+ build(params) {
1256
+ const feePayer = Pubkey.from(params.feePayer.publicKey);
1257
+ const program = Pubkey.from(params.program);
1258
+ const sortedReadWrite = normalizeAccountList(params.accounts?.readWriteAccounts ?? []);
1259
+ const sortedReadOnly = normalizeAccountList(params.accounts?.readOnlyAccounts ?? []);
1260
+ let instructionData;
1261
+ if (params.buildInstructionData) {
1262
+ const context = createInstructionContext(feePayer, program, sortedReadWrite, sortedReadOnly);
1263
+ const result = params.buildInstructionData(context);
1264
+ instructionData = parseInstructionData(result);
1265
+ } else {
1266
+ instructionData = parseInstructionData(params.instructionData);
1267
+ }
1268
+ const baseFlags = params.header.flags ?? 0;
1269
+ const flags = params.proofs?.feePayerStateProof ? baseFlags | FLAG_HAS_FEE_PAYER_PROOF : baseFlags;
1270
+ const accounts = sortedReadWrite.length > 0 || sortedReadOnly.length > 0 ? { readWriteAccounts: sortedReadWrite, readOnlyAccounts: sortedReadOnly } : void 0;
1271
+ return new Transaction({
1272
+ feePayer,
1273
+ program,
1274
+ header: {
1275
+ ...params.header,
1276
+ flags
1277
+ },
1278
+ accounts,
1279
+ instructionData,
1280
+ proofs: params.proofs
1281
+ });
1282
+ }
1283
+ async buildAndSign(params) {
1284
+ if (!params.feePayer.privateKey) {
1285
+ throw new Error("Fee payer private key is required to sign the transaction");
1286
+ }
1287
+ const transaction = this.build(params);
1288
+ const signature = await transaction.sign(params.feePayer.privateKey);
1289
+ const rawTransaction = transaction.toWire();
1290
+ return { transaction, signature, rawTransaction };
1291
+ }
1292
+ };
1293
+
1294
+ // thru-ts-client-sdk/modules/proofs.ts
1295
+ var proofs_exports = {};
1296
+ __export(proofs_exports, {
1297
+ generateStateProof: () => generateStateProof,
1298
+ getStateRoots: () => getStateRoots
1299
+ });
1300
+
1301
+ // thru-ts-client-sdk/domain/proofs/StateProof.ts
1302
+ var StateProof = class _StateProof {
1303
+ constructor(params) {
1304
+ this.proof = copyBytes3(params.proof);
1305
+ this.slot = params.slot;
1306
+ }
1307
+ static fromProto(proto) {
1308
+ return new _StateProof({
1309
+ proof: proto.proof,
1310
+ slot: proto.slot ?? 0n
1311
+ });
1312
+ }
1313
+ };
1314
+ function copyBytes3(bytes) {
1315
+ const copy = new Uint8Array(bytes.length);
1316
+ copy.set(bytes);
1317
+ return copy;
1318
+ }
1319
+
1320
+ // thru-ts-client-sdk/modules/proofs.ts
1321
+ async function generateStateProof(ctx, options) {
1322
+ const targetSlot = options.targetSlot ?? 0n;
1323
+ const request = create(StateProofRequestSchema, {
1324
+ address: options.address ? Pubkey.from(options.address).toProtoPubkey() : void 0,
1325
+ proofType: options.proofType,
1326
+ targetSlot
1327
+ });
1328
+ const schemaRequest = create(GenerateStateProofRequestSchema, { request });
1329
+ const response = await ctx.query.generateStateProof(
1330
+ schemaRequest,
1331
+ withCallOptions(ctx)
1332
+ );
1333
+ if (!response.proof) {
1334
+ throw new Error("State proof response missing proof");
1335
+ }
1336
+ return StateProof.fromProto(response.proof);
1337
+ }
1338
+ async function getStateRoots(ctx, options = {}) {
1339
+ const request = create(GetStateRootsRequestSchema, {
1340
+ slot: options.slot
1341
+ });
1342
+ return ctx.query.getStateRoots(request, withCallOptions(ctx));
1343
+ }
1344
+
1345
+ // thru-ts-client-sdk/modules/accounts.ts
1346
+ function getAccount(ctx, address, options = {}) {
1347
+ const request = create(GetAccountRequestSchema, {
1348
+ address: Pubkey.from(address).toProtoPubkey(),
1349
+ view: options.view ?? DEFAULT_ACCOUNT_VIEW,
1350
+ versionContext: options.versionContext ?? DEFAULT_VERSION_CONTEXT,
1351
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS,
1352
+ dataSlice: options.dataSlice
1353
+ });
1354
+ return ctx.query.getAccount(request, withCallOptions(ctx)).then(Account.fromProto);
1355
+ }
1356
+ function getRawAccount(ctx, address, options = {}) {
1357
+ const request = create(GetRawAccountRequestSchema, {
1358
+ address: Pubkey.from(address).toProtoPubkey(),
1359
+ view: options.view ?? DEFAULT_ACCOUNT_VIEW,
1360
+ versionContext: options.versionContext ?? DEFAULT_VERSION_CONTEXT,
1361
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
1362
+ });
1363
+ return ctx.query.getRawAccount(request, withCallOptions(ctx));
1364
+ }
1365
+ function listAccounts(ctx, options) {
1366
+ const request = create(ListAccountsRequestSchema, {
1367
+ view: options.view ?? DEFAULT_ACCOUNT_VIEW,
1368
+ versionContext: options.versionContext ?? DEFAULT_VERSION_CONTEXT,
1369
+ filter: options.filter?.toProto(),
1370
+ page: options.page?.toProto(),
1371
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
1372
+ });
1373
+ return ctx.query.listAccounts(request, withCallOptions(ctx)).then((response) => ({
1374
+ accounts: response.accounts.map((proto) => Account.fromProto(proto)),
1375
+ page: PageResponse.fromProto(response.page)
1376
+ }));
1377
+ }
1378
+ async function createAccount(ctx, options) {
1379
+ const feePayer = Pubkey.from(options.publicKey).toBytes();
1380
+ const proofResponse = await generateStateProof(ctx, {
1381
+ address: options.publicKey,
1382
+ proofType: 1 /* CREATING */
1383
+ // targetSlot omitted - server will auto-select
1384
+ });
1385
+ const proofBytes = proofResponse.proof;
1386
+ if (!proofBytes || proofBytes.length === 0) {
1387
+ throw new Error("State proof generation returned empty proof");
1388
+ }
1389
+ const startSlot = proofResponse.slot;
1390
+ const program = new Uint8Array(32);
1391
+ program[31] = 3;
1392
+ const builder = new TransactionBuilder();
1393
+ const headerDefaults = {
1394
+ fee: 0n,
1395
+ nonce: 0n,
1396
+ startSlot,
1397
+ expiryAfter: 100,
1398
+ computeUnits: 1e4,
1399
+ memoryUnits: 1e4,
1400
+ stateUnits: 1e4
1401
+ };
1402
+ const header = mergeTransactionHeader(headerDefaults, options.header);
1403
+ const transaction = builder.build({
1404
+ feePayer: { publicKey: feePayer },
1405
+ program,
1406
+ header,
1407
+ proofs: { feePayerStateProof: proofBytes }
1408
+ });
1409
+ return transaction;
1410
+ }
1411
+
1412
+ // thru-ts-client-sdk/modules/blocks.ts
1413
+ var blocks_exports = {};
1414
+ __export(blocks_exports, {
1415
+ getBlock: () => getBlock,
1416
+ getRawBlock: () => getRawBlock,
1417
+ listBlocks: () => listBlocks
1418
+ });
1419
+
1420
+ // thru-ts-client-sdk/domain/transactions/streaming.ts
1421
+ function toStreamTransactionUpdate(proto) {
1422
+ const signatureBytes = proto.signature?.value ? new Uint8Array(proto.signature.value) : new Uint8Array();
1423
+ const executionResult = proto.executionResult ? Transaction.executionResultFromProto(proto.executionResult) : void 0;
1424
+ if (!proto.header) {
1425
+ return {
1426
+ kind: "partial",
1427
+ signature: signatureBytes,
1428
+ slot: proto.slot,
1429
+ executionResult
1430
+ };
1431
+ }
1432
+ return {
1433
+ kind: "full",
1434
+ transaction: Transaction.fromProto(proto)
1435
+ };
1436
+ }
1437
+ function toTrackTransactionUpdate(response) {
1438
+ const signatureBytes = response.signature?.value ? new Uint8Array(response.signature.value) : void 0;
1439
+ const executionResult = response.executionResult ? Transaction.executionResultFromProto(response.executionResult) : void 0;
1440
+ return {
1441
+ signature: signatureBytes,
1442
+ status: consensusStatusToString(response.consensusStatus),
1443
+ statusCode: response.consensusStatus,
1444
+ slot: response.slot !== 0n ? response.slot : void 0,
1445
+ executionResult,
1446
+ transaction: void 0
1447
+ };
1448
+ }
1449
+
1450
+ // thru-ts-client-sdk/domain/transactions/TransactionStatusSnapshot.ts
1451
+ var TransactionStatusSnapshot = class _TransactionStatusSnapshot {
1452
+ constructor(params) {
1453
+ this.signature = copyBytes4(params.signature);
1454
+ this.statusCode = params.consensusStatus;
1455
+ this.status = params.consensusStatus != null ? consensusStatusToString(params.consensusStatus) : void 0;
1456
+ this.executionResult = params.executionResult;
1457
+ }
1458
+ static fromProto(proto) {
1459
+ if (!proto.signature?.value) {
1460
+ throw new Error("TransactionStatus proto missing signature");
1461
+ }
1462
+ return new _TransactionStatusSnapshot({
1463
+ signature: proto.signature.value,
1464
+ consensusStatus: proto.consensusStatus,
1465
+ executionResult: proto.executionResult ? Transaction.executionResultFromProto(proto.executionResult) : void 0
1466
+ });
1467
+ }
1468
+ };
1469
+ function copyBytes4(bytes) {
1470
+ const copy = new Uint8Array(bytes.length);
1471
+ copy.set(bytes);
1472
+ return copy;
1473
+ }
1474
+
1475
+ // thru-ts-client-sdk/domain/blocks/BlockFooter.ts
1476
+ var BlockFooter = class _BlockFooter {
1477
+ constructor(params) {
1478
+ this.signature = copyBytes5(params.signature);
1479
+ this.status = params.status;
1480
+ this.consumedComputeUnits = params.consumedComputeUnits;
1481
+ this.consumedStateUnits = params.consumedStateUnits;
1482
+ this.attestorPayment = params.attestorPayment;
1483
+ }
1484
+ static fromProto(proto) {
1485
+ return new _BlockFooter({
1486
+ signature: proto.signature?.value,
1487
+ status: proto.status ?? 0 /* UNSPECIFIED */,
1488
+ consumedComputeUnits: proto.consumedComputeUnits ?? 0n,
1489
+ consumedStateUnits: proto.consumedStateUnits ?? 0,
1490
+ attestorPayment: proto.attestorPayment ?? 0n
1491
+ });
1492
+ }
1493
+ };
1494
+ function copyBytes5(bytes) {
1495
+ if (!bytes) return void 0;
1496
+ const out = new Uint8Array(bytes.length);
1497
+ out.set(bytes);
1498
+ return out;
1499
+ }
1500
+
1501
+ // thru-ts-client-sdk/domain/blocks/BlockHeader.ts
1502
+ var BlockHeader = class _BlockHeader {
1503
+ constructor(params) {
1504
+ this.slot = params.slot;
1505
+ this.version = params.version;
1506
+ this.headerSignature = copyBytes6(params.headerSignature);
1507
+ this.producer = copyBytes6(params.producer);
1508
+ this.expiryTimestamp = params.expiryTimestamp;
1509
+ this.startSlot = params.startSlot;
1510
+ this.expiryAfter = params.expiryAfter;
1511
+ this.maxBlockSize = params.maxBlockSize;
1512
+ this.maxComputeUnits = params.maxComputeUnits;
1513
+ this.maxStateUnits = params.maxStateUnits;
1514
+ this.bondAmountLockUp = params.bondAmountLockUp;
1515
+ this.weightSlot = params.weightSlot;
1516
+ this.blockHash = copyBytes6(params.blockHash);
1517
+ this.chainId = params.chainId;
1518
+ }
1519
+ static fromProto(proto) {
1520
+ return new _BlockHeader({
1521
+ slot: proto.slot ?? 0n,
1522
+ version: proto.version ?? 0,
1523
+ headerSignature: proto.headerSignature?.value,
1524
+ producer: proto.producer?.value,
1525
+ expiryTimestamp: proto.expiryTimestamp,
1526
+ startSlot: proto.startSlot ?? 0n,
1527
+ expiryAfter: proto.expiryAfter,
1528
+ maxBlockSize: proto.maxBlockSize,
1529
+ maxComputeUnits: proto.maxComputeUnits,
1530
+ maxStateUnits: proto.maxStateUnits,
1531
+ bondAmountLockUp: proto.bondAmountLockUp,
1532
+ weightSlot: proto.weightSlot,
1533
+ blockHash: proto.blockHash?.value,
1534
+ chainId: proto.chainId
1535
+ });
1536
+ }
1537
+ withBlockHash(blockHash) {
1538
+ return new _BlockHeader({
1539
+ slot: this.slot,
1540
+ version: this.version,
1541
+ headerSignature: this.headerSignature,
1542
+ producer: this.producer,
1543
+ expiryTimestamp: this.expiryTimestamp,
1544
+ startSlot: this.startSlot,
1545
+ expiryAfter: this.expiryAfter,
1546
+ maxBlockSize: this.maxBlockSize,
1547
+ maxComputeUnits: this.maxComputeUnits,
1548
+ maxStateUnits: this.maxStateUnits,
1549
+ bondAmountLockUp: this.bondAmountLockUp,
1550
+ weightSlot: this.weightSlot,
1551
+ blockHash,
1552
+ chainId: this.chainId
1553
+ });
1554
+ }
1555
+ };
1556
+ function copyBytes6(bytes) {
1557
+ if (!bytes) return void 0;
1558
+ const out = new Uint8Array(bytes.length);
1559
+ out.set(bytes);
1560
+ return out;
1561
+ }
1562
+
1563
+ // thru-ts-client-sdk/domain/blocks/Block.ts
1564
+ var BLOCK_HASH_SIZE = 32;
1565
+ var RESERVED_FOOTER_PADDING = 0n;
1566
+ var SIGNATURE_PREFIX_SIZE = SIGNATURE_SIZE2;
1567
+ var Block = class _Block {
1568
+ constructor(params) {
1569
+ this.header = params.header;
1570
+ this.footer = params.footer;
1571
+ this.body = params.body ? new Uint8Array(params.body) : void 0;
1572
+ this.consensusStatus = params.consensusStatus;
1573
+ }
1574
+ static fromProto(proto) {
1575
+ if (!proto.header) {
1576
+ throw new Error("Block proto missing header");
1577
+ }
1578
+ const rawBody = proto.body ? new Uint8Array(proto.body) : void 0;
1579
+ const transactionBody = _Block.extractTransactionBody(rawBody, !!proto.footer);
1580
+ const block = new _Block({
1581
+ header: BlockHeader.fromProto(proto.header),
1582
+ footer: proto.footer ? BlockFooter.fromProto(proto.footer) : void 0,
1583
+ body: transactionBody,
1584
+ consensusStatus: proto.consensusStatus
1585
+ });
1586
+ block.attestorPayment = block.footer?.attestorPayment ?? 0n;
1587
+ return block;
1588
+ }
1589
+ static fromWire(data) {
1590
+ const result = _Block.tryParseWireWithHeaderSize(data, BLOCK_HEADER_SIZE);
1591
+ if (result) {
1592
+ return result;
1593
+ }
1594
+ const legacyResult = _Block.tryParseWireWithHeaderSize(data, BLOCK_HEADER_SIZE_LEGACY);
1595
+ if (legacyResult) {
1596
+ return legacyResult;
1597
+ }
1598
+ throw new Error(`Block data too short: ${data.length} bytes (expected at least ${BLOCK_HEADER_SIZE})`);
1599
+ }
1600
+ static tryParseWireWithHeaderSize(data, headerSize) {
1601
+ if (data.length < headerSize) {
1602
+ return null;
1603
+ }
1604
+ const headerBytes = data.slice(0, headerSize);
1605
+ let header;
1606
+ let blockTimeNs;
1607
+ try {
1608
+ const parsed = this.parseHeaderWithSize(headerBytes, headerSize);
1609
+ header = parsed.header;
1610
+ blockTimeNs = parsed.blockTimeNs;
1611
+ } catch {
1612
+ return null;
1613
+ }
1614
+ if (header.version !== BLOCK_VERSION_V1) {
1615
+ return null;
1616
+ }
1617
+ let finalHeader = header;
1618
+ let footer;
1619
+ let footerInfo;
1620
+ let body;
1621
+ if (data.length >= headerSize + BLOCK_FOOTER_SIZE) {
1622
+ const footerOffset = data.length - BLOCK_FOOTER_SIZE;
1623
+ const footerBytes = data.slice(footerOffset);
1624
+ try {
1625
+ const parsedFooter = this.parseFooter(footerBytes);
1626
+ footer = parsedFooter.footer;
1627
+ footerInfo = { blockHash: parsedFooter.blockHash, attestorPayment: parsedFooter.attestorPayment };
1628
+ finalHeader = header.withBlockHash(parsedFooter.blockHash);
1629
+ } catch {
1630
+ return null;
1631
+ }
1632
+ body = footerOffset > headerSize ? data.slice(headerSize, footerOffset) : void 0;
1633
+ } else {
1634
+ body = data.length > headerSize ? data.slice(headerSize) : void 0;
1635
+ }
1636
+ if (body && body.length > 0 && !_Block.looksLikeValidTransactionBody(body)) {
1637
+ return null;
1638
+ }
1639
+ const block = new _Block({ header: finalHeader, footer, body });
1640
+ block.blockTimeNs = blockTimeNs;
1641
+ block.attestorPayment = footerInfo?.attestorPayment ?? 0n;
1642
+ return block;
1643
+ }
1644
+ toWire() {
1645
+ const headerBytes = this.serializeHeader();
1646
+ const bodyBytes = this.body ?? new Uint8Array(0);
1647
+ const footerBytes = this.footer ? this.serializeFooter() : void 0;
1648
+ const totalLength = headerBytes.length + bodyBytes.length + (footerBytes?.length ?? 0);
1649
+ const result = new Uint8Array(totalLength);
1650
+ result.set(headerBytes, 0);
1651
+ result.set(bodyBytes, headerBytes.length);
1652
+ if (footerBytes) {
1653
+ result.set(footerBytes, headerBytes.length + bodyBytes.length);
1654
+ }
1655
+ return result;
1656
+ }
1657
+ getTransactions() {
1658
+ if (!this.body || this.body.length === 0) {
1659
+ return [];
1660
+ }
1661
+ return _Block.parseTransactionsFromBody(this.body);
1662
+ }
1663
+ static extractTransactionBody(raw, hasFooter) {
1664
+ if (!raw || raw.length === 0) {
1665
+ return void 0;
1666
+ }
1667
+ const bodyWithCurrentHeader = _Block.extractWithHeaderSize(raw, hasFooter, BLOCK_HEADER_SIZE);
1668
+ if (bodyWithCurrentHeader && bodyWithCurrentHeader.length > 0 && _Block.looksLikeValidTransactionBody(bodyWithCurrentHeader)) {
1669
+ return bodyWithCurrentHeader;
1670
+ }
1671
+ const bodyWithLegacyHeader = _Block.extractWithHeaderSize(raw, hasFooter, BLOCK_HEADER_SIZE_LEGACY);
1672
+ if (bodyWithLegacyHeader && bodyWithLegacyHeader.length > 0 && _Block.looksLikeValidTransactionBody(bodyWithLegacyHeader)) {
1673
+ return bodyWithLegacyHeader;
1674
+ }
1675
+ return void 0;
1676
+ }
1677
+ static extractWithHeaderSize(raw, hasFooter, headerSize) {
1678
+ if (raw.length <= headerSize) {
1679
+ return void 0;
1680
+ }
1681
+ const footerSize = hasFooter && raw.length >= headerSize + BLOCK_FOOTER_SIZE ? BLOCK_FOOTER_SIZE : 0;
1682
+ const start = headerSize;
1683
+ const end = Math.max(start, raw.length - footerSize);
1684
+ if (end <= start) {
1685
+ return void 0;
1686
+ }
1687
+ return raw.slice(start, end);
1688
+ }
1689
+ /**
1690
+ * Checks if the data looks like a valid transaction body.
1691
+ * Uses heuristics to detect if we've correctly offset into the block data.
1692
+ * Wire format: header (112 bytes) + body + signature (64 bytes at end)
1693
+ * This is a lenient heuristic for format detection - version/flag validation
1694
+ * happens in Transaction.parseWire.
1695
+ */
1696
+ static looksLikeValidTransactionBody(data) {
1697
+ const MIN_TXN_SIZE = TXN_HEADER_BODY_SIZE + SIGNATURE_SIZE2;
1698
+ if (data.length < MIN_TXN_SIZE) {
1699
+ return false;
1700
+ }
1701
+ const readwriteCount = data[2] | data[3] << 8;
1702
+ const readonlyCount = data[4] | data[5] << 8;
1703
+ const totalAccounts = readwriteCount + readonlyCount;
1704
+ if (totalAccounts > 1024) {
1705
+ return false;
1706
+ }
1707
+ const instrDataSize = data[6] | data[7] << 8;
1708
+ const expectedMinSize = TXN_HEADER_BODY_SIZE + totalAccounts * PUBKEY_SIZE2 + instrDataSize + SIGNATURE_SIZE2;
1709
+ if (data.length < expectedMinSize) {
1710
+ return false;
1711
+ }
1712
+ return true;
1713
+ }
1714
+ serializeHeader() {
1715
+ const buffer = new ArrayBuffer(BLOCK_HEADER_SIZE);
1716
+ const bytes = new Uint8Array(buffer);
1717
+ const view = new DataView(buffer);
1718
+ const signature = normalizeBytes(this.header.headerSignature, SIGNATURE_SIZE2);
1719
+ bytes.set(signature, 0);
1720
+ let offset = SIGNATURE_PREFIX_SIZE;
1721
+ const version = this.header.version ?? BLOCK_VERSION_V1;
1722
+ view.setUint8(offset, version & 255);
1723
+ offset += 1;
1724
+ bytes.fill(0, offset, offset + 5);
1725
+ offset += 5;
1726
+ view.setUint16(offset, this.header.chainId ?? 0, true);
1727
+ offset += 2;
1728
+ const producer = normalizeBytes(this.header.producer, PUBKEY_SIZE2);
1729
+ bytes.set(producer, offset);
1730
+ offset += PUBKEY_SIZE2;
1731
+ const bondAmountLockUp = this.header.bondAmountLockUp ?? 0n;
1732
+ view.setBigUint64(offset, bondAmountLockUp, true);
1733
+ offset += 8;
1734
+ const expiryTimestampNs = timestampToNanoseconds(this.header.expiryTimestamp);
1735
+ view.setBigUint64(offset, expiryTimestampNs, true);
1736
+ offset += 8;
1737
+ const startSlot = this.header.startSlot ?? 0n;
1738
+ view.setBigUint64(offset, startSlot, true);
1739
+ offset += 8;
1740
+ view.setUint32(offset, this.header.expiryAfter ?? 0, true);
1741
+ offset += 4;
1742
+ view.setUint32(offset, this.header.maxBlockSize ?? 0, true);
1743
+ offset += 4;
1744
+ view.setBigUint64(offset, this.header.maxComputeUnits ?? 0n, true);
1745
+ offset += 8;
1746
+ view.setUint32(offset, this.header.maxStateUnits ?? 0, true);
1747
+ offset += 4;
1748
+ bytes.fill(0, offset, offset + 4);
1749
+ offset += 4;
1750
+ view.setBigUint64(offset, this.header.weightSlot ?? 0n, true);
1751
+ offset += 8;
1752
+ const blockTimeNs = this.blockTimeNs ?? 0n;
1753
+ view.setBigUint64(offset, blockTimeNs, true);
1754
+ return bytes;
1755
+ }
1756
+ serializeFooter() {
1757
+ const buffer = new ArrayBuffer(BLOCK_FOOTER_SIZE);
1758
+ const bytes = new Uint8Array(buffer);
1759
+ const view = new DataView(buffer);
1760
+ const attestorPayment = this.footer?.attestorPayment ?? this.attestorPayment ?? RESERVED_FOOTER_PADDING;
1761
+ view.setBigUint64(0, attestorPayment, true);
1762
+ const blockHash = normalizeBytes(this.header.blockHash, BLOCK_HASH_SIZE);
1763
+ bytes.set(blockHash, 8);
1764
+ const signature = normalizeBytes(this.footer?.signature, SIGNATURE_SIZE2);
1765
+ bytes.set(signature, 8 + BLOCK_HASH_SIZE);
1766
+ return bytes;
1767
+ }
1768
+ static parseHeader(bytes) {
1769
+ if (bytes.length !== BLOCK_HEADER_SIZE) {
1770
+ throw new Error(`Invalid block header size: ${bytes.length}`);
1771
+ }
1772
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1773
+ let offset = 0;
1774
+ const signature = bytes.slice(offset, offset + SIGNATURE_SIZE2);
1775
+ offset += SIGNATURE_SIZE2;
1776
+ const version = view.getUint8(offset);
1777
+ offset += 1;
1778
+ offset += 5;
1779
+ const chainId = view.getUint16(offset, true);
1780
+ offset += 2;
1781
+ const producer = bytes.slice(offset, offset + PUBKEY_SIZE2);
1782
+ offset += PUBKEY_SIZE2;
1783
+ const bondAmountLockUp = view.getBigUint64(offset, true);
1784
+ offset += 8;
1785
+ const expiryTimestampNs = view.getBigUint64(offset, true);
1786
+ offset += 8;
1787
+ const startSlot = view.getBigUint64(offset, true);
1788
+ offset += 8;
1789
+ const expiryAfter = view.getUint32(offset, true);
1790
+ offset += 4;
1791
+ const maxBlockSize = view.getUint32(offset, true);
1792
+ offset += 4;
1793
+ const maxComputeUnits = view.getBigUint64(offset, true);
1794
+ offset += 8;
1795
+ const maxStateUnits = view.getUint32(offset, true);
1796
+ offset += 4;
1797
+ offset += 4;
1798
+ const weightSlot = view.getBigUint64(offset, true);
1799
+ offset += 8;
1800
+ const blockTimeNs = view.getBigUint64(offset, true);
1801
+ const header = new BlockHeader({
1802
+ slot: startSlot,
1803
+ version,
1804
+ headerSignature: signature,
1805
+ producer,
1806
+ expiryTimestamp: nanosecondsToTimestamp(expiryTimestampNs),
1807
+ startSlot,
1808
+ expiryAfter,
1809
+ maxBlockSize,
1810
+ maxComputeUnits,
1811
+ maxStateUnits,
1812
+ bondAmountLockUp,
1813
+ weightSlot,
1814
+ chainId
1815
+ });
1816
+ return { header, blockTimeNs };
1817
+ }
1818
+ /**
1819
+ * Parses a block header with a specific expected size.
1820
+ * Handles both current (168 bytes with weight_slot) and legacy (160 bytes without weight_slot) formats.
1821
+ */
1822
+ static parseHeaderWithSize(bytes, expectedSize) {
1823
+ if (bytes.length !== expectedSize) {
1824
+ throw new Error(`Invalid block header size: ${bytes.length}, expected ${expectedSize}`);
1825
+ }
1826
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1827
+ let offset = 0;
1828
+ const signature = bytes.slice(offset, offset + SIGNATURE_SIZE2);
1829
+ offset += SIGNATURE_SIZE2;
1830
+ const version = view.getUint8(offset);
1831
+ offset += 1;
1832
+ offset += 5;
1833
+ const chainId = view.getUint16(offset, true);
1834
+ offset += 2;
1835
+ const producer = bytes.slice(offset, offset + PUBKEY_SIZE2);
1836
+ offset += PUBKEY_SIZE2;
1837
+ const bondAmountLockUp = view.getBigUint64(offset, true);
1838
+ offset += 8;
1839
+ const expiryTimestampNs = view.getBigUint64(offset, true);
1840
+ offset += 8;
1841
+ const startSlot = view.getBigUint64(offset, true);
1842
+ offset += 8;
1843
+ const expiryAfter = view.getUint32(offset, true);
1844
+ offset += 4;
1845
+ const maxBlockSize = view.getUint32(offset, true);
1846
+ offset += 4;
1847
+ const maxComputeUnits = view.getBigUint64(offset, true);
1848
+ offset += 8;
1849
+ const maxStateUnits = view.getUint32(offset, true);
1850
+ offset += 4;
1851
+ offset += 4;
1852
+ let weightSlot;
1853
+ let blockTimeNs;
1854
+ if (expectedSize === BLOCK_HEADER_SIZE) {
1855
+ weightSlot = view.getBigUint64(offset, true);
1856
+ offset += 8;
1857
+ blockTimeNs = view.getBigUint64(offset, true);
1858
+ } else {
1859
+ blockTimeNs = view.getBigUint64(offset, true);
1860
+ }
1861
+ const header = new BlockHeader({
1862
+ slot: startSlot,
1863
+ version,
1864
+ headerSignature: signature,
1865
+ producer,
1866
+ expiryTimestamp: nanosecondsToTimestamp(expiryTimestampNs),
1867
+ startSlot,
1868
+ expiryAfter,
1869
+ maxBlockSize,
1870
+ maxComputeUnits,
1871
+ maxStateUnits,
1872
+ bondAmountLockUp,
1873
+ weightSlot,
1874
+ chainId
1875
+ });
1876
+ return { header, blockTimeNs };
1877
+ }
1878
+ static parseFooter(bytes) {
1879
+ if (bytes.length !== BLOCK_FOOTER_SIZE) {
1880
+ throw new Error(`Invalid block footer size: ${bytes.length}`);
1881
+ }
1882
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1883
+ let offset = 0;
1884
+ const attestorPayment = view.getBigUint64(offset, true);
1885
+ offset += 8;
1886
+ const blockHash = bytes.slice(offset, offset + BLOCK_HASH_SIZE);
1887
+ offset += BLOCK_HASH_SIZE;
1888
+ const signature = bytes.slice(offset, offset + SIGNATURE_SIZE2);
1889
+ const footer = new BlockFooter({
1890
+ signature,
1891
+ status: 0 /* UNSPECIFIED */,
1892
+ consumedComputeUnits: 0n,
1893
+ consumedStateUnits: 0,
1894
+ attestorPayment
1895
+ });
1896
+ return { footer, blockHash, attestorPayment };
1897
+ }
1898
+ static parseTransactionsFromBody(body) {
1899
+ const transactions = [];
1900
+ let offset = 0;
1901
+ while (offset < body.length) {
1902
+ const slice = body.subarray(offset);
1903
+ if (slice.length < 176) {
1904
+ break;
1905
+ }
1906
+ try {
1907
+ const { transaction, size } = Transaction.parseWire(slice);
1908
+ transactions.push(transaction);
1909
+ offset += size;
1910
+ } catch {
1911
+ break;
1912
+ }
1913
+ }
1914
+ return transactions;
1915
+ }
1916
+ };
1917
+ function normalizeBytes(bytes, size) {
1918
+ if (!bytes || bytes.length !== size) {
1919
+ return new Uint8Array(size);
1920
+ }
1921
+ return bytes;
1922
+ }
1923
+ function toBlockHash(value) {
1924
+ return create(BlockHashSchema, { value: ensureBytes(value, "blockHash") });
1925
+ }
1926
+ function deriveProgramAddress(options) {
1927
+ const programAddress = Pubkey.from(options.programAddress).toBytes();
1928
+ const seed = normalizeSeed(options.seed);
1929
+ const ephemeral = options.ephemeral === true;
1930
+ const derivationInput = new Uint8Array(
1931
+ programAddress.length + 1 + seed.length
1932
+ );
1933
+ derivationInput.set(programAddress, 0);
1934
+ derivationInput[programAddress.length] = ephemeral ? 1 : 0;
1935
+ derivationInput.set(seed, programAddress.length + 1);
1936
+ const hash = sha256(derivationInput);
1937
+ const derivedBytes = new Uint8Array(hash.slice(0, 32));
1938
+ return {
1939
+ bytes: derivedBytes,
1940
+ address: encodeAddress(derivedBytes)
1941
+ };
1942
+ }
1943
+ function deriveAddress(inputs) {
1944
+ if (inputs.length === 0) {
1945
+ throw new Error("At least one input is required");
1946
+ }
1947
+ const normalizedInputs = inputs.map((input) => normalizeToBytes(input));
1948
+ const totalLength = normalizedInputs.reduce(
1949
+ (sum, arr) => sum + arr.length,
1950
+ 0
1951
+ );
1952
+ const derivationInput = new Uint8Array(totalLength);
1953
+ let offset = 0;
1954
+ for (const input of normalizedInputs) {
1955
+ derivationInput.set(input, offset);
1956
+ offset += input.length;
1957
+ }
1958
+ const hash = sha256(derivationInput);
1959
+ const derivedBytes = new Uint8Array(hash.slice(0, 32));
1960
+ return {
1961
+ bytes: derivedBytes,
1962
+ address: encodeAddress(derivedBytes)
1963
+ };
1964
+ }
1965
+ function normalizeToBytes(input) {
1966
+ if (input instanceof Uint8Array) {
1967
+ return input;
1968
+ }
1969
+ return Pubkey.from(input).toBytes();
1970
+ }
1971
+ function normalizeSeed(value) {
1972
+ if (value instanceof Uint8Array) {
1973
+ if (value.length === 0) {
1974
+ throw new Error("Seed cannot be empty");
1975
+ }
1976
+ if (value.length > 32) {
1977
+ throw new Error("Seed cannot exceed 32 bytes");
1978
+ }
1979
+ const seed = new Uint8Array(32);
1980
+ seed.set(value);
1981
+ return seed;
1982
+ }
1983
+ if (typeof value === "string") {
1984
+ if (value.length === 0) {
1985
+ throw new Error("Seed cannot be empty");
1986
+ }
1987
+ if (isHexString(value)) {
1988
+ const bytes = hexToBytes(value);
1989
+ if (bytes.length !== 32) {
1990
+ throw new Error(
1991
+ `Hex seed must decode to 32 bytes, got ${bytes.length}`
1992
+ );
1993
+ }
1994
+ return bytes;
1995
+ }
1996
+ const encoder = new TextEncoder();
1997
+ const utf8 = encoder.encode(value);
1998
+ if (utf8.length > 32) {
1999
+ throw new Error(`UTF-8 seed too long: ${utf8.length} bytes (max 32)`);
2000
+ }
2001
+ const seed = new Uint8Array(32);
2002
+ seed.set(utf8);
2003
+ return seed;
2004
+ }
2005
+ throw new Error("Seed must be provided as Uint8Array or string");
2006
+ }
2007
+
2008
+ // thru-ts-client-sdk/modules/blocks.ts
2009
+ async function getBlock(ctx, selector, options = {}) {
2010
+ const request = create(GetBlockRequestSchema, {
2011
+ selector: isSlotSelector(selector) ? { case: "slot", value: typeof selector.slot === "bigint" ? selector.slot : BigInt(selector.slot) } : { case: "blockHash", value: toBlockHash(selector.blockHash) },
2012
+ view: options.view ?? DEFAULT_BLOCK_VIEW,
2013
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
2014
+ });
2015
+ const proto = await ctx.query.getBlock(request, withCallOptions(ctx));
2016
+ const protoBlock = Block.fromProto(proto);
2017
+ try {
2018
+ const rawBlock = await getRawBlock(ctx, selector);
2019
+ const rawBytes = rawBlock?.rawBlock;
2020
+ if (rawBytes && rawBytes.length >= BLOCK_HEADER_SIZE) {
2021
+ const rawBlockParsed = Block.fromWire(rawBytes);
2022
+ if (rawBlockParsed.blockTimeNs !== void 0) {
2023
+ protoBlock.blockTimeNs = rawBlockParsed.blockTimeNs;
2024
+ }
2025
+ if (rawBlockParsed.attestorPayment !== void 0) {
2026
+ protoBlock.attestorPayment = rawBlockParsed.attestorPayment;
2027
+ }
2028
+ }
2029
+ } catch (error) {
2030
+ console.debug("blocks.getBlock: failed to enrich with raw block", error);
2031
+ }
2032
+ return protoBlock;
2033
+ }
2034
+ function getRawBlock(ctx, selector, options = {}) {
2035
+ const request = create(GetRawBlockRequestSchema, {
2036
+ selector: isSlotSelector(selector) ? { case: "slot", value: typeof selector.slot === "bigint" ? selector.slot : BigInt(selector.slot) } : { case: "blockHash", value: toBlockHash(selector.blockHash) },
2037
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
2038
+ });
2039
+ return ctx.query.getRawBlock(request, withCallOptions(ctx));
2040
+ }
2041
+ async function listBlocks(ctx, options = {}) {
2042
+ const request = create(ListBlocksRequestSchema, {
2043
+ filter: options.filter?.toProto(),
2044
+ page: options.page?.toProto(),
2045
+ view: options.view ?? DEFAULT_BLOCK_VIEW,
2046
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
2047
+ });
2048
+ const response = await ctx.query.listBlocks(request, withCallOptions(ctx));
2049
+ return {
2050
+ blocks: response.blocks.map((proto) => Block.fromProto(proto)),
2051
+ page: PageResponse.fromProto(response.page)
2052
+ };
2053
+ }
2054
+
2055
+ // thru-ts-client-sdk/modules/consensus.ts
2056
+ var consensus_exports = {};
2057
+ __export(consensus_exports, {
2058
+ consensusStatusToString: () => consensusStatusToString,
2059
+ currentOrHistoricalVersionContext: () => currentOrHistoricalVersionContext,
2060
+ currentVersionContext: () => currentVersionContext,
2061
+ seqVersionContext: () => seqVersionContext,
2062
+ slotVersionContext: () => slotVersionContext,
2063
+ timestampVersionContext: () => timestampVersionContext,
2064
+ versionContext: () => versionContext
2065
+ });
2066
+ function currentVersionContext() {
2067
+ return create(VersionContextSchema, {
2068
+ version: { case: "current", value: create(CurrentVersionSchema) }
2069
+ });
2070
+ }
2071
+ function currentOrHistoricalVersionContext() {
2072
+ return create(VersionContextSchema, {
2073
+ version: { case: "currentOrHistorical", value: create(CurrentOrHistoricalVersionSchema) }
2074
+ });
2075
+ }
2076
+ function slotVersionContext(slot) {
2077
+ return create(VersionContextSchema, {
2078
+ version: { case: "slot", value: toUint64(slot, "slot") }
2079
+ });
2080
+ }
2081
+ function timestampVersionContext(value) {
2082
+ return create(VersionContextSchema, {
2083
+ version: { case: "timestamp", value: normalizeTimestamp(value) }
2084
+ });
2085
+ }
2086
+ function seqVersionContext(seq) {
2087
+ return create(VersionContextSchema, {
2088
+ version: { case: "seq", value: toUint64(seq, "seq") }
2089
+ });
2090
+ }
2091
+ function versionContext(input) {
2092
+ if (!input) {
2093
+ return currentVersionContext();
2094
+ }
2095
+ if ("version" in input) {
2096
+ return input;
2097
+ }
2098
+ if ("current" in input) {
2099
+ return currentVersionContext();
2100
+ }
2101
+ if ("currentOrHistorical" in input) {
2102
+ return currentOrHistoricalVersionContext();
2103
+ }
2104
+ if ("slot" in input) {
2105
+ return slotVersionContext(input.slot);
2106
+ }
2107
+ if ("timestamp" in input) {
2108
+ return timestampVersionContext(input.timestamp);
2109
+ }
2110
+ if ("seq" in input) {
2111
+ return seqVersionContext(input.seq);
2112
+ }
2113
+ throw new Error("Version context input must specify current, slot, timestamp, or seq");
2114
+ }
2115
+ function toUint64(value, field) {
2116
+ if (typeof value === "bigint") {
2117
+ if (value < 0n) {
2118
+ throw new Error(`${field} must be non-negative`);
2119
+ }
2120
+ return value;
2121
+ }
2122
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {
2123
+ throw new Error(`${field} must be a non-negative integer`);
2124
+ }
2125
+ return BigInt(value);
2126
+ }
2127
+ function normalizeTimestamp(value) {
2128
+ if (value instanceof Date) {
2129
+ const ms = value.getTime();
2130
+ return {
2131
+ seconds: BigInt(Math.floor(ms / 1e3)),
2132
+ nanos: ms % 1e3 * 1e6
2133
+ };
2134
+ }
2135
+ if (typeof value === "number") {
2136
+ if (!Number.isFinite(value)) {
2137
+ throw new Error("timestamp must be a finite number");
2138
+ }
2139
+ const ms = Math.trunc(value);
2140
+ return {
2141
+ seconds: BigInt(Math.floor(ms / 1e3)),
2142
+ nanos: ms % 1e3 * 1e6
2143
+ };
2144
+ }
2145
+ if (typeof value === "object" && value !== null) {
2146
+ return value;
2147
+ }
2148
+ throw new Error("timestamp must be a Date, number, or protobuf Timestamp");
2149
+ }
2150
+
2151
+ // thru-ts-client-sdk/modules/events.ts
2152
+ var events_exports = {};
2153
+ __export(events_exports, {
2154
+ getEvent: () => getEvent,
2155
+ listEvents: () => listEvents
2156
+ });
2157
+
2158
+ // thru-ts-client-sdk/domain/events/ChainEvent.ts
2159
+ var ChainEvent = class _ChainEvent {
2160
+ constructor(params) {
2161
+ if (!params.id) {
2162
+ throw new Error("ChainEvent id is required");
2163
+ }
2164
+ this.id = params.id;
2165
+ this.transactionSignature = copyBytes7(params.transactionSignature);
2166
+ this.program = copyBytes7(params.program);
2167
+ this.payload = copyBytes7(params.payload);
2168
+ this.slot = params.slot;
2169
+ this.callIndex = params.callIndex;
2170
+ this.programIndex = params.programIndex;
2171
+ this.payloadSize = params.payloadSize;
2172
+ this.timestampNs = params.timestampNs;
2173
+ }
2174
+ static fromQuery(proto) {
2175
+ return new _ChainEvent({
2176
+ id: proto.eventId,
2177
+ transactionSignature: proto.transactionSignature?.value,
2178
+ program: proto.program?.value,
2179
+ payload: proto.payload,
2180
+ slot: proto.slot,
2181
+ callIndex: proto.callIdx,
2182
+ programIndex: proto.programIdx,
2183
+ payloadSize: proto.payloadSize
2184
+ });
2185
+ }
2186
+ static fromStream(proto) {
2187
+ const id = normalizeStreamEventId(proto.eventId);
2188
+ return new _ChainEvent({
2189
+ id,
2190
+ transactionSignature: proto.signature?.value,
2191
+ program: proto.program?.value,
2192
+ payload: proto.payload,
2193
+ slot: proto.slot,
2194
+ callIndex: proto.callIdx,
2195
+ timestampNs: timestampToNanoseconds(proto.timestamp)
2196
+ });
2197
+ }
2198
+ };
2199
+ function copyBytes7(input) {
2200
+ if (!input) {
2201
+ return void 0;
2202
+ }
2203
+ const copy = new Uint8Array(input.length);
2204
+ copy.set(input);
2205
+ return copy;
2206
+ }
2207
+ function normalizeStreamEventId(id) {
2208
+ const parts = id.split(":");
2209
+ if (parts.length >= 4) {
2210
+ return parts.slice(0, 4).join(":");
2211
+ }
2212
+ return id;
2213
+ }
2214
+
2215
+ // thru-ts-client-sdk/modules/events.ts
2216
+ function getEvent(ctx, eventId, options = {}) {
2217
+ if (!eventId) {
2218
+ throw new Error("eventId is required");
2219
+ }
2220
+ const request = create(GetEventRequestSchema, {
2221
+ eventId,
2222
+ versionContext: options.versionContext ?? DEFAULT_VERSION_CONTEXT
2223
+ });
2224
+ return ctx.query.getEvent(request, withCallOptions(ctx)).then((proto) => ChainEvent.fromQuery(proto));
2225
+ }
2226
+ function listEvents(ctx, options = {}) {
2227
+ const request = create(ListEventsRequestSchema, {
2228
+ filter: options.filter?.toProto(),
2229
+ page: options.page?.toProto(),
2230
+ versionContext: options.versionContext ?? DEFAULT_VERSION_CONTEXT,
2231
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
2232
+ });
2233
+ return ctx.query.listEvents(request, withCallOptions(ctx)).then((response) => ({
2234
+ events: response.events.map((proto) => ChainEvent.fromQuery(proto)),
2235
+ page: PageResponse.fromProto(response.page)
2236
+ }));
2237
+ }
2238
+
2239
+ // thru-ts-client-sdk/modules/height.ts
2240
+ var height_exports = {};
2241
+ __export(height_exports, {
2242
+ getBlockHeight: () => getBlockHeight
2243
+ });
2244
+
2245
+ // thru-ts-client-sdk/domain/height/HeightSnapshot.ts
2246
+ var HeightSnapshot = class _HeightSnapshot {
2247
+ constructor(params) {
2248
+ this.finalized = params.finalized;
2249
+ this.locallyExecuted = params.locallyExecuted;
2250
+ this.clusterExecuted = params.clusterExecuted;
2251
+ }
2252
+ static fromProto(proto) {
2253
+ return new _HeightSnapshot({
2254
+ finalized: proto.finalized ?? 0n,
2255
+ locallyExecuted: proto.locallyExecuted ?? 0n,
2256
+ clusterExecuted: proto.clusterExecuted ?? 0n
2257
+ });
2258
+ }
2259
+ delta(other) {
2260
+ return {
2261
+ finalized: this.finalized - other.finalized,
2262
+ locallyExecuted: this.locallyExecuted - other.locallyExecuted,
2263
+ clusterExecuted: this.clusterExecuted - other.clusterExecuted
2264
+ };
2265
+ }
2266
+ };
2267
+
2268
+ // thru-ts-client-sdk/modules/height.ts
2269
+ function getBlockHeight(ctx) {
2270
+ const request = create(GetHeightRequestSchema);
2271
+ return ctx.query.getHeight(request, withCallOptions(ctx)).then((proto) => HeightSnapshot.fromProto(proto));
2272
+ }
2273
+
2274
+ // thru-ts-client-sdk/modules/chain.ts
2275
+ var chain_exports = {};
2276
+ __export(chain_exports, {
2277
+ getChainId: () => getChainId,
2278
+ getChainInfo: () => getChainInfo
2279
+ });
2280
+ async function getChainInfo(ctx) {
2281
+ const request = create(GetChainInfoRequestSchema);
2282
+ return ctx.query.getChainInfo(request, withCallOptions(ctx));
2283
+ }
2284
+ async function getChainId(ctx) {
2285
+ const response = await getChainInfo(ctx);
2286
+ return response.chainId;
2287
+ }
2288
+
2289
+ // thru-ts-client-sdk/modules/keys.ts
2290
+ var keys_exports = {};
2291
+ __export(keys_exports, {
2292
+ fromPrivateKey: () => fromPrivateKey,
2293
+ generateKeyPair: () => generateKeyPair
2294
+ });
2295
+ async function generateKeyPair() {
2296
+ const seed = generateSeed();
2297
+ const account = await ThruHDWallet.getAccount(seed, 0);
2298
+ seed.fill(0);
2299
+ return {
2300
+ address: account.address,
2301
+ publicKey: account.publicKey,
2302
+ privateKey: account.privateKey
2303
+ };
2304
+ }
2305
+ async function fromPrivateKey(privateKey) {
2306
+ return new Uint8Array(await getPublicKeyAsync(privateKey));
2307
+ }
2308
+ function generateSeed() {
2309
+ const cryptoObj = getWebCrypto();
2310
+ const bytes = new Uint8Array(64);
2311
+ cryptoObj.getRandomValues(bytes);
2312
+ return bytes;
2313
+ }
2314
+
2315
+ // thru-ts-client-sdk/modules/node.ts
2316
+ var node_exports = {};
2317
+ __export(node_exports, {
2318
+ getNodePubkey: () => getNodePubkey,
2319
+ getNodeRecords: () => getNodeRecords,
2320
+ getNodeStatus: () => getNodeStatus
2321
+ });
2322
+ async function getNodeStatus(ctx) {
2323
+ const request = create(GetNodeStatusRequestSchema, {});
2324
+ return ctx.query.getNodeStatus(request, withCallOptions(ctx));
2325
+ }
2326
+ async function getNodePubkey(ctx) {
2327
+ const request = create(GetNodePubkeyRequestSchema, {});
2328
+ return ctx.query.getNodePubkey(request, withCallOptions(ctx));
2329
+ }
2330
+ async function getNodeRecords(ctx) {
2331
+ const request = create(GetNodeRecordsRequestSchema, {});
2332
+ return ctx.query.getNodeRecords(request, withCallOptions(ctx));
2333
+ }
2334
+
2335
+ // thru-ts-client-sdk/modules/nonce.ts
2336
+ var nonce_exports = {};
2337
+ __export(nonce_exports, {
2338
+ AccountNonceObserver: () => AccountNonceObserver,
2339
+ FeePayerNonceManager: () => FeePayerNonceManager
2340
+ });
2341
+
2342
+ // thru-ts-client-sdk/modules/streaming.ts
2343
+ var streaming_exports = {};
2344
+ __export(streaming_exports, {
2345
+ collectStream: () => collectStream,
2346
+ firstStreamValue: () => firstStreamValue,
2347
+ forEachStreamValue: () => forEachStreamValue,
2348
+ streamAccountUpdates: () => streamAccountUpdates,
2349
+ streamBlocks: () => streamBlocks,
2350
+ streamEvents: () => streamEvents,
2351
+ streamHeight: () => streamHeight,
2352
+ streamNodeRecords: () => streamNodeRecords,
2353
+ streamSlotMetrics: () => streamSlotMetrics,
2354
+ streamTransactions: () => streamTransactions,
2355
+ trackTransaction: () => trackTransaction
2356
+ });
2357
+ function copyBytes8(source) {
2358
+ const bytes = new Uint8Array(source.length);
2359
+ bytes.set(source);
2360
+ return bytes;
2361
+ }
2362
+ function toUint(value) {
2363
+ if (typeof value === "bigint") {
2364
+ if (value < 0n) {
2365
+ throw new Error("FilterParamValue.uint requires a non-negative value");
2366
+ }
2367
+ return value;
2368
+ }
2369
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {
2370
+ throw new Error("FilterParamValue.uint requires a non-negative integer");
2371
+ }
2372
+ return BigInt(value);
2373
+ }
2374
+ var FilterParamValue = class _FilterParamValue {
2375
+ constructor(params) {
2376
+ this.case = params.case;
2377
+ if (!params.case) {
2378
+ this.value = void 0;
2379
+ return;
2380
+ }
2381
+ switch (params.case) {
2382
+ case "stringValue":
2383
+ if (typeof params.value !== "string") {
2384
+ throw new Error("FilterParamValue.string requires a string value");
2385
+ }
2386
+ this.value = params.value;
2387
+ return;
2388
+ case "bytesValue":
2389
+ if (!(params.value instanceof Uint8Array)) {
2390
+ throw new Error("FilterParamValue.bytes requires a Uint8Array value");
2391
+ }
2392
+ this.value = copyBytes8(params.value);
2393
+ return;
2394
+ case "boolValue":
2395
+ if (typeof params.value !== "boolean") {
2396
+ throw new Error("FilterParamValue.bool requires a boolean value");
2397
+ }
2398
+ this.value = params.value;
2399
+ return;
2400
+ case "intValue":
2401
+ if (typeof params.value !== "bigint") {
2402
+ throw new Error("FilterParamValue.int requires a bigint value");
2403
+ }
2404
+ this.value = params.value;
2405
+ return;
2406
+ case "doubleValue":
2407
+ if (typeof params.value !== "number") {
2408
+ throw new Error("FilterParamValue.double requires a number value");
2409
+ }
2410
+ this.value = params.value;
2411
+ return;
2412
+ case "uintValue":
2413
+ if (typeof params.value !== "bigint") {
2414
+ throw new Error("FilterParamValue.uint requires a bigint value");
2415
+ }
2416
+ this.value = params.value;
2417
+ return;
2418
+ case "pubkeyValue":
2419
+ if (!(params.value instanceof Uint8Array)) {
2420
+ throw new Error("FilterParamValue.pubkey requires a Uint8Array value");
2421
+ }
2422
+ this.value = copyBytes8(params.value);
2423
+ return;
2424
+ case "signatureValue":
2425
+ if (!(params.value instanceof Uint8Array)) {
2426
+ throw new Error("FilterParamValue.signature requires a Uint8Array value");
2427
+ }
2428
+ this.value = copyBytes8(params.value);
2429
+ return;
2430
+ case "taPubkeyValue":
2431
+ if (typeof params.value !== "string") {
2432
+ throw new Error("FilterParamValue.taPubkey requires a string value");
2433
+ }
2434
+ this.value = params.value;
2435
+ return;
2436
+ case "tsSignatureValue":
2437
+ if (typeof params.value !== "string") {
2438
+ throw new Error("FilterParamValue.tsSignature requires a string value");
2439
+ }
2440
+ this.value = params.value;
2441
+ return;
2442
+ default:
2443
+ this.value = void 0;
2444
+ }
2445
+ }
2446
+ static none() {
2447
+ return new _FilterParamValue({});
2448
+ }
2449
+ static string(value) {
2450
+ return new _FilterParamValue({ case: "stringValue", value });
2451
+ }
2452
+ static bytes(value) {
2453
+ return new _FilterParamValue({ case: "bytesValue", value });
2454
+ }
2455
+ static bool(value) {
2456
+ return new _FilterParamValue({ case: "boolValue", value });
2457
+ }
2458
+ static int(value) {
2459
+ return new _FilterParamValue({ case: "intValue", value });
2460
+ }
2461
+ static double(value) {
2462
+ if (!Number.isFinite(value)) {
2463
+ throw new Error("FilterParamValue.double requires a finite number");
2464
+ }
2465
+ return new _FilterParamValue({ case: "doubleValue", value });
2466
+ }
2467
+ static uint(value) {
2468
+ return new _FilterParamValue({ case: "uintValue", value: toUint(value) });
2469
+ }
2470
+ static pubkey(value) {
2471
+ return new _FilterParamValue({
2472
+ case: "pubkeyValue",
2473
+ value: Pubkey.from(value).toBytes()
2474
+ });
2475
+ }
2476
+ static signature(value) {
2477
+ return new _FilterParamValue({
2478
+ case: "signatureValue",
2479
+ value: Signature.from(value).toBytes()
2480
+ });
2481
+ }
2482
+ static taPubkey(value) {
2483
+ return new _FilterParamValue({
2484
+ case: "taPubkeyValue",
2485
+ value: Pubkey.from(value).toThruFmt()
2486
+ });
2487
+ }
2488
+ static tsSignature(value) {
2489
+ return new _FilterParamValue({
2490
+ case: "tsSignatureValue",
2491
+ value: Signature.from(value).toThruFmt()
2492
+ });
2493
+ }
2494
+ static fromProto(proto) {
2495
+ const kind = proto.kind;
2496
+ if (!kind.case) {
2497
+ return _FilterParamValue.none();
2498
+ }
2499
+ switch (kind.case) {
2500
+ case "stringValue":
2501
+ return _FilterParamValue.string(kind.value);
2502
+ case "bytesValue":
2503
+ return _FilterParamValue.bytes(kind.value);
2504
+ case "boolValue":
2505
+ return _FilterParamValue.bool(kind.value);
2506
+ case "intValue":
2507
+ return _FilterParamValue.int(kind.value);
2508
+ case "doubleValue":
2509
+ return _FilterParamValue.double(kind.value);
2510
+ case "uintValue":
2511
+ return _FilterParamValue.uint(kind.value);
2512
+ case "pubkeyValue":
2513
+ return _FilterParamValue.pubkey(Pubkey.fromProtoPubkey(kind.value).toBytes());
2514
+ case "signatureValue":
2515
+ return _FilterParamValue.signature(Signature.fromProtoSignature(kind.value).toBytes());
2516
+ case "taPubkeyValue":
2517
+ return _FilterParamValue.taPubkey(Pubkey.fromProtoTaPubkey(kind.value).toThruFmt());
2518
+ case "tsSignatureValue":
2519
+ return _FilterParamValue.tsSignature(Signature.fromProtoTsSignature(kind.value).toThruFmt());
2520
+ default:
2521
+ return _FilterParamValue.none();
2522
+ }
2523
+ }
2524
+ toProto() {
2525
+ if (!this.case) {
2526
+ return create(FilterParamValueSchema);
2527
+ }
2528
+ switch (this.case) {
2529
+ case "stringValue":
2530
+ return create(FilterParamValueSchema, {
2531
+ kind: {
2532
+ case: "stringValue",
2533
+ value: this.value
2534
+ }
2535
+ });
2536
+ case "bytesValue":
2537
+ return create(FilterParamValueSchema, {
2538
+ kind: {
2539
+ case: "bytesValue",
2540
+ value: copyBytes8(this.value)
2541
+ }
2542
+ });
2543
+ case "boolValue":
2544
+ return create(FilterParamValueSchema, {
2545
+ kind: {
2546
+ case: "boolValue",
2547
+ value: this.value
2548
+ }
2549
+ });
2550
+ case "intValue":
2551
+ return create(FilterParamValueSchema, {
2552
+ kind: {
2553
+ case: "intValue",
2554
+ value: this.value
2555
+ }
2556
+ });
2557
+ case "doubleValue":
2558
+ return create(FilterParamValueSchema, {
2559
+ kind: {
2560
+ case: "doubleValue",
2561
+ value: this.value
2562
+ }
2563
+ });
2564
+ case "uintValue":
2565
+ return create(FilterParamValueSchema, {
2566
+ kind: {
2567
+ case: "uintValue",
2568
+ value: this.value
2569
+ }
2570
+ });
2571
+ case "pubkeyValue":
2572
+ return create(FilterParamValueSchema, {
2573
+ kind: {
2574
+ case: "pubkeyValue",
2575
+ value: Pubkey.from(this.value).toProtoPubkey()
2576
+ }
2577
+ });
2578
+ case "signatureValue":
2579
+ return create(FilterParamValueSchema, {
2580
+ kind: {
2581
+ case: "signatureValue",
2582
+ value: Signature.from(this.value).toProtoSignature()
2583
+ }
2584
+ });
2585
+ case "taPubkeyValue":
2586
+ return create(FilterParamValueSchema, {
2587
+ kind: {
2588
+ case: "taPubkeyValue",
2589
+ value: Pubkey.from(this.value).toProtoTaPubkey()
2590
+ }
2591
+ });
2592
+ case "tsSignatureValue":
2593
+ return create(FilterParamValueSchema, {
2594
+ kind: {
2595
+ case: "tsSignatureValue",
2596
+ value: Signature.from(this.value).toProtoTsSignature()
2597
+ }
2598
+ });
2599
+ default:
2600
+ throw new Error("FilterParamValue has an unknown kind");
2601
+ }
2602
+ }
2603
+ getCase() {
2604
+ return this.case;
2605
+ }
2606
+ getString() {
2607
+ return this.case === "stringValue" ? this.value : void 0;
2608
+ }
2609
+ getBytes() {
2610
+ if (this.case !== "bytesValue" || !(this.value instanceof Uint8Array)) {
2611
+ return void 0;
2612
+ }
2613
+ return copyBytes8(this.value);
2614
+ }
2615
+ getBool() {
2616
+ return this.case === "boolValue" ? this.value : void 0;
2617
+ }
2618
+ getInt() {
2619
+ return this.case === "intValue" ? this.value : void 0;
2620
+ }
2621
+ getUint() {
2622
+ return this.case === "uintValue" ? this.value : void 0;
2623
+ }
2624
+ getDouble() {
2625
+ return this.case === "doubleValue" ? this.value : void 0;
2626
+ }
2627
+ getPubkey() {
2628
+ if (this.case !== "pubkeyValue") {
2629
+ return void 0;
2630
+ }
2631
+ return copyBytes8(this.value);
2632
+ }
2633
+ getSignature() {
2634
+ if (this.case !== "signatureValue") {
2635
+ return void 0;
2636
+ }
2637
+ return copyBytes8(this.value);
2638
+ }
2639
+ getTaPubkey() {
2640
+ return this.case === "taPubkeyValue" ? this.value : void 0;
2641
+ }
2642
+ getTsSignature() {
2643
+ return this.case === "tsSignatureValue" ? this.value : void 0;
2644
+ }
2645
+ };
2646
+ var Filter = class _Filter {
2647
+ constructor(init = {}) {
2648
+ this.expression = init.expression;
2649
+ this.params = /* @__PURE__ */ new Map();
2650
+ if (!init.params) {
2651
+ return;
2652
+ }
2653
+ if (init.params instanceof Map) {
2654
+ for (const [key, value] of init.params.entries()) {
2655
+ this.setParamInternal(key, value);
2656
+ }
2657
+ return;
2658
+ }
2659
+ if (typeof init.params === "object" && !Array.isArray(init.params)) {
2660
+ for (const [key, value] of Object.entries(init.params)) {
2661
+ this.setParamInternal(key, value);
2662
+ }
2663
+ return;
2664
+ }
2665
+ for (const [key, value] of init.params) {
2666
+ this.setParamInternal(key, value);
2667
+ }
2668
+ }
2669
+ static fromProto(proto) {
2670
+ const params = Object.entries(proto.params ?? {}).map(([key, value]) => [key, FilterParamValue.fromProto(value)]);
2671
+ return new _Filter({
2672
+ expression: proto.expression,
2673
+ params
2674
+ });
2675
+ }
2676
+ toProto() {
2677
+ const protoParams = {};
2678
+ for (const [key, value] of this.params.entries()) {
2679
+ protoParams[key] = value.toProto();
2680
+ }
2681
+ return create(FilterSchema, {
2682
+ expression: this.expression,
2683
+ params: protoParams
2684
+ });
2685
+ }
2686
+ hasParam(name) {
2687
+ return this.params.has(name);
2688
+ }
2689
+ getParam(name) {
2690
+ const param = this.params.get(name);
2691
+ return param;
2692
+ }
2693
+ listParams() {
2694
+ return Array.from(this.params.keys());
2695
+ }
2696
+ entries() {
2697
+ return Array.from(this.params.entries());
2698
+ }
2699
+ withExpression(expression) {
2700
+ return new _Filter({ expression, params: this.params });
2701
+ }
2702
+ withParam(name, value) {
2703
+ const params = new Map(this.params);
2704
+ params.set(name, value);
2705
+ return new _Filter({ expression: this.expression, params });
2706
+ }
2707
+ withoutParam(name) {
2708
+ if (!this.params.has(name)) {
2709
+ return this;
2710
+ }
2711
+ const params = new Map(this.params);
2712
+ params.delete(name);
2713
+ return new _Filter({ expression: this.expression, params });
2714
+ }
2715
+ setParamInternal(name, value) {
2716
+ if (!(value instanceof FilterParamValue)) {
2717
+ throw new Error(`Filter parameter "${name}" must be a FilterParamValue`);
2718
+ }
2719
+ this.params.set(name, value);
2720
+ }
2721
+ };
2722
+
2723
+ // thru-ts-client-sdk/modules/streaming.ts
2724
+ function streamBlocks(ctx, options = {}) {
2725
+ const request = create(StreamBlocksRequestSchema, {
2726
+ startSlot: options.startSlot,
2727
+ filter: options.filter?.toProto(),
2728
+ view: options.view ?? DEFAULT_BLOCK_VIEW,
2729
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
2730
+ });
2731
+ const iterable = ctx.streaming.streamBlocks(request, withCallOptions(ctx, { signal: options.signal }));
2732
+ async function* mapper() {
2733
+ for await (const response of iterable) {
2734
+ if (!response.block) {
2735
+ continue;
2736
+ }
2737
+ yield { block: Block.fromProto(response.block) };
2738
+ }
2739
+ }
2740
+ return mapper();
2741
+ }
2742
+ function streamAccountUpdates(ctx, address, options = {}) {
2743
+ const addressBytes = Pubkey.from(address).toBytes();
2744
+ const addressFilter = new Filter({
2745
+ expression: "account_address.value == params.address",
2746
+ params: {
2747
+ address: FilterParamValue.bytes(addressBytes)
2748
+ }
2749
+ });
2750
+ let mergedFilter = addressFilter;
2751
+ if (options.filter) {
2752
+ const combinedParams = {};
2753
+ for (const [key, value] of addressFilter.entries()) {
2754
+ combinedParams[key] = value;
2755
+ }
2756
+ for (const [key, value] of options.filter.entries()) {
2757
+ combinedParams[key] = value;
2758
+ }
2759
+ mergedFilter = new Filter({
2760
+ expression: `(${addressFilter.expression}) && (${options.filter.expression})`,
2761
+ params: combinedParams
2762
+ });
2763
+ }
2764
+ const request = create(StreamAccountUpdatesRequestSchema, {
2765
+ view: options.view ?? DEFAULT_ACCOUNT_VIEW,
2766
+ filter: mergedFilter.toProto()
2767
+ });
2768
+ const iterable = ctx.streaming.streamAccountUpdates(request, withCallOptions(ctx, { signal: options.signal }));
2769
+ async function* mapper() {
2770
+ for await (const response of iterable) {
2771
+ const update = toStreamAccountUpdate(response);
2772
+ if (!update) {
2773
+ continue;
2774
+ }
2775
+ yield { update };
2776
+ }
2777
+ }
2778
+ return mapper();
2779
+ }
2780
+ function streamTransactions(ctx, options = {}) {
2781
+ const request = create(StreamTransactionsRequestSchema, {
2782
+ filter: options.filter?.toProto(),
2783
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
2784
+ });
2785
+ const iterable = ctx.streaming.streamTransactions(request, withCallOptions(ctx, { signal: options.signal }));
2786
+ async function* mapper() {
2787
+ for await (const response of iterable) {
2788
+ if (!response.transaction) {
2789
+ continue;
2790
+ }
2791
+ try {
2792
+ yield toStreamTransactionUpdate(response.transaction);
2793
+ } catch (err) {
2794
+ console.error("streamTransactions: failed to decode transaction update", err);
2795
+ }
2796
+ }
2797
+ }
2798
+ return mapper();
2799
+ }
2800
+ function streamEvents(ctx, options = {}) {
2801
+ const request = create(StreamEventsRequestSchema, {
2802
+ filter: options.filter?.toProto()
2803
+ });
2804
+ const iterable = ctx.streaming.streamEvents(request, withCallOptions(ctx, { signal: options.signal }));
2805
+ async function* mapper() {
2806
+ for await (const response of iterable) {
2807
+ yield { event: ChainEvent.fromStream(response) };
2808
+ }
2809
+ }
2810
+ return mapper();
2811
+ }
2812
+ function trackTransaction(ctx, signature, options = {}) {
2813
+ const timeoutMs = options.timeoutMs;
2814
+ const request = create(TrackTransactionRequestSchema, {
2815
+ signature: Signature.from(signature).toProtoSignature(),
2816
+ timeout: timeoutMs != null ? {
2817
+ seconds: BigInt(Math.floor(timeoutMs / 1e3)),
2818
+ nanos: timeoutMs % 1e3 * 1e6
2819
+ } : void 0
2820
+ });
2821
+ const iterable = ctx.streaming.trackTransaction(request, withCallOptions(ctx, { signal: options.signal }));
2822
+ async function* mapper() {
2823
+ for await (const response of iterable) {
2824
+ yield toTrackTransactionUpdate(response);
2825
+ }
2826
+ }
2827
+ return mapper();
2828
+ }
2829
+ function streamHeight(ctx, options = {}) {
2830
+ const request = create(StreamHeightRequestSchema, {});
2831
+ const iterable = ctx.streaming.streamHeight(request, withCallOptions(ctx, { signal: options.signal }));
2832
+ async function* mapper() {
2833
+ for await (const response of iterable) {
2834
+ yield { height: HeightSnapshot.fromProto(response) };
2835
+ }
2836
+ }
2837
+ return mapper();
2838
+ }
2839
+ function streamSlotMetrics(ctx, options = {}) {
2840
+ const request = create(StreamSlotMetricsRequestSchema, {
2841
+ startSlot: options.startSlot
2842
+ });
2843
+ const iterable = ctx.streaming.streamSlotMetrics(request, withCallOptions(ctx, { signal: options.signal }));
2844
+ async function* mapper() {
2845
+ for await (const response of iterable) {
2846
+ yield {
2847
+ slot: response.slot,
2848
+ collectedFees: response.collectedFees,
2849
+ globalActivatedStateCounter: response.globalActivatedStateCounter,
2850
+ globalDeactivatedStateCounter: response.globalDeactivatedStateCounter,
2851
+ blockTimestamp: response.blockTimestamp
2852
+ };
2853
+ }
2854
+ }
2855
+ return mapper();
2856
+ }
2857
+ function streamNodeRecords(ctx, options = {}) {
2858
+ const request = create(StreamNodeRecordsRequestSchema, {});
2859
+ const iterable = ctx.streaming.streamNodeRecords(request, withCallOptions(ctx, { signal: options.signal }));
2860
+ async function* mapper() {
2861
+ for await (const response of iterable) {
2862
+ if (response.message.case === "record") {
2863
+ yield { type: "record", record: response.message.value };
2864
+ } else if (response.message.case === "finished") {
2865
+ yield { type: "finished" };
2866
+ }
2867
+ }
2868
+ }
2869
+ return mapper();
2870
+ }
2871
+ async function collectStream(iterable, options = {}) {
2872
+ const { limit, signal } = options;
2873
+ throwIfAborted(signal);
2874
+ if (limit != null && limit <= 0) {
2875
+ return [];
2876
+ }
2877
+ const results = [];
2878
+ let count = 0;
2879
+ for await (const value of iterable) {
2880
+ throwIfAborted(signal);
2881
+ results.push(value);
2882
+ count += 1;
2883
+ if (limit != null && count >= limit) {
2884
+ break;
2885
+ }
2886
+ }
2887
+ return results;
2888
+ }
2889
+ async function firstStreamValue(iterable, options = {}) {
2890
+ const values = await collectStream(iterable, { ...options, limit: 1 });
2891
+ return values[0];
2892
+ }
2893
+ async function forEachStreamValue(iterable, handler, options = {}) {
2894
+ let index = 0;
2895
+ for await (const value of iterable) {
2896
+ throwIfAborted(options.signal);
2897
+ await handler(value, index++);
2898
+ }
2899
+ }
2900
+ function throwIfAborted(signal) {
2901
+ if (!signal) {
2902
+ return;
2903
+ }
2904
+ if (signal.aborted) {
2905
+ const reason = signal.reason;
2906
+ if (reason instanceof Error) {
2907
+ throw reason;
2908
+ }
2909
+ if (reason !== void 0) {
2910
+ throw new Error(String(reason));
2911
+ }
2912
+ throw new DOMException("The operation was aborted.", "AbortError");
2913
+ }
2914
+ }
2915
+
2916
+ // thru-ts-client-sdk/modules/nonce.ts
2917
+ var DEFAULT_NONCE_WAIT_TIMEOUT_MS = 1e4;
2918
+ var AccountNonceObserver = class {
2919
+ constructor(ctx, account, options = {}) {
2920
+ this.abortController = new AbortController();
2921
+ this.waiters = /* @__PURE__ */ new Set();
2922
+ this.closed = false;
2923
+ this.streamStarted = false;
2924
+ this.ctx = ctx;
2925
+ this.account = Pubkey.from(account);
2926
+ this.versionContext = options.versionContext ?? currentVersionContext();
2927
+ options.signal?.addEventListener("abort", () => this.close(), { once: true });
2928
+ }
2929
+ getLatestNonce() {
2930
+ return this.latestNonce;
2931
+ }
2932
+ async refresh() {
2933
+ const account = await getAccount(this.ctx, this.account, {
2934
+ view: 4 /* FULL */,
2935
+ versionContext: this.versionContext
2936
+ });
2937
+ this.observeNonce(account.meta?.nonce);
2938
+ return this.latestNonce;
2939
+ }
2940
+ start() {
2941
+ if (this.streamStarted || this.closed) {
2942
+ return;
2943
+ }
2944
+ this.streamStarted = true;
2945
+ void this.runStream();
2946
+ }
2947
+ async waitForNonceAtLeast(target, options = {}) {
2948
+ if (this.closed) {
2949
+ throw new Error("AccountNonceObserver is closed");
2950
+ }
2951
+ if (this.latestNonce === void 0 || this.latestNonce < target) {
2952
+ this.start();
2953
+ await this.refresh();
2954
+ }
2955
+ if (this.closed) {
2956
+ throw new Error("AccountNonceObserver is closed");
2957
+ }
2958
+ if (this.latestNonce !== void 0 && this.latestNonce >= target) {
2959
+ return this.latestNonce;
2960
+ }
2961
+ return new Promise((resolve, reject) => {
2962
+ const timeoutMs = options.timeoutMs ?? DEFAULT_NONCE_WAIT_TIMEOUT_MS;
2963
+ const waiter = {
2964
+ target,
2965
+ resolve,
2966
+ reject
2967
+ };
2968
+ waiter.timeoutId = setTimeout(() => {
2969
+ this.waiters.delete(waiter);
2970
+ reject(new Error(`Timed out waiting for nonce >= ${target.toString()} after ${timeoutMs}ms`));
2971
+ }, timeoutMs);
2972
+ this.waiters.add(waiter);
2973
+ });
2974
+ }
2975
+ close() {
2976
+ if (this.closed) {
2977
+ return;
2978
+ }
2979
+ this.closed = true;
2980
+ this.abortController.abort();
2981
+ for (const waiter of this.waiters) {
2982
+ if (waiter.timeoutId) {
2983
+ clearTimeout(waiter.timeoutId);
2984
+ }
2985
+ waiter.reject(new Error("AccountNonceObserver closed"));
2986
+ }
2987
+ this.waiters.clear();
2988
+ }
2989
+ async runStream() {
2990
+ try {
2991
+ for await (const { update } of streamAccountUpdates(this.ctx, this.account, {
2992
+ view: 4 /* FULL */,
2993
+ signal: this.abortController.signal
2994
+ })) {
2995
+ if (this.closed) {
2996
+ return;
2997
+ }
2998
+ if (update.kind === "snapshot") {
2999
+ this.observeNonce(update.snapshot.account.meta?.nonce);
3000
+ continue;
3001
+ }
3002
+ this.observeNonce(update.update.meta?.nonce);
3003
+ }
3004
+ } catch (error) {
3005
+ if (!this.closed) {
3006
+ this.rejectWaiters(error instanceof Error ? error : new Error(String(error)));
3007
+ }
3008
+ } finally {
3009
+ this.streamStarted = false;
3010
+ if (!this.closed) {
3011
+ this.rejectWaiters(new Error("Account nonce stream ended unexpectedly"));
3012
+ }
3013
+ }
3014
+ }
3015
+ observeNonce(nonce) {
3016
+ if (nonce === void 0) {
3017
+ return;
3018
+ }
3019
+ if (this.latestNonce === void 0 || nonce > this.latestNonce) {
3020
+ this.latestNonce = nonce;
3021
+ }
3022
+ this.resolveReadyWaiters();
3023
+ }
3024
+ resolveReadyWaiters() {
3025
+ if (this.latestNonce === void 0) {
3026
+ return;
3027
+ }
3028
+ for (const waiter of Array.from(this.waiters)) {
3029
+ if (this.latestNonce < waiter.target) {
3030
+ continue;
3031
+ }
3032
+ this.waiters.delete(waiter);
3033
+ if (waiter.timeoutId) {
3034
+ clearTimeout(waiter.timeoutId);
3035
+ }
3036
+ waiter.resolve(this.latestNonce);
3037
+ }
3038
+ }
3039
+ rejectWaiters(error) {
3040
+ for (const waiter of this.waiters) {
3041
+ if (waiter.timeoutId) {
3042
+ clearTimeout(waiter.timeoutId);
3043
+ }
3044
+ waiter.reject(error);
3045
+ }
3046
+ this.waiters.clear();
3047
+ }
3048
+ };
3049
+ var FeePayerNonceManager = class {
3050
+ constructor(ctx, feePayer, options = {}) {
3051
+ this.allocationQueue = Promise.resolve();
3052
+ this.observer = options.observer ?? new AccountNonceObserver(ctx, feePayer);
3053
+ }
3054
+ async allocate(count) {
3055
+ return this.withAllocationLock(() => this.allocateUnsafe(count));
3056
+ }
3057
+ reset(nextNonce) {
3058
+ this.nextNonce = nextNonce;
3059
+ }
3060
+ async sync() {
3061
+ const latestNonce = await this.observer.refresh();
3062
+ if (latestNonce === void 0) {
3063
+ throw new Error("Unable to read fee payer nonce");
3064
+ }
3065
+ this.nextNonce = latestNonce;
3066
+ return latestNonce;
3067
+ }
3068
+ async waitForNonceAtLeast(target, options) {
3069
+ const nonce = await this.observer.waitForNonceAtLeast(target, options);
3070
+ if (this.nextNonce === void 0 || nonce > this.nextNonce) {
3071
+ this.nextNonce = nonce;
3072
+ }
3073
+ return nonce;
3074
+ }
3075
+ close() {
3076
+ this.observer.close();
3077
+ }
3078
+ async allocateUnsafe(count) {
3079
+ if (!Number.isInteger(count) || count <= 0) {
3080
+ throw new Error("Nonce allocation count must be a positive integer");
3081
+ }
3082
+ const latestNonce = await this.observer.refresh();
3083
+ if (latestNonce === void 0) {
3084
+ throw new Error("Unable to read fee payer nonce");
3085
+ }
3086
+ const baseNonce = this.nextNonce === void 0 || latestNonce > this.nextNonce ? latestNonce : this.nextNonce;
3087
+ const barrierNonce = baseNonce + BigInt(count);
3088
+ const nonces = Array.from({ length: count }, (_, index) => baseNonce + BigInt(index));
3089
+ this.nextNonce = barrierNonce;
3090
+ return {
3091
+ baseNonce,
3092
+ nonces,
3093
+ barrierNonce
3094
+ };
3095
+ }
3096
+ async withAllocationLock(work) {
3097
+ const previous = this.allocationQueue;
3098
+ let release;
3099
+ this.allocationQueue = new Promise((resolve) => {
3100
+ release = resolve;
3101
+ });
3102
+ await previous;
3103
+ try {
3104
+ return await work();
3105
+ } finally {
3106
+ release();
3107
+ }
3108
+ }
3109
+ };
3110
+
3111
+ // thru-ts-client-sdk/modules/slots.ts
3112
+ var slots_exports = {};
3113
+ __export(slots_exports, {
3114
+ getSlotMetrics: () => getSlotMetrics,
3115
+ listSlotMetrics: () => listSlotMetrics
3116
+ });
3117
+ async function getSlotMetrics(ctx, slot) {
3118
+ const request = create(GetSlotMetricsRequestSchema, { slot });
3119
+ return ctx.query.getSlotMetrics(request, withCallOptions(ctx));
3120
+ }
3121
+ async function listSlotMetrics(ctx, options) {
3122
+ const request = create(ListSlotMetricsRequestSchema, {
3123
+ startSlot: options.startSlot,
3124
+ endSlot: options.endSlot,
3125
+ limit: options.limit
3126
+ });
3127
+ return ctx.query.listSlotMetrics(request, withCallOptions(ctx));
3128
+ }
3129
+
3130
+ // thru-ts-client-sdk/modules/transactions.ts
3131
+ var transactions_exports = {};
3132
+ __export(transactions_exports, {
3133
+ batchSendAndTrack: () => batchSendAndTrack,
3134
+ batchSendTransactions: () => batchSendTransactions,
3135
+ buildAndSignTransaction: () => buildAndSignTransaction,
3136
+ buildTransaction: () => buildTransaction,
3137
+ getRawTransaction: () => getRawTransaction,
3138
+ getTransaction: () => getTransaction,
3139
+ getTransactionStatus: () => getTransactionStatus,
3140
+ listTransactions: () => listTransactions,
3141
+ listTransactionsForAccount: () => listTransactionsForAccount,
3142
+ sendAndTrackTxn: () => sendAndTrackTxn,
3143
+ sendTransaction: () => sendTransaction
3144
+ });
3145
+ async function getTransaction(ctx, signature, options = {}) {
3146
+ const request = create(GetTransactionRequestSchema, {
3147
+ signature: Signature.from(signature).toProtoSignature(),
3148
+ view: options.view ?? DEFAULT_TRANSACTION_VIEW,
3149
+ versionContext: options.versionContext ?? DEFAULT_VERSION_CONTEXT,
3150
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
3151
+ });
3152
+ const proto = await ctx.query.getTransaction(request, withCallOptions(ctx));
3153
+ return Transaction.fromProto(proto);
3154
+ }
3155
+ async function getRawTransaction(ctx, signature, options = {}) {
3156
+ const request = create(GetRawTransactionRequestSchema, {
3157
+ signature: Signature.from(signature).toProtoSignature(),
3158
+ versionContext: options.versionContext ?? DEFAULT_VERSION_CONTEXT,
3159
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
3160
+ });
3161
+ return ctx.query.getRawTransaction(request, withCallOptions(ctx));
3162
+ }
3163
+ async function getTransactionStatus(ctx, signature) {
3164
+ const request = create(GetTransactionStatusRequestSchema, {
3165
+ signature: Signature.from(signature).toProtoSignature()
3166
+ });
3167
+ const proto = await ctx.query.getTransactionStatus(request, withCallOptions(ctx));
3168
+ return TransactionStatusSnapshot.fromProto(proto);
3169
+ }
3170
+ async function listTransactionsForAccount(ctx, account, options = {}) {
3171
+ const request = create(ListTransactionsForAccountRequestSchema, {
3172
+ account: Pubkey.from(account).toProtoPubkey(),
3173
+ filter: options.filter?.toProto(),
3174
+ page: options.page?.toProto()
3175
+ });
3176
+ const response = await ctx.query.listTransactionsForAccount(
3177
+ request,
3178
+ withCallOptions(ctx)
3179
+ );
3180
+ const protoTransactionSignatures = (response.transactions ?? []).map((transaction) => transaction.signature);
3181
+ const transactions = await Promise.all(
3182
+ protoTransactionSignatures.map((signature) => {
3183
+ if (!signature) {
3184
+ throw new Error("ListTransactionsForAccount returned an empty signature");
3185
+ }
3186
+ return getTransaction(ctx, signature.value, options.transactionOptions);
3187
+ })
3188
+ );
3189
+ return {
3190
+ transactions,
3191
+ page: PageResponse.fromProto(response.page)
3192
+ };
3193
+ }
3194
+ async function listTransactions(ctx, options = {}) {
3195
+ const request = create(ListTransactionsRequestSchema, {
3196
+ filter: options.filter?.toProto(),
3197
+ page: options.page?.toProto(),
3198
+ returnEvents: options.returnEvents,
3199
+ versionContext: options.versionContext ?? DEFAULT_VERSION_CONTEXT,
3200
+ minConsensus: options.minConsensus ?? DEFAULT_MIN_CONSENSUS
3201
+ });
3202
+ const response = await ctx.query.listTransactions(
3203
+ request,
3204
+ withCallOptions(ctx)
3205
+ );
3206
+ return {
3207
+ transactions: response.transactions.map((proto) => Transaction.fromProto(proto)),
3208
+ page: PageResponse.fromProto(response.page)
3209
+ };
3210
+ }
3211
+ async function buildTransaction(ctx, options) {
3212
+ const builder = createTransactionBuilder();
3213
+ const params = await createBuildParams(ctx, options);
3214
+ return builder.build(params);
3215
+ }
3216
+ async function buildAndSignTransaction(ctx, options) {
3217
+ const builder = createTransactionBuilder();
3218
+ const params = await createBuildParams(ctx, options);
3219
+ if (!params.feePayer.privateKey) {
3220
+ throw new Error("Fee payer private key is required to sign the transaction");
3221
+ }
3222
+ return builder.buildAndSign(params);
3223
+ }
3224
+ async function sendTransaction(ctx, transaction) {
3225
+ const raw = transaction instanceof Uint8Array ? transaction : transaction.toWire();
3226
+ return sendRawTransaction(ctx, raw);
3227
+ }
3228
+ async function batchSendTransactions(ctx, transactions, options = {}) {
3229
+ const rawTransactions = transactions.map(
3230
+ (tx) => tx instanceof Uint8Array ? tx : tx.toWire()
3231
+ );
3232
+ const request = create(BatchSendTransactionsRequestSchema, {
3233
+ rawTransactions,
3234
+ numRetries: options.numRetries ?? 0
3235
+ });
3236
+ return ctx.command.batchSendTransactions(request, withCallOptions(ctx));
3237
+ }
3238
+ async function batchSendAndTrack(ctx, transactions, options = {}) {
3239
+ const rawTransactions = transactions.map(
3240
+ (tx) => tx instanceof Uint8Array ? tx : tx.toWire()
3241
+ );
3242
+ const signatures = rawTransactions.map(extractSignature);
3243
+ const trackControllers = rawTransactions.map(() => new AbortController());
3244
+ const abortStatuses = rawTransactions.map(() => void 0);
3245
+ const trackPromises = signatures.map(
3246
+ (signature, index) => trackUntilExecution(ctx, signature, {
3247
+ timeoutMs: options.trackTimeoutMs,
3248
+ signal: trackControllers[index].signal,
3249
+ getAbortStatus: () => abortStatuses[index]
3250
+ })
3251
+ );
3252
+ options.signal?.addEventListener(
3253
+ "abort",
3254
+ () => {
3255
+ for (let index = 0; index < trackControllers.length; index += 1) {
3256
+ abortStatuses[index] ?? (abortStatuses[index] = "cancelled");
3257
+ trackControllers[index].abort();
3258
+ }
3259
+ },
3260
+ { once: true }
3261
+ );
3262
+ let response;
3263
+ try {
3264
+ response = await batchSendTransactions(ctx, rawTransactions, {
3265
+ numRetries: options.numRetries ?? 0
3266
+ });
3267
+ } catch (error) {
3268
+ for (const controller of trackControllers) {
3269
+ controller.abort();
3270
+ }
3271
+ await Promise.allSettled(trackPromises);
3272
+ throw error;
3273
+ }
3274
+ const accepted = signatures.map((_, index) => response.accepted[index] === true);
3275
+ for (let index = 0; index < accepted.length; index += 1) {
3276
+ if (!accepted[index]) {
3277
+ abortStatuses[index] = "not_accepted";
3278
+ trackControllers[index].abort();
3279
+ }
3280
+ }
3281
+ const tracked = await Promise.all(trackPromises);
3282
+ return signatures.map((signature, index) => ({
3283
+ signature,
3284
+ accepted: accepted[index],
3285
+ ...tracked[index]
3286
+ }));
3287
+ }
3288
+ function sendAndTrackTxn(ctx, transaction, options = {}) {
3289
+ const raw = transaction instanceof Uint8Array ? transaction : transaction.toWire();
3290
+ const request = create(SendAndTrackTxnRequestSchema, {
3291
+ transaction: raw,
3292
+ timeout: options.timeoutMs != null ? {
3293
+ seconds: BigInt(Math.floor(options.timeoutMs / 1e3)),
3294
+ nanos: options.timeoutMs % 1e3 * 1e6
3295
+ } : void 0
3296
+ });
3297
+ const iterable = ctx.command.sendAndTrackTxn(request, {
3298
+ ...withCallOptions(ctx),
3299
+ signal: options.signal
3300
+ });
3301
+ async function* mapper() {
3302
+ for await (const response of iterable) {
3303
+ yield {
3304
+ status: response.status,
3305
+ signature: response.signature ? { value: response.signature.value } : void 0,
3306
+ consensusStatus: response.consensusStatus,
3307
+ executionResult: response.executionResult ? {
3308
+ vmError: response.executionResult.vmError,
3309
+ consumedComputeUnits: response.executionResult.consumedComputeUnits,
3310
+ userErrorCode: response.executionResult.userErrorCode
3311
+ } : void 0
3312
+ };
3313
+ }
3314
+ }
3315
+ return mapper();
3316
+ }
3317
+ async function sendRawTransaction(ctx, rawTransaction) {
3318
+ const request = create(SendTransactionRequestSchema, { rawTransaction });
3319
+ const response = await ctx.command.sendTransaction(request, withCallOptions(ctx));
3320
+ if (!response.signature?.value) {
3321
+ throw new Error("No signature returned from sendTransaction");
3322
+ }
3323
+ return encodeSignature(response.signature.value);
3324
+ }
3325
+ function extractSignature(rawTransaction) {
3326
+ if (rawTransaction.length < 64) {
3327
+ throw new Error(`Raw transaction too short to contain a signature: ${rawTransaction.length} bytes`);
3328
+ }
3329
+ const signatureBytes = rawTransaction.slice(rawTransaction.length - 64);
3330
+ return Signature.from(signatureBytes).toThruFmt();
3331
+ }
3332
+ async function trackUntilExecution(ctx, signature, options = {}) {
3333
+ let finalizedSeen = false;
3334
+ let latestUpdate;
3335
+ try {
3336
+ for await (const update of trackTransaction(ctx, signature, options)) {
3337
+ latestUpdate = update;
3338
+ if (update.statusCode === 3 /* FINALIZED */ || update.status === "finalized") {
3339
+ finalizedSeen = true;
3340
+ }
3341
+ if (update.executionResult) {
3342
+ return {
3343
+ trackStatus: "executed",
3344
+ update,
3345
+ executionResult: update.executionResult
3346
+ };
3347
+ }
3348
+ }
3349
+ } catch (error) {
3350
+ if (options.signal?.aborted) {
3351
+ return {
3352
+ trackStatus: options.getAbortStatus?.() ?? "cancelled",
3353
+ error
3354
+ };
3355
+ }
3356
+ if (finalizedSeen) {
3357
+ return {
3358
+ trackStatus: "finalized_without_execution",
3359
+ update: latestUpdate,
3360
+ error
3361
+ };
3362
+ }
3363
+ return {
3364
+ trackStatus: "track_error",
3365
+ update: latestUpdate,
3366
+ error
3367
+ };
3368
+ }
3369
+ if (finalizedSeen) {
3370
+ return {
3371
+ trackStatus: "finalized_without_execution",
3372
+ update: latestUpdate
3373
+ };
3374
+ }
3375
+ return {
3376
+ trackStatus: "timeout",
3377
+ update: latestUpdate
3378
+ };
3379
+ }
3380
+ function createTransactionBuilder() {
3381
+ return new TransactionBuilder();
3382
+ }
3383
+ async function createBuildParams(ctx, options) {
3384
+ const feePayerPublicKey = Pubkey.from(options.feePayer.publicKey).toBytes();
3385
+ const program = Pubkey.from(options.program).toBytes();
3386
+ const header = await createTransactionHeader(ctx, options.header ?? {}, feePayerPublicKey);
3387
+ const accounts = parseAccounts(options.accounts);
3388
+ const context = createInstructionContext2(feePayerPublicKey, program, accounts);
3389
+ const instructionData = await resolveInstructionData(options.instructionData, context);
3390
+ const proofs = createProofs(options);
3391
+ return {
3392
+ feePayer: {
3393
+ publicKey: feePayerPublicKey,
3394
+ privateKey: options.feePayer.privateKey
3395
+ },
3396
+ program: Pubkey.from(options.program).toBytes(),
3397
+ header,
3398
+ accounts,
3399
+ instructionData,
3400
+ proofs
3401
+ };
3402
+ }
3403
+ async function createTransactionHeader(ctx, header, feePayerPublicKey) {
3404
+ const nonce = header.nonce ?? await fetchFeePayerNonce(ctx, feePayerPublicKey);
3405
+ const startSlot = header.startSlot ?? await fetchFinalizedSlot(ctx);
3406
+ const chainId = header.chainId ?? await fetchChainId(ctx);
3407
+ return {
3408
+ fee: header.fee ?? DEFAULT_FEE,
3409
+ nonce,
3410
+ startSlot,
3411
+ expiryAfter: header.expiryAfter ?? DEFAULT_EXPIRY_AFTER,
3412
+ chainId,
3413
+ computeUnits: header.computeUnits ?? DEFAULT_COMPUTE_UNITS,
3414
+ stateUnits: header.stateUnits ?? DEFAULT_STATE_UNITS,
3415
+ memoryUnits: header.memoryUnits ?? DEFAULT_MEMORY_UNITS,
3416
+ flags: header.flags
3417
+ };
3418
+ }
3419
+ function parseAccounts(accounts) {
3420
+ if (!accounts) {
3421
+ return void 0;
3422
+ }
3423
+ const readWrite = accounts.readWrite?.map(
3424
+ (value, index) => Pubkey.from(value).toBytes()
3425
+ );
3426
+ const readOnly = accounts.readOnly?.map(
3427
+ (value, index) => Pubkey.from(value).toBytes()
3428
+ );
3429
+ const result = {};
3430
+ if (readWrite && readWrite.length > 0) {
3431
+ result.readWriteAccounts = normalizeAccountList(readWrite);
3432
+ }
3433
+ if (readOnly && readOnly.length > 0) {
3434
+ result.readOnlyAccounts = normalizeAccountList(readOnly);
3435
+ }
3436
+ if (!result.readWriteAccounts && !result.readOnlyAccounts) {
3437
+ return void 0;
3438
+ }
3439
+ return result;
3440
+ }
3441
+ function createInstructionContext2(feePayer, program, accounts) {
3442
+ const allAccounts = [
3443
+ Pubkey.from(feePayer),
3444
+ Pubkey.from(program),
3445
+ ...accounts?.readWriteAccounts?.map((value) => Pubkey.from(value)) ?? [],
3446
+ ...accounts?.readOnlyAccounts?.map((value) => Pubkey.from(value)) ?? []
3447
+ ];
3448
+ const getAccountIndex = (pubkey) => {
3449
+ for (let i = 0; i < allAccounts.length; i++) {
3450
+ if (allAccounts[i].equals(Pubkey.from(pubkey))) {
3451
+ return i;
3452
+ }
3453
+ }
3454
+ throw new Error("Account not found in transaction accounts");
3455
+ };
3456
+ return { accounts: allAccounts, getAccountIndex };
3457
+ }
3458
+ async function resolveInstructionData(value, context) {
3459
+ if (value === void 0) {
3460
+ return void 0;
3461
+ }
3462
+ if (typeof value === "function") {
3463
+ return await value(context);
3464
+ }
3465
+ if (value instanceof Uint8Array) {
3466
+ return value;
3467
+ }
3468
+ return parseInstructionData(value);
3469
+ }
3470
+ function createProofs(options) {
3471
+ const proofs = {};
3472
+ if (options.feePayerStateProof) {
3473
+ proofs.feePayerStateProof = options.feePayerStateProof;
3474
+ }
3475
+ if (options.feePayerAccountMetaRaw) {
3476
+ proofs.feePayerAccountMetaRaw = options.feePayerAccountMetaRaw;
3477
+ }
3478
+ const hasProofs = Boolean(proofs.feePayerStateProof || proofs.feePayerAccountMetaRaw);
3479
+ return hasProofs ? proofs : void 0;
3480
+ }
3481
+ async function fetchFeePayerNonce(ctx, feePayer) {
3482
+ const account = await getAccount(ctx, feePayer, { view: 4 /* FULL */ });
3483
+ const nonce = account.meta?.nonce;
3484
+ if (nonce === void 0) {
3485
+ throw new Error("Fee payer account nonce is unavailable");
3486
+ }
3487
+ return nonce;
3488
+ }
3489
+ async function fetchFinalizedSlot(ctx) {
3490
+ const height = await getBlockHeight(ctx);
3491
+ return height.finalized;
3492
+ }
3493
+ async function fetchChainId(ctx) {
3494
+ return getChainId(ctx);
3495
+ }
3496
+
3497
+ // thru-ts-client-sdk/domain/version/VersionInfo.ts
3498
+ var VersionInfo = class _VersionInfo {
3499
+ constructor(components) {
3500
+ this.components = { ...components };
3501
+ }
3502
+ static fromProto(proto) {
3503
+ return new _VersionInfo(proto.versions ?? {});
3504
+ }
3505
+ get(component) {
3506
+ return this.components[component];
3507
+ }
3508
+ };
3509
+
3510
+ // thru-ts-client-sdk/modules/version.ts
3511
+ function getVersion(ctx) {
3512
+ const request = create(GetVersionRequestSchema);
3513
+ return ctx.query.getVersion(request, withCallOptions(ctx)).then((response) => VersionInfo.fromProto(response));
3514
+ }
3515
+
3516
+ // thru-ts-client-sdk/core/bound-client.ts
3517
+ function bind(ctx, fn) {
3518
+ return ((...args) => fn(ctx, ...args));
3519
+ }
3520
+ function createBoundThruClient(ctx) {
3521
+ return {
3522
+ ctx,
3523
+ blocks: {
3524
+ get: bind(ctx, getBlock),
3525
+ getRaw: bind(ctx, getRawBlock),
3526
+ list: bind(ctx, listBlocks),
3527
+ stream: bind(ctx, streamBlocks),
3528
+ getBlockHeight: bind(ctx, getBlockHeight),
3529
+ streamHeight: bind(ctx, streamHeight)
3530
+ },
3531
+ accounts: {
3532
+ get: bind(ctx, getAccount),
3533
+ getRaw: bind(ctx, getRawAccount),
3534
+ list: bind(ctx, listAccounts),
3535
+ stream: bind(ctx, streamAccountUpdates),
3536
+ create: bind(ctx, createAccount)
3537
+ },
3538
+ transactions: {
3539
+ get: bind(ctx, getTransaction),
3540
+ getRaw: bind(ctx, getRawTransaction),
3541
+ getStatus: bind(ctx, getTransactionStatus),
3542
+ list: bind(ctx, listTransactions),
3543
+ listForAccount: bind(ctx, listTransactionsForAccount),
3544
+ stream: bind(ctx, streamTransactions),
3545
+ build: bind(ctx, buildTransaction),
3546
+ buildAndSign: bind(ctx, buildAndSignTransaction),
3547
+ send: bind(ctx, sendTransaction),
3548
+ batchSend: bind(ctx, batchSendTransactions),
3549
+ batchSendAndTrack: bind(ctx, batchSendAndTrack),
3550
+ sendAndTrack: bind(ctx, sendAndTrackTxn),
3551
+ track: bind(ctx, trackTransaction)
3552
+ },
3553
+ nonce: {
3554
+ createObserver: (account, options) => new AccountNonceObserver(ctx, account, options),
3555
+ createFeePayerManager: (feePayer, options) => new FeePayerNonceManager(ctx, feePayer, options)
3556
+ },
3557
+ helpers: {
3558
+ createSignature: Signature.from,
3559
+ createPubkey: Pubkey.from,
3560
+ deriveProgramAddress,
3561
+ deriveAddress
3562
+ },
3563
+ keys: {
3564
+ generateKeyPair,
3565
+ fromPrivateKey
3566
+ },
3567
+ events: {
3568
+ get: bind(ctx, getEvent),
3569
+ list: bind(ctx, listEvents),
3570
+ stream: bind(ctx, streamEvents)
3571
+ },
3572
+ slots: {
3573
+ getMetrics: bind(ctx, getSlotMetrics),
3574
+ listMetrics: bind(ctx, listSlotMetrics),
3575
+ streamMetrics: bind(ctx, streamSlotMetrics)
3576
+ },
3577
+ proofs: {
3578
+ generate: bind(ctx, generateStateProof),
3579
+ getStateRoots: bind(ctx, getStateRoots)
3580
+ },
3581
+ node: {
3582
+ getStatus: bind(ctx, getNodeStatus),
3583
+ getPubkey: bind(ctx, getNodePubkey),
3584
+ getRecords: bind(ctx, getNodeRecords),
3585
+ streamRecords: bind(ctx, streamNodeRecords)
3586
+ },
3587
+ chain: {
3588
+ getChainInfo: bind(ctx, getChainInfo),
3589
+ getChainId: bind(ctx, getChainId)
3590
+ },
3591
+ version: {
3592
+ get: bind(ctx, getVersion)
3593
+ },
3594
+ consensus: {
3595
+ statusToString: consensusStatusToString,
3596
+ versionContext,
3597
+ currentVersionContext,
3598
+ currentOrHistoricalVersionContext,
3599
+ slotVersionContext,
3600
+ timestampVersionContext,
3601
+ seqVersionContext
3602
+ }
3603
+ };
3604
+ }
3605
+
3606
+ // thru-ts-client-sdk/client.ts
3607
+ function createThruClient(config = {}) {
3608
+ const ctx = createThruClientContext(config);
3609
+ return createBoundThruClient(ctx);
3610
+ }
3611
+
3612
+ export { Account, AccountNonceObserver, Block, ChainEvent, FeePayerNonceManager, Filter, FilterParamValue, HeightSnapshot, PageRequest, PageResponse, Pubkey, Signature, SignatureDomain, StateProof, Transaction, TransactionBuilder, TransactionStatusSnapshot, VersionInfo, accounts_exports, blocks_exports, chain_exports, collectStream, consensus_exports, createThruClient, deriveAddress, deriveProgramAddress, events_exports, firstStreamValue, forEachStreamValue, height_exports, keys_exports, node_exports, nonce_exports, proofs_exports, signWithDomain, slots_exports, streaming_exports, transactions_exports, verifyWithDomain };
3613
+ //# sourceMappingURL=chunk-CVBQ4UPL.js.map
3614
+ //# sourceMappingURL=chunk-CVBQ4UPL.js.map