@thru/thru-sdk 0.1.36 → 0.2.0

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.
@@ -54,6 +54,7 @@ interface TransactionHeaderInput extends ResourceLimits {
54
54
  nonce: bigint;
55
55
  startSlot: bigint;
56
56
  expiryAfter?: number;
57
+ chainId?: number;
57
58
  flags?: number;
58
59
  }
59
60
  interface TransactionAccountsInput {
@@ -75,12 +76,37 @@ interface FeePayerInput {
75
76
  publicKey: PubkeyInput;
76
77
  privateKey?: Uint8Array;
77
78
  }
79
+ /**
80
+ * Function that builds instruction data with access to the final account ordering.
81
+ * Use this when your instruction data contains account indices.
82
+ */
83
+ type InstructionDataBuilder = (context: InstructionContext) => Uint8Array | string;
78
84
  interface BuildTransactionParams {
79
85
  feePayer: FeePayerInput;
80
86
  program: PubkeyInput;
81
87
  header: TransactionHeaderInput;
82
88
  accounts?: TransactionAccountsInput;
89
+ /**
90
+ * Static instruction data. Use this when your instruction data does not
91
+ * contain account indices, or when you've pre-computed the indices.
92
+ */
83
93
  instructionData?: Uint8Array | string;
94
+ /**
95
+ * Builder function that receives the final account ordering.
96
+ * Use this when your instruction data contains account indices to ensure
97
+ * they match the post-sort transaction layout.
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * buildInstructionData: ({ getAccountIndex }) => {
102
+ * return buildMyInstruction(
103
+ * getAccountIndex(configAddress),
104
+ * getAccountIndex(trancheAddress),
105
+ * );
106
+ * }
107
+ * ```
108
+ */
109
+ buildInstructionData?: InstructionDataBuilder;
84
110
  proofs?: OptionalProofs;
85
111
  }
86
112
  interface BuiltTransactionResult {
@@ -123,6 +149,7 @@ declare class Transaction {
123
149
  readonly nonce: bigint;
124
150
  readonly startSlot: bigint;
125
151
  readonly expiryAfter: number;
152
+ readonly chainId: number;
126
153
  readonly requestedComputeUnits: number;
127
154
  readonly requestedStateUnits: number;
128
155
  readonly requestedMemoryUnits: number;
@@ -469,6 +496,7 @@ interface BlockHeaderParams {
469
496
  bondAmountLockUp?: bigint;
470
497
  weightSlot?: bigint;
471
498
  blockHash?: Uint8Array;
499
+ chainId?: number;
472
500
  }
473
501
  declare class BlockHeader {
474
502
  readonly slot: bigint;
@@ -484,6 +512,7 @@ declare class BlockHeader {
484
512
  readonly bondAmountLockUp?: bigint;
485
513
  readonly weightSlot?: bigint;
486
514
  readonly blockHash?: Uint8Array;
515
+ readonly chainId?: number;
487
516
  constructor(params: BlockHeaderParams);
488
517
  static fromProto(proto: BlockHeader$1): BlockHeader;
489
518
  withBlockHash(blockHash: Uint8Array): BlockHeader;
@@ -832,6 +861,7 @@ interface TransactionHeaderConfig {
832
861
  nonce?: bigint;
833
862
  startSlot?: bigint;
834
863
  expiryAfter?: number;
864
+ chainId?: number;
835
865
  computeUnits?: number;
836
866
  stateUnits?: number;
837
867
  memoryUnits?: number;
@@ -927,4 +957,4 @@ declare class VersionInfo {
927
957
  get(component: string): string | undefined;
928
958
  }
929
959
 
930
- export { type StreamAccountUpdatesResult as $, Account as A, type BuildTransactionParams as B, ChainEvent as C, type AccountQueryOptions as D, type CreateAccountOptions as E, Filter as F, type BlockList as G, HeightSnapshot as H, type BlockQueryOptions as I, type ListBlocksOptions as J, type RawBlockQueryOptions as K, type ListAccountsOptions as L, type GetEventOptions as M, type BlockSelector as N, type DeriveAddressInput as O, PageRequest as P, type DeriveAddressResult as Q, type RawAccountQueryOptions as R, type SignedTransactionResult as S, Transaction as T, type DeriveProgramAddressOptions as U, VersionInfo as V, type DeriveProgramAddressResult as W, type GeneratedKeyPair as X, type StreamAccountUpdate as Y, type HeightSnapshotParams as Z, type StreamAccountUpdatesOptions as _, accounts as a, type StreamBlocksOptions as a0, type StreamBlocksResult as a1, type StreamEventsOptions as a2, type StreamEventsResult as a3, type StreamTransactionsOptions as a4, type StreamTransactionsResult as a5, type StreamTransactionUpdate as a6, type TrackTransactionOptions as a7, type TrackTransactionUpdate as a8, type TransactionExecutionEvent as a9, getTransaction as aA, getRawTransaction as aB, getTransactionStatus as aC, listTransactions as aD, listTransactionsForAccount as aE, streamTransactions as aF, buildTransaction as aG, buildAndSignTransaction as aH, sendTransaction as aI, batchSendTransactions as aJ, trackTransaction as aK, getEvent as aL, listEvents as aM, streamEvents as aN, generateStateProof as aO, generateKeyPair as aP, fromPrivateKey as aQ, consensusStatusToString as aR, versionContext as aS, currentVersionContext as aT, currentOrHistoricalVersionContext as aU, slotVersionContext as aV, timestampVersionContext as aW, seqVersionContext as aX, type ThruClientConfig as aY, type TransactionExecutionResultData as aa, type InstructionContext as ab, type BatchSendTransactionsOptions as ac, type BuildAndSignTransactionOptions as ad, type BuildTransactionOptions as ae, type InstructionData as af, type ListTransactionsForAccountOptions as ag, type RawTransactionQueryOptions as ah, type TransactionAccountsConfig as ai, type TransactionFeePayerConfig as aj, type TransactionHeaderConfig as ak, type TransactionList as al, type TransactionQueryOptions as am, type GenerateStateProofOptions as an, type ThruClientContext as ao, getBlock as ap, getRawBlock as aq, listBlocks as ar, streamBlocks as as, getBlockHeight as at, streamHeight as au, getAccount as av, getRawAccount as aw, listAccounts as ax, streamAccountUpdates as ay, createAccount as az, blocks as b, consensus as c, Block as d, events as e, FilterParamValue as f, PageResponse as g, height as h, Pubkey as i, Signature as j, keys as k, StateProof as l, TransactionStatusSnapshot as m, deriveAddress as n, deriveProgramAddress as o, proofs as p, collectStream as q, firstStreamValue as r, streaming as s, transactions as t, forEachStreamValue as u, type PageRequestParams as v, type PageResponseParams as w, type PubkeyInput as x, type SignatureInput as y, type VersionContextInput as z };
960
+ export { type StreamAccountUpdatesOptions as $, Account as A, type BuildTransactionParams as B, ChainEvent as C, type VersionContextInput as D, type AccountQueryOptions as E, Filter as F, type CreateAccountOptions as G, HeightSnapshot as H, type BlockList as I, type BlockQueryOptions as J, type ListBlocksOptions as K, type ListAccountsOptions as L, type RawBlockQueryOptions as M, type GetEventOptions as N, type BlockSelector as O, PageRequest as P, type DeriveAddressInput as Q, type RawAccountQueryOptions as R, type SignedTransactionResult as S, Transaction as T, type DeriveAddressResult as U, VersionInfo as V, type DeriveProgramAddressOptions as W, type DeriveProgramAddressResult as X, type GeneratedKeyPair as Y, type StreamAccountUpdate as Z, type HeightSnapshotParams as _, type ThruClientContext as a, type StreamAccountUpdatesResult as a0, type StreamBlocksOptions as a1, type StreamBlocksResult as a2, type StreamEventsOptions as a3, type StreamEventsResult as a4, type StreamTransactionsOptions as a5, type StreamTransactionsResult as a6, type StreamTransactionUpdate as a7, type TrackTransactionOptions as a8, type TrackTransactionUpdate as a9, getTransaction as aA, getRawTransaction as aB, getTransactionStatus as aC, listTransactions as aD, listTransactionsForAccount as aE, streamTransactions as aF, buildTransaction as aG, buildAndSignTransaction as aH, sendTransaction as aI, batchSendTransactions as aJ, trackTransaction as aK, getEvent as aL, listEvents as aM, streamEvents as aN, generateStateProof as aO, generateKeyPair as aP, fromPrivateKey as aQ, consensusStatusToString as aR, versionContext as aS, currentVersionContext as aT, currentOrHistoricalVersionContext as aU, slotVersionContext as aV, timestampVersionContext as aW, seqVersionContext as aX, type ThruClientConfig as aY, type TransactionExecutionEvent as aa, type TransactionExecutionResultData as ab, type InstructionContext as ac, type BatchSendTransactionsOptions as ad, type BuildAndSignTransactionOptions as ae, type BuildTransactionOptions as af, type InstructionData as ag, type ListTransactionsForAccountOptions as ah, type RawTransactionQueryOptions as ai, type TransactionAccountsConfig as aj, type TransactionFeePayerConfig as ak, type TransactionHeaderConfig as al, type TransactionList as am, type TransactionQueryOptions as an, type GenerateStateProofOptions as ao, getBlock as ap, getRawBlock as aq, listBlocks as ar, streamBlocks as as, getBlockHeight as at, streamHeight as au, getAccount as av, getRawAccount as aw, listAccounts as ax, streamAccountUpdates as ay, createAccount as az, accounts as b, blocks as c, consensus as d, events as e, Block as f, FilterParamValue as g, height as h, PageResponse as i, Pubkey as j, keys as k, Signature as l, StateProof as m, TransactionStatusSnapshot as n, deriveAddress as o, proofs as p, deriveProgramAddress as q, collectStream as r, streaming as s, transactions as t, firstStreamValue as u, forEachStreamValue as v, type PageRequestParams as w, type PageResponseParams as x, type PubkeyInput as y, type SignatureInput as z };
@@ -1,7 +1,7 @@
1
1
  import { utils, etc, Point, CURVE, getPublicKeyAsync } from '@noble/ed25519';
2
2
  import { create } from '@bufbuild/protobuf';
3
3
  import { encodeAddress, decodeAddress, isHexString, hexToBytes, encodeSignature, decodeSignature, ensureBytes } from '@thru/helpers';
4
- import { AccountView, BlockView, TransactionView, ConsensusStatus, VersionContextSchema, CurrentVersionSchema, PubkeySchema, TaPubkeySchema, SignatureSchema, TsSignatureSchema, TransactionVmError, StreamingService, CommandService, QueryService, PageRequestSchema, PageResponseSchema, StateProofRequestSchema, GenerateStateProofRequestSchema, GetAccountRequestSchema, GetRawAccountRequestSchema, ListAccountsRequestSchema, StateProofType, ExecutionStatus, GetBlockRequestSchema, GetRawBlockRequestSchema, ListBlocksRequestSchema, CurrentOrHistoricalVersionSchema, GetEventRequestSchema, ListEventsRequestSchema, GetHeightRequestSchema, FilterParamValueSchema, FilterSchema, StreamBlocksRequestSchema, StreamAccountUpdatesRequestSchema, StreamTransactionsRequestSchema, StreamEventsRequestSchema, TrackTransactionRequestSchema, StreamHeightRequestSchema, GetTransactionRequestSchema, GetRawTransactionRequestSchema, GetTransactionStatusRequestSchema, ListTransactionsForAccountRequestSchema, ListTransactionsRequestSchema, BatchSendTransactionsRequestSchema, SendTransactionRequestSchema, BlockHashSchema } from '@thru/proto';
4
+ import { AccountView, BlockView, TransactionView, ConsensusStatus, VersionContextSchema, CurrentVersionSchema, PubkeySchema, TaPubkeySchema, SignatureSchema, TsSignatureSchema, TransactionVmError, StreamingService, CommandService, QueryService, PageRequestSchema, PageResponseSchema, StateProofRequestSchema, GenerateStateProofRequestSchema, GetAccountRequestSchema, GetRawAccountRequestSchema, ListAccountsRequestSchema, StateProofType, ExecutionStatus, GetBlockRequestSchema, GetRawBlockRequestSchema, ListBlocksRequestSchema, GetChainInfoRequestSchema, CurrentOrHistoricalVersionSchema, GetEventRequestSchema, ListEventsRequestSchema, GetHeightRequestSchema, FilterParamValueSchema, FilterSchema, StreamBlocksRequestSchema, StreamAccountUpdatesRequestSchema, StreamTransactionsRequestSchema, StreamEventsRequestSchema, TrackTransactionRequestSchema, StreamHeightRequestSchema, GetTransactionRequestSchema, GetRawTransactionRequestSchema, GetTransactionStatusRequestSchema, ListTransactionsForAccountRequestSchema, ListTransactionsRequestSchema, BatchSendTransactionsRequestSchema, SendTransactionRequestSchema, BlockHashSchema } from '@thru/proto';
5
5
  import { createClient } from '@connectrpc/connect';
6
6
  import { createGrpcWebTransport } from '@connectrpc/connect-web';
7
7
  import { sha256 } from '@noble/hashes/sha2';
@@ -298,7 +298,7 @@ var HASH_SIZE = 32;
298
298
  var BLOCK_HEADER_SIZE = 168;
299
299
  var BLOCK_FOOTER_SIZE = 104;
300
300
  var BLOCK_VERSION_V1 = 1;
301
- var TXN_HEADER_SIZE = 176;
301
+ var TXN_HEADER_SIZE = 112;
302
302
  var TXN_VERSION_V1 = 1;
303
303
  var TXN_MAX_ACCOUNTS = 1024;
304
304
  var STATE_PROOF_HEADER_SIZE = 40;
@@ -310,7 +310,6 @@ var STATE_PROOF_TYPE_CREATION = 2;
310
310
 
311
311
  // thru-ts-client-sdk/domain/transactions/Transaction.ts
312
312
  var DEFAULT_FLAGS = 0;
313
- var SIGNATURE_PREFIX_SIZE = SIGNATURE_SIZE2;
314
313
  var MAX_INSTRUCTION_DATA_LENGTH = 65535;
315
314
  var BYTE_POPCOUNT = new Uint8Array(256).map((_value, index) => {
316
315
  let v = index;
@@ -330,6 +329,7 @@ var Transaction = class _Transaction {
330
329
  this.nonce = params.header.nonce;
331
330
  this.startSlot = params.header.startSlot;
332
331
  this.expiryAfter = params.header.expiryAfter ?? 0;
332
+ this.chainId = params.header.chainId ?? 1;
333
333
  this.requestedComputeUnits = params.header.computeUnits ?? 0;
334
334
  this.requestedStateUnits = params.header.stateUnits ?? 0;
335
335
  this.requestedMemoryUnits = params.header.memoryUnits ?? 0;
@@ -354,15 +354,12 @@ var Transaction = class _Transaction {
354
354
  return transaction;
355
355
  }
356
356
  static parseWire(data, options = {}) {
357
- if (data.length < TXN_HEADER_SIZE) {
358
- throw new Error(`Transaction data too short: ${data.length} bytes (expected at least ${TXN_HEADER_SIZE})`);
357
+ if (data.length < TXN_HEADER_SIZE + SIGNATURE_SIZE2) {
358
+ throw new Error(`Transaction data too short: ${data.length} bytes (expected at least ${TXN_HEADER_SIZE + SIGNATURE_SIZE2})`);
359
359
  }
360
360
  const strict = options.strict ?? false;
361
361
  const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
362
362
  let offset = 0;
363
- const signatureBytes = data.slice(offset, offset + SIGNATURE_SIZE2);
364
- const hasSignature = hasNonZeroBytes(signatureBytes);
365
- offset += SIGNATURE_SIZE2;
366
363
  const version = view.getUint8(offset);
367
364
  offset += 1;
368
365
  if (strict && version !== TXN_VERSION_V1) {
@@ -394,7 +391,9 @@ var Transaction = class _Transaction {
394
391
  offset += 8;
395
392
  const expiryAfter = view.getUint32(offset, true);
396
393
  offset += 4;
397
- offset += 4;
394
+ const chainId = view.getUint16(offset, true);
395
+ offset += 2;
396
+ offset += 2;
398
397
  _Transaction.ensureAvailable(data.length, offset, PUBKEY_SIZE2, "fee payer account");
399
398
  const feePayer = data.slice(offset, offset + PUBKEY_SIZE2);
400
399
  offset += PUBKEY_SIZE2;
@@ -410,36 +409,63 @@ var Transaction = class _Transaction {
410
409
  `Transaction references ${totalAccountCount} accounts (maximum allowed ${TXN_MAX_ACCOUNTS})`
411
410
  );
412
411
  }
412
+ const accountsSize = totalAccountCount * PUBKEY_SIZE2;
413
+ let expectedBodySize = accountsSize + instructionDataSize;
414
+ if ((flags & TXN_FLAG_HAS_FEE_PAYER_PROOF) !== 0) {
415
+ const proofOffset = TXN_HEADER_SIZE + accountsSize + instructionDataSize;
416
+ _Transaction.ensureAvailable(data.length, proofOffset, STATE_PROOF_HEADER_SIZE, "state proof header");
417
+ const proofView = new DataView(data.buffer, data.byteOffset + proofOffset, STATE_PROOF_HEADER_SIZE);
418
+ const typeSlot = proofView.getBigUint64(0, true);
419
+ const proofType = Number(typeSlot >> 62n & 0x3n);
420
+ const pathBitset = data.subarray(proofOffset + 8, proofOffset + 40);
421
+ const siblingCount = countSetBits(pathBitset);
422
+ const bodyCount = proofType + siblingCount;
423
+ const proofFootprint = STATE_PROOF_HEADER_SIZE + bodyCount * HASH_SIZE;
424
+ expectedBodySize += proofFootprint;
425
+ if (proofType === STATE_PROOF_TYPE_EXISTING) {
426
+ expectedBodySize += ACCOUNT_META_FOOTPRINT;
427
+ }
428
+ }
429
+ const txnSize = TXN_HEADER_SIZE + expectedBodySize + SIGNATURE_SIZE2;
430
+ _Transaction.ensureAvailable(data.length, 0, txnSize, "full transaction");
431
+ const sigStart = TXN_HEADER_SIZE + expectedBodySize;
413
432
  const readWriteAccounts = [];
414
433
  for (let i = 0; i < readwriteAccountsCount; i++) {
415
- _Transaction.ensureAvailable(data.length, offset, PUBKEY_SIZE2, "read-write accounts");
434
+ _Transaction.ensureAvailable(sigStart, offset, PUBKEY_SIZE2, "read-write accounts");
416
435
  readWriteAccounts.push(data.slice(offset, offset + PUBKEY_SIZE2));
417
436
  offset += PUBKEY_SIZE2;
418
437
  }
419
438
  const readOnlyAccounts = [];
420
439
  for (let i = 0; i < readonlyAccountsCount; i++) {
421
- _Transaction.ensureAvailable(data.length, offset, PUBKEY_SIZE2, "read-only accounts");
440
+ _Transaction.ensureAvailable(sigStart, offset, PUBKEY_SIZE2, "read-only accounts");
422
441
  readOnlyAccounts.push(data.slice(offset, offset + PUBKEY_SIZE2));
423
442
  offset += PUBKEY_SIZE2;
424
443
  }
425
444
  let instructionData;
426
445
  if (instructionDataSize > 0) {
427
- _Transaction.ensureAvailable(data.length, offset, instructionDataSize, "instruction data");
446
+ _Transaction.ensureAvailable(sigStart, offset, instructionDataSize, "instruction data");
428
447
  instructionData = data.slice(offset, offset + instructionDataSize);
429
448
  offset += instructionDataSize;
430
449
  }
431
450
  let feePayerStateProof;
432
451
  let feePayerAccountMetaRaw;
433
452
  if ((flags & TXN_FLAG_HAS_FEE_PAYER_PROOF) !== 0) {
434
- const { proofBytes, footprint, proofType } = _Transaction.parseStateProof(data.subarray(offset));
453
+ const { proofBytes, footprint, proofType } = _Transaction.parseStateProof(data.subarray(offset, sigStart));
435
454
  feePayerStateProof = proofBytes;
436
455
  offset += footprint;
437
456
  if (proofType === STATE_PROOF_TYPE_EXISTING) {
438
- _Transaction.ensureAvailable(data.length, offset, ACCOUNT_META_FOOTPRINT, "fee payer account metadata");
457
+ _Transaction.ensureAvailable(sigStart, offset, ACCOUNT_META_FOOTPRINT, "fee payer account metadata");
439
458
  feePayerAccountMetaRaw = data.slice(offset, offset + ACCOUNT_META_FOOTPRINT);
440
459
  offset += ACCOUNT_META_FOOTPRINT;
441
460
  }
442
461
  }
462
+ if (offset !== sigStart) {
463
+ throw new Error(
464
+ `Transaction body has trailing bytes: expected ${offset + SIGNATURE_SIZE2} bytes but found ${txnSize}`
465
+ );
466
+ }
467
+ const signatureBytes = data.slice(sigStart, sigStart + SIGNATURE_SIZE2);
468
+ const hasSignature = hasNonZeroBytes(signatureBytes);
443
469
  const transaction = new _Transaction({
444
470
  version,
445
471
  feePayer: Pubkey.from(feePayer),
@@ -449,6 +475,7 @@ var Transaction = class _Transaction {
449
475
  nonce,
450
476
  startSlot,
451
477
  expiryAfter,
478
+ chainId,
452
479
  computeUnits: requestedComputeUnits,
453
480
  stateUnits: requestedStateUnits,
454
481
  memoryUnits: requestedMemoryUnits,
@@ -468,7 +495,7 @@ var Transaction = class _Transaction {
468
495
  if (hasSignature) {
469
496
  transaction.setSignature(Signature.from(signatureBytes));
470
497
  }
471
- return { transaction, size: offset };
498
+ return { transaction, size: offset + SIGNATURE_SIZE2 };
472
499
  }
473
500
  static fromProto(proto) {
474
501
  if (!proto.header) {
@@ -528,6 +555,7 @@ var Transaction = class _Transaction {
528
555
  nonce: header.nonce ?? 0n,
529
556
  startSlot: header.startSlot ?? 0n,
530
557
  expiryAfter: header.expiryAfter ?? 0,
558
+ chainId: header.chainId ?? 1,
531
559
  computeUnits: header.requestedComputeUnits ?? 0,
532
560
  stateUnits: header.requestedStateUnits ?? 0,
533
561
  memoryUnits: header.requestedMemoryUnits ?? 0,
@@ -585,27 +613,18 @@ var Transaction = class _Transaction {
585
613
  return this.signature;
586
614
  }
587
615
  toWireForSigning() {
588
- const header = this.createHeader(void 0);
589
- const view = new Uint8Array(header);
590
- return this.buildWirePayload(view.subarray(SIGNATURE_PREFIX_SIZE));
616
+ const header = this.createHeader();
617
+ return this.buildWirePayload(new Uint8Array(header), false);
591
618
  }
592
619
  toWire() {
593
- const header = this.createHeader(this.signature?.toBytes());
594
- return this.buildWirePayload(new Uint8Array(header));
620
+ const header = this.createHeader();
621
+ return this.buildWirePayload(new Uint8Array(header), true);
595
622
  }
596
- createHeader(signature) {
623
+ createHeader() {
597
624
  const buffer = new ArrayBuffer(TXN_HEADER_SIZE);
598
625
  const headerBytes = new Uint8Array(buffer);
599
626
  const view = new DataView(buffer);
600
- if (signature) {
601
- if (signature.length !== SIGNATURE_SIZE2) {
602
- throw new Error(`Signature must contain ${SIGNATURE_SIZE2} bytes`);
603
- }
604
- headerBytes.set(signature, 0);
605
- } else {
606
- headerBytes.fill(0, 0, SIGNATURE_SIZE2);
607
- }
608
- let offset = SIGNATURE_PREFIX_SIZE;
627
+ let offset = 0;
609
628
  view.setUint8(offset, this.version & 255);
610
629
  offset += 1;
611
630
  view.setUint8(offset, this.flags & 255);
@@ -634,17 +653,20 @@ var Transaction = class _Transaction {
634
653
  offset += 8;
635
654
  view.setUint32(offset, ensureUint32(this.expiryAfter), true);
636
655
  offset += 4;
637
- offset += 4;
656
+ view.setUint16(offset, ensureUint16(this.chainId), true);
657
+ offset += 2;
658
+ offset += 2;
638
659
  headerBytes.set(this.feePayer.toBytes(), offset);
639
660
  offset += PUBKEY_SIZE2;
640
661
  headerBytes.set(this.program.toBytes(), offset);
641
662
  return buffer;
642
663
  }
643
- buildWirePayload(headerPrefix) {
664
+ buildWirePayload(headerBytes, includeSignature) {
644
665
  const dynamicLength = this.readWriteAccounts.length * PUBKEY_SIZE2 + this.readOnlyAccounts.length * PUBKEY_SIZE2 + (this.instructionData?.length ?? 0) + (this.feePayerStateProof?.length ?? 0) + (this.feePayerAccountMetaRaw?.length ?? 0);
645
- const result = new Uint8Array(headerPrefix.length + dynamicLength);
646
- result.set(headerPrefix, 0);
647
- let offset = headerPrefix.length;
666
+ const signatureLength = includeSignature ? SIGNATURE_SIZE2 : 0;
667
+ const result = new Uint8Array(headerBytes.length + dynamicLength + signatureLength);
668
+ result.set(headerBytes, 0);
669
+ let offset = headerBytes.length;
648
670
  offset = appendAccountList(result, offset, this.readWriteAccounts.map((account) => account.toBytes()));
649
671
  offset = appendAccountList(result, offset, this.readOnlyAccounts.map((account) => account.toBytes()));
650
672
  if (this.instructionData) {
@@ -659,6 +681,11 @@ var Transaction = class _Transaction {
659
681
  result.set(this.feePayerAccountMetaRaw, offset);
660
682
  offset += this.feePayerAccountMetaRaw.length;
661
683
  }
684
+ if (includeSignature) {
685
+ if (this.signature) {
686
+ result.set(this.signature.toBytes(), offset);
687
+ }
688
+ }
662
689
  return result;
663
690
  }
664
691
  static parseBodySections(body, readwriteCount, readonlyCount, instructionDataSize, flags) {
@@ -862,18 +889,56 @@ function parseInstructionData(value) {
862
889
  }
863
890
  throw new Error("Instruction data must be provided as hex string or Uint8Array");
864
891
  }
892
+ function createInstructionContext(feePayer, program, sortedReadWrite, sortedReadOnly) {
893
+ const accounts = [
894
+ feePayer,
895
+ program,
896
+ ...sortedReadWrite.map((bytes) => Pubkey.from(bytes)),
897
+ ...sortedReadOnly.map((bytes) => Pubkey.from(bytes))
898
+ ];
899
+ const indexMap = /* @__PURE__ */ new Map();
900
+ for (let i = 0; i < accounts.length; i++) {
901
+ const key = toHex(accounts[i].toBytes());
902
+ if (!indexMap.has(key)) {
903
+ indexMap.set(key, i);
904
+ }
905
+ }
906
+ return {
907
+ accounts,
908
+ getAccountIndex: (pubkey) => {
909
+ const bytes = Pubkey.from(pubkey).toBytes();
910
+ const key = toHex(bytes);
911
+ const index = indexMap.get(key);
912
+ if (index === void 0) {
913
+ throw new Error(`Account ${key} not found in transaction accounts`);
914
+ }
915
+ return index;
916
+ }
917
+ };
918
+ }
865
919
 
866
920
  // thru-ts-client-sdk/domain/transactions/TransactionBuilder.ts
867
921
  var FLAG_HAS_FEE_PAYER_PROOF = 1 << 0;
868
922
  var TransactionBuilder = class {
869
923
  build(params) {
870
- const accounts = this.normalizeAccounts(params.accounts);
924
+ const feePayer = Pubkey.from(params.feePayer.publicKey);
925
+ const program = Pubkey.from(params.program);
926
+ const sortedReadWrite = normalizeAccountList(params.accounts?.readWriteAccounts ?? []);
927
+ const sortedReadOnly = normalizeAccountList(params.accounts?.readOnlyAccounts ?? []);
928
+ let instructionData;
929
+ if (params.buildInstructionData) {
930
+ const context = createInstructionContext(feePayer, program, sortedReadWrite, sortedReadOnly);
931
+ const result = params.buildInstructionData(context);
932
+ instructionData = parseInstructionData(result);
933
+ } else {
934
+ instructionData = parseInstructionData(params.instructionData);
935
+ }
871
936
  const baseFlags = params.header.flags ?? 0;
872
937
  const flags = params.proofs?.feePayerStateProof ? baseFlags | FLAG_HAS_FEE_PAYER_PROOF : baseFlags;
873
- const instructionData = parseInstructionData(params.instructionData);
938
+ const accounts = sortedReadWrite.length > 0 || sortedReadOnly.length > 0 ? { readWriteAccounts: sortedReadWrite, readOnlyAccounts: sortedReadOnly } : void 0;
874
939
  return new Transaction({
875
- feePayer: Pubkey.from(params.feePayer.publicKey),
876
- program: Pubkey.from(params.program),
940
+ feePayer,
941
+ program,
877
942
  header: {
878
943
  ...params.header,
879
944
  flags
@@ -883,15 +948,6 @@ var TransactionBuilder = class {
883
948
  proofs: params.proofs
884
949
  });
885
950
  }
886
- normalizeAccounts(accounts) {
887
- if (!accounts) {
888
- return void 0;
889
- }
890
- return {
891
- readWriteAccounts: normalizeAccountList(accounts.readWriteAccounts ?? []),
892
- readOnlyAccounts: normalizeAccountList(accounts.readOnlyAccounts ?? [])
893
- };
894
- }
895
951
  async buildAndSign(params) {
896
952
  if (!params.feePayer.privateKey) {
897
953
  throw new Error("Fee payer private key is required to sign the transaction");
@@ -1429,6 +1485,7 @@ var BlockHeader = class _BlockHeader {
1429
1485
  this.bondAmountLockUp = params.bondAmountLockUp;
1430
1486
  this.weightSlot = params.weightSlot;
1431
1487
  this.blockHash = copyBytes6(params.blockHash);
1488
+ this.chainId = params.chainId;
1432
1489
  }
1433
1490
  static fromProto(proto) {
1434
1491
  return new _BlockHeader({
@@ -1444,7 +1501,8 @@ var BlockHeader = class _BlockHeader {
1444
1501
  maxStateUnits: proto.maxStateUnits,
1445
1502
  bondAmountLockUp: proto.bondAmountLockUp,
1446
1503
  weightSlot: proto.weightSlot,
1447
- blockHash: proto.blockHash?.value
1504
+ blockHash: proto.blockHash?.value,
1505
+ chainId: proto.chainId
1448
1506
  });
1449
1507
  }
1450
1508
  withBlockHash(blockHash) {
@@ -1461,7 +1519,8 @@ var BlockHeader = class _BlockHeader {
1461
1519
  maxStateUnits: this.maxStateUnits,
1462
1520
  bondAmountLockUp: this.bondAmountLockUp,
1463
1521
  weightSlot: this.weightSlot,
1464
- blockHash
1522
+ blockHash,
1523
+ chainId: this.chainId
1465
1524
  });
1466
1525
  }
1467
1526
  };
@@ -1475,7 +1534,7 @@ function copyBytes6(bytes) {
1475
1534
  // thru-ts-client-sdk/domain/blocks/Block.ts
1476
1535
  var BLOCK_HASH_SIZE = 32;
1477
1536
  var RESERVED_FOOTER_PADDING = 0n;
1478
- var SIGNATURE_PREFIX_SIZE2 = SIGNATURE_SIZE2;
1537
+ var SIGNATURE_PREFIX_SIZE = SIGNATURE_SIZE2;
1479
1538
  var Block = class _Block {
1480
1539
  constructor(params) {
1481
1540
  this.header = params.header;
@@ -1564,12 +1623,14 @@ var Block = class _Block {
1564
1623
  const view = new DataView(buffer);
1565
1624
  const signature = normalizeBytes(this.header.headerSignature, SIGNATURE_SIZE2);
1566
1625
  bytes.set(signature, 0);
1567
- let offset = SIGNATURE_PREFIX_SIZE2;
1626
+ let offset = SIGNATURE_PREFIX_SIZE;
1568
1627
  const version = this.header.version ?? BLOCK_VERSION_V1;
1569
1628
  view.setUint8(offset, version & 255);
1570
1629
  offset += 1;
1571
- bytes.fill(0, offset, offset + 7);
1572
- offset += 7;
1630
+ bytes.fill(0, offset, offset + 5);
1631
+ offset += 5;
1632
+ view.setUint16(offset, this.header.chainId ?? 0, true);
1633
+ offset += 2;
1573
1634
  const producer = normalizeBytes(this.header.producer, PUBKEY_SIZE2);
1574
1635
  bytes.set(producer, offset);
1575
1636
  offset += PUBKEY_SIZE2;
@@ -1592,6 +1653,8 @@ var Block = class _Block {
1592
1653
  offset += 4;
1593
1654
  bytes.fill(0, offset, offset + 4);
1594
1655
  offset += 4;
1656
+ view.setBigUint64(offset, this.header.weightSlot ?? 0n, true);
1657
+ offset += 8;
1595
1658
  const blockTimeNs = this.blockTimeNs ?? 0n;
1596
1659
  view.setBigUint64(offset, blockTimeNs, true);
1597
1660
  return bytes;
@@ -1618,7 +1681,9 @@ var Block = class _Block {
1618
1681
  offset += SIGNATURE_SIZE2;
1619
1682
  const version = view.getUint8(offset);
1620
1683
  offset += 1;
1621
- offset += 7;
1684
+ offset += 5;
1685
+ const chainId = view.getUint16(offset, true);
1686
+ offset += 2;
1622
1687
  const producer = bytes.slice(offset, offset + PUBKEY_SIZE2);
1623
1688
  offset += PUBKEY_SIZE2;
1624
1689
  const bondAmountLockUp = view.getBigUint64(offset, true);
@@ -1636,6 +1701,8 @@ var Block = class _Block {
1636
1701
  const maxStateUnits = view.getUint32(offset, true);
1637
1702
  offset += 4;
1638
1703
  offset += 4;
1704
+ const weightSlot = view.getBigUint64(offset, true);
1705
+ offset += 8;
1639
1706
  const blockTimeNs = view.getBigUint64(offset, true);
1640
1707
  const header = new BlockHeader({
1641
1708
  slot: startSlot,
@@ -1648,7 +1715,9 @@ var Block = class _Block {
1648
1715
  maxBlockSize,
1649
1716
  maxComputeUnits,
1650
1717
  maxStateUnits,
1651
- bondAmountLockUp
1718
+ bondAmountLockUp,
1719
+ weightSlot,
1720
+ chainId
1652
1721
  });
1653
1722
  return { header, blockTimeNs };
1654
1723
  }
@@ -1828,6 +1897,17 @@ async function listBlocks(ctx, options = {}) {
1828
1897
  };
1829
1898
  }
1830
1899
 
1900
+ // thru-ts-client-sdk/modules/chain.ts
1901
+ var chain_exports = {};
1902
+ __export(chain_exports, {
1903
+ getChainId: () => getChainId
1904
+ });
1905
+ async function getChainId(ctx) {
1906
+ const request = create(GetChainInfoRequestSchema);
1907
+ const response = await ctx.query.getChainInfo(request, withCallOptions(ctx));
1908
+ return response.chainId;
1909
+ }
1910
+
1831
1911
  // thru-ts-client-sdk/modules/consensus.ts
1832
1912
  var consensus_exports = {};
1833
1913
  __export(consensus_exports, {
@@ -2729,7 +2809,7 @@ async function createBuildParams(ctx, options) {
2729
2809
  const program = Pubkey.from(options.program).toBytes();
2730
2810
  const header = await createTransactionHeader(ctx, options.header ?? {}, feePayerPublicKey);
2731
2811
  const accounts = parseAccounts(options.accounts);
2732
- const context = createInstructionContext(feePayerPublicKey, program, accounts);
2812
+ const context = createInstructionContext2(feePayerPublicKey, program, accounts);
2733
2813
  const instructionData = await resolveInstructionData(options.instructionData, context);
2734
2814
  const proofs = createProofs(options);
2735
2815
  return {
@@ -2747,11 +2827,13 @@ async function createBuildParams(ctx, options) {
2747
2827
  async function createTransactionHeader(ctx, header, feePayerPublicKey) {
2748
2828
  const nonce = header.nonce ?? await fetchFeePayerNonce(ctx, feePayerPublicKey);
2749
2829
  const startSlot = header.startSlot ?? await fetchFinalizedSlot(ctx);
2830
+ const chainId = header.chainId ?? await fetchChainId(ctx);
2750
2831
  return {
2751
2832
  fee: header.fee ?? DEFAULT_FEE,
2752
2833
  nonce,
2753
2834
  startSlot,
2754
2835
  expiryAfter: header.expiryAfter ?? DEFAULT_EXPIRY_AFTER,
2836
+ chainId,
2755
2837
  computeUnits: header.computeUnits ?? DEFAULT_COMPUTE_UNITS,
2756
2838
  stateUnits: header.stateUnits ?? DEFAULT_STATE_UNITS,
2757
2839
  memoryUnits: header.memoryUnits ?? DEFAULT_MEMORY_UNITS,
@@ -2780,7 +2862,7 @@ function parseAccounts(accounts) {
2780
2862
  }
2781
2863
  return result;
2782
2864
  }
2783
- function createInstructionContext(feePayer, program, accounts) {
2865
+ function createInstructionContext2(feePayer, program, accounts) {
2784
2866
  const allAccounts = [
2785
2867
  Pubkey.from(feePayer),
2786
2868
  Pubkey.from(program),
@@ -2832,6 +2914,9 @@ async function fetchFinalizedSlot(ctx) {
2832
2914
  const height = await getBlockHeight(ctx);
2833
2915
  return height.finalized;
2834
2916
  }
2917
+ async function fetchChainId(ctx) {
2918
+ return getChainId(ctx);
2919
+ }
2835
2920
 
2836
2921
  // thru-ts-client-sdk/domain/version/VersionInfo.ts
2837
2922
  var VersionInfo = class _VersionInfo {
@@ -2846,6 +2931,6 @@ var VersionInfo = class _VersionInfo {
2846
2931
  }
2847
2932
  };
2848
2933
 
2849
- export { Account, Block, ChainEvent, Filter, FilterParamValue, HeightSnapshot, PageRequest, PageResponse, Pubkey, Signature, SignatureDomain, StateProof, Transaction, TransactionBuilder, TransactionStatusSnapshot, VersionInfo, accounts_exports, batchSendTransactions, blocks_exports, buildAndSignTransaction, buildTransaction, collectStream, consensusStatusToString, consensus_exports, createAccount, createThruClientContext, currentOrHistoricalVersionContext, currentVersionContext, deriveAddress, deriveProgramAddress, events_exports, firstStreamValue, forEachStreamValue, fromPrivateKey, generateKeyPair, generateStateProof, getAccount, getBlock, getBlockHeight, getEvent, getRawAccount, getRawBlock, getRawTransaction, getTransaction, getTransactionStatus, height_exports, keys_exports, listAccounts, listBlocks, listEvents, listTransactions, listTransactionsForAccount, proofs_exports, sendTransaction, seqVersionContext, signWithDomain, slotVersionContext, streamAccountUpdates, streamBlocks, streamEvents, streamHeight, streamTransactions, streaming_exports, timestampVersionContext, trackTransaction, transactions_exports, verifyWithDomain, versionContext, withCallOptions };
2850
- //# sourceMappingURL=chunk-PU2M7EPY.js.map
2851
- //# sourceMappingURL=chunk-PU2M7EPY.js.map
2934
+ export { Account, Block, ChainEvent, Filter, FilterParamValue, HeightSnapshot, PageRequest, PageResponse, Pubkey, Signature, SignatureDomain, StateProof, Transaction, TransactionBuilder, TransactionStatusSnapshot, VersionInfo, accounts_exports, batchSendTransactions, blocks_exports, buildAndSignTransaction, buildTransaction, chain_exports, collectStream, consensusStatusToString, consensus_exports, createAccount, createThruClientContext, currentOrHistoricalVersionContext, currentVersionContext, deriveAddress, deriveProgramAddress, events_exports, firstStreamValue, forEachStreamValue, fromPrivateKey, generateKeyPair, generateStateProof, getAccount, getBlock, getBlockHeight, getEvent, getRawAccount, getRawBlock, getRawTransaction, getTransaction, getTransactionStatus, height_exports, keys_exports, listAccounts, listBlocks, listEvents, listTransactions, listTransactionsForAccount, proofs_exports, sendTransaction, seqVersionContext, signWithDomain, slotVersionContext, streamAccountUpdates, streamBlocks, streamEvents, streamHeight, streamTransactions, streaming_exports, timestampVersionContext, trackTransaction, transactions_exports, verifyWithDomain, versionContext, withCallOptions };
2935
+ //# sourceMappingURL=chunk-YIQKZL4H.js.map
2936
+ //# sourceMappingURL=chunk-YIQKZL4H.js.map