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