@solana/transactions 2.0.0-experimental.cf6545e → 2.0.0-experimental.cf6ca9d

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.
@@ -1,7 +1,12 @@
1
1
  'use strict';
2
2
 
3
3
  var umiSerializers = require('@metaplex-foundation/umi-serializers');
4
+ var codecsCore = require('@solana/codecs-core');
5
+ var codecsDataStructures = require('@solana/codecs-data-structures');
6
+ var codecsNumbers = require('@solana/codecs-numbers');
4
7
  var addresses = require('@solana/addresses');
8
+ var functional = require('@solana/functional');
9
+ var codecsStrings = require('@solana/codecs-strings');
5
10
  var keys = require('@solana/keys');
6
11
 
7
12
  // ../build-scripts/env-shim.ts
@@ -31,8 +36,8 @@ function assertIsBlockhash(putativeBlockhash) {
31
36
  ) {
32
37
  throw new Error("Expected input string to decode to a byte array of length 32.");
33
38
  }
34
- const bytes3 = umiSerializers.base58.serialize(putativeBlockhash);
35
- const numBytes = bytes3.byteLength;
39
+ const bytes = umiSerializers.base58.serialize(putativeBlockhash);
40
+ const numBytes = bytes.byteLength;
36
41
  if (numBytes !== 32) {
37
42
  throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
38
43
  }
@@ -117,7 +122,7 @@ function isAdvanceNonceAccountInstruction(instruction) {
117
122
  instruction.accounts?.length === 3 && // First account is nonce account address
118
123
  instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar
119
124
  instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account
120
- instruction.accounts[2].address != null && instruction.accounts[2].role === AccountRole.READONLY_SIGNER;
125
+ instruction.accounts[2].address != null && isSignerRole(instruction.accounts[2].role);
121
126
  }
122
127
  function isAdvanceNonceAccountInstructionData(data) {
123
128
  return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
@@ -125,21 +130,38 @@ function isAdvanceNonceAccountInstructionData(data) {
125
130
  function isDurableNonceTransaction(transaction) {
126
131
  return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);
127
132
  }
133
+ function isAdvanceNonceAccountInstructionForNonce(instruction, nonceAccountAddress, nonceAuthorityAddress) {
134
+ return instruction.accounts[0].address === nonceAccountAddress && instruction.accounts[2].address === nonceAuthorityAddress;
135
+ }
128
136
  function setTransactionLifetimeUsingDurableNonce({
129
137
  nonce,
130
138
  nonceAccountAddress,
131
139
  nonceAuthorityAddress
132
140
  }, transaction) {
133
- const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction);
134
- if (isAlreadyDurableNonceTransaction && transaction.lifetimeConstraint.nonce === nonce && transaction.instructions[0].accounts[0].address === nonceAccountAddress && transaction.instructions[0].accounts[2].address === nonceAuthorityAddress) {
135
- return transaction;
141
+ let newInstructions;
142
+ const firstInstruction = transaction.instructions[0];
143
+ if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {
144
+ if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {
145
+ if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {
146
+ return transaction;
147
+ } else {
148
+ newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];
149
+ }
150
+ } else {
151
+ newInstructions = [
152
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
153
+ ...transaction.instructions.slice(1)
154
+ ];
155
+ }
156
+ } else {
157
+ newInstructions = [
158
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
159
+ ...transaction.instructions
160
+ ];
136
161
  }
137
162
  const out = {
138
163
  ...getUnsignedTransaction(transaction),
139
- instructions: [
140
- createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
141
- ...isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions
142
- ],
164
+ instructions: newInstructions,
143
165
  lifetimeConstraint: {
144
166
  nonce
145
167
  }
@@ -230,7 +252,7 @@ function getAddressMapFromInstructions(feePayer, instructions) {
230
252
  const shouldReplaceEntry = (
231
253
  // Consider using the new LOOKUP_TABLE if its address is different...
232
254
  entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
233
- (addressComparator || (addressComparator = addresses.getBase58EncodedAddressComparator()))(
255
+ (addressComparator || (addressComparator = addresses.getAddressComparator()))(
234
256
  accountMeta.lookupTableAddress,
235
257
  entry.lookupTableAddress
236
258
  ) < 0
@@ -336,7 +358,7 @@ function getOrderedAccountsFromAddressMap(addressMap) {
336
358
  if (leftIsWritable !== isWritableRole(rightEntry.role)) {
337
359
  return leftIsWritable ? -1 : 1;
338
360
  }
339
- addressComparator || (addressComparator = addresses.getBase58EncodedAddressComparator());
361
+ addressComparator || (addressComparator = addresses.getAddressComparator());
340
362
  if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
341
363
  return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
342
364
  } else {
@@ -365,7 +387,7 @@ function getCompiledAddressTableLookups(orderedAccounts) {
365
387
  entry.readableIndices.push(account.addressIndex);
366
388
  }
367
389
  }
368
- return Object.keys(index).sort(addresses.getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({
390
+ return Object.keys(index).sort(addresses.getAddressComparator()).map((lookupTableAddress) => ({
369
391
  lookupTableAddress,
370
392
  ...index[lookupTableAddress]
371
393
  }));
@@ -444,151 +466,317 @@ function compileMessage(transaction) {
444
466
  version: transaction.version
445
467
  };
446
468
  }
447
- function getAddressTableLookupCodec() {
448
- return umiSerializers.struct(
449
- [
450
- [
451
- "lookupTableAddress",
452
- addresses.getBase58EncodedAddressCodec(
453
- __DEV__ ? {
454
- description: "The address of the address lookup table account from which instruction addresses should be looked up"
455
- } : void 0
456
- )
457
- ],
458
- [
459
- "writableIndices",
460
- umiSerializers.array(umiSerializers.u8(), {
461
- ...__DEV__ ? {
462
- description: "The indices of the accounts in the lookup table that should be loaded as writeable"
463
- } : null,
464
- size: umiSerializers.shortU16()
465
- })
466
- ],
467
- [
468
- "readableIndices",
469
- umiSerializers.array(umiSerializers.u8(), {
470
- ...__DEV__ ? {
471
- description: "The indices of the accounts in the lookup table that should be loaded as read-only"
472
- } : void 0,
473
- size: umiSerializers.shortU16()
474
- })
475
- ]
476
- ],
477
- __DEV__ ? {
478
- description: "A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it"
479
- } : void 0
469
+
470
+ // src/compile-transaction.ts
471
+ function getCompiledTransaction(transaction) {
472
+ const compiledMessage = compileMessage(transaction);
473
+ let signatures;
474
+ if ("signatures" in transaction) {
475
+ signatures = [];
476
+ for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {
477
+ signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));
478
+ }
479
+ } else {
480
+ signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));
481
+ }
482
+ return {
483
+ compiledMessage,
484
+ signatures
485
+ };
486
+ }
487
+ function getAccountMetas(message) {
488
+ const { header } = message;
489
+ const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;
490
+ const numWritableNonSignerAccounts = message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;
491
+ const accountMetas = [];
492
+ let accountIndex = 0;
493
+ for (let i = 0; i < numWritableSignerAccounts; i++) {
494
+ accountMetas.push({
495
+ address: message.staticAccounts[accountIndex],
496
+ role: AccountRole.WRITABLE_SIGNER
497
+ });
498
+ accountIndex++;
499
+ }
500
+ for (let i = 0; i < header.numReadonlySignerAccounts; i++) {
501
+ accountMetas.push({
502
+ address: message.staticAccounts[accountIndex],
503
+ role: AccountRole.READONLY_SIGNER
504
+ });
505
+ accountIndex++;
506
+ }
507
+ for (let i = 0; i < numWritableNonSignerAccounts; i++) {
508
+ accountMetas.push({
509
+ address: message.staticAccounts[accountIndex],
510
+ role: AccountRole.WRITABLE
511
+ });
512
+ accountIndex++;
513
+ }
514
+ for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {
515
+ accountMetas.push({
516
+ address: message.staticAccounts[accountIndex],
517
+ role: AccountRole.READONLY
518
+ });
519
+ accountIndex++;
520
+ }
521
+ return accountMetas;
522
+ }
523
+ function convertInstruction(instruction, accountMetas) {
524
+ const programAddress = accountMetas[instruction.programAddressIndex]?.address;
525
+ if (!programAddress) {
526
+ throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);
527
+ }
528
+ const accounts = instruction.accountIndices?.map((accountIndex) => accountMetas[accountIndex]);
529
+ const { data } = instruction;
530
+ return {
531
+ programAddress,
532
+ ...accounts && accounts.length ? { accounts } : {},
533
+ ...data && data.length ? { data } : {}
534
+ };
535
+ }
536
+ function getLifetimeConstraint(messageLifetimeToken, firstInstruction, lastValidBlockHeight) {
537
+ if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {
538
+ return {
539
+ blockhash: messageLifetimeToken,
540
+ lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n
541
+ // U64 MAX
542
+ };
543
+ } else {
544
+ const nonceAccountAddress = firstInstruction.accounts[0].address;
545
+ addresses.assertIsAddress(nonceAccountAddress);
546
+ const nonceAuthorityAddress = firstInstruction.accounts[2].address;
547
+ addresses.assertIsAddress(nonceAuthorityAddress);
548
+ return {
549
+ nonce: messageLifetimeToken,
550
+ nonceAccountAddress,
551
+ nonceAuthorityAddress
552
+ };
553
+ }
554
+ }
555
+ function convertSignatures(compiledTransaction) {
556
+ const {
557
+ compiledMessage: { staticAccounts },
558
+ signatures
559
+ } = compiledTransaction;
560
+ return signatures.reduce((acc, sig, index) => {
561
+ const allZeros = sig.every((byte) => byte === 0);
562
+ if (allZeros)
563
+ return acc;
564
+ const address = staticAccounts[index];
565
+ return { ...acc, [address]: sig };
566
+ }, {});
567
+ }
568
+ function decompileTransaction(compiledTransaction, lastValidBlockHeight) {
569
+ const { compiledMessage } = compiledTransaction;
570
+ if ("addressTableLookups" in compiledMessage && compiledMessage.addressTableLookups.length > 0) {
571
+ throw new Error("Cannot convert transaction with addressTableLookups");
572
+ }
573
+ const feePayer = compiledMessage.staticAccounts[0];
574
+ if (!feePayer)
575
+ throw new Error("No fee payer set in CompiledTransaction");
576
+ const accountMetas = getAccountMetas(compiledMessage);
577
+ const instructions = compiledMessage.instructions.map(
578
+ (compiledInstruction) => convertInstruction(compiledInstruction, accountMetas)
579
+ );
580
+ const firstInstruction = instructions[0];
581
+ const lifetimeConstraint = getLifetimeConstraint(
582
+ compiledMessage.lifetimeToken,
583
+ firstInstruction,
584
+ lastValidBlockHeight
585
+ );
586
+ const signatures = convertSignatures(compiledTransaction);
587
+ return functional.pipe(
588
+ createTransaction({ version: compiledMessage.version }),
589
+ (tx) => setTransactionFeePayer(feePayer, tx),
590
+ (tx) => instructions.reduce((acc, instruction) => {
591
+ return appendTransactionInstruction(instruction, acc);
592
+ }, tx),
593
+ (tx) => "blockhash" in lifetimeConstraint ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx) : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),
594
+ (tx) => compiledTransaction.signatures.length ? { ...tx, signatures } : tx
480
595
  );
481
596
  }
482
- function getMessageHeaderCodec() {
483
- return umiSerializers.struct(
484
- [
597
+ var lookupTableAddressDescription = __DEV__ ? "The address of the address lookup table account from which instruction addresses should be looked up" : "lookupTableAddress";
598
+ var writableIndicesDescription = __DEV__ ? "The indices of the accounts in the lookup table that should be loaded as writeable" : "writableIndices";
599
+ var readableIndicesDescription = __DEV__ ? "The indices of the accounts in the lookup table that should be loaded as read-only" : "readableIndices";
600
+ var addressTableLookupDescription = __DEV__ ? "A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it" : "addressTableLookup";
601
+ var memoizedAddressTableLookupEncoder;
602
+ function getAddressTableLookupEncoder() {
603
+ if (!memoizedAddressTableLookupEncoder) {
604
+ memoizedAddressTableLookupEncoder = codecsDataStructures.getStructEncoder(
485
605
  [
486
- "numSignerAccounts",
487
- umiSerializers.u8(
488
- __DEV__ ? {
489
- description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction"
490
- } : void 0
491
- )
606
+ ["lookupTableAddress", addresses.getAddressEncoder({ description: lookupTableAddressDescription })],
607
+ [
608
+ "writableIndices",
609
+ codecsDataStructures.getArrayEncoder(codecsNumbers.getU8Encoder(), {
610
+ description: writableIndicesDescription,
611
+ size: codecsNumbers.getShortU16Encoder()
612
+ })
613
+ ],
614
+ [
615
+ "readableIndices",
616
+ codecsDataStructures.getArrayEncoder(codecsNumbers.getU8Encoder(), {
617
+ description: readableIndicesDescription,
618
+ size: codecsNumbers.getShortU16Encoder()
619
+ })
620
+ ]
492
621
  ],
622
+ { description: addressTableLookupDescription }
623
+ );
624
+ }
625
+ return memoizedAddressTableLookupEncoder;
626
+ }
627
+ var memoizedAddressTableLookupDecoder;
628
+ function getAddressTableLookupDecoder() {
629
+ if (!memoizedAddressTableLookupDecoder) {
630
+ memoizedAddressTableLookupDecoder = codecsDataStructures.getStructDecoder(
493
631
  [
494
- "numReadonlySignerAccounts",
495
- umiSerializers.u8(
496
- __DEV__ ? {
497
- description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable"
498
- } : void 0
499
- )
632
+ ["lookupTableAddress", addresses.getAddressDecoder({ description: lookupTableAddressDescription })],
633
+ [
634
+ "writableIndices",
635
+ codecsDataStructures.getArrayDecoder(codecsNumbers.getU8Decoder(), {
636
+ description: writableIndicesDescription,
637
+ size: codecsNumbers.getShortU16Decoder()
638
+ })
639
+ ],
640
+ [
641
+ "readableIndices",
642
+ codecsDataStructures.getArrayDecoder(codecsNumbers.getU8Decoder(), {
643
+ description: readableIndicesDescription,
644
+ size: codecsNumbers.getShortU16Decoder()
645
+ })
646
+ ]
500
647
  ],
501
- [
502
- "numReadonlyNonSignerAccounts",
503
- umiSerializers.u8(
504
- __DEV__ ? {
505
- description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable"
506
- } : void 0
507
- )
508
- ]
648
+ { description: addressTableLookupDescription }
649
+ );
650
+ }
651
+ return memoizedAddressTableLookupDecoder;
652
+ }
653
+ var memoizedU8Encoder;
654
+ function getMemoizedU8Encoder() {
655
+ if (!memoizedU8Encoder)
656
+ memoizedU8Encoder = codecsNumbers.getU8Encoder();
657
+ return memoizedU8Encoder;
658
+ }
659
+ function getMemoizedU8EncoderDescription(description) {
660
+ const encoder = getMemoizedU8Encoder();
661
+ return {
662
+ ...encoder,
663
+ description: description ?? encoder.description
664
+ };
665
+ }
666
+ var memoizedU8Decoder;
667
+ function getMemoizedU8Decoder() {
668
+ if (!memoizedU8Decoder)
669
+ memoizedU8Decoder = codecsNumbers.getU8Decoder();
670
+ return memoizedU8Decoder;
671
+ }
672
+ function getMemoizedU8DecoderDescription(description) {
673
+ const decoder = getMemoizedU8Decoder();
674
+ return {
675
+ ...decoder,
676
+ description: description ?? decoder.description
677
+ };
678
+ }
679
+ var numSignerAccountsDescription = __DEV__ ? "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction" : void 0;
680
+ var numReadonlySignerAccountsDescription = __DEV__ ? "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable" : void 0;
681
+ var numReadonlyNonSignerAccountsDescription = __DEV__ ? "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable" : void 0;
682
+ var messageHeaderDescription = __DEV__ ? "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses" : void 0;
683
+ function getMessageHeaderEncoder() {
684
+ return codecsDataStructures.getStructEncoder(
685
+ [
686
+ ["numSignerAccounts", getMemoizedU8EncoderDescription(numSignerAccountsDescription)],
687
+ ["numReadonlySignerAccounts", getMemoizedU8EncoderDescription(numReadonlySignerAccountsDescription)],
688
+ ["numReadonlyNonSignerAccounts", getMemoizedU8EncoderDescription(numReadonlyNonSignerAccountsDescription)]
509
689
  ],
510
- __DEV__ ? {
511
- description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses"
512
- } : void 0
690
+ {
691
+ description: messageHeaderDescription
692
+ }
513
693
  );
514
694
  }
515
- function getInstructionCodec() {
516
- return umiSerializers.mapSerializer(
517
- umiSerializers.struct([
518
- [
519
- "programAddressIndex",
520
- umiSerializers.u8(
521
- __DEV__ ? {
522
- description: "The index of the program being called, according to the well-ordered accounts list for this transaction"
523
- } : void 0
524
- )
525
- ],
526
- [
527
- "accountIndices",
528
- umiSerializers.array(
529
- umiSerializers.u8({
530
- description: __DEV__ ? "The index of an account, according to the well-ordered accounts list for this transaction" : ""
531
- }),
532
- {
533
- description: __DEV__ ? "An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them" : "",
534
- size: umiSerializers.shortU16()
535
- }
536
- )
537
- ],
538
- [
539
- "data",
540
- umiSerializers.bytes({
541
- description: __DEV__ ? "An optional buffer of data passed to the instruction" : "",
542
- size: umiSerializers.shortU16()
543
- })
544
- ]
545
- ]),
546
- (value) => {
547
- if (value.accountIndices !== void 0 && value.data !== void 0) {
548
- return value;
549
- }
550
- return {
551
- ...value,
552
- accountIndices: value.accountIndices ?? [],
553
- data: value.data ?? new Uint8Array(0)
554
- };
555
- },
556
- (value) => {
557
- if (value.accountIndices.length && value.data.byteLength) {
558
- return value;
559
- }
560
- const { accountIndices, data, ...rest } = value;
561
- return {
562
- ...rest,
563
- ...accountIndices.length ? { accountIndices } : null,
564
- ...data.byteLength ? { data } : null
565
- };
695
+ function getMessageHeaderDecoder() {
696
+ return codecsDataStructures.getStructDecoder(
697
+ [
698
+ ["numSignerAccounts", getMemoizedU8DecoderDescription(numSignerAccountsDescription)],
699
+ ["numReadonlySignerAccounts", getMemoizedU8DecoderDescription(numReadonlySignerAccountsDescription)],
700
+ ["numReadonlyNonSignerAccounts", getMemoizedU8DecoderDescription(numReadonlyNonSignerAccountsDescription)]
701
+ ],
702
+ {
703
+ description: messageHeaderDescription
566
704
  }
567
705
  );
568
706
  }
569
-
570
- // src/serializers/unimplemented.ts
571
- function getError(type, name) {
572
- const functionSuffix = name + type[0].toUpperCase() + type.slice(1);
573
- return new Error(
574
- `No ${type} exists for ${name}. Use \`get${functionSuffix}()\` if you need a ${type}, and \`get${name}Codec()\` if you need to both encode and decode ${name}`
575
- );
707
+ var programAddressIndexDescription = __DEV__ ? "The index of the program being called, according to the well-ordered accounts list for this transaction" : "programAddressIndex";
708
+ var accountIndexDescription = __DEV__ ? "The index of an account, according to the well-ordered accounts list for this transaction" : void 0;
709
+ var accountIndicesDescription = __DEV__ ? "An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them" : "accountIndices";
710
+ var dataDescription = __DEV__ ? "An optional buffer of data passed to the instruction" : "data";
711
+ var memoizedGetInstructionEncoder;
712
+ function getInstructionEncoder() {
713
+ if (!memoizedGetInstructionEncoder) {
714
+ memoizedGetInstructionEncoder = codecsCore.mapEncoder(
715
+ codecsDataStructures.getStructEncoder([
716
+ ["programAddressIndex", codecsNumbers.getU8Encoder({ description: programAddressIndexDescription })],
717
+ [
718
+ "accountIndices",
719
+ codecsDataStructures.getArrayEncoder(codecsNumbers.getU8Encoder({ description: accountIndexDescription }), {
720
+ description: accountIndicesDescription,
721
+ size: codecsNumbers.getShortU16Encoder()
722
+ })
723
+ ],
724
+ ["data", codecsDataStructures.getBytesEncoder({ description: dataDescription, size: codecsNumbers.getShortU16Encoder() })]
725
+ ]),
726
+ // Convert an instruction to have all fields defined
727
+ (instruction) => {
728
+ if (instruction.accountIndices !== void 0 && instruction.data !== void 0) {
729
+ return instruction;
730
+ }
731
+ return {
732
+ ...instruction,
733
+ accountIndices: instruction.accountIndices ?? [],
734
+ data: instruction.data ?? new Uint8Array(0)
735
+ };
736
+ }
737
+ );
738
+ }
739
+ return memoizedGetInstructionEncoder;
576
740
  }
577
- function getUnimplementedDecoder(name) {
578
- return () => {
579
- throw getError("decoder", name);
580
- };
741
+ var memoizedGetInstructionDecoder;
742
+ function getInstructionDecoder() {
743
+ if (!memoizedGetInstructionDecoder) {
744
+ memoizedGetInstructionDecoder = codecsCore.mapDecoder(
745
+ codecsDataStructures.getStructDecoder([
746
+ ["programAddressIndex", codecsNumbers.getU8Decoder({ description: programAddressIndexDescription })],
747
+ [
748
+ "accountIndices",
749
+ codecsDataStructures.getArrayDecoder(codecsNumbers.getU8Decoder({ description: accountIndexDescription }), {
750
+ description: accountIndicesDescription,
751
+ size: codecsNumbers.getShortU16Decoder()
752
+ })
753
+ ],
754
+ ["data", codecsDataStructures.getBytesDecoder({ description: dataDescription, size: codecsNumbers.getShortU16Decoder() })]
755
+ ]),
756
+ // Convert an instruction to exclude optional fields if they are empty
757
+ (instruction) => {
758
+ if (instruction.accountIndices.length && instruction.data.byteLength) {
759
+ return instruction;
760
+ }
761
+ const { accountIndices, data, ...rest } = instruction;
762
+ return {
763
+ ...rest,
764
+ ...accountIndices.length ? { accountIndices } : null,
765
+ ...data.byteLength ? { data } : null
766
+ };
767
+ }
768
+ );
769
+ }
770
+ return memoizedGetInstructionDecoder;
581
771
  }
582
-
583
- // src/serializers/transaction-version.ts
584
772
  var VERSION_FLAG_MASK = 128;
585
773
  var BASE_CONFIG = {
586
774
  description: __DEV__ ? "A single byte that encodes the version of the transaction" : "",
587
775
  fixedSize: null,
588
776
  maxSize: 1
589
777
  };
590
- function deserialize(bytes3, offset = 0) {
591
- const firstByte = bytes3[offset];
778
+ function decode(bytes, offset = 0) {
779
+ const firstByte = bytes[offset];
592
780
  if ((firstByte & VERSION_FLAG_MASK) === 0) {
593
781
  return ["legacy", offset];
594
782
  } else {
@@ -596,7 +784,7 @@ function deserialize(bytes3, offset = 0) {
596
784
  return [version, offset + 1];
597
785
  }
598
786
  }
599
- function serialize(value) {
787
+ function encode(value) {
600
788
  if (value === "legacy") {
601
789
  return new Uint8Array();
602
790
  }
@@ -605,99 +793,251 @@ function serialize(value) {
605
793
  }
606
794
  return new Uint8Array([value | VERSION_FLAG_MASK]);
607
795
  }
608
- function getTransactionVersionCodec() {
796
+ function getTransactionVersionDecoder() {
609
797
  return {
610
798
  ...BASE_CONFIG,
611
- deserialize,
612
- serialize
799
+ decode
800
+ };
801
+ }
802
+ function getTransactionVersionEncoder() {
803
+ return {
804
+ ...BASE_CONFIG,
805
+ encode
613
806
  };
614
807
  }
615
808
 
616
809
  // src/serializers/message.ts
617
- var BASE_CONFIG2 = {
618
- description: __DEV__ ? "The wire format of a Solana transaction message" : "",
619
- fixedSize: null,
620
- maxSize: null
621
- };
622
- function serialize2(compiledMessage) {
623
- if (compiledMessage.version === "legacy") {
624
- return umiSerializers.struct(getPreludeStructSerializerTuple()).serialize(compiledMessage);
625
- } else {
626
- return umiSerializers.mapSerializer(
627
- umiSerializers.struct([
628
- ...getPreludeStructSerializerTuple(),
629
- ["addressTableLookups", getAddressTableLookupsSerializer()]
630
- ]),
631
- (value) => {
632
- if (value.version === "legacy") {
633
- return value;
634
- }
635
- return {
636
- ...value,
637
- addressTableLookups: value.addressTableLookups ?? []
638
- };
810
+ var staticAccountsDescription = __DEV__ ? "A compact-array of static account addresses belonging to this transaction" : "staticAccounts";
811
+ var lifetimeTokenDescription = __DEV__ ? "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" : "lifetimeToken";
812
+ var instructionsDescription = __DEV__ ? "A compact-array of instructions belonging to this transaction" : "instructions";
813
+ var addressTableLookupsDescription = __DEV__ ? "A compact array of address table lookups belonging to this transaction" : "addressTableLookups";
814
+ function getCompiledMessageLegacyEncoder() {
815
+ return codecsDataStructures.getStructEncoder(getPreludeStructEncoderTuple());
816
+ }
817
+ function getCompiledMessageVersionedEncoder() {
818
+ return codecsCore.mapEncoder(
819
+ codecsDataStructures.getStructEncoder([
820
+ ...getPreludeStructEncoderTuple(),
821
+ ["addressTableLookups", getAddressTableLookupArrayEncoder()]
822
+ ]),
823
+ (value) => {
824
+ if (value.version === "legacy") {
825
+ return value;
639
826
  }
640
- ).serialize(compiledMessage);
641
- }
827
+ return {
828
+ ...value,
829
+ addressTableLookups: value.addressTableLookups ?? []
830
+ };
831
+ }
832
+ );
642
833
  }
643
- function getPreludeStructSerializerTuple() {
834
+ function getPreludeStructEncoderTuple() {
644
835
  return [
645
- ["version", getTransactionVersionCodec()],
646
- ["header", getMessageHeaderCodec()],
836
+ ["version", getTransactionVersionEncoder()],
837
+ ["header", getMessageHeaderEncoder()],
647
838
  [
648
839
  "staticAccounts",
649
- umiSerializers.array(addresses.getBase58EncodedAddressCodec(), {
650
- description: __DEV__ ? "A compact-array of static account addresses belonging to this transaction" : "",
651
- size: umiSerializers.shortU16()
840
+ codecsDataStructures.getArrayEncoder(addresses.getAddressEncoder(), {
841
+ description: staticAccountsDescription,
842
+ size: codecsNumbers.getShortU16Encoder()
652
843
  })
653
844
  ],
654
845
  [
655
846
  "lifetimeToken",
656
- umiSerializers.string({
657
- description: __DEV__ ? "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" : "",
658
- encoding: umiSerializers.base58,
847
+ codecsStrings.getStringEncoder({
848
+ description: lifetimeTokenDescription,
849
+ encoding: codecsStrings.getBase58Encoder(),
659
850
  size: 32
660
851
  })
661
852
  ],
662
853
  [
663
854
  "instructions",
664
- umiSerializers.array(getInstructionCodec(), {
665
- description: __DEV__ ? "A compact-array of instructions belonging to this transaction" : "",
666
- size: umiSerializers.shortU16()
855
+ codecsDataStructures.getArrayEncoder(getInstructionEncoder(), {
856
+ description: instructionsDescription,
857
+ size: codecsNumbers.getShortU16Encoder()
667
858
  })
668
859
  ]
669
860
  ];
670
861
  }
671
- function getAddressTableLookupsSerializer() {
672
- return umiSerializers.array(getAddressTableLookupCodec(), {
673
- ...__DEV__ ? { description: "A compact array of address table lookups belonging to this transaction" } : null,
674
- size: umiSerializers.shortU16()
862
+ function getPreludeStructDecoderTuple() {
863
+ return [
864
+ ["version", getTransactionVersionDecoder()],
865
+ ["header", getMessageHeaderDecoder()],
866
+ [
867
+ "staticAccounts",
868
+ codecsDataStructures.getArrayDecoder(addresses.getAddressDecoder(), {
869
+ description: staticAccountsDescription,
870
+ size: codecsNumbers.getShortU16Decoder()
871
+ })
872
+ ],
873
+ [
874
+ "lifetimeToken",
875
+ codecsStrings.getStringDecoder({
876
+ description: lifetimeTokenDescription,
877
+ encoding: codecsStrings.getBase58Decoder(),
878
+ size: 32
879
+ })
880
+ ],
881
+ [
882
+ "instructions",
883
+ codecsDataStructures.getArrayDecoder(getInstructionDecoder(), {
884
+ description: instructionsDescription,
885
+ size: codecsNumbers.getShortU16Decoder()
886
+ })
887
+ ],
888
+ ["addressTableLookups", getAddressTableLookupArrayDecoder()]
889
+ ];
890
+ }
891
+ function getAddressTableLookupArrayEncoder() {
892
+ return codecsDataStructures.getArrayEncoder(getAddressTableLookupEncoder(), {
893
+ description: addressTableLookupsDescription,
894
+ size: codecsNumbers.getShortU16Encoder()
675
895
  });
676
896
  }
897
+ function getAddressTableLookupArrayDecoder() {
898
+ return codecsDataStructures.getArrayDecoder(getAddressTableLookupDecoder(), {
899
+ description: addressTableLookupsDescription,
900
+ size: codecsNumbers.getShortU16Decoder()
901
+ });
902
+ }
903
+ var messageDescription = __DEV__ ? "The wire format of a Solana transaction message" : "message";
677
904
  function getCompiledMessageEncoder() {
678
905
  return {
679
- ...BASE_CONFIG2,
680
- deserialize: getUnimplementedDecoder("CompiledMessage"),
681
- serialize: serialize2
906
+ description: messageDescription,
907
+ encode: (compiledMessage) => {
908
+ if (compiledMessage.version === "legacy") {
909
+ return getCompiledMessageLegacyEncoder().encode(compiledMessage);
910
+ } else {
911
+ return getCompiledMessageVersionedEncoder().encode(compiledMessage);
912
+ }
913
+ },
914
+ fixedSize: null,
915
+ maxSize: null
682
916
  };
683
917
  }
918
+ function getCompiledMessageDecoder() {
919
+ return codecsCore.mapDecoder(
920
+ codecsDataStructures.getStructDecoder(getPreludeStructDecoderTuple(), {
921
+ description: messageDescription
922
+ }),
923
+ ({ addressTableLookups, ...restOfMessage }) => {
924
+ if (restOfMessage.version === "legacy" || !addressTableLookups?.length) {
925
+ return restOfMessage;
926
+ }
927
+ return { ...restOfMessage, addressTableLookups };
928
+ }
929
+ );
930
+ }
684
931
 
685
- // src/signatures.ts
686
- async function getCompiledMessageSignature(message, secretKey) {
687
- const wireMessageBytes = getCompiledMessageEncoder().serialize(message);
688
- const signature = await keys.signBytes(secretKey, wireMessageBytes);
689
- return signature;
932
+ // src/serializers/transaction.ts
933
+ var signaturesDescription = __DEV__ ? "A compact array of 64-byte, base-64 encoded Ed25519 signatures" : "signatures";
934
+ var transactionDescription = __DEV__ ? "The wire format of a Solana transaction" : "transaction";
935
+ function getCompiledTransactionEncoder() {
936
+ return codecsDataStructures.getStructEncoder(
937
+ [
938
+ [
939
+ "signatures",
940
+ codecsDataStructures.getArrayEncoder(codecsDataStructures.getBytesEncoder({ size: 64 }), {
941
+ description: signaturesDescription,
942
+ size: codecsNumbers.getShortU16Encoder()
943
+ })
944
+ ],
945
+ ["compiledMessage", getCompiledMessageEncoder()]
946
+ ],
947
+ {
948
+ description: transactionDescription
949
+ }
950
+ );
690
951
  }
691
- async function signTransaction(keyPair, transaction) {
952
+ function getSignatureDecoder() {
953
+ return codecsCore.mapDecoder(codecsDataStructures.getBytesDecoder({ size: 64 }), (bytes) => bytes);
954
+ }
955
+ function getCompiledTransactionDecoder() {
956
+ return codecsDataStructures.getStructDecoder(
957
+ [
958
+ [
959
+ "signatures",
960
+ codecsDataStructures.getArrayDecoder(getSignatureDecoder(), {
961
+ description: signaturesDescription,
962
+ size: codecsNumbers.getShortU16Decoder()
963
+ })
964
+ ],
965
+ ["compiledMessage", getCompiledMessageDecoder()]
966
+ ],
967
+ {
968
+ description: transactionDescription
969
+ }
970
+ );
971
+ }
972
+ function getTransactionEncoder() {
973
+ return codecsCore.mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);
974
+ }
975
+ function getTransactionDecoder(lastValidBlockHeight) {
976
+ return codecsCore.mapDecoder(
977
+ getCompiledTransactionDecoder(),
978
+ (compiledTransaction) => decompileTransaction(compiledTransaction, lastValidBlockHeight)
979
+ );
980
+ }
981
+ function getTransactionCodec(lastValidBlockHeight) {
982
+ return codecsCore.combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));
983
+ }
984
+ function assertIsTransactionSignature(putativeTransactionSignature) {
985
+ try {
986
+ if (
987
+ // Lowest value (64 bytes of zeroes)
988
+ putativeTransactionSignature.length < 64 || // Highest value (64 bytes of 255)
989
+ putativeTransactionSignature.length > 88
990
+ ) {
991
+ throw new Error("Expected input string to decode to a byte array of length 64.");
992
+ }
993
+ const bytes = umiSerializers.base58.serialize(putativeTransactionSignature);
994
+ const numBytes = bytes.byteLength;
995
+ if (numBytes !== 64) {
996
+ throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
997
+ }
998
+ } catch (e) {
999
+ throw new Error(`\`${putativeTransactionSignature}\` is not a transaction signature`, {
1000
+ cause: e
1001
+ });
1002
+ }
1003
+ }
1004
+ function isTransactionSignature(putativeTransactionSignature) {
1005
+ if (
1006
+ // Lowest value (64 bytes of zeroes)
1007
+ putativeTransactionSignature.length < 64 || // Highest value (64 bytes of 255)
1008
+ putativeTransactionSignature.length > 88
1009
+ ) {
1010
+ return false;
1011
+ }
1012
+ const bytes = umiSerializers.base58.serialize(putativeTransactionSignature);
1013
+ const numBytes = bytes.byteLength;
1014
+ if (numBytes !== 64) {
1015
+ return false;
1016
+ }
1017
+ return true;
1018
+ }
1019
+ function getSignatureFromTransaction(transaction) {
1020
+ const signatureBytes = transaction.signatures[transaction.feePayer];
1021
+ if (!signatureBytes) {
1022
+ throw new Error(
1023
+ "Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer."
1024
+ );
1025
+ }
1026
+ const transactionSignature2 = umiSerializers.base58.deserialize(signatureBytes)[0];
1027
+ return transactionSignature2;
1028
+ }
1029
+ async function signTransaction(keyPairs, transaction) {
692
1030
  const compiledMessage = compileMessage(transaction);
693
- const [signerPublicKey, signature] = await Promise.all([
694
- addresses.getAddressFromPublicKey(keyPair.publicKey),
695
- getCompiledMessageSignature(compiledMessage, keyPair.privateKey)
696
- ]);
697
- const nextSignatures = {
698
- ..."signatures" in transaction ? transaction.signatures : null,
699
- ...{ [signerPublicKey]: signature }
700
- };
1031
+ const nextSignatures = "signatures" in transaction ? { ...transaction.signatures } : {};
1032
+ const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);
1033
+ const publicKeySignaturePairs = await Promise.all(
1034
+ keyPairs.map(
1035
+ (keyPair) => Promise.all([addresses.getAddressFromPublicKey(keyPair.publicKey), keys.signBytes(keyPair.privateKey, wireMessageBytes)])
1036
+ )
1037
+ );
1038
+ for (const [signerPublicKey, signature] of publicKeySignaturePairs) {
1039
+ nextSignatures[signerPublicKey] = signature;
1040
+ }
701
1041
  const out = {
702
1042
  ...transaction,
703
1043
  signatures: nextSignatures
@@ -705,55 +1045,23 @@ async function signTransaction(keyPair, transaction) {
705
1045
  Object.freeze(out);
706
1046
  return out;
707
1047
  }
708
-
709
- // src/compile-transaction.ts
710
- function getCompiledTransaction(transaction) {
711
- const compiledMessage = compileMessage(transaction);
712
- let signatures;
713
- if ("signatures" in transaction) {
714
- signatures = [];
715
- for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {
716
- signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));
717
- }
718
- } else {
719
- signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));
720
- }
721
- return {
722
- compiledMessage,
723
- signatures
724
- };
725
- }
726
-
727
- // src/serializers/transaction.ts
728
- var BASE_CONFIG3 = {
729
- description: __DEV__ ? "The wire format of a Solana transaction" : "",
730
- fixedSize: null,
731
- maxSize: null
732
- };
733
- function serialize3(transaction) {
734
- const compiledTransaction = getCompiledTransaction(transaction);
735
- return umiSerializers.struct([
736
- [
737
- "signatures",
738
- umiSerializers.array(umiSerializers.bytes({ size: 64 }), {
739
- ...__DEV__ ? { description: "A compact array of 64-byte, base-64 encoded Ed25519 signatures" } : null,
740
- size: umiSerializers.shortU16()
741
- })
742
- ],
743
- ["compiledMessage", getCompiledMessageEncoder()]
744
- ]).serialize(compiledTransaction);
1048
+ function transactionSignature(putativeTransactionSignature) {
1049
+ assertIsTransactionSignature(putativeTransactionSignature);
1050
+ return putativeTransactionSignature;
745
1051
  }
746
- function getTransactionEncoder() {
747
- return {
748
- ...BASE_CONFIG3,
749
- deserialize: getUnimplementedDecoder("CompiledMessage"),
750
- serialize: serialize3
751
- };
1052
+ function assertTransactionIsFullySigned(transaction) {
1053
+ const signerAddressesFromInstructions = transaction.instructions.flatMap((i) => i.accounts?.filter((a) => isSignerRole(a.role)) ?? []).map((a) => a.address);
1054
+ const requiredSigners = /* @__PURE__ */ new Set([transaction.feePayer, ...signerAddressesFromInstructions]);
1055
+ requiredSigners.forEach((address) => {
1056
+ if (!transaction.signatures[address]) {
1057
+ throw new Error(`Transaction is missing signature for address \`${address}\``);
1058
+ }
1059
+ });
752
1060
  }
753
1061
 
754
1062
  // src/wire-transaction.ts
755
1063
  function getBase64EncodedWireTransaction(transaction) {
756
- const wireTransactionBytes = getTransactionEncoder().serialize(transaction);
1064
+ const wireTransactionBytes = getTransactionEncoder().encode(transaction);
757
1065
  {
758
1066
  return btoa(String.fromCharCode(...wireTransactionBytes));
759
1067
  }
@@ -762,10 +1070,21 @@ function getBase64EncodedWireTransaction(transaction) {
762
1070
  exports.appendTransactionInstruction = appendTransactionInstruction;
763
1071
  exports.assertIsBlockhash = assertIsBlockhash;
764
1072
  exports.assertIsDurableNonceTransaction = assertIsDurableNonceTransaction;
1073
+ exports.assertIsTransactionSignature = assertIsTransactionSignature;
1074
+ exports.assertTransactionIsFullySigned = assertTransactionIsFullySigned;
765
1075
  exports.createTransaction = createTransaction;
766
1076
  exports.getBase64EncodedWireTransaction = getBase64EncodedWireTransaction;
1077
+ exports.getSignatureFromTransaction = getSignatureFromTransaction;
1078
+ exports.getTransactionCodec = getTransactionCodec;
1079
+ exports.getTransactionDecoder = getTransactionDecoder;
1080
+ exports.getTransactionEncoder = getTransactionEncoder;
1081
+ exports.isAdvanceNonceAccountInstruction = isAdvanceNonceAccountInstruction;
1082
+ exports.isTransactionSignature = isTransactionSignature;
767
1083
  exports.prependTransactionInstruction = prependTransactionInstruction;
768
1084
  exports.setTransactionFeePayer = setTransactionFeePayer;
769
1085
  exports.setTransactionLifetimeUsingBlockhash = setTransactionLifetimeUsingBlockhash;
770
1086
  exports.setTransactionLifetimeUsingDurableNonce = setTransactionLifetimeUsingDurableNonce;
771
1087
  exports.signTransaction = signTransaction;
1088
+ exports.transactionSignature = transactionSignature;
1089
+ //# sourceMappingURL=out.js.map
1090
+ //# sourceMappingURL=index.browser.cjs.map