@solana/transactions 2.0.0-experimental.c29513e → 2.0.0-experimental.c42ccfd

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