@solana/transactions 2.0.0-experimental.2a97655 → 2.0.0-experimental.2ac1df6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +272 -5
  3. package/dist/index.browser.cjs +433 -276
  4. package/dist/index.browser.cjs.map +1 -1
  5. package/dist/index.browser.js +425 -278
  6. package/dist/index.browser.js.map +1 -1
  7. package/dist/index.native.js +425 -278
  8. package/dist/index.native.js.map +1 -1
  9. package/dist/index.node.cjs +433 -276
  10. package/dist/index.node.cjs.map +1 -1
  11. package/dist/index.node.js +425 -278
  12. package/dist/index.node.js.map +1 -1
  13. package/dist/types/accounts.d.ts +3 -3
  14. package/dist/types/accounts.d.ts.map +1 -1
  15. package/dist/types/blockhash.d.ts +5 -4
  16. package/dist/types/blockhash.d.ts.map +1 -1
  17. package/dist/types/compilable-transaction.d.ts +7 -0
  18. package/dist/types/compilable-transaction.d.ts.map +1 -0
  19. package/dist/types/compile-address-table-lookups.d.ts +3 -3
  20. package/dist/types/compile-address-table-lookups.d.ts.map +1 -1
  21. package/dist/types/compile-header.d.ts +1 -1
  22. package/dist/types/compile-instructions.d.ts +2 -2
  23. package/dist/types/compile-instructions.d.ts.map +1 -1
  24. package/dist/types/compile-lifetime-token.d.ts +1 -1
  25. package/dist/types/compile-static-accounts.d.ts +3 -3
  26. package/dist/types/compile-static-accounts.d.ts.map +1 -1
  27. package/dist/types/compile-transaction.d.ts +6 -7
  28. package/dist/types/compile-transaction.d.ts.map +1 -1
  29. package/dist/types/create-transaction.d.ts +1 -1
  30. package/dist/types/decompile-transaction.d.ts +5 -0
  31. package/dist/types/decompile-transaction.d.ts.map +1 -0
  32. package/dist/types/durable-nonce.d.ts +11 -10
  33. package/dist/types/durable-nonce.d.ts.map +1 -1
  34. package/dist/types/fee-payer.d.ts +6 -5
  35. package/dist/types/fee-payer.d.ts.map +1 -1
  36. package/dist/types/index.d.ts +11 -8
  37. package/dist/types/index.d.ts.map +1 -1
  38. package/dist/types/instructions.d.ts +2 -2
  39. package/dist/types/message.d.ts +6 -10
  40. package/dist/types/message.d.ts.map +1 -1
  41. package/dist/types/serializers/address-table-lookup.d.ts +5 -3
  42. package/dist/types/serializers/address-table-lookup.d.ts.map +1 -1
  43. package/dist/types/serializers/header.d.ts +5 -3
  44. package/dist/types/serializers/header.d.ts.map +1 -1
  45. package/dist/types/serializers/index.d.ts +3 -0
  46. package/dist/types/serializers/index.d.ts.map +1 -0
  47. package/dist/types/serializers/instruction.d.ts +5 -3
  48. package/dist/types/serializers/instruction.d.ts.map +1 -1
  49. package/dist/types/serializers/message.d.ts +5 -5
  50. package/dist/types/serializers/message.d.ts.map +1 -1
  51. package/dist/types/serializers/transaction-version.d.ts +5 -5
  52. package/dist/types/serializers/transaction-version.d.ts.map +1 -1
  53. package/dist/types/serializers/transaction.d.ts +6 -5
  54. package/dist/types/serializers/transaction.d.ts.map +1 -1
  55. package/dist/types/signatures.d.ts +10 -5
  56. package/dist/types/signatures.d.ts.map +1 -1
  57. package/dist/types/types.d.ts +13 -13
  58. package/dist/types/types.d.ts.map +1 -1
  59. package/dist/types/unsigned-transaction.d.ts +1 -1
  60. package/dist/types/wire-transaction.d.ts +3 -3
  61. package/dist/types/wire-transaction.d.ts.map +1 -1
  62. package/package.json +24 -20
  63. package/dist/index.development.js +0 -1323
  64. package/dist/index.development.js.map +0 -1
  65. package/dist/index.production.min.js +0 -20
  66. package/dist/types/serializers/unimplemented.d.ts +0 -3
  67. package/dist/types/serializers/unimplemented.d.ts.map +0 -1
@@ -1,10 +1,14 @@
1
1
  'use strict';
2
2
 
3
- var umiSerializers = require('@metaplex-foundation/umi-serializers');
3
+ var codecsStrings = require('@solana/codecs-strings');
4
+ var addresses = require('@solana/addresses');
5
+ var codecsCore = require('@solana/codecs-core');
6
+ var codecsDataStructures = require('@solana/codecs-data-structures');
7
+ var codecsNumbers = require('@solana/codecs-numbers');
8
+ var functional = require('@solana/functional');
4
9
  var keys = require('@solana/keys');
5
10
 
6
- // ../build-scripts/env-shim.ts
7
- var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
11
+ // src/blockhash.ts
8
12
 
9
13
  // src/unsigned-transaction.ts
10
14
  function getUnsignedTransaction(transaction) {
@@ -21,7 +25,10 @@ function getUnsignedTransaction(transaction) {
21
25
  }
22
26
 
23
27
  // src/blockhash.ts
28
+ var base58Encoder;
24
29
  function assertIsBlockhash(putativeBlockhash) {
30
+ if (!base58Encoder)
31
+ base58Encoder = codecsStrings.getBase58Encoder();
25
32
  try {
26
33
  if (
27
34
  // Lowest value (32 bytes of zeroes)
@@ -30,8 +37,8 @@ function assertIsBlockhash(putativeBlockhash) {
30
37
  ) {
31
38
  throw new Error("Expected input string to decode to a byte array of length 32.");
32
39
  }
33
- const bytes3 = umiSerializers.base58.serialize(putativeBlockhash);
34
- const numBytes = bytes3.byteLength;
40
+ const bytes = base58Encoder.encode(putativeBlockhash);
41
+ const numBytes = bytes.byteLength;
35
42
  if (numBytes !== 32) {
36
43
  throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
37
44
  }
@@ -41,6 +48,22 @@ function assertIsBlockhash(putativeBlockhash) {
41
48
  });
42
49
  }
43
50
  }
51
+ function isTransactionWithBlockhashLifetime(transaction) {
52
+ const lifetimeConstraintShapeMatches = "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.blockhash === "string" && typeof transaction.lifetimeConstraint.lastValidBlockHeight === "bigint";
53
+ if (!lifetimeConstraintShapeMatches)
54
+ return false;
55
+ try {
56
+ assertIsBlockhash(transaction.lifetimeConstraint.blockhash);
57
+ return true;
58
+ } catch {
59
+ return false;
60
+ }
61
+ }
62
+ function assertIsTransactionWithBlockhashLifetime(transaction) {
63
+ if (!isTransactionWithBlockhashLifetime(transaction)) {
64
+ throw new Error("Transaction does not have a blockhash lifetime");
65
+ }
66
+ }
44
67
  function setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) {
45
68
  if ("lifetimeConstraint" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) {
46
69
  return transaction;
@@ -116,7 +139,7 @@ function isAdvanceNonceAccountInstruction(instruction) {
116
139
  instruction.accounts?.length === 3 && // First account is nonce account address
117
140
  instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar
118
141
  instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account
119
- instruction.accounts[2].address != null && instruction.accounts[2].role === AccountRole.READONLY_SIGNER;
142
+ instruction.accounts[2].address != null && isSignerRole(instruction.accounts[2].role);
120
143
  }
121
144
  function isAdvanceNonceAccountInstructionData(data) {
122
145
  return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
@@ -124,21 +147,38 @@ function isAdvanceNonceAccountInstructionData(data) {
124
147
  function isDurableNonceTransaction(transaction) {
125
148
  return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);
126
149
  }
150
+ function isAdvanceNonceAccountInstructionForNonce(instruction, nonceAccountAddress, nonceAuthorityAddress) {
151
+ return instruction.accounts[0].address === nonceAccountAddress && instruction.accounts[2].address === nonceAuthorityAddress;
152
+ }
127
153
  function setTransactionLifetimeUsingDurableNonce({
128
154
  nonce,
129
155
  nonceAccountAddress,
130
156
  nonceAuthorityAddress
131
157
  }, transaction) {
132
- const isAlreadyDurableNonceTransaction = isDurableNonceTransaction(transaction);
133
- if (isAlreadyDurableNonceTransaction && transaction.lifetimeConstraint.nonce === nonce && transaction.instructions[0].accounts[0].address === nonceAccountAddress && transaction.instructions[0].accounts[2].address === nonceAuthorityAddress) {
134
- return transaction;
158
+ let newInstructions;
159
+ const firstInstruction = transaction.instructions[0];
160
+ if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {
161
+ if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {
162
+ if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {
163
+ return transaction;
164
+ } else {
165
+ newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];
166
+ }
167
+ } else {
168
+ newInstructions = [
169
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
170
+ ...transaction.instructions.slice(1)
171
+ ];
172
+ }
173
+ } else {
174
+ newInstructions = [
175
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
176
+ ...transaction.instructions
177
+ ];
135
178
  }
136
179
  const out = {
137
180
  ...getUnsignedTransaction(transaction),
138
- instructions: [
139
- createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
140
- ...isAlreadyDurableNonceTransaction ? transaction.instructions.slice(1) : transaction.instructions
141
- ],
181
+ instructions: newInstructions,
142
182
  lifetimeConstraint: {
143
183
  nonce
144
184
  }
@@ -229,7 +269,7 @@ function getAddressMapFromInstructions(feePayer, instructions) {
229
269
  const shouldReplaceEntry = (
230
270
  // Consider using the new LOOKUP_TABLE if its address is different...
231
271
  entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
232
- (addressComparator || (addressComparator = keys.getBase58EncodedAddressComparator()))(
272
+ (addressComparator ||= addresses.getAddressComparator())(
233
273
  accountMeta.lookupTableAddress,
234
274
  entry.lookupTableAddress
235
275
  ) < 0
@@ -335,7 +375,7 @@ function getOrderedAccountsFromAddressMap(addressMap) {
335
375
  if (leftIsWritable !== isWritableRole(rightEntry.role)) {
336
376
  return leftIsWritable ? -1 : 1;
337
377
  }
338
- addressComparator || (addressComparator = keys.getBase58EncodedAddressComparator());
378
+ addressComparator ||= addresses.getAddressComparator();
339
379
  if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
340
380
  return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
341
381
  } else {
@@ -348,23 +388,22 @@ function getOrderedAccountsFromAddressMap(addressMap) {
348
388
  return orderedAccounts;
349
389
  }
350
390
  function getCompiledAddressTableLookups(orderedAccounts) {
351
- var _a;
352
391
  const index = {};
353
392
  for (const account of orderedAccounts) {
354
393
  if (!("lookupTableAddress" in account)) {
355
394
  continue;
356
395
  }
357
- const entry = index[_a = account.lookupTableAddress] || (index[_a] = {
396
+ const entry = index[account.lookupTableAddress] ||= {
358
397
  readableIndices: [],
359
398
  writableIndices: []
360
- });
399
+ };
361
400
  if (account.role === AccountRole.WRITABLE) {
362
401
  entry.writableIndices.push(account.addressIndex);
363
402
  } else {
364
403
  entry.readableIndices.push(account.addressIndex);
365
404
  }
366
405
  }
367
- return Object.keys(index).sort(keys.getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({
406
+ return Object.keys(index).sort(addresses.getAddressComparator()).map((lookupTableAddress) => ({
368
407
  lookupTableAddress,
369
408
  ...index[lookupTableAddress]
370
409
  }));
@@ -443,266 +482,215 @@ function compileMessage(transaction) {
443
482
  version: transaction.version
444
483
  };
445
484
  }
446
- function getAddressTableLookupCodec() {
447
- return umiSerializers.struct(
448
- [
449
- [
450
- "lookupTableAddress",
451
- keys.getBase58EncodedAddressCodec(
452
- __DEV__ ? {
453
- description: "The address of the address lookup table account from which instruction addresses should be looked up"
454
- } : void 0
455
- )
456
- ],
485
+ var memoizedAddressTableLookupEncoder;
486
+ function getAddressTableLookupEncoder() {
487
+ if (!memoizedAddressTableLookupEncoder) {
488
+ memoizedAddressTableLookupEncoder = codecsDataStructures.getStructEncoder([
489
+ ["lookupTableAddress", addresses.getAddressEncoder()],
457
490
  [
458
491
  "writableIndices",
459
- umiSerializers.array(umiSerializers.u8(), {
460
- ...__DEV__ ? {
461
- description: "The indices of the accounts in the lookup table that should be loaded as writeable"
462
- } : null,
463
- size: umiSerializers.shortU16()
464
- })
492
+ codecsDataStructures.getArrayEncoder(codecsNumbers.getU8Encoder(), { size: codecsNumbers.getShortU16Encoder() })
465
493
  ],
466
494
  [
467
495
  "readableIndices",
468
- umiSerializers.array(umiSerializers.u8(), {
469
- ...__DEV__ ? {
470
- description: "The indices of the accounts in the lookup table that should be loaded as read-only"
471
- } : void 0,
472
- size: umiSerializers.shortU16()
473
- })
496
+ codecsDataStructures.getArrayEncoder(codecsNumbers.getU8Encoder(), { size: codecsNumbers.getShortU16Encoder() })
474
497
  ]
475
- ],
476
- __DEV__ ? {
477
- 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"
478
- } : void 0
479
- );
498
+ ]);
499
+ }
500
+ return memoizedAddressTableLookupEncoder;
501
+ }
502
+ var memoizedAddressTableLookupDecoder;
503
+ function getAddressTableLookupDecoder() {
504
+ if (!memoizedAddressTableLookupDecoder) {
505
+ memoizedAddressTableLookupDecoder = codecsDataStructures.getStructDecoder([
506
+ ["lookupTableAddress", addresses.getAddressDecoder()],
507
+ ["writableIndices", codecsDataStructures.getArrayDecoder(codecsNumbers.getU8Decoder(), { size: codecsNumbers.getShortU16Decoder() })],
508
+ ["readableIndices", codecsDataStructures.getArrayDecoder(codecsNumbers.getU8Decoder(), { size: codecsNumbers.getShortU16Decoder() })]
509
+ ]);
510
+ }
511
+ return memoizedAddressTableLookupDecoder;
512
+ }
513
+ var memoizedU8Encoder;
514
+ function getMemoizedU8Encoder() {
515
+ if (!memoizedU8Encoder)
516
+ memoizedU8Encoder = codecsNumbers.getU8Encoder();
517
+ return memoizedU8Encoder;
518
+ }
519
+ var memoizedU8Decoder;
520
+ function getMemoizedU8Decoder() {
521
+ if (!memoizedU8Decoder)
522
+ memoizedU8Decoder = codecsNumbers.getU8Decoder();
523
+ return memoizedU8Decoder;
524
+ }
525
+ function getMessageHeaderEncoder() {
526
+ return codecsDataStructures.getStructEncoder([
527
+ ["numSignerAccounts", getMemoizedU8Encoder()],
528
+ ["numReadonlySignerAccounts", getMemoizedU8Encoder()],
529
+ ["numReadonlyNonSignerAccounts", getMemoizedU8Encoder()]
530
+ ]);
480
531
  }
481
- function getMessageHeaderCodec() {
482
- return umiSerializers.struct(
483
- [
484
- [
485
- "numSignerAccounts",
486
- umiSerializers.u8(
487
- __DEV__ ? {
488
- description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction"
489
- } : void 0
490
- )
491
- ],
492
- [
493
- "numReadonlySignerAccounts",
494
- umiSerializers.u8(
495
- __DEV__ ? {
496
- 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"
497
- } : void 0
498
- )
499
- ],
500
- [
501
- "numReadonlyNonSignerAccounts",
502
- umiSerializers.u8(
503
- __DEV__ ? {
504
- description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable"
505
- } : void 0
506
- )
507
- ]
508
- ],
509
- __DEV__ ? {
510
- description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses"
511
- } : void 0
512
- );
532
+ function getMessageHeaderDecoder() {
533
+ return codecsDataStructures.getStructDecoder([
534
+ ["numSignerAccounts", getMemoizedU8Decoder()],
535
+ ["numReadonlySignerAccounts", getMemoizedU8Decoder()],
536
+ ["numReadonlyNonSignerAccounts", getMemoizedU8Decoder()]
537
+ ]);
513
538
  }
514
- function getInstructionCodec() {
515
- return umiSerializers.mapSerializer(
516
- umiSerializers.struct([
517
- [
518
- "programAddressIndex",
519
- umiSerializers.u8(
520
- __DEV__ ? {
521
- description: "The index of the program being called, according to the well-ordered accounts list for this transaction"
522
- } : void 0
523
- )
524
- ],
525
- [
526
- "addressIndices",
527
- umiSerializers.array(
528
- umiSerializers.u8({
529
- description: __DEV__ ? "The index of an account, according to the well-ordered accounts list for this transaction" : ""
530
- }),
531
- {
532
- 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" : "",
533
- size: umiSerializers.shortU16()
534
- }
535
- )
536
- ],
537
- [
538
- "data",
539
- umiSerializers.bytes({
540
- description: __DEV__ ? "An optional buffer of data passed to the instruction" : "",
541
- size: umiSerializers.shortU16()
542
- })
543
- ]
539
+ var memoizedGetInstructionEncoder;
540
+ function getInstructionEncoder() {
541
+ if (!memoizedGetInstructionEncoder) {
542
+ memoizedGetInstructionEncoder = codecsCore.mapEncoder(
543
+ codecsDataStructures.getStructEncoder([
544
+ ["programAddressIndex", codecsNumbers.getU8Encoder()],
545
+ ["accountIndices", codecsDataStructures.getArrayEncoder(codecsNumbers.getU8Encoder(), { size: codecsNumbers.getShortU16Encoder() })],
546
+ ["data", codecsDataStructures.getBytesEncoder({ size: codecsNumbers.getShortU16Encoder() })]
547
+ ]),
548
+ // Convert an instruction to have all fields defined
549
+ (instruction) => {
550
+ if (instruction.accountIndices !== void 0 && instruction.data !== void 0) {
551
+ return instruction;
552
+ }
553
+ return {
554
+ ...instruction,
555
+ accountIndices: instruction.accountIndices ?? [],
556
+ data: instruction.data ?? new Uint8Array(0)
557
+ };
558
+ }
559
+ );
560
+ }
561
+ return memoizedGetInstructionEncoder;
562
+ }
563
+ var memoizedGetInstructionDecoder;
564
+ function getInstructionDecoder() {
565
+ if (!memoizedGetInstructionDecoder) {
566
+ memoizedGetInstructionDecoder = codecsCore.mapDecoder(
567
+ codecsDataStructures.getStructDecoder([
568
+ ["programAddressIndex", codecsNumbers.getU8Decoder()],
569
+ ["accountIndices", codecsDataStructures.getArrayDecoder(codecsNumbers.getU8Decoder(), { size: codecsNumbers.getShortU16Decoder() })],
570
+ ["data", codecsDataStructures.getBytesDecoder({ size: codecsNumbers.getShortU16Decoder() })]
571
+ ]),
572
+ // Convert an instruction to exclude optional fields if they are empty
573
+ (instruction) => {
574
+ if (instruction.accountIndices.length && instruction.data.byteLength) {
575
+ return instruction;
576
+ }
577
+ const { accountIndices, data, ...rest } = instruction;
578
+ return {
579
+ ...rest,
580
+ ...accountIndices.length ? { accountIndices } : null,
581
+ ...data.byteLength ? { data } : null
582
+ };
583
+ }
584
+ );
585
+ }
586
+ return memoizedGetInstructionDecoder;
587
+ }
588
+ var VERSION_FLAG_MASK = 128;
589
+ function getTransactionVersionEncoder() {
590
+ return codecsCore.createEncoder({
591
+ getSizeFromValue: (value) => value === "legacy" ? 0 : 1,
592
+ maxSize: 1,
593
+ write: (value, bytes, offset) => {
594
+ if (value === "legacy") {
595
+ return offset;
596
+ }
597
+ if (value < 0 || value > 127) {
598
+ throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`);
599
+ }
600
+ bytes.set([value | VERSION_FLAG_MASK], offset);
601
+ return offset + 1;
602
+ }
603
+ });
604
+ }
605
+ function getTransactionVersionDecoder() {
606
+ return codecsCore.createDecoder({
607
+ maxSize: 1,
608
+ read: (bytes, offset) => {
609
+ const firstByte = bytes[offset];
610
+ if ((firstByte & VERSION_FLAG_MASK) === 0) {
611
+ return ["legacy", offset];
612
+ } else {
613
+ const version = firstByte ^ VERSION_FLAG_MASK;
614
+ return [version, offset + 1];
615
+ }
616
+ }
617
+ });
618
+ }
619
+
620
+ // src/serializers/message.ts
621
+ function getCompiledMessageLegacyEncoder() {
622
+ return codecsDataStructures.getStructEncoder(getPreludeStructEncoderTuple());
623
+ }
624
+ function getCompiledMessageVersionedEncoder() {
625
+ return codecsCore.mapEncoder(
626
+ codecsDataStructures.getStructEncoder([
627
+ ...getPreludeStructEncoderTuple(),
628
+ ["addressTableLookups", getAddressTableLookupArrayEncoder()]
544
629
  ]),
545
630
  (value) => {
546
- if (value.addressIndices !== void 0 && value.data !== void 0) {
631
+ if (value.version === "legacy") {
547
632
  return value;
548
633
  }
549
634
  return {
550
635
  ...value,
551
- addressIndices: value.addressIndices ?? [],
552
- data: value.data ?? new Uint8Array(0)
553
- };
554
- },
555
- (value) => {
556
- if (value.addressIndices.length && value.data.byteLength) {
557
- return value;
558
- }
559
- const { addressIndices, data, ...rest } = value;
560
- return {
561
- ...rest,
562
- ...addressIndices.length ? { addressIndices } : null,
563
- ...data.byteLength ? { data } : null
636
+ addressTableLookups: value.addressTableLookups ?? []
564
637
  };
565
638
  }
566
639
  );
567
640
  }
568
-
569
- // src/serializers/unimplemented.ts
570
- function getError(type, name) {
571
- const functionSuffix = name + type[0].toUpperCase() + type.slice(1);
572
- return new Error(
573
- `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}`
574
- );
575
- }
576
- function getUnimplementedDecoder(name) {
577
- return () => {
578
- throw getError("decoder", name);
579
- };
580
- }
581
-
582
- // src/serializers/transaction-version.ts
583
- var VERSION_FLAG_MASK = 128;
584
- var BASE_CONFIG = {
585
- description: __DEV__ ? "A single byte that encodes the version of the transaction" : "",
586
- fixedSize: null,
587
- maxSize: 1
588
- };
589
- function deserialize(bytes3, offset = 0) {
590
- const firstByte = bytes3[offset];
591
- if ((firstByte & VERSION_FLAG_MASK) === 0) {
592
- return ["legacy", offset];
593
- } else {
594
- const version = firstByte ^ VERSION_FLAG_MASK;
595
- return [version, offset + 1];
596
- }
597
- }
598
- function serialize(value) {
599
- if (value === "legacy") {
600
- return new Uint8Array();
601
- }
602
- if (value < 0 || value > 127) {
603
- throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`);
604
- }
605
- return new Uint8Array([value | VERSION_FLAG_MASK]);
606
- }
607
- function getTransactionVersionCodec() {
608
- return {
609
- ...BASE_CONFIG,
610
- deserialize,
611
- serialize
612
- };
613
- }
614
-
615
- // src/serializers/message.ts
616
- var BASE_CONFIG2 = {
617
- description: __DEV__ ? "The wire format of a Solana transaction message" : "",
618
- fixedSize: null,
619
- maxSize: null
620
- };
621
- function serialize2(compiledMessage) {
622
- if (compiledMessage.version === "legacy") {
623
- return umiSerializers.struct(getPreludeStructSerializerTuple()).serialize(compiledMessage);
624
- } else {
625
- return umiSerializers.mapSerializer(
626
- umiSerializers.struct([
627
- ...getPreludeStructSerializerTuple(),
628
- ["addressTableLookups", getAddressTableLookupsSerializer()]
629
- ]),
630
- (value) => {
631
- if (value.version === "legacy") {
632
- return value;
633
- }
634
- return {
635
- ...value,
636
- addressTableLookups: value.addressTableLookups ?? []
637
- };
638
- }
639
- ).serialize(compiledMessage);
640
- }
641
+ function getPreludeStructEncoderTuple() {
642
+ return [
643
+ ["version", getTransactionVersionEncoder()],
644
+ ["header", getMessageHeaderEncoder()],
645
+ ["staticAccounts", codecsDataStructures.getArrayEncoder(addresses.getAddressEncoder(), { size: codecsNumbers.getShortU16Encoder() })],
646
+ ["lifetimeToken", codecsStrings.getStringEncoder({ encoding: codecsStrings.getBase58Encoder(), size: 32 })],
647
+ ["instructions", codecsDataStructures.getArrayEncoder(getInstructionEncoder(), { size: codecsNumbers.getShortU16Encoder() })]
648
+ ];
641
649
  }
642
- function getPreludeStructSerializerTuple() {
650
+ function getPreludeStructDecoderTuple() {
643
651
  return [
644
- ["version", getTransactionVersionCodec()],
645
- ["header", getMessageHeaderCodec()],
646
- [
647
- "staticAccounts",
648
- umiSerializers.array(keys.getBase58EncodedAddressCodec(), {
649
- description: __DEV__ ? "A compact-array of static account addresses belonging to this transaction" : "",
650
- size: umiSerializers.shortU16()
651
- })
652
- ],
653
- [
654
- "lifetimeToken",
655
- umiSerializers.string({
656
- description: __DEV__ ? "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" : "",
657
- encoding: umiSerializers.base58,
658
- size: 32
659
- })
660
- ],
661
- [
662
- "instructions",
663
- umiSerializers.array(getInstructionCodec(), {
664
- description: __DEV__ ? "A compact-array of instructions belonging to this transaction" : "",
665
- size: umiSerializers.shortU16()
666
- })
667
- ]
652
+ ["version", getTransactionVersionDecoder()],
653
+ ["header", getMessageHeaderDecoder()],
654
+ ["staticAccounts", codecsDataStructures.getArrayDecoder(addresses.getAddressDecoder(), { size: codecsNumbers.getShortU16Decoder() })],
655
+ ["lifetimeToken", codecsStrings.getStringDecoder({ encoding: codecsStrings.getBase58Decoder(), size: 32 })],
656
+ ["instructions", codecsDataStructures.getArrayDecoder(getInstructionDecoder(), { size: codecsNumbers.getShortU16Decoder() })],
657
+ ["addressTableLookups", getAddressTableLookupArrayDecoder()]
668
658
  ];
669
659
  }
670
- function getAddressTableLookupsSerializer() {
671
- return umiSerializers.array(getAddressTableLookupCodec(), {
672
- ...__DEV__ ? { description: "A compact array of address table lookups belonging to this transaction" } : null,
673
- size: umiSerializers.shortU16()
674
- });
660
+ function getAddressTableLookupArrayEncoder() {
661
+ return codecsDataStructures.getArrayEncoder(getAddressTableLookupEncoder(), { size: codecsNumbers.getShortU16Encoder() });
662
+ }
663
+ function getAddressTableLookupArrayDecoder() {
664
+ return codecsDataStructures.getArrayDecoder(getAddressTableLookupDecoder(), { size: codecsNumbers.getShortU16Decoder() });
675
665
  }
676
666
  function getCompiledMessageEncoder() {
677
- return {
678
- ...BASE_CONFIG2,
679
- deserialize: getUnimplementedDecoder("CompiledMessage"),
680
- serialize: serialize2
681
- };
667
+ return codecsCore.createEncoder({
668
+ getSizeFromValue: (compiledMessage) => {
669
+ if (compiledMessage.version === "legacy") {
670
+ return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);
671
+ } else {
672
+ return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);
673
+ }
674
+ },
675
+ write: (compiledMessage, bytes, offset) => {
676
+ if (compiledMessage.version === "legacy") {
677
+ return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);
678
+ } else {
679
+ return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);
680
+ }
681
+ }
682
+ });
682
683
  }
683
-
684
- // src/signatures.ts
685
- async function getCompiledMessageSignature(message, secretKey) {
686
- const wireMessageBytes = getCompiledMessageEncoder().serialize(message);
687
- const signature = await keys.signBytes(secretKey, wireMessageBytes);
688
- return signature;
684
+ function getCompiledMessageDecoder() {
685
+ return codecsCore.mapDecoder(codecsDataStructures.getStructDecoder(getPreludeStructDecoderTuple()), ({ addressTableLookups, ...restOfMessage }) => {
686
+ if (restOfMessage.version === "legacy" || !addressTableLookups?.length) {
687
+ return restOfMessage;
688
+ }
689
+ return { ...restOfMessage, addressTableLookups };
690
+ });
689
691
  }
690
- async function signTransaction(keyPair, transaction) {
691
- const compiledMessage = compileMessage(transaction);
692
- const [signerPublicKey, signature] = await Promise.all([
693
- keys.getBase58EncodedAddressFromPublicKey(keyPair.publicKey),
694
- getCompiledMessageSignature(compiledMessage, keyPair.privateKey)
695
- ]);
696
- const nextSignatures = {
697
- ..."signatures" in transaction ? transaction.signatures : null,
698
- ...{ [signerPublicKey]: signature }
699
- };
700
- const out = {
701
- ...transaction,
702
- signatures: nextSignatures
703
- };
704
- Object.freeze(out);
705
- return out;
692
+ function getCompiledMessageCodec() {
693
+ return codecsCore.combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());
706
694
  }
707
695
 
708
696
  // src/compile-transaction.ts
@@ -722,47 +710,216 @@ function getCompiledTransaction(transaction) {
722
710
  signatures
723
711
  };
724
712
  }
713
+ function getAccountMetas(message) {
714
+ const { header } = message;
715
+ const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;
716
+ const numWritableNonSignerAccounts = message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;
717
+ const accountMetas = [];
718
+ let accountIndex = 0;
719
+ for (let i = 0; i < numWritableSignerAccounts; i++) {
720
+ accountMetas.push({
721
+ address: message.staticAccounts[accountIndex],
722
+ role: AccountRole.WRITABLE_SIGNER
723
+ });
724
+ accountIndex++;
725
+ }
726
+ for (let i = 0; i < header.numReadonlySignerAccounts; i++) {
727
+ accountMetas.push({
728
+ address: message.staticAccounts[accountIndex],
729
+ role: AccountRole.READONLY_SIGNER
730
+ });
731
+ accountIndex++;
732
+ }
733
+ for (let i = 0; i < numWritableNonSignerAccounts; i++) {
734
+ accountMetas.push({
735
+ address: message.staticAccounts[accountIndex],
736
+ role: AccountRole.WRITABLE
737
+ });
738
+ accountIndex++;
739
+ }
740
+ for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {
741
+ accountMetas.push({
742
+ address: message.staticAccounts[accountIndex],
743
+ role: AccountRole.READONLY
744
+ });
745
+ accountIndex++;
746
+ }
747
+ return accountMetas;
748
+ }
749
+ function convertInstruction(instruction, accountMetas) {
750
+ const programAddress = accountMetas[instruction.programAddressIndex]?.address;
751
+ if (!programAddress) {
752
+ throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);
753
+ }
754
+ const accounts = instruction.accountIndices?.map((accountIndex) => accountMetas[accountIndex]);
755
+ const { data } = instruction;
756
+ return {
757
+ programAddress,
758
+ ...accounts && accounts.length ? { accounts } : {},
759
+ ...data && data.length ? { data } : {}
760
+ };
761
+ }
762
+ function getLifetimeConstraint(messageLifetimeToken, firstInstruction, lastValidBlockHeight) {
763
+ if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {
764
+ return {
765
+ blockhash: messageLifetimeToken,
766
+ lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n
767
+ // U64 MAX
768
+ };
769
+ } else {
770
+ const nonceAccountAddress = firstInstruction.accounts[0].address;
771
+ addresses.assertIsAddress(nonceAccountAddress);
772
+ const nonceAuthorityAddress = firstInstruction.accounts[2].address;
773
+ addresses.assertIsAddress(nonceAuthorityAddress);
774
+ return {
775
+ nonce: messageLifetimeToken,
776
+ nonceAccountAddress,
777
+ nonceAuthorityAddress
778
+ };
779
+ }
780
+ }
781
+ function convertSignatures(compiledTransaction) {
782
+ const {
783
+ compiledMessage: { staticAccounts },
784
+ signatures
785
+ } = compiledTransaction;
786
+ return signatures.reduce((acc, sig, index) => {
787
+ const allZeros = sig.every((byte) => byte === 0);
788
+ if (allZeros)
789
+ return acc;
790
+ const address = staticAccounts[index];
791
+ return { ...acc, [address]: sig };
792
+ }, {});
793
+ }
794
+ function decompileTransaction(compiledTransaction, lastValidBlockHeight) {
795
+ const { compiledMessage } = compiledTransaction;
796
+ if ("addressTableLookups" in compiledMessage && compiledMessage.addressTableLookups.length > 0) {
797
+ throw new Error("Cannot convert transaction with addressTableLookups");
798
+ }
799
+ const feePayer = compiledMessage.staticAccounts[0];
800
+ if (!feePayer)
801
+ throw new Error("No fee payer set in CompiledTransaction");
802
+ const accountMetas = getAccountMetas(compiledMessage);
803
+ const instructions = compiledMessage.instructions.map(
804
+ (compiledInstruction) => convertInstruction(compiledInstruction, accountMetas)
805
+ );
806
+ const firstInstruction = instructions[0];
807
+ const lifetimeConstraint = getLifetimeConstraint(
808
+ compiledMessage.lifetimeToken,
809
+ firstInstruction,
810
+ lastValidBlockHeight
811
+ );
812
+ const signatures = convertSignatures(compiledTransaction);
813
+ return functional.pipe(
814
+ createTransaction({ version: compiledMessage.version }),
815
+ (tx) => setTransactionFeePayer(feePayer, tx),
816
+ (tx) => instructions.reduce((acc, instruction) => {
817
+ return appendTransactionInstruction(instruction, acc);
818
+ }, tx),
819
+ (tx) => "blockhash" in lifetimeConstraint ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx) : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),
820
+ (tx) => compiledTransaction.signatures.length ? { ...tx, signatures } : tx
821
+ );
822
+ }
725
823
 
726
824
  // src/serializers/transaction.ts
727
- var BASE_CONFIG3 = {
728
- description: __DEV__ ? "The wire format of a Solana transaction" : "",
729
- fixedSize: null,
730
- maxSize: null
731
- };
732
- function serialize3(transaction) {
733
- const compiledTransaction = getCompiledTransaction(transaction);
734
- return umiSerializers.struct([
825
+ function getCompiledTransactionEncoder() {
826
+ return codecsDataStructures.getStructEncoder([
827
+ ["signatures", codecsDataStructures.getArrayEncoder(codecsDataStructures.getBytesEncoder({ size: 64 }), { size: codecsNumbers.getShortU16Encoder() })],
828
+ ["compiledMessage", getCompiledMessageEncoder()]
829
+ ]);
830
+ }
831
+ function getCompiledTransactionDecoder() {
832
+ return codecsDataStructures.getStructDecoder([
735
833
  [
736
834
  "signatures",
737
- umiSerializers.array(umiSerializers.bytes({ size: 64 }), {
738
- ...__DEV__ ? { description: "A compact array of 64-byte, base-64 encoded Ed25519 signatures" } : null,
739
- size: umiSerializers.shortU16()
835
+ codecsDataStructures.getArrayDecoder(codecsDataStructures.getBytesDecoder({ size: 64 }), {
836
+ size: codecsNumbers.getShortU16Decoder()
740
837
  })
741
838
  ],
742
- ["compiledMessage", getCompiledMessageEncoder()]
743
- ]).serialize(compiledTransaction);
839
+ ["compiledMessage", getCompiledMessageDecoder()]
840
+ ]);
744
841
  }
745
842
  function getTransactionEncoder() {
746
- return {
747
- ...BASE_CONFIG3,
748
- deserialize: getUnimplementedDecoder("CompiledMessage"),
749
- serialize: serialize3
843
+ return codecsCore.mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);
844
+ }
845
+ function getTransactionDecoder(lastValidBlockHeight) {
846
+ return codecsCore.mapDecoder(
847
+ getCompiledTransactionDecoder(),
848
+ (compiledTransaction) => decompileTransaction(compiledTransaction, lastValidBlockHeight)
849
+ );
850
+ }
851
+ function getTransactionCodec(lastValidBlockHeight) {
852
+ return codecsCore.combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));
853
+ }
854
+ var base58Decoder;
855
+ function getSignatureFromTransaction(transaction) {
856
+ if (!base58Decoder)
857
+ base58Decoder = codecsStrings.getBase58Decoder();
858
+ const signatureBytes = transaction.signatures[transaction.feePayer];
859
+ if (!signatureBytes) {
860
+ throw new Error(
861
+ "Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer."
862
+ );
863
+ }
864
+ const transactionSignature = base58Decoder.decode(signatureBytes);
865
+ return transactionSignature;
866
+ }
867
+ async function partiallySignTransaction(keyPairs, transaction) {
868
+ const compiledMessage = compileMessage(transaction);
869
+ const nextSignatures = "signatures" in transaction ? { ...transaction.signatures } : {};
870
+ const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);
871
+ const publicKeySignaturePairs = await Promise.all(
872
+ keyPairs.map(
873
+ (keyPair) => Promise.all([addresses.getAddressFromPublicKey(keyPair.publicKey), keys.signBytes(keyPair.privateKey, wireMessageBytes)])
874
+ )
875
+ );
876
+ for (const [signerPublicKey, signature] of publicKeySignaturePairs) {
877
+ nextSignatures[signerPublicKey] = signature;
878
+ }
879
+ const out = {
880
+ ...transaction,
881
+ signatures: nextSignatures
750
882
  };
883
+ Object.freeze(out);
884
+ return out;
885
+ }
886
+ async function signTransaction(keyPairs, transaction) {
887
+ const out = await partiallySignTransaction(keyPairs, transaction);
888
+ assertTransactionIsFullySigned(out);
889
+ Object.freeze(out);
890
+ return out;
891
+ }
892
+ function assertTransactionIsFullySigned(transaction) {
893
+ const signerAddressesFromInstructions = transaction.instructions.flatMap((i) => i.accounts?.filter((a) => isSignerRole(a.role)) ?? []).map((a) => a.address);
894
+ const requiredSigners = /* @__PURE__ */ new Set([transaction.feePayer, ...signerAddressesFromInstructions]);
895
+ requiredSigners.forEach((address) => {
896
+ if (!transaction.signatures[address]) {
897
+ throw new Error(`Transaction is missing signature for address \`${address}\``);
898
+ }
899
+ });
751
900
  }
752
-
753
- // src/wire-transaction.ts
754
901
  function getBase64EncodedWireTransaction(transaction) {
755
- const wireTransactionBytes = getTransactionEncoder().serialize(transaction);
756
- {
757
- return btoa(String.fromCharCode(...wireTransactionBytes));
758
- }
902
+ const wireTransactionBytes = getTransactionEncoder().encode(transaction);
903
+ return codecsStrings.getBase64Decoder().decode(wireTransactionBytes);
759
904
  }
760
905
 
761
906
  exports.appendTransactionInstruction = appendTransactionInstruction;
762
907
  exports.assertIsBlockhash = assertIsBlockhash;
763
908
  exports.assertIsDurableNonceTransaction = assertIsDurableNonceTransaction;
909
+ exports.assertIsTransactionWithBlockhashLifetime = assertIsTransactionWithBlockhashLifetime;
910
+ exports.assertTransactionIsFullySigned = assertTransactionIsFullySigned;
911
+ exports.compileMessage = compileMessage;
764
912
  exports.createTransaction = createTransaction;
765
913
  exports.getBase64EncodedWireTransaction = getBase64EncodedWireTransaction;
914
+ exports.getCompiledMessageCodec = getCompiledMessageCodec;
915
+ exports.getCompiledMessageDecoder = getCompiledMessageDecoder;
916
+ exports.getCompiledMessageEncoder = getCompiledMessageEncoder;
917
+ exports.getSignatureFromTransaction = getSignatureFromTransaction;
918
+ exports.getTransactionCodec = getTransactionCodec;
919
+ exports.getTransactionDecoder = getTransactionDecoder;
920
+ exports.getTransactionEncoder = getTransactionEncoder;
921
+ exports.isAdvanceNonceAccountInstruction = isAdvanceNonceAccountInstruction;
922
+ exports.partiallySignTransaction = partiallySignTransaction;
766
923
  exports.prependTransactionInstruction = prependTransactionInstruction;
767
924
  exports.setTransactionFeePayer = setTransactionFeePayer;
768
925
  exports.setTransactionLifetimeUsingBlockhash = setTransactionLifetimeUsingBlockhash;