@solana/transactions 2.0.0-experimental.98b85fd → 2.0.0-experimental.997a7cc

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 (71) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +276 -5
  3. package/dist/index.browser.cjs +624 -346
  4. package/dist/index.browser.cjs.map +1 -1
  5. package/dist/index.browser.js +606 -347
  6. package/dist/index.browser.js.map +1 -1
  7. package/dist/index.native.js +608 -347
  8. package/dist/index.native.js.map +1 -1
  9. package/dist/index.node.cjs +624 -346
  10. package/dist/index.node.cjs.map +1 -1
  11. package/dist/index.node.js +606 -347
  12. package/dist/index.node.js.map +1 -1
  13. package/dist/types/accounts.d.ts +4 -4
  14. package/dist/types/accounts.d.ts.map +1 -0
  15. package/dist/types/blockhash.d.ts +7 -4
  16. package/dist/types/blockhash.d.ts.map +1 -0
  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 -0
  21. package/dist/types/compile-header.d.ts +1 -1
  22. package/dist/types/compile-header.d.ts.map +1 -0
  23. package/dist/types/compile-instructions.d.ts +2 -2
  24. package/dist/types/compile-instructions.d.ts.map +1 -0
  25. package/dist/types/compile-lifetime-token.d.ts +2 -2
  26. package/dist/types/compile-lifetime-token.d.ts.map +1 -0
  27. package/dist/types/compile-static-accounts.d.ts +3 -3
  28. package/dist/types/compile-static-accounts.d.ts.map +1 -0
  29. package/dist/types/compile-transaction.d.ts +6 -7
  30. package/dist/types/compile-transaction.d.ts.map +1 -0
  31. package/dist/types/create-transaction.d.ts +1 -1
  32. package/dist/types/create-transaction.d.ts.map +1 -0
  33. package/dist/types/decompile-transaction.d.ts +13 -0
  34. package/dist/types/decompile-transaction.d.ts.map +1 -0
  35. package/dist/types/durable-nonce.d.ts +23 -10
  36. package/dist/types/durable-nonce.d.ts.map +1 -0
  37. package/dist/types/fee-payer.d.ts +6 -5
  38. package/dist/types/fee-payer.d.ts.map +1 -0
  39. package/dist/types/index.d.ts +13 -8
  40. package/dist/types/index.d.ts.map +1 -0
  41. package/dist/types/instructions.d.ts +6 -4
  42. package/dist/types/instructions.d.ts.map +1 -0
  43. package/dist/types/message.d.ts +6 -10
  44. package/dist/types/message.d.ts.map +1 -0
  45. package/dist/types/serializers/address-table-lookup.d.ts +5 -3
  46. package/dist/types/serializers/address-table-lookup.d.ts.map +1 -0
  47. package/dist/types/serializers/header.d.ts +5 -3
  48. package/dist/types/serializers/header.d.ts.map +1 -0
  49. package/dist/types/serializers/index.d.ts +3 -0
  50. package/dist/types/serializers/index.d.ts.map +1 -0
  51. package/dist/types/serializers/instruction.d.ts +5 -3
  52. package/dist/types/serializers/instruction.d.ts.map +1 -0
  53. package/dist/types/serializers/message.d.ts +5 -5
  54. package/dist/types/serializers/message.d.ts.map +1 -0
  55. package/dist/types/serializers/transaction-version.d.ts +5 -5
  56. package/dist/types/serializers/transaction-version.d.ts.map +1 -0
  57. package/dist/types/serializers/transaction.d.ts +9 -5
  58. package/dist/types/serializers/transaction.d.ts.map +1 -0
  59. package/dist/types/signatures.d.ts +10 -7
  60. package/dist/types/signatures.d.ts.map +1 -0
  61. package/dist/types/types.d.ts +13 -13
  62. package/dist/types/types.d.ts.map +1 -0
  63. package/dist/types/unsigned-transaction.d.ts +4 -0
  64. package/dist/types/unsigned-transaction.d.ts.map +1 -0
  65. package/dist/types/wire-transaction.d.ts +3 -3
  66. package/dist/types/wire-transaction.d.ts.map +1 -0
  67. package/package.json +21 -38
  68. package/dist/index.development.js +0 -1265
  69. package/dist/index.development.js.map +0 -1
  70. package/dist/index.production.min.js +0 -17
  71. package/dist/types/serializers/unimplemented.d.ts +0 -3
@@ -1,102 +1,89 @@
1
- import { base58, struct, array, bytes, shortU16, mapSerializer, string, u8 } from '@metaplex-foundation/umi-serializers';
2
- import { getBase58EncodedAddressFromPublicKey, signBytes, getBase58EncodedAddressComparator, getBase58EncodedAddressCodec } from '@solana/keys';
1
+ import { SolanaError, SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME, SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND, SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE } from '@solana/errors';
2
+ import { getBase58Decoder, getBase64Decoder, getStringEncoder, getBase58Encoder, getStringDecoder } from '@solana/codecs-strings';
3
+ import { getAddressFromPublicKey, assertIsAddress, getAddressComparator, getAddressEncoder, getAddressDecoder } from '@solana/addresses';
4
+ import { pipe } from '@solana/functional';
5
+ import { createEncoder, mapDecoder, combineCodec, mapEncoder, createDecoder } from '@solana/codecs-core';
6
+ import { getStructDecoder, getArrayDecoder, getBytesDecoder, getStructEncoder, getArrayEncoder, getBytesEncoder } from '@solana/codecs-data-structures';
7
+ import { getShortU16Decoder, getShortU16Encoder, getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';
8
+ import { signBytes } from '@solana/keys';
3
9
 
4
- // ../build-scripts/env-shim.ts
5
- var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
10
+ // src/blockhash.ts
11
+ var base58Encoder;
6
12
  function assertIsBlockhash(putativeBlockhash) {
7
- try {
8
- if (
9
- // Lowest value (32 bytes of zeroes)
10
- putativeBlockhash.length < 32 || // Highest value (32 bytes of 255)
11
- putativeBlockhash.length > 44
12
- ) {
13
- throw new Error("Expected input string to decode to a byte array of length 32.");
14
- }
15
- const bytes3 = base58.serialize(putativeBlockhash);
16
- const numBytes = bytes3.byteLength;
17
- if (numBytes !== 32) {
18
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
19
- }
20
- } catch (e) {
21
- throw new Error(`\`${putativeBlockhash}\` is not a blockhash`, {
22
- cause: e
13
+ if (!base58Encoder)
14
+ base58Encoder = getBase58Encoder();
15
+ if (
16
+ // Lowest value (32 bytes of zeroes)
17
+ putativeBlockhash.length < 32 || // Highest value (32 bytes of 255)
18
+ putativeBlockhash.length > 44
19
+ ) {
20
+ throw new SolanaError(SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, {
21
+ actualLength: putativeBlockhash.length
22
+ });
23
+ }
24
+ const bytes = base58Encoder.encode(putativeBlockhash);
25
+ const numBytes = bytes.byteLength;
26
+ if (numBytes !== 32) {
27
+ throw new SolanaError(SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, {
28
+ actualLength: numBytes
23
29
  });
24
30
  }
25
31
  }
26
32
 
27
- // src/create-transaction.ts
28
- function createTransaction({
29
- version
30
- }) {
31
- const out = {
32
- instructions: [],
33
- version
34
- };
35
- Object.freeze(out);
36
- return out;
37
- }
38
-
39
- // src/fee-payer.ts
40
- function setTransactionFeePayer(feePayer, transaction) {
41
- if ("feePayer" in transaction && feePayer === transaction.feePayer) {
42
- return transaction;
43
- }
44
- let out;
33
+ // src/unsigned-transaction.ts
34
+ function getUnsignedTransaction(transaction) {
45
35
  if ("signatures" in transaction) {
46
36
  const {
47
37
  signatures: _,
48
38
  // eslint-disable-line @typescript-eslint/no-unused-vars
49
39
  ...unsignedTransaction
50
40
  } = transaction;
51
- out = {
52
- ...unsignedTransaction,
53
- feePayer
54
- };
41
+ return unsignedTransaction;
55
42
  } else {
56
- out = {
57
- ...transaction,
58
- feePayer
59
- };
43
+ return transaction;
60
44
  }
61
- Object.freeze(out);
62
- return out;
63
45
  }
64
46
 
65
- // src/instructions.ts
66
- function replaceInstructions(transaction, nextInstructions) {
67
- let out;
68
- if ("signatures" in transaction) {
69
- const {
70
- signatures: _,
71
- // eslint-disable-line @typescript-eslint/no-unused-vars
72
- ...unsignedTransaction
73
- } = transaction;
74
- out = {
75
- ...unsignedTransaction,
76
- instructions: nextInstructions
77
- };
78
- } else {
79
- out = {
80
- ...transaction,
81
- instructions: nextInstructions
82
- };
47
+ // src/blockhash.ts
48
+ function isTransactionWithBlockhashLifetime(transaction) {
49
+ const lifetimeConstraintShapeMatches = "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.blockhash === "string" && typeof transaction.lifetimeConstraint.lastValidBlockHeight === "bigint";
50
+ if (!lifetimeConstraintShapeMatches)
51
+ return false;
52
+ try {
53
+ assertIsBlockhash(transaction.lifetimeConstraint.blockhash);
54
+ return true;
55
+ } catch {
56
+ return false;
83
57
  }
84
- return out;
85
58
  }
86
- function appendTransactionInstruction(instruction, transaction) {
87
- const nextInstructions = [...transaction.instructions, instruction];
88
- const out = replaceInstructions(transaction, nextInstructions);
59
+ function assertIsTransactionWithBlockhashLifetime(transaction) {
60
+ if (!isTransactionWithBlockhashLifetime(transaction)) {
61
+ throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);
62
+ }
63
+ }
64
+ function setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) {
65
+ if ("lifetimeConstraint" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) {
66
+ return transaction;
67
+ }
68
+ const out = {
69
+ ...getUnsignedTransaction(transaction),
70
+ lifetimeConstraint: blockhashLifetimeConstraint
71
+ };
89
72
  Object.freeze(out);
90
73
  return out;
91
74
  }
92
- function prependTransactionInstruction(instruction, transaction) {
93
- const nextInstructions = [instruction, ...transaction.instructions];
94
- const out = replaceInstructions(transaction, nextInstructions);
75
+
76
+ // src/create-transaction.ts
77
+ function createTransaction({
78
+ version
79
+ }) {
80
+ const out = {
81
+ instructions: [],
82
+ version
83
+ };
95
84
  Object.freeze(out);
96
85
  return out;
97
86
  }
98
-
99
- // ../instructions/dist/index.browser.js
100
87
  var AccountRole = /* @__PURE__ */ ((AccountRole2) => {
101
88
  AccountRole2[AccountRole2["WRITABLE_SIGNER"] = /* 3 */
102
89
  3] = "WRITABLE_SIGNER";
@@ -118,6 +105,271 @@ function isWritableRole(role) {
118
105
  function mergeRoles(roleA, roleB) {
119
106
  return roleA | roleB;
120
107
  }
108
+ var RECENT_BLOCKHASHES_SYSVAR_ADDRESS = "SysvarRecentB1ockHashes11111111111111111111";
109
+ var SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111";
110
+ function assertIsDurableNonceTransaction(transaction) {
111
+ if (!isDurableNonceTransaction(transaction)) {
112
+ throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);
113
+ }
114
+ }
115
+ function createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) {
116
+ return {
117
+ accounts: [
118
+ { address: nonceAccountAddress, role: AccountRole.WRITABLE },
119
+ {
120
+ address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,
121
+ role: AccountRole.READONLY
122
+ },
123
+ { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER }
124
+ ],
125
+ data: new Uint8Array([4, 0, 0, 0]),
126
+ programAddress: SYSTEM_PROGRAM_ADDRESS
127
+ };
128
+ }
129
+ function isAdvanceNonceAccountInstruction(instruction) {
130
+ return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data
131
+ instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts
132
+ instruction.accounts?.length === 3 && // First account is nonce account address
133
+ instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar
134
+ instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account
135
+ instruction.accounts[2].address != null && isSignerRole(instruction.accounts[2].role);
136
+ }
137
+ function isAdvanceNonceAccountInstructionData(data) {
138
+ return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
139
+ }
140
+ function isDurableNonceTransaction(transaction) {
141
+ return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);
142
+ }
143
+ function isAdvanceNonceAccountInstructionForNonce(instruction, nonceAccountAddress, nonceAuthorityAddress) {
144
+ return instruction.accounts[0].address === nonceAccountAddress && instruction.accounts[2].address === nonceAuthorityAddress;
145
+ }
146
+ function setTransactionLifetimeUsingDurableNonce({
147
+ nonce,
148
+ nonceAccountAddress,
149
+ nonceAuthorityAddress
150
+ }, transaction) {
151
+ let newInstructions;
152
+ const firstInstruction = transaction.instructions[0];
153
+ if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {
154
+ if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {
155
+ if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {
156
+ return transaction;
157
+ } else {
158
+ newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];
159
+ }
160
+ } else {
161
+ newInstructions = [
162
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
163
+ ...transaction.instructions.slice(1)
164
+ ];
165
+ }
166
+ } else {
167
+ newInstructions = [
168
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
169
+ ...transaction.instructions
170
+ ];
171
+ }
172
+ const out = {
173
+ ...getUnsignedTransaction(transaction),
174
+ instructions: newInstructions,
175
+ lifetimeConstraint: {
176
+ nonce
177
+ }
178
+ };
179
+ Object.freeze(out);
180
+ return out;
181
+ }
182
+
183
+ // src/fee-payer.ts
184
+ function setTransactionFeePayer(feePayer, transaction) {
185
+ if ("feePayer" in transaction && feePayer === transaction.feePayer) {
186
+ return transaction;
187
+ }
188
+ const out = {
189
+ ...getUnsignedTransaction(transaction),
190
+ feePayer
191
+ };
192
+ Object.freeze(out);
193
+ return out;
194
+ }
195
+
196
+ // src/instructions.ts
197
+ function appendTransactionInstruction(instruction, transaction) {
198
+ return appendTransactionInstructions([instruction], transaction);
199
+ }
200
+ function appendTransactionInstructions(instructions, transaction) {
201
+ const out = {
202
+ ...getUnsignedTransaction(transaction),
203
+ instructions: [...transaction.instructions, ...instructions]
204
+ };
205
+ Object.freeze(out);
206
+ return out;
207
+ }
208
+ function prependTransactionInstruction(instruction, transaction) {
209
+ return prependTransactionInstructions([instruction], transaction);
210
+ }
211
+ function prependTransactionInstructions(instructions, transaction) {
212
+ const out = {
213
+ ...getUnsignedTransaction(transaction),
214
+ instructions: [...instructions, ...transaction.instructions]
215
+ };
216
+ Object.freeze(out);
217
+ return out;
218
+ }
219
+
220
+ // src/decompile-transaction.ts
221
+ function getAccountMetas(message) {
222
+ const { header } = message;
223
+ const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;
224
+ const numWritableNonSignerAccounts = message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;
225
+ const accountMetas = [];
226
+ let accountIndex = 0;
227
+ for (let i = 0; i < numWritableSignerAccounts; i++) {
228
+ accountMetas.push({
229
+ address: message.staticAccounts[accountIndex],
230
+ role: AccountRole.WRITABLE_SIGNER
231
+ });
232
+ accountIndex++;
233
+ }
234
+ for (let i = 0; i < header.numReadonlySignerAccounts; i++) {
235
+ accountMetas.push({
236
+ address: message.staticAccounts[accountIndex],
237
+ role: AccountRole.READONLY_SIGNER
238
+ });
239
+ accountIndex++;
240
+ }
241
+ for (let i = 0; i < numWritableNonSignerAccounts; i++) {
242
+ accountMetas.push({
243
+ address: message.staticAccounts[accountIndex],
244
+ role: AccountRole.WRITABLE
245
+ });
246
+ accountIndex++;
247
+ }
248
+ for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {
249
+ accountMetas.push({
250
+ address: message.staticAccounts[accountIndex],
251
+ role: AccountRole.READONLY
252
+ });
253
+ accountIndex++;
254
+ }
255
+ return accountMetas;
256
+ }
257
+ function getAddressLookupMetas(compiledAddressTableLookups, addressesByLookupTableAddress) {
258
+ const compiledAddressTableLookupAddresses = compiledAddressTableLookups.map((l) => l.lookupTableAddress);
259
+ const missing = compiledAddressTableLookupAddresses.filter((a) => addressesByLookupTableAddress[a] === void 0);
260
+ if (missing.length > 0) {
261
+ throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING, {
262
+ lookupTableAddresses: missing
263
+ });
264
+ }
265
+ const readOnlyMetas = [];
266
+ const writableMetas = [];
267
+ for (const lookup of compiledAddressTableLookups) {
268
+ const addresses = addressesByLookupTableAddress[lookup.lookupTableAddress];
269
+ const highestIndex = Math.max(...lookup.readableIndices, ...lookup.writableIndices);
270
+ if (highestIndex >= addresses.length) {
271
+ throw new SolanaError(
272
+ SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,
273
+ {
274
+ highestKnownIndex: addresses.length - 1,
275
+ highestRequestedIndex: highestIndex,
276
+ lookupTableAddress: lookup.lookupTableAddress
277
+ }
278
+ );
279
+ }
280
+ const readOnlyForLookup = lookup.readableIndices.map((r) => ({
281
+ address: addresses[r],
282
+ addressIndex: r,
283
+ lookupTableAddress: lookup.lookupTableAddress,
284
+ role: AccountRole.READONLY
285
+ }));
286
+ readOnlyMetas.push(...readOnlyForLookup);
287
+ const writableForLookup = lookup.writableIndices.map((w) => ({
288
+ address: addresses[w],
289
+ addressIndex: w,
290
+ lookupTableAddress: lookup.lookupTableAddress,
291
+ role: AccountRole.WRITABLE
292
+ }));
293
+ writableMetas.push(...writableForLookup);
294
+ }
295
+ return [...writableMetas, ...readOnlyMetas];
296
+ }
297
+ function convertInstruction(instruction, accountMetas) {
298
+ const programAddress = accountMetas[instruction.programAddressIndex]?.address;
299
+ if (!programAddress) {
300
+ throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND, {
301
+ index: instruction.programAddressIndex
302
+ });
303
+ }
304
+ const accounts = instruction.accountIndices?.map((accountIndex) => accountMetas[accountIndex]);
305
+ const { data } = instruction;
306
+ return {
307
+ programAddress,
308
+ ...accounts && accounts.length ? { accounts } : {},
309
+ ...data && data.length ? { data } : {}
310
+ };
311
+ }
312
+ function getLifetimeConstraint(messageLifetimeToken, firstInstruction, lastValidBlockHeight) {
313
+ if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {
314
+ return {
315
+ blockhash: messageLifetimeToken,
316
+ lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n
317
+ // U64 MAX
318
+ };
319
+ } else {
320
+ const nonceAccountAddress = firstInstruction.accounts[0].address;
321
+ assertIsAddress(nonceAccountAddress);
322
+ const nonceAuthorityAddress = firstInstruction.accounts[2].address;
323
+ assertIsAddress(nonceAuthorityAddress);
324
+ return {
325
+ nonce: messageLifetimeToken,
326
+ nonceAccountAddress,
327
+ nonceAuthorityAddress
328
+ };
329
+ }
330
+ }
331
+ function convertSignatures(compiledTransaction) {
332
+ const {
333
+ compiledMessage: { staticAccounts },
334
+ signatures
335
+ } = compiledTransaction;
336
+ return signatures.reduce((acc, sig, index) => {
337
+ const allZeros = sig.every((byte) => byte === 0);
338
+ if (allZeros)
339
+ return acc;
340
+ const address = staticAccounts[index];
341
+ return { ...acc, [address]: sig };
342
+ }, {});
343
+ }
344
+ function decompileTransaction(compiledTransaction, config) {
345
+ const { compiledMessage } = compiledTransaction;
346
+ const feePayer = compiledMessage.staticAccounts[0];
347
+ if (!feePayer) {
348
+ throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING);
349
+ }
350
+ const accountMetas = getAccountMetas(compiledMessage);
351
+ const accountLookupMetas = "addressTableLookups" in compiledMessage && compiledMessage.addressTableLookups !== void 0 && compiledMessage.addressTableLookups.length > 0 ? getAddressLookupMetas(compiledMessage.addressTableLookups, config?.addressesByLookupTableAddress ?? {}) : [];
352
+ const transactionMetas = [...accountMetas, ...accountLookupMetas];
353
+ const instructions = compiledMessage.instructions.map(
354
+ (compiledInstruction) => convertInstruction(compiledInstruction, transactionMetas)
355
+ );
356
+ const firstInstruction = instructions[0];
357
+ const lifetimeConstraint = getLifetimeConstraint(
358
+ compiledMessage.lifetimeToken,
359
+ firstInstruction,
360
+ config?.lastValidBlockHeight
361
+ );
362
+ const signatures = convertSignatures(compiledTransaction);
363
+ return pipe(
364
+ createTransaction({ version: compiledMessage.version }),
365
+ (tx) => setTransactionFeePayer(feePayer, tx),
366
+ (tx) => instructions.reduce((acc, instruction) => {
367
+ return appendTransactionInstruction(instruction, acc);
368
+ }, tx),
369
+ (tx) => "blockhash" in lifetimeConstraint ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx) : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),
370
+ (tx) => Object.keys(signatures).length > 0 ? { ...tx, signatures } : tx
371
+ );
372
+ }
121
373
  function upsert(addressMap, address, update) {
122
374
  addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });
123
375
  }
@@ -134,13 +386,13 @@ function getAddressMapFromInstructions(feePayer, instructions) {
134
386
  if (isWritableRole(entry.role)) {
135
387
  switch (entry[TYPE]) {
136
388
  case 0 /* FEE_PAYER */:
137
- throw new Error(
138
- `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.`
139
- );
389
+ throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, {
390
+ programAddress: instruction.programAddress
391
+ });
140
392
  default:
141
- throw new Error(
142
- `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.`
143
- );
393
+ throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, {
394
+ programAddress: instruction.programAddress
395
+ });
144
396
  }
145
397
  }
146
398
  if (entry[TYPE] === 2 /* STATIC */) {
@@ -170,7 +422,7 @@ function getAddressMapFromInstructions(feePayer, instructions) {
170
422
  const shouldReplaceEntry = (
171
423
  // Consider using the new LOOKUP_TABLE if its address is different...
172
424
  entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
173
- (addressComparator || (addressComparator = getBase58EncodedAddressComparator()))(
425
+ (addressComparator ||= getAddressComparator())(
174
426
  accountMeta.lookupTableAddress,
175
427
  entry.lookupTableAddress
176
428
  ) < 0
@@ -205,8 +457,11 @@ function getAddressMapFromInstructions(feePayer, instructions) {
205
457
  addressesOfInvokedPrograms.has(account.address)
206
458
  ) {
207
459
  if (isWritableRole(accountMeta.role)) {
208
- throw new Error(
209
- `This transaction includes an address (\`${account.address}\`) which is both invoked and marked writable. Program addresses may not be writable.`
460
+ throw new SolanaError(
461
+ SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,
462
+ {
463
+ programAddress: account.address
464
+ }
210
465
  );
211
466
  }
212
467
  if (entry.role !== nextRole) {
@@ -276,7 +531,7 @@ function getOrderedAccountsFromAddressMap(addressMap) {
276
531
  if (leftIsWritable !== isWritableRole(rightEntry.role)) {
277
532
  return leftIsWritable ? -1 : 1;
278
533
  }
279
- addressComparator || (addressComparator = getBase58EncodedAddressComparator());
534
+ addressComparator ||= getAddressComparator();
280
535
  if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
281
536
  return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
282
537
  } else {
@@ -289,23 +544,22 @@ function getOrderedAccountsFromAddressMap(addressMap) {
289
544
  return orderedAccounts;
290
545
  }
291
546
  function getCompiledAddressTableLookups(orderedAccounts) {
292
- var _a;
293
547
  const index = {};
294
548
  for (const account of orderedAccounts) {
295
549
  if (!("lookupTableAddress" in account)) {
296
550
  continue;
297
551
  }
298
- const entry = index[_a = account.lookupTableAddress] || (index[_a] = {
552
+ const entry = index[account.lookupTableAddress] ||= {
299
553
  readableIndices: [],
300
554
  writableIndices: []
301
- });
555
+ };
302
556
  if (account.role === AccountRole.WRITABLE) {
303
557
  entry.writableIndices.push(account.addressIndex);
304
558
  } else {
305
559
  entry.readableIndices.push(account.addressIndex);
306
560
  }
307
561
  }
308
- return Object.keys(index).sort(getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({
562
+ return Object.keys(index).sort(getAddressComparator()).map((lookupTableAddress) => ({
309
563
  lookupTableAddress,
310
564
  ...index[lookupTableAddress]
311
565
  }));
@@ -384,266 +638,220 @@ function compileMessage(transaction) {
384
638
  version: transaction.version
385
639
  };
386
640
  }
387
- function getAddressTableLookupCodec() {
388
- return struct(
389
- [
390
- [
391
- "lookupTableAddress",
392
- getBase58EncodedAddressCodec(
393
- __DEV__ ? {
394
- description: "The address of the address lookup table account from which instruction addresses should be looked up"
395
- } : void 0
396
- )
397
- ],
641
+ var memoizedAddressTableLookupEncoder;
642
+ function getAddressTableLookupEncoder() {
643
+ if (!memoizedAddressTableLookupEncoder) {
644
+ memoizedAddressTableLookupEncoder = getStructEncoder([
645
+ ["lookupTableAddress", getAddressEncoder()],
398
646
  [
399
647
  "writableIndices",
400
- array(u8(), {
401
- ...__DEV__ ? {
402
- description: "The indices of the accounts in the lookup table that should be loaded as writeable"
403
- } : null,
404
- size: shortU16()
405
- })
648
+ getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })
406
649
  ],
407
650
  [
408
651
  "readableIndices",
409
- array(u8(), {
410
- ...__DEV__ ? {
411
- description: "The indices of the accounts in the lookup table that should be loaded as read-only"
412
- } : void 0,
413
- size: shortU16()
414
- })
652
+ getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })
415
653
  ]
416
- ],
417
- __DEV__ ? {
418
- 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"
419
- } : void 0
420
- );
654
+ ]);
655
+ }
656
+ return memoizedAddressTableLookupEncoder;
657
+ }
658
+ var memoizedAddressTableLookupDecoder;
659
+ function getAddressTableLookupDecoder() {
660
+ if (!memoizedAddressTableLookupDecoder) {
661
+ memoizedAddressTableLookupDecoder = getStructDecoder([
662
+ ["lookupTableAddress", getAddressDecoder()],
663
+ ["writableIndices", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],
664
+ ["readableIndices", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })]
665
+ ]);
666
+ }
667
+ return memoizedAddressTableLookupDecoder;
668
+ }
669
+ var memoizedU8Encoder;
670
+ function getMemoizedU8Encoder() {
671
+ if (!memoizedU8Encoder)
672
+ memoizedU8Encoder = getU8Encoder();
673
+ return memoizedU8Encoder;
674
+ }
675
+ var memoizedU8Decoder;
676
+ function getMemoizedU8Decoder() {
677
+ if (!memoizedU8Decoder)
678
+ memoizedU8Decoder = getU8Decoder();
679
+ return memoizedU8Decoder;
680
+ }
681
+ function getMessageHeaderEncoder() {
682
+ return getStructEncoder([
683
+ ["numSignerAccounts", getMemoizedU8Encoder()],
684
+ ["numReadonlySignerAccounts", getMemoizedU8Encoder()],
685
+ ["numReadonlyNonSignerAccounts", getMemoizedU8Encoder()]
686
+ ]);
421
687
  }
422
- function getMessageHeaderCodec() {
423
- return struct(
424
- [
425
- [
426
- "numSignerAccounts",
427
- u8(
428
- __DEV__ ? {
429
- description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction"
430
- } : void 0
431
- )
432
- ],
433
- [
434
- "numReadonlySignerAccounts",
435
- u8(
436
- __DEV__ ? {
437
- 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"
438
- } : void 0
439
- )
440
- ],
441
- [
442
- "numReadonlyNonSignerAccounts",
443
- u8(
444
- __DEV__ ? {
445
- description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable"
446
- } : void 0
447
- )
448
- ]
449
- ],
450
- __DEV__ ? {
451
- description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses"
452
- } : void 0
453
- );
688
+ function getMessageHeaderDecoder() {
689
+ return getStructDecoder([
690
+ ["numSignerAccounts", getMemoizedU8Decoder()],
691
+ ["numReadonlySignerAccounts", getMemoizedU8Decoder()],
692
+ ["numReadonlyNonSignerAccounts", getMemoizedU8Decoder()]
693
+ ]);
454
694
  }
455
- function getInstructionCodec() {
456
- return mapSerializer(
457
- struct([
458
- [
459
- "programAddressIndex",
460
- u8(
461
- __DEV__ ? {
462
- description: "The index of the program being called, according to the well-ordered accounts list for this transaction"
463
- } : void 0
464
- )
465
- ],
466
- [
467
- "addressIndices",
468
- array(
469
- u8({
470
- description: __DEV__ ? "The index of an account, according to the well-ordered accounts list for this transaction" : ""
471
- }),
472
- {
473
- 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" : "",
474
- size: shortU16()
475
- }
476
- )
477
- ],
478
- [
479
- "data",
480
- bytes({
481
- description: __DEV__ ? "An optional buffer of data passed to the instruction" : "",
482
- size: shortU16()
483
- })
484
- ]
695
+ var memoizedGetInstructionEncoder;
696
+ function getInstructionEncoder() {
697
+ if (!memoizedGetInstructionEncoder) {
698
+ memoizedGetInstructionEncoder = mapEncoder(
699
+ getStructEncoder([
700
+ ["programAddressIndex", getU8Encoder()],
701
+ ["accountIndices", getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],
702
+ ["data", getBytesEncoder({ size: getShortU16Encoder() })]
703
+ ]),
704
+ // Convert an instruction to have all fields defined
705
+ (instruction) => {
706
+ if (instruction.accountIndices !== void 0 && instruction.data !== void 0) {
707
+ return instruction;
708
+ }
709
+ return {
710
+ ...instruction,
711
+ accountIndices: instruction.accountIndices ?? [],
712
+ data: instruction.data ?? new Uint8Array(0)
713
+ };
714
+ }
715
+ );
716
+ }
717
+ return memoizedGetInstructionEncoder;
718
+ }
719
+ var memoizedGetInstructionDecoder;
720
+ function getInstructionDecoder() {
721
+ if (!memoizedGetInstructionDecoder) {
722
+ memoizedGetInstructionDecoder = mapDecoder(
723
+ getStructDecoder([
724
+ ["programAddressIndex", getU8Decoder()],
725
+ ["accountIndices", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],
726
+ ["data", getBytesDecoder({ size: getShortU16Decoder() })]
727
+ ]),
728
+ // Convert an instruction to exclude optional fields if they are empty
729
+ (instruction) => {
730
+ if (instruction.accountIndices.length && instruction.data.byteLength) {
731
+ return instruction;
732
+ }
733
+ const { accountIndices, data, ...rest } = instruction;
734
+ return {
735
+ ...rest,
736
+ ...accountIndices.length ? { accountIndices } : null,
737
+ ...data.byteLength ? { data } : null
738
+ };
739
+ }
740
+ );
741
+ }
742
+ return memoizedGetInstructionDecoder;
743
+ }
744
+ var VERSION_FLAG_MASK = 128;
745
+ function getTransactionVersionEncoder() {
746
+ return createEncoder({
747
+ getSizeFromValue: (value) => value === "legacy" ? 0 : 1,
748
+ maxSize: 1,
749
+ write: (value, bytes, offset) => {
750
+ if (value === "legacy") {
751
+ return offset;
752
+ }
753
+ if (value < 0 || value > 127) {
754
+ throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, {
755
+ actualVersion: value
756
+ });
757
+ }
758
+ bytes.set([value | VERSION_FLAG_MASK], offset);
759
+ return offset + 1;
760
+ }
761
+ });
762
+ }
763
+ function getTransactionVersionDecoder() {
764
+ return createDecoder({
765
+ maxSize: 1,
766
+ read: (bytes, offset) => {
767
+ const firstByte = bytes[offset];
768
+ if ((firstByte & VERSION_FLAG_MASK) === 0) {
769
+ return ["legacy", offset];
770
+ } else {
771
+ const version = firstByte ^ VERSION_FLAG_MASK;
772
+ return [version, offset + 1];
773
+ }
774
+ }
775
+ });
776
+ }
777
+
778
+ // src/serializers/message.ts
779
+ function getCompiledMessageLegacyEncoder() {
780
+ return getStructEncoder(getPreludeStructEncoderTuple());
781
+ }
782
+ function getCompiledMessageVersionedEncoder() {
783
+ return mapEncoder(
784
+ getStructEncoder([
785
+ ...getPreludeStructEncoderTuple(),
786
+ ["addressTableLookups", getAddressTableLookupArrayEncoder()]
485
787
  ]),
486
788
  (value) => {
487
- if (value.addressIndices !== void 0 && value.data !== void 0) {
789
+ if (value.version === "legacy") {
488
790
  return value;
489
791
  }
490
792
  return {
491
793
  ...value,
492
- addressIndices: value.addressIndices ?? [],
493
- data: value.data ?? new Uint8Array(0)
494
- };
495
- },
496
- (value) => {
497
- if (value.addressIndices.length && value.data.byteLength) {
498
- return value;
499
- }
500
- const { addressIndices, data, ...rest } = value;
501
- return {
502
- ...rest,
503
- ...addressIndices.length ? { addressIndices } : null,
504
- ...data.byteLength ? { data } : null
794
+ addressTableLookups: value.addressTableLookups ?? []
505
795
  };
506
796
  }
507
797
  );
508
798
  }
509
-
510
- // src/serializers/unimplemented.ts
511
- function getError(type, name) {
512
- const functionSuffix = name + type[0].toUpperCase() + type.slice(1);
513
- return new Error(
514
- `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}`
515
- );
516
- }
517
- function getUnimplementedDecoder(name) {
518
- return () => {
519
- throw getError("decoder", name);
520
- };
521
- }
522
-
523
- // src/serializers/transaction-version.ts
524
- var VERSION_FLAG_MASK = 128;
525
- var BASE_CONFIG = {
526
- description: __DEV__ ? "A single byte that encodes the version of the transaction" : "",
527
- fixedSize: null,
528
- maxSize: 1
529
- };
530
- function deserialize(bytes3, offset = 0) {
531
- const firstByte = bytes3[offset];
532
- if ((firstByte & VERSION_FLAG_MASK) === 0) {
533
- return ["legacy", offset];
534
- } else {
535
- const version = firstByte ^ VERSION_FLAG_MASK;
536
- return [version, offset + 1];
537
- }
538
- }
539
- function serialize(value) {
540
- if (value === "legacy") {
541
- return new Uint8Array();
542
- }
543
- if (value < 0 || value > 127) {
544
- throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`);
545
- }
546
- return new Uint8Array([value | VERSION_FLAG_MASK]);
547
- }
548
- function getTransactionVersionCodec() {
549
- return {
550
- ...BASE_CONFIG,
551
- deserialize,
552
- serialize
553
- };
554
- }
555
-
556
- // src/serializers/message.ts
557
- var BASE_CONFIG2 = {
558
- description: __DEV__ ? "The wire format of a Solana transaction message" : "",
559
- fixedSize: null,
560
- maxSize: null
561
- };
562
- function serialize2(compiledMessage) {
563
- if (compiledMessage.version === "legacy") {
564
- return struct(getPreludeStructSerializerTuple()).serialize(compiledMessage);
565
- } else {
566
- return mapSerializer(
567
- struct([
568
- ...getPreludeStructSerializerTuple(),
569
- ["addressTableLookups", getAddressTableLookupsSerializer()]
570
- ]),
571
- (value) => {
572
- if (value.version === "legacy") {
573
- return value;
574
- }
575
- return {
576
- ...value,
577
- addressTableLookups: value.addressTableLookups ?? []
578
- };
579
- }
580
- ).serialize(compiledMessage);
581
- }
799
+ function getPreludeStructEncoderTuple() {
800
+ return [
801
+ ["version", getTransactionVersionEncoder()],
802
+ ["header", getMessageHeaderEncoder()],
803
+ ["staticAccounts", getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],
804
+ ["lifetimeToken", getStringEncoder({ encoding: getBase58Encoder(), size: 32 })],
805
+ ["instructions", getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })]
806
+ ];
582
807
  }
583
- function getPreludeStructSerializerTuple() {
808
+ function getPreludeStructDecoderTuple() {
584
809
  return [
585
- ["version", getTransactionVersionCodec()],
586
- ["header", getMessageHeaderCodec()],
587
- [
588
- "staticAccounts",
589
- array(getBase58EncodedAddressCodec(), {
590
- description: __DEV__ ? "A compact-array of static account addresses belonging to this transaction" : "",
591
- size: shortU16()
592
- })
593
- ],
594
- [
595
- "lifetimeToken",
596
- string({
597
- description: __DEV__ ? "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" : "",
598
- encoding: base58,
599
- size: 32
600
- })
601
- ],
602
- [
603
- "instructions",
604
- array(getInstructionCodec(), {
605
- description: __DEV__ ? "A compact-array of instructions belonging to this transaction" : "",
606
- size: shortU16()
607
- })
608
- ]
810
+ ["version", getTransactionVersionDecoder()],
811
+ ["header", getMessageHeaderDecoder()],
812
+ ["staticAccounts", getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],
813
+ ["lifetimeToken", getStringDecoder({ encoding: getBase58Decoder(), size: 32 })],
814
+ ["instructions", getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],
815
+ ["addressTableLookups", getAddressTableLookupArrayDecoder()]
609
816
  ];
610
817
  }
611
- function getAddressTableLookupsSerializer() {
612
- return array(getAddressTableLookupCodec(), {
613
- ...__DEV__ ? { description: "A compact array of address table lookups belonging to this transaction" } : null,
614
- size: shortU16()
615
- });
818
+ function getAddressTableLookupArrayEncoder() {
819
+ return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });
820
+ }
821
+ function getAddressTableLookupArrayDecoder() {
822
+ return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });
616
823
  }
617
824
  function getCompiledMessageEncoder() {
618
- return {
619
- ...BASE_CONFIG2,
620
- deserialize: getUnimplementedDecoder("CompiledMessage"),
621
- serialize: serialize2
622
- };
825
+ return createEncoder({
826
+ getSizeFromValue: (compiledMessage) => {
827
+ if (compiledMessage.version === "legacy") {
828
+ return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);
829
+ } else {
830
+ return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);
831
+ }
832
+ },
833
+ write: (compiledMessage, bytes, offset) => {
834
+ if (compiledMessage.version === "legacy") {
835
+ return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);
836
+ } else {
837
+ return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);
838
+ }
839
+ }
840
+ });
623
841
  }
624
-
625
- // src/signatures.ts
626
- async function getCompiledMessageSignature(message, secretKey) {
627
- const wireMessageBytes = getCompiledMessageEncoder().serialize(message);
628
- const signature = await signBytes(secretKey, wireMessageBytes);
629
- return signature;
842
+ function getCompiledMessageDecoder() {
843
+ return mapDecoder(
844
+ getStructDecoder(getPreludeStructDecoderTuple()),
845
+ ({ addressTableLookups, ...restOfMessage }) => {
846
+ if (restOfMessage.version === "legacy" || !addressTableLookups?.length) {
847
+ return restOfMessage;
848
+ }
849
+ return { ...restOfMessage, addressTableLookups };
850
+ }
851
+ );
630
852
  }
631
- async function signTransaction(keyPair, transaction) {
632
- const compiledMessage = compileMessage(transaction);
633
- const [signerPublicKey, signature] = await Promise.all([
634
- getBase58EncodedAddressFromPublicKey(keyPair.publicKey),
635
- getCompiledMessageSignature(compiledMessage, keyPair.privateKey)
636
- ]);
637
- const nextSignatures = {
638
- ..."signatures" in transaction ? transaction.signatures : null,
639
- ...{ [signerPublicKey]: signature }
640
- };
641
- const out = {
642
- ...transaction,
643
- signatures: nextSignatures
644
- };
645
- Object.freeze(out);
646
- return out;
853
+ function getCompiledMessageCodec() {
854
+ return combineCodec(getCompiledMessageEncoder(), getCompiledMessageDecoder());
647
855
  }
648
856
 
649
857
  // src/compile-transaction.ts
@@ -665,40 +873,91 @@ function getCompiledTransaction(transaction) {
665
873
  }
666
874
 
667
875
  // src/serializers/transaction.ts
668
- var BASE_CONFIG3 = {
669
- description: __DEV__ ? "The wire format of a Solana transaction" : "",
670
- fixedSize: null,
671
- maxSize: null
672
- };
673
- function serialize3(transaction) {
674
- const compiledTransaction = getCompiledTransaction(transaction);
675
- return struct([
876
+ function getCompiledTransactionEncoder() {
877
+ return getStructEncoder([
878
+ ["signatures", getArrayEncoder(getBytesEncoder({ size: 64 }), { size: getShortU16Encoder() })],
879
+ ["compiledMessage", getCompiledMessageEncoder()]
880
+ ]);
881
+ }
882
+ function getCompiledTransactionDecoder() {
883
+ return getStructDecoder([
676
884
  [
677
885
  "signatures",
678
- array(bytes({ size: 64 }), {
679
- ...__DEV__ ? { description: "A compact array of 64-byte, base-64 encoded Ed25519 signatures" } : null,
680
- size: shortU16()
886
+ getArrayDecoder(getBytesDecoder({ size: 64 }), {
887
+ size: getShortU16Decoder()
681
888
  })
682
889
  ],
683
- ["compiledMessage", getCompiledMessageEncoder()]
684
- ]).serialize(compiledTransaction);
890
+ ["compiledMessage", getCompiledMessageDecoder()]
891
+ ]);
685
892
  }
686
893
  function getTransactionEncoder() {
687
- return {
688
- ...BASE_CONFIG3,
689
- deserialize: getUnimplementedDecoder("CompiledMessage"),
690
- serialize: serialize3
894
+ return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);
895
+ }
896
+ function getTransactionDecoder(config) {
897
+ return mapDecoder(
898
+ getCompiledTransactionDecoder(),
899
+ (compiledTransaction) => decompileTransaction(compiledTransaction, config)
900
+ );
901
+ }
902
+ function getTransactionCodec(config) {
903
+ return combineCodec(getTransactionEncoder(), getTransactionDecoder(config));
904
+ }
905
+ var base58Decoder;
906
+ function getSignatureFromTransaction(transaction) {
907
+ if (!base58Decoder)
908
+ base58Decoder = getBase58Decoder();
909
+ const signatureBytes = transaction.signatures[transaction.feePayer];
910
+ if (!signatureBytes) {
911
+ throw new SolanaError(SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING);
912
+ }
913
+ const transactionSignature = base58Decoder.decode(signatureBytes);
914
+ return transactionSignature;
915
+ }
916
+ async function partiallySignTransaction(keyPairs, transaction) {
917
+ const compiledMessage = compileMessage(transaction);
918
+ const nextSignatures = "signatures" in transaction ? { ...transaction.signatures } : {};
919
+ const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);
920
+ const publicKeySignaturePairs = await Promise.all(
921
+ keyPairs.map(
922
+ (keyPair) => Promise.all([getAddressFromPublicKey(keyPair.publicKey), signBytes(keyPair.privateKey, wireMessageBytes)])
923
+ )
924
+ );
925
+ for (const [signerPublicKey, signature] of publicKeySignaturePairs) {
926
+ nextSignatures[signerPublicKey] = signature;
927
+ }
928
+ const out = {
929
+ ...transaction,
930
+ signatures: nextSignatures
691
931
  };
932
+ Object.freeze(out);
933
+ return out;
692
934
  }
693
-
694
- // src/wire-transaction.ts
695
- function getBase64EncodedWireTransaction(transaction) {
696
- const wireTransactionBytes = getTransactionEncoder().serialize(transaction);
697
- {
698
- return btoa(String.fromCharCode(...wireTransactionBytes));
935
+ async function signTransaction(keyPairs, transaction) {
936
+ const out = await partiallySignTransaction(keyPairs, transaction);
937
+ assertTransactionIsFullySigned(out);
938
+ Object.freeze(out);
939
+ return out;
940
+ }
941
+ function assertTransactionIsFullySigned(transaction) {
942
+ const signerAddressesFromInstructions = transaction.instructions.flatMap((i) => i.accounts?.filter((a) => isSignerRole(a.role)) ?? []).map((a) => a.address);
943
+ const requiredSigners = /* @__PURE__ */ new Set([transaction.feePayer, ...signerAddressesFromInstructions]);
944
+ const missingSigs = [];
945
+ requiredSigners.forEach((address) => {
946
+ if (!transaction.signatures[address]) {
947
+ missingSigs.push(address);
948
+ }
949
+ });
950
+ if (missingSigs.length > 0) {
951
+ throw new SolanaError(SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, {
952
+ addresses: missingSigs
953
+ });
699
954
  }
700
955
  }
956
+ function getBase64EncodedWireTransaction(transaction) {
957
+ const wireTransactionBytes = getTransactionEncoder().encode(transaction);
958
+ return getBase64Decoder().decode(wireTransactionBytes);
959
+ }
701
960
 
702
- export { appendTransactionInstruction, assertIsBlockhash, createTransaction, getBase64EncodedWireTransaction, prependTransactionInstruction, setTransactionFeePayer, signTransaction };
961
+ export { appendTransactionInstruction, appendTransactionInstructions, assertIsDurableNonceTransaction, assertIsTransactionWithBlockhashLifetime, assertTransactionIsFullySigned, compileMessage, createTransaction, decompileTransaction, getBase64EncodedWireTransaction, getCompiledMessageCodec, getCompiledMessageDecoder, getCompiledMessageEncoder, getCompiledTransactionDecoder, getSignatureFromTransaction, getTransactionCodec, getTransactionDecoder, getTransactionEncoder, getUnsignedTransaction, isAdvanceNonceAccountInstruction, partiallySignTransaction, prependTransactionInstruction, prependTransactionInstructions, setTransactionFeePayer, setTransactionLifetimeUsingBlockhash, setTransactionLifetimeUsingDurableNonce, signTransaction };
703
962
  //# sourceMappingURL=out.js.map
704
963
  //# sourceMappingURL=index.browser.js.map