@solana/transactions 2.0.0-experimental.0e113c0 → 2.0.0-experimental.10bfcd8

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 (40) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +314 -5
  3. package/dist/index.browser.cjs +1051 -39
  4. package/dist/index.browser.cjs.map +1 -1
  5. package/dist/index.browser.js +1035 -40
  6. package/dist/index.browser.js.map +1 -1
  7. package/dist/index.development.js +1794 -39
  8. package/dist/index.development.js.map +1 -1
  9. package/dist/index.native.js +1035 -40
  10. package/dist/index.native.js.map +1 -1
  11. package/dist/index.node.cjs +1049 -39
  12. package/dist/index.node.cjs.map +1 -1
  13. package/dist/index.node.js +1035 -40
  14. package/dist/index.node.js.map +1 -1
  15. package/dist/index.production.min.js +20 -5
  16. package/dist/types/accounts.d.ts +28 -0
  17. package/dist/types/blockhash.d.ts +9 -1
  18. package/dist/types/compile-address-table-lookups.d.ts +10 -0
  19. package/dist/types/compile-header.d.ts +9 -0
  20. package/dist/types/compile-instructions.d.ts +10 -0
  21. package/dist/types/compile-lifetime-token.d.ts +3 -0
  22. package/dist/types/compile-static-accounts.d.ts +4 -0
  23. package/dist/types/compile-transaction.d.ts +11 -0
  24. package/dist/types/decompile-transaction.d.ts +7 -0
  25. package/dist/types/durable-nonce.d.ts +23 -10
  26. package/dist/types/fee-payer.d.ts +3 -2
  27. package/dist/types/index.d.ts +2 -0
  28. package/dist/types/message.d.ts +30 -0
  29. package/dist/types/serializers/address-table-lookup.d.ts +8 -0
  30. package/dist/types/serializers/header.d.ts +8 -0
  31. package/dist/types/serializers/index.d.ts +2 -0
  32. package/dist/types/serializers/instruction.d.ts +8 -0
  33. package/dist/types/serializers/message.d.ts +6 -0
  34. package/dist/types/serializers/transaction-version.d.ts +6 -0
  35. package/dist/types/serializers/transaction.d.ts +9 -0
  36. package/dist/types/signatures.d.ts +15 -7
  37. package/dist/types/types.d.ts +7 -0
  38. package/dist/types/unsigned-transaction.d.ts +4 -0
  39. package/dist/types/wire-transaction.d.ts +6 -0
  40. package/package.json +23 -20
@@ -2,6 +2,127 @@ this.globalThis = this.globalThis || {};
2
2
  this.globalThis.solanaWeb3 = (function (exports) {
3
3
  'use strict';
4
4
 
5
+ var __defProp = Object.defineProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __publicField = (obj, key, value) => {
8
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
9
+ return value;
10
+ };
11
+
12
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/errors.mjs
13
+ var InvalidBaseStringError = class extends Error {
14
+ constructor(value, base, cause) {
15
+ const message = `Expected a string of base ${base}, got [${value}].`;
16
+ super(message);
17
+ __publicField(this, "name", "InvalidBaseStringError");
18
+ this.cause = cause;
19
+ }
20
+ };
21
+
22
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/baseX.mjs
23
+ var baseX = (alphabet) => {
24
+ const base = alphabet.length;
25
+ const baseBigInt = BigInt(base);
26
+ return {
27
+ description: `base${base}`,
28
+ fixedSize: null,
29
+ maxSize: null,
30
+ serialize(value) {
31
+ if (!value.match(new RegExp(`^[${alphabet}]*$`))) {
32
+ throw new InvalidBaseStringError(value, base);
33
+ }
34
+ if (value === "")
35
+ return new Uint8Array();
36
+ const chars = [...value];
37
+ let trailIndex = chars.findIndex((c) => c !== alphabet[0]);
38
+ trailIndex = trailIndex === -1 ? chars.length : trailIndex;
39
+ const leadingZeroes = Array(trailIndex).fill(0);
40
+ if (trailIndex === chars.length)
41
+ return Uint8Array.from(leadingZeroes);
42
+ const tailChars = chars.slice(trailIndex);
43
+ let base10Number = 0n;
44
+ let baseXPower = 1n;
45
+ for (let i = tailChars.length - 1; i >= 0; i -= 1) {
46
+ base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));
47
+ baseXPower *= baseBigInt;
48
+ }
49
+ const tailBytes = [];
50
+ while (base10Number > 0n) {
51
+ tailBytes.unshift(Number(base10Number % 256n));
52
+ base10Number /= 256n;
53
+ }
54
+ return Uint8Array.from(leadingZeroes.concat(tailBytes));
55
+ },
56
+ deserialize(buffer, offset = 0) {
57
+ if (buffer.length === 0)
58
+ return ["", 0];
59
+ const bytes = buffer.slice(offset);
60
+ let trailIndex = bytes.findIndex((n) => n !== 0);
61
+ trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
62
+ const leadingZeroes = alphabet[0].repeat(trailIndex);
63
+ if (trailIndex === bytes.length)
64
+ return [leadingZeroes, buffer.length];
65
+ let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
66
+ const tailChars = [];
67
+ while (base10Number > 0n) {
68
+ tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);
69
+ base10Number /= baseBigInt;
70
+ }
71
+ return [leadingZeroes + tailChars.join(""), buffer.length];
72
+ }
73
+ };
74
+ };
75
+
76
+ // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.9/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/base58.mjs
77
+ var base58 = baseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
78
+
79
+ // src/unsigned-transaction.ts
80
+ function getUnsignedTransaction(transaction) {
81
+ if ("signatures" in transaction) {
82
+ const {
83
+ signatures: _,
84
+ // eslint-disable-line @typescript-eslint/no-unused-vars
85
+ ...unsignedTransaction
86
+ } = transaction;
87
+ return unsignedTransaction;
88
+ } else {
89
+ return transaction;
90
+ }
91
+ }
92
+
93
+ // src/blockhash.ts
94
+ function assertIsBlockhash(putativeBlockhash) {
95
+ try {
96
+ if (
97
+ // Lowest value (32 bytes of zeroes)
98
+ putativeBlockhash.length < 32 || // Highest value (32 bytes of 255)
99
+ putativeBlockhash.length > 44
100
+ ) {
101
+ throw new Error("Expected input string to decode to a byte array of length 32.");
102
+ }
103
+ const bytes = base58.serialize(putativeBlockhash);
104
+ const numBytes = bytes.byteLength;
105
+ if (numBytes !== 32) {
106
+ throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
107
+ }
108
+ } catch (e2) {
109
+ throw new Error(`\`${putativeBlockhash}\` is not a blockhash`, {
110
+ cause: e2
111
+ });
112
+ }
113
+ }
114
+ function setTransactionLifetimeUsingBlockhash(blockhashLifetimeConstraint, transaction) {
115
+ if ("lifetimeConstraint" in transaction && transaction.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transaction.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) {
116
+ return transaction;
117
+ }
118
+ const out = {
119
+ ...getUnsignedTransaction(transaction),
120
+ lifetimeConstraint: blockhashLifetimeConstraint
121
+ };
122
+ Object.freeze(out);
123
+ return out;
124
+ }
125
+
5
126
  // src/create-transaction.ts
6
127
  function createTransaction({
7
128
  version
@@ -14,70 +135,1704 @@ this.globalThis.solanaWeb3 = (function (exports) {
14
135
  return out;
15
136
  }
16
137
 
138
+ // ../instructions/dist/index.browser.js
139
+ var AccountRole = /* @__PURE__ */ ((AccountRole2) => {
140
+ AccountRole2[AccountRole2["WRITABLE_SIGNER"] = /* 3 */
141
+ 3] = "WRITABLE_SIGNER";
142
+ AccountRole2[AccountRole2["READONLY_SIGNER"] = /* 2 */
143
+ 2] = "READONLY_SIGNER";
144
+ AccountRole2[AccountRole2["WRITABLE"] = /* 1 */
145
+ 1] = "WRITABLE";
146
+ AccountRole2[AccountRole2["READONLY"] = /* 0 */
147
+ 0] = "READONLY";
148
+ return AccountRole2;
149
+ })(AccountRole || {});
150
+ var IS_WRITABLE_BITMASK = 1;
151
+ function isSignerRole(role) {
152
+ return role >= 2;
153
+ }
154
+ function isWritableRole(role) {
155
+ return (role & IS_WRITABLE_BITMASK) !== 0;
156
+ }
157
+ function mergeRoles(roleA, roleB) {
158
+ return roleA | roleB;
159
+ }
160
+
161
+ // src/durable-nonce.ts
162
+ var RECENT_BLOCKHASHES_SYSVAR_ADDRESS = "SysvarRecentB1ockHashes11111111111111111111";
163
+ var SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111";
164
+ function assertIsDurableNonceTransaction(transaction) {
165
+ if (!isDurableNonceTransaction(transaction)) {
166
+ throw new Error("Transaction is not a durable nonce transaction");
167
+ }
168
+ }
169
+ function createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) {
170
+ return {
171
+ accounts: [
172
+ { address: nonceAccountAddress, role: AccountRole.WRITABLE },
173
+ {
174
+ address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,
175
+ role: AccountRole.READONLY
176
+ },
177
+ { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER }
178
+ ],
179
+ data: new Uint8Array([4, 0, 0, 0]),
180
+ programAddress: SYSTEM_PROGRAM_ADDRESS
181
+ };
182
+ }
183
+ function isAdvanceNonceAccountInstruction(instruction) {
184
+ return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data
185
+ instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts
186
+ instruction.accounts?.length === 3 && // First account is nonce account address
187
+ instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar
188
+ instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account
189
+ instruction.accounts[2].address != null && isSignerRole(instruction.accounts[2].role);
190
+ }
191
+ function isAdvanceNonceAccountInstructionData(data) {
192
+ return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
193
+ }
194
+ function isDurableNonceTransaction(transaction) {
195
+ return "lifetimeConstraint" in transaction && typeof transaction.lifetimeConstraint.nonce === "string" && transaction.instructions[0] != null && isAdvanceNonceAccountInstruction(transaction.instructions[0]);
196
+ }
197
+ function isAdvanceNonceAccountInstructionForNonce(instruction, nonceAccountAddress, nonceAuthorityAddress) {
198
+ return instruction.accounts[0].address === nonceAccountAddress && instruction.accounts[2].address === nonceAuthorityAddress;
199
+ }
200
+ function setTransactionLifetimeUsingDurableNonce({
201
+ nonce,
202
+ nonceAccountAddress,
203
+ nonceAuthorityAddress
204
+ }, transaction) {
205
+ let newInstructions;
206
+ const firstInstruction = transaction.instructions[0];
207
+ if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {
208
+ if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {
209
+ if (isDurableNonceTransaction(transaction) && transaction.lifetimeConstraint.nonce === nonce) {
210
+ return transaction;
211
+ } else {
212
+ newInstructions = [firstInstruction, ...transaction.instructions.slice(1)];
213
+ }
214
+ } else {
215
+ newInstructions = [
216
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
217
+ ...transaction.instructions.slice(1)
218
+ ];
219
+ }
220
+ } else {
221
+ newInstructions = [
222
+ createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress),
223
+ ...transaction.instructions
224
+ ];
225
+ }
226
+ const out = {
227
+ ...getUnsignedTransaction(transaction),
228
+ instructions: newInstructions,
229
+ lifetimeConstraint: {
230
+ nonce
231
+ }
232
+ };
233
+ Object.freeze(out);
234
+ return out;
235
+ }
236
+
17
237
  // src/fee-payer.ts
18
238
  function setTransactionFeePayer(feePayer, transaction) {
19
239
  if ("feePayer" in transaction && feePayer === transaction.feePayer) {
20
240
  return transaction;
21
241
  }
22
- let out;
23
- if ("signatures" in transaction) {
24
- const {
25
- signatures: _,
26
- // eslint-disable-line @typescript-eslint/no-unused-vars
27
- ...unsignedTransaction
28
- } = transaction;
29
- out = {
30
- ...unsignedTransaction,
31
- feePayer
32
- };
33
- } else {
34
- out = {
35
- ...transaction,
36
- feePayer
37
- };
38
- }
242
+ const out = {
243
+ ...getUnsignedTransaction(transaction),
244
+ feePayer
245
+ };
39
246
  Object.freeze(out);
40
247
  return out;
41
248
  }
42
249
 
43
250
  // src/instructions.ts
44
- function replaceInstructions(transaction, nextInstructions) {
45
- let out;
251
+ function appendTransactionInstruction(instruction, transaction) {
252
+ const out = {
253
+ ...getUnsignedTransaction(transaction),
254
+ instructions: [...transaction.instructions, instruction]
255
+ };
256
+ Object.freeze(out);
257
+ return out;
258
+ }
259
+ function prependTransactionInstruction(instruction, transaction) {
260
+ const out = {
261
+ ...getUnsignedTransaction(transaction),
262
+ instructions: [instruction, ...transaction.instructions]
263
+ };
264
+ Object.freeze(out);
265
+ return out;
266
+ }
267
+
268
+ // ../codecs-core/dist/index.browser.js
269
+ function assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {
270
+ if (bytes.length - offset <= 0) {
271
+ throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);
272
+ }
273
+ }
274
+ function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {
275
+ const bytesLength = bytes.length - offset;
276
+ if (bytesLength < expected) {
277
+ throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);
278
+ }
279
+ }
280
+ var mergeBytes = (byteArrays) => {
281
+ const nonEmptyByteArrays = byteArrays.filter((arr) => arr.length);
282
+ if (nonEmptyByteArrays.length === 0) {
283
+ return byteArrays.length ? byteArrays[0] : new Uint8Array();
284
+ }
285
+ if (nonEmptyByteArrays.length === 1) {
286
+ return nonEmptyByteArrays[0];
287
+ }
288
+ const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);
289
+ const result = new Uint8Array(totalLength);
290
+ let offset = 0;
291
+ nonEmptyByteArrays.forEach((arr) => {
292
+ result.set(arr, offset);
293
+ offset += arr.length;
294
+ });
295
+ return result;
296
+ };
297
+ var padBytes = (bytes, length) => {
298
+ if (bytes.length >= length)
299
+ return bytes;
300
+ const paddedBytes = new Uint8Array(length).fill(0);
301
+ paddedBytes.set(bytes);
302
+ return paddedBytes;
303
+ };
304
+ var fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);
305
+ function combineCodec(encoder, decoder, description) {
306
+ if (encoder.fixedSize !== decoder.fixedSize) {
307
+ throw new Error(
308
+ `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`
309
+ );
310
+ }
311
+ if (encoder.maxSize !== decoder.maxSize) {
312
+ throw new Error(
313
+ `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`
314
+ );
315
+ }
316
+ if (description === void 0 && encoder.description !== decoder.description) {
317
+ throw new Error(
318
+ `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. Pass a custom description as a third argument if you want to override the description and bypass this error.`
319
+ );
320
+ }
321
+ return {
322
+ decode: decoder.decode,
323
+ description: description ?? encoder.description,
324
+ encode: encoder.encode,
325
+ fixedSize: encoder.fixedSize,
326
+ maxSize: encoder.maxSize
327
+ };
328
+ }
329
+ function fixCodecHelper(data, fixedBytes, description) {
330
+ return {
331
+ description: description ?? `fixed(${fixedBytes}, ${data.description})`,
332
+ fixedSize: fixedBytes,
333
+ maxSize: fixedBytes
334
+ };
335
+ }
336
+ function fixEncoder(encoder, fixedBytes, description) {
337
+ return {
338
+ ...fixCodecHelper(encoder, fixedBytes, description),
339
+ encode: (value) => fixBytes(encoder.encode(value), fixedBytes)
340
+ };
341
+ }
342
+ function fixDecoder(decoder, fixedBytes, description) {
343
+ return {
344
+ ...fixCodecHelper(decoder, fixedBytes, description),
345
+ decode: (bytes, offset = 0) => {
346
+ assertByteArrayHasEnoughBytesForCodec("fixCodec", fixedBytes, bytes, offset);
347
+ if (offset > 0 || bytes.length > fixedBytes) {
348
+ bytes = bytes.slice(offset, offset + fixedBytes);
349
+ }
350
+ if (decoder.fixedSize !== null) {
351
+ bytes = fixBytes(bytes, decoder.fixedSize);
352
+ }
353
+ const [value] = decoder.decode(bytes, 0);
354
+ return [value, offset + fixedBytes];
355
+ }
356
+ };
357
+ }
358
+ function mapEncoder(encoder, unmap) {
359
+ return {
360
+ description: encoder.description,
361
+ encode: (value) => encoder.encode(unmap(value)),
362
+ fixedSize: encoder.fixedSize,
363
+ maxSize: encoder.maxSize
364
+ };
365
+ }
366
+ function mapDecoder(decoder, map) {
367
+ return {
368
+ decode: (bytes, offset = 0) => {
369
+ const [value, length] = decoder.decode(bytes, offset);
370
+ return [map(value, bytes, offset), length];
371
+ },
372
+ description: decoder.description,
373
+ fixedSize: decoder.fixedSize,
374
+ maxSize: decoder.maxSize
375
+ };
376
+ }
377
+
378
+ // ../codecs-numbers/dist/index.browser.js
379
+ function assertNumberIsBetweenForCodec(codecDescription, min, max, value) {
380
+ if (value < min || value > max) {
381
+ throw new Error(
382
+ `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`
383
+ );
384
+ }
385
+ }
386
+ function sharedNumberFactory(input) {
387
+ let littleEndian;
388
+ let defaultDescription = input.name;
389
+ if (input.size > 1) {
390
+ littleEndian = !("endian" in input.options) || input.options.endian === 0;
391
+ defaultDescription += littleEndian ? "(le)" : "(be)";
392
+ }
393
+ return {
394
+ description: input.options.description ?? defaultDescription,
395
+ fixedSize: input.size,
396
+ littleEndian,
397
+ maxSize: input.size
398
+ };
399
+ }
400
+ function numberEncoderFactory(input) {
401
+ const codecData = sharedNumberFactory(input);
402
+ return {
403
+ description: codecData.description,
404
+ encode(value) {
405
+ if (input.range) {
406
+ assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);
407
+ }
408
+ const arrayBuffer = new ArrayBuffer(input.size);
409
+ input.set(new DataView(arrayBuffer), value, codecData.littleEndian);
410
+ return new Uint8Array(arrayBuffer);
411
+ },
412
+ fixedSize: codecData.fixedSize,
413
+ maxSize: codecData.maxSize
414
+ };
415
+ }
416
+ function numberDecoderFactory(input) {
417
+ const codecData = sharedNumberFactory(input);
418
+ return {
419
+ decode(bytes, offset = 0) {
420
+ assertByteArrayIsNotEmptyForCodec(codecData.description, bytes, offset);
421
+ assertByteArrayHasEnoughBytesForCodec(codecData.description, input.size, bytes, offset);
422
+ const view = new DataView(toArrayBuffer(bytes, offset, input.size));
423
+ return [input.get(view, codecData.littleEndian), offset + input.size];
424
+ },
425
+ description: codecData.description,
426
+ fixedSize: codecData.fixedSize,
427
+ maxSize: codecData.maxSize
428
+ };
429
+ }
430
+ function toArrayBuffer(bytes, offset, length) {
431
+ const bytesOffset = bytes.byteOffset + (offset ?? 0);
432
+ const bytesLength = length ?? bytes.byteLength;
433
+ return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);
434
+ }
435
+ var getShortU16Encoder = (options = {}) => ({
436
+ description: options.description ?? "shortU16",
437
+ encode: (value) => {
438
+ assertNumberIsBetweenForCodec("shortU16", 0, 65535, value);
439
+ const bytes = [0];
440
+ for (let ii = 0; ; ii += 1) {
441
+ const alignedValue = value >> ii * 7;
442
+ if (alignedValue === 0) {
443
+ break;
444
+ }
445
+ const nextSevenBits = 127 & alignedValue;
446
+ bytes[ii] = nextSevenBits;
447
+ if (ii > 0) {
448
+ bytes[ii - 1] |= 128;
449
+ }
450
+ }
451
+ return new Uint8Array(bytes);
452
+ },
453
+ fixedSize: null,
454
+ maxSize: 3
455
+ });
456
+ var getShortU16Decoder = (options = {}) => ({
457
+ decode: (bytes, offset = 0) => {
458
+ let value = 0;
459
+ let byteCount = 0;
460
+ while (++byteCount) {
461
+ const byteIndex = byteCount - 1;
462
+ const currentByte = bytes[offset + byteIndex];
463
+ const nextSevenBits = 127 & currentByte;
464
+ value |= nextSevenBits << byteIndex * 7;
465
+ if ((currentByte & 128) === 0) {
466
+ break;
467
+ }
468
+ }
469
+ return [value, offset + byteCount];
470
+ },
471
+ description: options.description ?? "shortU16",
472
+ fixedSize: null,
473
+ maxSize: 3
474
+ });
475
+ var getU32Encoder = (options = {}) => numberEncoderFactory({
476
+ name: "u32",
477
+ options,
478
+ range: [0, Number("0xffffffff")],
479
+ set: (view, value, le) => view.setUint32(0, value, le),
480
+ size: 4
481
+ });
482
+ var getU32Decoder = (options = {}) => numberDecoderFactory({
483
+ get: (view, le) => view.getUint32(0, le),
484
+ name: "u32",
485
+ options,
486
+ size: 4
487
+ });
488
+ var getU8Encoder = (options = {}) => numberEncoderFactory({
489
+ name: "u8",
490
+ options,
491
+ range: [0, Number("0xff")],
492
+ set: (view, value) => view.setUint8(0, value),
493
+ size: 1
494
+ });
495
+ var getU8Decoder = (options = {}) => numberDecoderFactory({
496
+ get: (view) => view.getUint8(0),
497
+ name: "u8",
498
+ options,
499
+ size: 1
500
+ });
501
+
502
+ // ../codecs-data-structures/dist/index.browser.js
503
+ function sumCodecSizes(sizes) {
504
+ return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
505
+ }
506
+ function decodeArrayLikeCodecSize(size, childrenSizes, bytes, offset) {
507
+ if (typeof size === "number") {
508
+ return [size, offset];
509
+ }
510
+ if (typeof size === "object") {
511
+ return size.decode(bytes, offset);
512
+ }
513
+ if (size === "remainder") {
514
+ const childrenSize = sumCodecSizes(childrenSizes);
515
+ if (childrenSize === null) {
516
+ throw new Error('Codecs of "remainder" size must have fixed-size items.');
517
+ }
518
+ const remainder = bytes.slice(offset).length;
519
+ if (remainder % childrenSize !== 0) {
520
+ throw new Error(
521
+ `The remainder of the byte array (${remainder} bytes) cannot be split into chunks of ${childrenSize} bytes. Codecs of "remainder" size must have a remainder that is a multiple of its item size. In other words, ${remainder} modulo ${childrenSize} should be equal to zero.`
522
+ );
523
+ }
524
+ return [remainder / childrenSize, offset];
525
+ }
526
+ throw new Error(`Unrecognized array-like codec size: ${JSON.stringify(size)}`);
527
+ }
528
+ function getArrayLikeCodecSizeDescription(size) {
529
+ return typeof size === "object" ? size.description : `${size}`;
530
+ }
531
+ function getArrayLikeCodecSizeFromChildren(size, childrenSizes) {
532
+ if (typeof size !== "number")
533
+ return null;
534
+ if (size === 0)
535
+ return 0;
536
+ const childrenSize = sumCodecSizes(childrenSizes);
537
+ return childrenSize === null ? null : childrenSize * size;
538
+ }
539
+ function getArrayLikeCodecSizePrefix(size, realSize) {
540
+ return typeof size === "object" ? size.encode(realSize) : new Uint8Array();
541
+ }
542
+ function assertValidNumberOfItemsForCodec(codecDescription, expected, actual) {
543
+ if (expected !== actual) {
544
+ throw new Error(`Expected [${codecDescription}] to have ${expected} items, got ${actual}.`);
545
+ }
546
+ }
547
+ function arrayCodecHelper(item, size, description) {
548
+ if (size === "remainder" && item.fixedSize === null) {
549
+ throw new Error('Codecs of "remainder" size must have fixed-size items.');
550
+ }
551
+ return {
552
+ description: description ?? `array(${item.description}; ${getArrayLikeCodecSizeDescription(size)})`,
553
+ fixedSize: getArrayLikeCodecSizeFromChildren(size, [item.fixedSize]),
554
+ maxSize: getArrayLikeCodecSizeFromChildren(size, [item.maxSize])
555
+ };
556
+ }
557
+ function getArrayEncoder(item, options = {}) {
558
+ const size = options.size ?? getU32Encoder();
559
+ return {
560
+ ...arrayCodecHelper(item, size, options.description),
561
+ encode: (value) => {
562
+ if (typeof size === "number") {
563
+ assertValidNumberOfItemsForCodec("array", size, value.length);
564
+ }
565
+ return mergeBytes([getArrayLikeCodecSizePrefix(size, value.length), ...value.map((v) => item.encode(v))]);
566
+ }
567
+ };
568
+ }
569
+ function getArrayDecoder(item, options = {}) {
570
+ const size = options.size ?? getU32Decoder();
571
+ return {
572
+ ...arrayCodecHelper(item, size, options.description),
573
+ decode: (bytes, offset = 0) => {
574
+ if (typeof size === "object" && bytes.slice(offset).length === 0) {
575
+ return [[], offset];
576
+ }
577
+ const [resolvedSize, newOffset] = decodeArrayLikeCodecSize(size, [item.fixedSize], bytes, offset);
578
+ offset = newOffset;
579
+ const values = [];
580
+ for (let i = 0; i < resolvedSize; i += 1) {
581
+ const [value, newOffset2] = item.decode(bytes, offset);
582
+ values.push(value);
583
+ offset = newOffset2;
584
+ }
585
+ return [values, offset];
586
+ }
587
+ };
588
+ }
589
+ function getBytesEncoder(options = {}) {
590
+ const size = options.size ?? "variable";
591
+ const sizeDescription = typeof size === "object" ? size.description : `${size}`;
592
+ const description = options.description ?? `bytes(${sizeDescription})`;
593
+ const byteEncoder = {
594
+ description,
595
+ encode: (value) => value,
596
+ fixedSize: null,
597
+ maxSize: null
598
+ };
599
+ if (size === "variable") {
600
+ return byteEncoder;
601
+ }
602
+ if (typeof size === "number") {
603
+ return fixEncoder(byteEncoder, size, description);
604
+ }
605
+ return {
606
+ ...byteEncoder,
607
+ encode: (value) => {
608
+ const contentBytes = byteEncoder.encode(value);
609
+ const lengthBytes = size.encode(contentBytes.length);
610
+ return mergeBytes([lengthBytes, contentBytes]);
611
+ }
612
+ };
613
+ }
614
+ function getBytesDecoder(options = {}) {
615
+ const size = options.size ?? "variable";
616
+ const sizeDescription = typeof size === "object" ? size.description : `${size}`;
617
+ const description = options.description ?? `bytes(${sizeDescription})`;
618
+ const byteDecoder = {
619
+ decode: (bytes, offset = 0) => {
620
+ const slice = bytes.slice(offset);
621
+ return [slice, offset + slice.length];
622
+ },
623
+ description,
624
+ fixedSize: null,
625
+ maxSize: null
626
+ };
627
+ if (size === "variable") {
628
+ return byteDecoder;
629
+ }
630
+ if (typeof size === "number") {
631
+ return fixDecoder(byteDecoder, size, description);
632
+ }
633
+ return {
634
+ ...byteDecoder,
635
+ decode: (bytes, offset = 0) => {
636
+ assertByteArrayIsNotEmptyForCodec("bytes", bytes, offset);
637
+ const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);
638
+ const length = Number(lengthBigInt);
639
+ offset = lengthOffset;
640
+ const contentBytes = bytes.slice(offset, offset + length);
641
+ assertByteArrayHasEnoughBytesForCodec("bytes", length, contentBytes);
642
+ const [value, contentOffset] = byteDecoder.decode(contentBytes);
643
+ offset += contentOffset;
644
+ return [value, offset];
645
+ }
646
+ };
647
+ }
648
+ function structCodecHelper(fields, description) {
649
+ const fieldDescriptions = fields.map(([name, codec]) => `${String(name)}: ${codec.description}`).join(", ");
650
+ return {
651
+ description: description ?? `struct(${fieldDescriptions})`,
652
+ fixedSize: sumCodecSizes(fields.map(([, field]) => field.fixedSize)),
653
+ maxSize: sumCodecSizes(fields.map(([, field]) => field.maxSize))
654
+ };
655
+ }
656
+ function getStructEncoder(fields, options = {}) {
657
+ return {
658
+ ...structCodecHelper(fields, options.description),
659
+ encode: (struct) => {
660
+ const fieldBytes = fields.map(([key, codec]) => codec.encode(struct[key]));
661
+ return mergeBytes(fieldBytes);
662
+ }
663
+ };
664
+ }
665
+ function getStructDecoder(fields, options = {}) {
666
+ return {
667
+ ...structCodecHelper(fields, options.description),
668
+ decode: (bytes, offset = 0) => {
669
+ const struct = {};
670
+ fields.forEach(([key, codec]) => {
671
+ const [value, newOffset] = codec.decode(bytes, offset);
672
+ offset = newOffset;
673
+ struct[key] = value;
674
+ });
675
+ return [struct, offset];
676
+ }
677
+ };
678
+ }
679
+
680
+ // ../codecs-strings/dist/index.browser.js
681
+ function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
682
+ if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
683
+ throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);
684
+ }
685
+ }
686
+ var getBaseXEncoder = (alphabet4) => {
687
+ const base = alphabet4.length;
688
+ const baseBigInt = BigInt(base);
689
+ return {
690
+ description: `base${base}`,
691
+ encode(value) {
692
+ assertValidBaseString(alphabet4, value);
693
+ if (value === "")
694
+ return new Uint8Array();
695
+ const chars = [...value];
696
+ let trailIndex = chars.findIndex((c) => c !== alphabet4[0]);
697
+ trailIndex = trailIndex === -1 ? chars.length : trailIndex;
698
+ const leadingZeroes = Array(trailIndex).fill(0);
699
+ if (trailIndex === chars.length)
700
+ return Uint8Array.from(leadingZeroes);
701
+ const tailChars = chars.slice(trailIndex);
702
+ let base10Number = 0n;
703
+ let baseXPower = 1n;
704
+ for (let i = tailChars.length - 1; i >= 0; i -= 1) {
705
+ base10Number += baseXPower * BigInt(alphabet4.indexOf(tailChars[i]));
706
+ baseXPower *= baseBigInt;
707
+ }
708
+ const tailBytes = [];
709
+ while (base10Number > 0n) {
710
+ tailBytes.unshift(Number(base10Number % 256n));
711
+ base10Number /= 256n;
712
+ }
713
+ return Uint8Array.from(leadingZeroes.concat(tailBytes));
714
+ },
715
+ fixedSize: null,
716
+ maxSize: null
717
+ };
718
+ };
719
+ var getBaseXDecoder = (alphabet4) => {
720
+ const base = alphabet4.length;
721
+ const baseBigInt = BigInt(base);
722
+ return {
723
+ decode(rawBytes, offset = 0) {
724
+ const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);
725
+ if (bytes.length === 0)
726
+ return ["", 0];
727
+ let trailIndex = bytes.findIndex((n) => n !== 0);
728
+ trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
729
+ const leadingZeroes = alphabet4[0].repeat(trailIndex);
730
+ if (trailIndex === bytes.length)
731
+ return [leadingZeroes, rawBytes.length];
732
+ let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
733
+ const tailChars = [];
734
+ while (base10Number > 0n) {
735
+ tailChars.unshift(alphabet4[Number(base10Number % baseBigInt)]);
736
+ base10Number /= baseBigInt;
737
+ }
738
+ return [leadingZeroes + tailChars.join(""), rawBytes.length];
739
+ },
740
+ description: `base${base}`,
741
+ fixedSize: null,
742
+ maxSize: null
743
+ };
744
+ };
745
+ var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
746
+ var getBase58Encoder = () => getBaseXEncoder(alphabet2);
747
+ var getBase58Decoder = () => getBaseXDecoder(alphabet2);
748
+ var removeNullCharacters = (value) => (
749
+ // eslint-disable-next-line no-control-regex
750
+ value.replace(/\u0000/g, "")
751
+ );
752
+ var e = globalThis.TextDecoder;
753
+ var o = globalThis.TextEncoder;
754
+ var getUtf8Encoder = () => {
755
+ let textEncoder;
756
+ return {
757
+ description: "utf8",
758
+ encode: (value) => new Uint8Array((textEncoder || (textEncoder = new o())).encode(value)),
759
+ fixedSize: null,
760
+ maxSize: null
761
+ };
762
+ };
763
+ var getUtf8Decoder = () => {
764
+ let textDecoder;
765
+ return {
766
+ decode(bytes, offset = 0) {
767
+ const value = (textDecoder || (textDecoder = new e())).decode(bytes.slice(offset));
768
+ return [removeNullCharacters(value), bytes.length];
769
+ },
770
+ description: "utf8",
771
+ fixedSize: null,
772
+ maxSize: null
773
+ };
774
+ };
775
+ var getStringEncoder = (options = {}) => {
776
+ const size = options.size ?? getU32Encoder();
777
+ const encoding = options.encoding ?? getUtf8Encoder();
778
+ const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
779
+ if (size === "variable") {
780
+ return { ...encoding, description };
781
+ }
782
+ if (typeof size === "number") {
783
+ return fixEncoder(encoding, size, description);
784
+ }
785
+ return {
786
+ description,
787
+ encode: (value) => {
788
+ const contentBytes = encoding.encode(value);
789
+ const lengthBytes = size.encode(contentBytes.length);
790
+ return mergeBytes([lengthBytes, contentBytes]);
791
+ },
792
+ fixedSize: null,
793
+ maxSize: null
794
+ };
795
+ };
796
+ var getStringDecoder = (options = {}) => {
797
+ const size = options.size ?? getU32Decoder();
798
+ const encoding = options.encoding ?? getUtf8Decoder();
799
+ const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
800
+ if (size === "variable") {
801
+ return { ...encoding, description };
802
+ }
803
+ if (typeof size === "number") {
804
+ return fixDecoder(encoding, size, description);
805
+ }
806
+ return {
807
+ decode: (bytes, offset = 0) => {
808
+ assertByteArrayIsNotEmptyForCodec("string", bytes, offset);
809
+ const [lengthBigInt, lengthOffset] = size.decode(bytes, offset);
810
+ const length = Number(lengthBigInt);
811
+ offset = lengthOffset;
812
+ const contentBytes = bytes.slice(offset, offset + length);
813
+ assertByteArrayHasEnoughBytesForCodec("string", length, contentBytes);
814
+ const [value, contentOffset] = encoding.decode(contentBytes);
815
+ offset += contentOffset;
816
+ return [value, offset];
817
+ },
818
+ description,
819
+ fixedSize: null,
820
+ maxSize: null
821
+ };
822
+ };
823
+ function getSizeDescription(size) {
824
+ return typeof size === "object" ? size.description : `${size}`;
825
+ }
826
+
827
+ // ../assertions/dist/index.browser.js
828
+ function assertIsSecureContext() {
829
+ if (!globalThis.isSecureContext) {
830
+ throw new Error(
831
+ "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
832
+ );
833
+ }
834
+ }
835
+ async function assertKeyExporterIsAvailable() {
836
+ assertIsSecureContext();
837
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.exportKey !== "function") {
838
+ throw new Error("No key export implementation could be found");
839
+ }
840
+ }
841
+ async function assertSigningCapabilityIsAvailable() {
842
+ assertIsSecureContext();
843
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") {
844
+ throw new Error("No signing implementation could be found");
845
+ }
846
+ }
847
+
848
+ // ../addresses/dist/index.browser.js
849
+ var memoizedBase58Encoder;
850
+ var memoizedBase58Decoder;
851
+ function getMemoizedBase58Encoder() {
852
+ if (!memoizedBase58Encoder)
853
+ memoizedBase58Encoder = getBase58Encoder();
854
+ return memoizedBase58Encoder;
855
+ }
856
+ function getMemoizedBase58Decoder() {
857
+ if (!memoizedBase58Decoder)
858
+ memoizedBase58Decoder = getBase58Decoder();
859
+ return memoizedBase58Decoder;
860
+ }
861
+ function assertIsAddress(putativeBase58EncodedAddress) {
862
+ try {
863
+ if (
864
+ // Lowest address (32 bytes of zeroes)
865
+ putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
866
+ putativeBase58EncodedAddress.length > 44
867
+ ) {
868
+ throw new Error("Expected input string to decode to a byte array of length 32.");
869
+ }
870
+ const base58Encoder = getMemoizedBase58Encoder();
871
+ const bytes = base58Encoder.encode(putativeBase58EncodedAddress);
872
+ const numBytes = bytes.byteLength;
873
+ if (numBytes !== 32) {
874
+ throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
875
+ }
876
+ } catch (e2) {
877
+ throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
878
+ cause: e2
879
+ });
880
+ }
881
+ }
882
+ function address(putativeBase58EncodedAddress) {
883
+ assertIsAddress(putativeBase58EncodedAddress);
884
+ return putativeBase58EncodedAddress;
885
+ }
886
+ function getAddressEncoder(config) {
887
+ return mapEncoder(
888
+ getStringEncoder({
889
+ description: config?.description ?? "Base58EncodedAddress",
890
+ encoding: getMemoizedBase58Encoder(),
891
+ size: 32
892
+ }),
893
+ (putativeAddress) => address(putativeAddress)
894
+ );
895
+ }
896
+ function getAddressDecoder(config) {
897
+ return getStringDecoder({
898
+ description: config?.description ?? "Base58EncodedAddress",
899
+ encoding: getMemoizedBase58Decoder(),
900
+ size: 32
901
+ });
902
+ }
903
+ function getAddressComparator() {
904
+ return new Intl.Collator("en", {
905
+ caseFirst: "lower",
906
+ ignorePunctuation: false,
907
+ localeMatcher: "best fit",
908
+ numeric: false,
909
+ sensitivity: "variant",
910
+ usage: "sort"
911
+ }).compare;
912
+ }
913
+ async function getAddressFromPublicKey(publicKey) {
914
+ await assertKeyExporterIsAvailable();
915
+ if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
916
+ throw new Error("The `CryptoKey` must be an `Ed25519` public key");
917
+ }
918
+ const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
919
+ const [base58EncodedAddress] = getAddressDecoder().decode(new Uint8Array(publicKeyBytes));
920
+ return base58EncodedAddress;
921
+ }
922
+
923
+ // src/accounts.ts
924
+ function upsert(addressMap, address2, update) {
925
+ addressMap[address2] = update(addressMap[address2] ?? { role: AccountRole.READONLY });
926
+ }
927
+ var TYPE = Symbol("AddressMapTypeProperty");
928
+ function getAddressMapFromInstructions(feePayer, instructions) {
929
+ const addressMap = {
930
+ [feePayer]: { [TYPE]: 0 /* FEE_PAYER */, role: AccountRole.WRITABLE_SIGNER }
931
+ };
932
+ const addressesOfInvokedPrograms = /* @__PURE__ */ new Set();
933
+ for (const instruction of instructions) {
934
+ upsert(addressMap, instruction.programAddress, (entry) => {
935
+ addressesOfInvokedPrograms.add(instruction.programAddress);
936
+ if (TYPE in entry) {
937
+ if (isWritableRole(entry.role)) {
938
+ switch (entry[TYPE]) {
939
+ case 0 /* FEE_PAYER */:
940
+ throw new Error(
941
+ `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.`
942
+ );
943
+ default:
944
+ throw new Error(
945
+ `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.`
946
+ );
947
+ }
948
+ }
949
+ if (entry[TYPE] === 2 /* STATIC */) {
950
+ return entry;
951
+ }
952
+ }
953
+ return { [TYPE]: 2 /* STATIC */, role: AccountRole.READONLY };
954
+ });
955
+ let addressComparator;
956
+ if (!instruction.accounts) {
957
+ continue;
958
+ }
959
+ for (const account of instruction.accounts) {
960
+ upsert(addressMap, account.address, (entry) => {
961
+ const {
962
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
963
+ address: _,
964
+ ...accountMeta
965
+ } = account;
966
+ if (TYPE in entry) {
967
+ switch (entry[TYPE]) {
968
+ case 0 /* FEE_PAYER */:
969
+ return entry;
970
+ case 1 /* LOOKUP_TABLE */: {
971
+ const nextRole = mergeRoles(entry.role, accountMeta.role);
972
+ if ("lookupTableAddress" in accountMeta) {
973
+ const shouldReplaceEntry = (
974
+ // Consider using the new LOOKUP_TABLE if its address is different...
975
+ entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
976
+ (addressComparator || (addressComparator = getAddressComparator()))(
977
+ accountMeta.lookupTableAddress,
978
+ entry.lookupTableAddress
979
+ ) < 0
980
+ );
981
+ if (shouldReplaceEntry) {
982
+ return {
983
+ [TYPE]: 1 /* LOOKUP_TABLE */,
984
+ ...accountMeta,
985
+ role: nextRole
986
+ };
987
+ }
988
+ } else if (isSignerRole(accountMeta.role)) {
989
+ return {
990
+ [TYPE]: 2 /* STATIC */,
991
+ role: nextRole
992
+ };
993
+ }
994
+ if (entry.role !== nextRole) {
995
+ return {
996
+ ...entry,
997
+ role: nextRole
998
+ };
999
+ } else {
1000
+ return entry;
1001
+ }
1002
+ }
1003
+ case 2 /* STATIC */: {
1004
+ const nextRole = mergeRoles(entry.role, accountMeta.role);
1005
+ if (
1006
+ // Check to see if this address represents a program that is invoked
1007
+ // in this transaction.
1008
+ addressesOfInvokedPrograms.has(account.address)
1009
+ ) {
1010
+ if (isWritableRole(accountMeta.role)) {
1011
+ throw new Error(
1012
+ `This transaction includes an address (\`${account.address}\`) which is both invoked and marked writable. Program addresses may not be writable.`
1013
+ );
1014
+ }
1015
+ if (entry.role !== nextRole) {
1016
+ return {
1017
+ ...entry,
1018
+ role: nextRole
1019
+ };
1020
+ } else {
1021
+ return entry;
1022
+ }
1023
+ } else if ("lookupTableAddress" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as
1024
+ // long as they are not require to sign the transaction.
1025
+ !isSignerRole(entry.role)) {
1026
+ return {
1027
+ ...accountMeta,
1028
+ [TYPE]: 1 /* LOOKUP_TABLE */,
1029
+ role: nextRole
1030
+ };
1031
+ } else {
1032
+ if (entry.role !== nextRole) {
1033
+ return {
1034
+ ...entry,
1035
+ role: nextRole
1036
+ };
1037
+ } else {
1038
+ return entry;
1039
+ }
1040
+ }
1041
+ }
1042
+ }
1043
+ }
1044
+ if ("lookupTableAddress" in accountMeta) {
1045
+ return {
1046
+ ...accountMeta,
1047
+ [TYPE]: 1 /* LOOKUP_TABLE */
1048
+ };
1049
+ } else {
1050
+ return {
1051
+ ...accountMeta,
1052
+ [TYPE]: 2 /* STATIC */
1053
+ };
1054
+ }
1055
+ });
1056
+ }
1057
+ }
1058
+ return addressMap;
1059
+ }
1060
+ function getOrderedAccountsFromAddressMap(addressMap) {
1061
+ let addressComparator;
1062
+ const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {
1063
+ if (leftEntry[TYPE] !== rightEntry[TYPE]) {
1064
+ if (leftEntry[TYPE] === 0 /* FEE_PAYER */) {
1065
+ return -1;
1066
+ } else if (rightEntry[TYPE] === 0 /* FEE_PAYER */) {
1067
+ return 1;
1068
+ } else if (leftEntry[TYPE] === 2 /* STATIC */) {
1069
+ return -1;
1070
+ } else if (rightEntry[TYPE] === 2 /* STATIC */) {
1071
+ return 1;
1072
+ }
1073
+ }
1074
+ const leftIsSigner = isSignerRole(leftEntry.role);
1075
+ if (leftIsSigner !== isSignerRole(rightEntry.role)) {
1076
+ return leftIsSigner ? -1 : 1;
1077
+ }
1078
+ const leftIsWritable = isWritableRole(leftEntry.role);
1079
+ if (leftIsWritable !== isWritableRole(rightEntry.role)) {
1080
+ return leftIsWritable ? -1 : 1;
1081
+ }
1082
+ addressComparator || (addressComparator = getAddressComparator());
1083
+ if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
1084
+ return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
1085
+ } else {
1086
+ return addressComparator(leftAddress, rightAddress);
1087
+ }
1088
+ }).map(([address2, addressMeta]) => ({
1089
+ address: address2,
1090
+ ...addressMeta
1091
+ }));
1092
+ return orderedAccounts;
1093
+ }
1094
+
1095
+ // src/compile-address-table-lookups.ts
1096
+ function getCompiledAddressTableLookups(orderedAccounts) {
1097
+ var _a;
1098
+ const index = {};
1099
+ for (const account of orderedAccounts) {
1100
+ if (!("lookupTableAddress" in account)) {
1101
+ continue;
1102
+ }
1103
+ const entry = index[_a = account.lookupTableAddress] || (index[_a] = {
1104
+ readableIndices: [],
1105
+ writableIndices: []
1106
+ });
1107
+ if (account.role === AccountRole.WRITABLE) {
1108
+ entry.writableIndices.push(account.addressIndex);
1109
+ } else {
1110
+ entry.readableIndices.push(account.addressIndex);
1111
+ }
1112
+ }
1113
+ return Object.keys(index).sort(getAddressComparator()).map((lookupTableAddress) => ({
1114
+ lookupTableAddress,
1115
+ ...index[lookupTableAddress]
1116
+ }));
1117
+ }
1118
+
1119
+ // src/compile-header.ts
1120
+ function getCompiledMessageHeader(orderedAccounts) {
1121
+ let numReadonlyNonSignerAccounts = 0;
1122
+ let numReadonlySignerAccounts = 0;
1123
+ let numSignerAccounts = 0;
1124
+ for (const account of orderedAccounts) {
1125
+ if ("lookupTableAddress" in account) {
1126
+ break;
1127
+ }
1128
+ const accountIsWritable = isWritableRole(account.role);
1129
+ if (isSignerRole(account.role)) {
1130
+ numSignerAccounts++;
1131
+ if (!accountIsWritable) {
1132
+ numReadonlySignerAccounts++;
1133
+ }
1134
+ } else if (!accountIsWritable) {
1135
+ numReadonlyNonSignerAccounts++;
1136
+ }
1137
+ }
1138
+ return {
1139
+ numReadonlyNonSignerAccounts,
1140
+ numReadonlySignerAccounts,
1141
+ numSignerAccounts
1142
+ };
1143
+ }
1144
+
1145
+ // src/compile-instructions.ts
1146
+ function getAccountIndex(orderedAccounts) {
1147
+ const out = {};
1148
+ for (const [index, account] of orderedAccounts.entries()) {
1149
+ out[account.address] = index;
1150
+ }
1151
+ return out;
1152
+ }
1153
+ function getCompiledInstructions(instructions, orderedAccounts) {
1154
+ const accountIndex = getAccountIndex(orderedAccounts);
1155
+ return instructions.map(({ accounts, data, programAddress }) => {
1156
+ return {
1157
+ programAddressIndex: accountIndex[programAddress],
1158
+ ...accounts ? { accountIndices: accounts.map(({ address: address2 }) => accountIndex[address2]) } : null,
1159
+ ...data ? { data } : null
1160
+ };
1161
+ });
1162
+ }
1163
+
1164
+ // src/compile-lifetime-token.ts
1165
+ function getCompiledLifetimeToken(lifetimeConstraint) {
1166
+ if ("nonce" in lifetimeConstraint) {
1167
+ return lifetimeConstraint.nonce;
1168
+ }
1169
+ return lifetimeConstraint.blockhash;
1170
+ }
1171
+
1172
+ // src/compile-static-accounts.ts
1173
+ function getCompiledStaticAccounts(orderedAccounts) {
1174
+ const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account);
1175
+ const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);
1176
+ return orderedStaticAccounts.map(({ address: address2 }) => address2);
1177
+ }
1178
+
1179
+ // src/message.ts
1180
+ function compileMessage(transaction) {
1181
+ const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);
1182
+ const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);
1183
+ return {
1184
+ ...transaction.version !== "legacy" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null,
1185
+ header: getCompiledMessageHeader(orderedAccounts),
1186
+ instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),
1187
+ lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),
1188
+ staticAccounts: getCompiledStaticAccounts(orderedAccounts),
1189
+ version: transaction.version
1190
+ };
1191
+ }
1192
+
1193
+ // src/compile-transaction.ts
1194
+ function getCompiledTransaction(transaction) {
1195
+ const compiledMessage = compileMessage(transaction);
1196
+ let signatures;
46
1197
  if ("signatures" in transaction) {
47
- const {
48
- signatures: _,
49
- // eslint-disable-line @typescript-eslint/no-unused-vars
50
- ...unsignedTransaction
51
- } = transaction;
52
- out = {
53
- ...unsignedTransaction,
54
- instructions: nextInstructions
1198
+ signatures = [];
1199
+ for (let ii = 0; ii < compiledMessage.header.numSignerAccounts; ii++) {
1200
+ signatures[ii] = transaction.signatures[compiledMessage.staticAccounts[ii]] ?? new Uint8Array(Array(64).fill(0));
1201
+ }
1202
+ } else {
1203
+ signatures = Array(compiledMessage.header.numSignerAccounts).fill(new Uint8Array(Array(64).fill(0)));
1204
+ }
1205
+ return {
1206
+ compiledMessage,
1207
+ signatures
1208
+ };
1209
+ }
1210
+
1211
+ // ../functional/dist/index.browser.js
1212
+ function pipe(init, ...fns) {
1213
+ return fns.reduce((acc, fn) => fn(acc), init);
1214
+ }
1215
+
1216
+ // src/decompile-transaction.ts
1217
+ function getAccountMetas(message) {
1218
+ const { header } = message;
1219
+ const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;
1220
+ const numWritableNonSignerAccounts = message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;
1221
+ const accountMetas = [];
1222
+ let accountIndex = 0;
1223
+ for (let i = 0; i < numWritableSignerAccounts; i++) {
1224
+ accountMetas.push({
1225
+ address: message.staticAccounts[accountIndex],
1226
+ role: AccountRole.WRITABLE_SIGNER
1227
+ });
1228
+ accountIndex++;
1229
+ }
1230
+ for (let i = 0; i < header.numReadonlySignerAccounts; i++) {
1231
+ accountMetas.push({
1232
+ address: message.staticAccounts[accountIndex],
1233
+ role: AccountRole.READONLY_SIGNER
1234
+ });
1235
+ accountIndex++;
1236
+ }
1237
+ for (let i = 0; i < numWritableNonSignerAccounts; i++) {
1238
+ accountMetas.push({
1239
+ address: message.staticAccounts[accountIndex],
1240
+ role: AccountRole.WRITABLE
1241
+ });
1242
+ accountIndex++;
1243
+ }
1244
+ for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {
1245
+ accountMetas.push({
1246
+ address: message.staticAccounts[accountIndex],
1247
+ role: AccountRole.READONLY
1248
+ });
1249
+ accountIndex++;
1250
+ }
1251
+ return accountMetas;
1252
+ }
1253
+ function convertInstruction(instruction, accountMetas) {
1254
+ const programAddress = accountMetas[instruction.programAddressIndex]?.address;
1255
+ if (!programAddress) {
1256
+ throw new Error(`Could not find program address at index ${instruction.programAddressIndex}`);
1257
+ }
1258
+ const accounts = instruction.accountIndices?.map((accountIndex) => accountMetas[accountIndex]);
1259
+ const { data } = instruction;
1260
+ return {
1261
+ programAddress,
1262
+ ...accounts && accounts.length ? { accounts } : {},
1263
+ ...data && data.length ? { data } : {}
1264
+ };
1265
+ }
1266
+ function getLifetimeConstraint(messageLifetimeToken, firstInstruction, lastValidBlockHeight) {
1267
+ if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {
1268
+ return {
1269
+ blockhash: messageLifetimeToken,
1270
+ lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n
1271
+ // U64 MAX
55
1272
  };
56
1273
  } else {
57
- out = {
58
- ...transaction,
59
- instructions: nextInstructions
1274
+ const nonceAccountAddress = firstInstruction.accounts[0].address;
1275
+ assertIsAddress(nonceAccountAddress);
1276
+ const nonceAuthorityAddress = firstInstruction.accounts[2].address;
1277
+ assertIsAddress(nonceAuthorityAddress);
1278
+ return {
1279
+ nonce: messageLifetimeToken,
1280
+ nonceAccountAddress,
1281
+ nonceAuthorityAddress
60
1282
  };
61
1283
  }
62
- return out;
63
1284
  }
64
- function appendTransactionInstruction(instruction, transaction) {
65
- const nextInstructions = [...transaction.instructions, instruction];
66
- const out = replaceInstructions(transaction, nextInstructions);
67
- Object.freeze(out);
68
- return out;
1285
+ function convertSignatures(compiledTransaction) {
1286
+ const {
1287
+ compiledMessage: { staticAccounts },
1288
+ signatures
1289
+ } = compiledTransaction;
1290
+ return signatures.reduce((acc, sig, index) => {
1291
+ const allZeros = sig.every((byte) => byte === 0);
1292
+ if (allZeros)
1293
+ return acc;
1294
+ const address2 = staticAccounts[index];
1295
+ return { ...acc, [address2]: sig };
1296
+ }, {});
69
1297
  }
70
- function prependTransactionInstruction(instruction, transaction) {
71
- const nextInstructions = [instruction, ...transaction.instructions];
72
- const out = replaceInstructions(transaction, nextInstructions);
1298
+ function decompileTransaction(compiledTransaction, lastValidBlockHeight) {
1299
+ const { compiledMessage } = compiledTransaction;
1300
+ if ("addressTableLookups" in compiledMessage && compiledMessage.addressTableLookups.length > 0) {
1301
+ throw new Error("Cannot convert transaction with addressTableLookups");
1302
+ }
1303
+ const feePayer = compiledMessage.staticAccounts[0];
1304
+ if (!feePayer)
1305
+ throw new Error("No fee payer set in CompiledTransaction");
1306
+ const accountMetas = getAccountMetas(compiledMessage);
1307
+ const instructions = compiledMessage.instructions.map(
1308
+ (compiledInstruction) => convertInstruction(compiledInstruction, accountMetas)
1309
+ );
1310
+ const firstInstruction = instructions[0];
1311
+ const lifetimeConstraint = getLifetimeConstraint(
1312
+ compiledMessage.lifetimeToken,
1313
+ firstInstruction,
1314
+ lastValidBlockHeight
1315
+ );
1316
+ const signatures = convertSignatures(compiledTransaction);
1317
+ return pipe(
1318
+ createTransaction({ version: compiledMessage.version }),
1319
+ (tx) => setTransactionFeePayer(feePayer, tx),
1320
+ (tx) => instructions.reduce((acc, instruction) => {
1321
+ return appendTransactionInstruction(instruction, acc);
1322
+ }, tx),
1323
+ (tx) => "blockhash" in lifetimeConstraint ? setTransactionLifetimeUsingBlockhash(lifetimeConstraint, tx) : setTransactionLifetimeUsingDurableNonce(lifetimeConstraint, tx),
1324
+ (tx) => compiledTransaction.signatures.length ? { ...tx, signatures } : tx
1325
+ );
1326
+ }
1327
+
1328
+ // src/serializers/address-table-lookup.ts
1329
+ var lookupTableAddressDescription = "The address of the address lookup table account from which instruction addresses should be looked up" ;
1330
+ var writableIndicesDescription = "The indices of the accounts in the lookup table that should be loaded as writeable" ;
1331
+ var readableIndicesDescription = "The indices of the accounts in the lookup table that should be loaded as read-only" ;
1332
+ var addressTableLookupDescription = "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" ;
1333
+ var memoizedAddressTableLookupEncoder;
1334
+ function getAddressTableLookupEncoder() {
1335
+ if (!memoizedAddressTableLookupEncoder) {
1336
+ memoizedAddressTableLookupEncoder = getStructEncoder(
1337
+ [
1338
+ ["lookupTableAddress", getAddressEncoder({ description: lookupTableAddressDescription })],
1339
+ [
1340
+ "writableIndices",
1341
+ getArrayEncoder(getU8Encoder(), {
1342
+ description: writableIndicesDescription,
1343
+ size: getShortU16Encoder()
1344
+ })
1345
+ ],
1346
+ [
1347
+ "readableIndices",
1348
+ getArrayEncoder(getU8Encoder(), {
1349
+ description: readableIndicesDescription,
1350
+ size: getShortU16Encoder()
1351
+ })
1352
+ ]
1353
+ ],
1354
+ { description: addressTableLookupDescription }
1355
+ );
1356
+ }
1357
+ return memoizedAddressTableLookupEncoder;
1358
+ }
1359
+ var memoizedAddressTableLookupDecoder;
1360
+ function getAddressTableLookupDecoder() {
1361
+ if (!memoizedAddressTableLookupDecoder) {
1362
+ memoizedAddressTableLookupDecoder = getStructDecoder(
1363
+ [
1364
+ ["lookupTableAddress", getAddressDecoder({ description: lookupTableAddressDescription })],
1365
+ [
1366
+ "writableIndices",
1367
+ getArrayDecoder(getU8Decoder(), {
1368
+ description: writableIndicesDescription,
1369
+ size: getShortU16Decoder()
1370
+ })
1371
+ ],
1372
+ [
1373
+ "readableIndices",
1374
+ getArrayDecoder(getU8Decoder(), {
1375
+ description: readableIndicesDescription,
1376
+ size: getShortU16Decoder()
1377
+ })
1378
+ ]
1379
+ ],
1380
+ { description: addressTableLookupDescription }
1381
+ );
1382
+ }
1383
+ return memoizedAddressTableLookupDecoder;
1384
+ }
1385
+
1386
+ // src/serializers/header.ts
1387
+ var memoizedU8Encoder;
1388
+ function getMemoizedU8Encoder() {
1389
+ if (!memoizedU8Encoder)
1390
+ memoizedU8Encoder = getU8Encoder();
1391
+ return memoizedU8Encoder;
1392
+ }
1393
+ function getMemoizedU8EncoderDescription(description) {
1394
+ const encoder = getMemoizedU8Encoder();
1395
+ return {
1396
+ ...encoder,
1397
+ description: description ?? encoder.description
1398
+ };
1399
+ }
1400
+ var memoizedU8Decoder;
1401
+ function getMemoizedU8Decoder() {
1402
+ if (!memoizedU8Decoder)
1403
+ memoizedU8Decoder = getU8Decoder();
1404
+ return memoizedU8Decoder;
1405
+ }
1406
+ function getMemoizedU8DecoderDescription(description) {
1407
+ const decoder = getMemoizedU8Decoder();
1408
+ return {
1409
+ ...decoder,
1410
+ description: description ?? decoder.description
1411
+ };
1412
+ }
1413
+ var numSignerAccountsDescription = "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction" ;
1414
+ var numReadonlySignerAccountsDescription = "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" ;
1415
+ var numReadonlyNonSignerAccountsDescription = "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable" ;
1416
+ var messageHeaderDescription = "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses" ;
1417
+ function getMessageHeaderEncoder() {
1418
+ return getStructEncoder(
1419
+ [
1420
+ ["numSignerAccounts", getMemoizedU8EncoderDescription(numSignerAccountsDescription)],
1421
+ ["numReadonlySignerAccounts", getMemoizedU8EncoderDescription(numReadonlySignerAccountsDescription)],
1422
+ ["numReadonlyNonSignerAccounts", getMemoizedU8EncoderDescription(numReadonlyNonSignerAccountsDescription)]
1423
+ ],
1424
+ {
1425
+ description: messageHeaderDescription
1426
+ }
1427
+ );
1428
+ }
1429
+ function getMessageHeaderDecoder() {
1430
+ return getStructDecoder(
1431
+ [
1432
+ ["numSignerAccounts", getMemoizedU8DecoderDescription(numSignerAccountsDescription)],
1433
+ ["numReadonlySignerAccounts", getMemoizedU8DecoderDescription(numReadonlySignerAccountsDescription)],
1434
+ ["numReadonlyNonSignerAccounts", getMemoizedU8DecoderDescription(numReadonlyNonSignerAccountsDescription)]
1435
+ ],
1436
+ {
1437
+ description: messageHeaderDescription
1438
+ }
1439
+ );
1440
+ }
1441
+
1442
+ // src/serializers/instruction.ts
1443
+ var programAddressIndexDescription = "The index of the program being called, according to the well-ordered accounts list for this transaction" ;
1444
+ var accountIndexDescription = "The index of an account, according to the well-ordered accounts list for this transaction" ;
1445
+ var accountIndicesDescription = "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" ;
1446
+ var dataDescription = "An optional buffer of data passed to the instruction" ;
1447
+ var memoizedGetInstructionEncoder;
1448
+ function getInstructionEncoder() {
1449
+ if (!memoizedGetInstructionEncoder) {
1450
+ memoizedGetInstructionEncoder = mapEncoder(
1451
+ getStructEncoder([
1452
+ ["programAddressIndex", getU8Encoder({ description: programAddressIndexDescription })],
1453
+ [
1454
+ "accountIndices",
1455
+ getArrayEncoder(getU8Encoder({ description: accountIndexDescription }), {
1456
+ description: accountIndicesDescription,
1457
+ size: getShortU16Encoder()
1458
+ })
1459
+ ],
1460
+ ["data", getBytesEncoder({ description: dataDescription, size: getShortU16Encoder() })]
1461
+ ]),
1462
+ // Convert an instruction to have all fields defined
1463
+ (instruction) => {
1464
+ if (instruction.accountIndices !== void 0 && instruction.data !== void 0) {
1465
+ return instruction;
1466
+ }
1467
+ return {
1468
+ ...instruction,
1469
+ accountIndices: instruction.accountIndices ?? [],
1470
+ data: instruction.data ?? new Uint8Array(0)
1471
+ };
1472
+ }
1473
+ );
1474
+ }
1475
+ return memoizedGetInstructionEncoder;
1476
+ }
1477
+ var memoizedGetInstructionDecoder;
1478
+ function getInstructionDecoder() {
1479
+ if (!memoizedGetInstructionDecoder) {
1480
+ memoizedGetInstructionDecoder = mapDecoder(
1481
+ getStructDecoder([
1482
+ ["programAddressIndex", getU8Decoder({ description: programAddressIndexDescription })],
1483
+ [
1484
+ "accountIndices",
1485
+ getArrayDecoder(getU8Decoder({ description: accountIndexDescription }), {
1486
+ description: accountIndicesDescription,
1487
+ size: getShortU16Decoder()
1488
+ })
1489
+ ],
1490
+ ["data", getBytesDecoder({ description: dataDescription, size: getShortU16Decoder() })]
1491
+ ]),
1492
+ // Convert an instruction to exclude optional fields if they are empty
1493
+ (instruction) => {
1494
+ if (instruction.accountIndices.length && instruction.data.byteLength) {
1495
+ return instruction;
1496
+ }
1497
+ const { accountIndices, data, ...rest } = instruction;
1498
+ return {
1499
+ ...rest,
1500
+ ...accountIndices.length ? { accountIndices } : null,
1501
+ ...data.byteLength ? { data } : null
1502
+ };
1503
+ }
1504
+ );
1505
+ }
1506
+ return memoizedGetInstructionDecoder;
1507
+ }
1508
+
1509
+ // src/serializers/transaction-version.ts
1510
+ var VERSION_FLAG_MASK = 128;
1511
+ var BASE_CONFIG = {
1512
+ description: "A single byte that encodes the version of the transaction" ,
1513
+ fixedSize: null,
1514
+ maxSize: 1
1515
+ };
1516
+ function decode(bytes, offset = 0) {
1517
+ const firstByte = bytes[offset];
1518
+ if ((firstByte & VERSION_FLAG_MASK) === 0) {
1519
+ return ["legacy", offset];
1520
+ } else {
1521
+ const version = firstByte ^ VERSION_FLAG_MASK;
1522
+ return [version, offset + 1];
1523
+ }
1524
+ }
1525
+ function encode(value) {
1526
+ if (value === "legacy") {
1527
+ return new Uint8Array();
1528
+ }
1529
+ if (value < 0 || value > 127) {
1530
+ throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`);
1531
+ }
1532
+ return new Uint8Array([value | VERSION_FLAG_MASK]);
1533
+ }
1534
+ function getTransactionVersionDecoder() {
1535
+ return {
1536
+ ...BASE_CONFIG,
1537
+ decode
1538
+ };
1539
+ }
1540
+ function getTransactionVersionEncoder() {
1541
+ return {
1542
+ ...BASE_CONFIG,
1543
+ encode
1544
+ };
1545
+ }
1546
+
1547
+ // src/serializers/message.ts
1548
+ var staticAccountsDescription = "A compact-array of static account addresses belonging to this transaction" ;
1549
+ var lifetimeTokenDescription = "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" ;
1550
+ var instructionsDescription = "A compact-array of instructions belonging to this transaction" ;
1551
+ var addressTableLookupsDescription = "A compact array of address table lookups belonging to this transaction" ;
1552
+ function getCompiledMessageLegacyEncoder() {
1553
+ return getStructEncoder(getPreludeStructEncoderTuple());
1554
+ }
1555
+ function getCompiledMessageVersionedEncoder() {
1556
+ return mapEncoder(
1557
+ getStructEncoder([
1558
+ ...getPreludeStructEncoderTuple(),
1559
+ ["addressTableLookups", getAddressTableLookupArrayEncoder()]
1560
+ ]),
1561
+ (value) => {
1562
+ if (value.version === "legacy") {
1563
+ return value;
1564
+ }
1565
+ return {
1566
+ ...value,
1567
+ addressTableLookups: value.addressTableLookups ?? []
1568
+ };
1569
+ }
1570
+ );
1571
+ }
1572
+ function getPreludeStructEncoderTuple() {
1573
+ return [
1574
+ ["version", getTransactionVersionEncoder()],
1575
+ ["header", getMessageHeaderEncoder()],
1576
+ [
1577
+ "staticAccounts",
1578
+ getArrayEncoder(getAddressEncoder(), {
1579
+ description: staticAccountsDescription,
1580
+ size: getShortU16Encoder()
1581
+ })
1582
+ ],
1583
+ [
1584
+ "lifetimeToken",
1585
+ getStringEncoder({
1586
+ description: lifetimeTokenDescription,
1587
+ encoding: getBase58Encoder(),
1588
+ size: 32
1589
+ })
1590
+ ],
1591
+ [
1592
+ "instructions",
1593
+ getArrayEncoder(getInstructionEncoder(), {
1594
+ description: instructionsDescription,
1595
+ size: getShortU16Encoder()
1596
+ })
1597
+ ]
1598
+ ];
1599
+ }
1600
+ function getPreludeStructDecoderTuple() {
1601
+ return [
1602
+ ["version", getTransactionVersionDecoder()],
1603
+ ["header", getMessageHeaderDecoder()],
1604
+ [
1605
+ "staticAccounts",
1606
+ getArrayDecoder(getAddressDecoder(), {
1607
+ description: staticAccountsDescription,
1608
+ size: getShortU16Decoder()
1609
+ })
1610
+ ],
1611
+ [
1612
+ "lifetimeToken",
1613
+ getStringDecoder({
1614
+ description: lifetimeTokenDescription,
1615
+ encoding: getBase58Decoder(),
1616
+ size: 32
1617
+ })
1618
+ ],
1619
+ [
1620
+ "instructions",
1621
+ getArrayDecoder(getInstructionDecoder(), {
1622
+ description: instructionsDescription,
1623
+ size: getShortU16Decoder()
1624
+ })
1625
+ ],
1626
+ ["addressTableLookups", getAddressTableLookupArrayDecoder()]
1627
+ ];
1628
+ }
1629
+ function getAddressTableLookupArrayEncoder() {
1630
+ return getArrayEncoder(getAddressTableLookupEncoder(), {
1631
+ description: addressTableLookupsDescription,
1632
+ size: getShortU16Encoder()
1633
+ });
1634
+ }
1635
+ function getAddressTableLookupArrayDecoder() {
1636
+ return getArrayDecoder(getAddressTableLookupDecoder(), {
1637
+ description: addressTableLookupsDescription,
1638
+ size: getShortU16Decoder()
1639
+ });
1640
+ }
1641
+ var messageDescription = "The wire format of a Solana transaction message" ;
1642
+ function getCompiledMessageEncoder() {
1643
+ return {
1644
+ description: messageDescription,
1645
+ encode: (compiledMessage) => {
1646
+ if (compiledMessage.version === "legacy") {
1647
+ return getCompiledMessageLegacyEncoder().encode(compiledMessage);
1648
+ } else {
1649
+ return getCompiledMessageVersionedEncoder().encode(compiledMessage);
1650
+ }
1651
+ },
1652
+ fixedSize: null,
1653
+ maxSize: null
1654
+ };
1655
+ }
1656
+ function getCompiledMessageDecoder() {
1657
+ return mapDecoder(
1658
+ getStructDecoder(getPreludeStructDecoderTuple(), {
1659
+ description: messageDescription
1660
+ }),
1661
+ ({ addressTableLookups, ...restOfMessage }) => {
1662
+ if (restOfMessage.version === "legacy" || !addressTableLookups?.length) {
1663
+ return restOfMessage;
1664
+ }
1665
+ return { ...restOfMessage, addressTableLookups };
1666
+ }
1667
+ );
1668
+ }
1669
+
1670
+ // src/serializers/transaction.ts
1671
+ var signaturesDescription = "A compact array of 64-byte, base-64 encoded Ed25519 signatures" ;
1672
+ var transactionDescription = "The wire format of a Solana transaction" ;
1673
+ function getCompiledTransactionEncoder() {
1674
+ return getStructEncoder(
1675
+ [
1676
+ [
1677
+ "signatures",
1678
+ getArrayEncoder(getBytesEncoder({ size: 64 }), {
1679
+ description: signaturesDescription,
1680
+ size: getShortU16Encoder()
1681
+ })
1682
+ ],
1683
+ ["compiledMessage", getCompiledMessageEncoder()]
1684
+ ],
1685
+ {
1686
+ description: transactionDescription
1687
+ }
1688
+ );
1689
+ }
1690
+ function getSignatureDecoder() {
1691
+ return mapDecoder(getBytesDecoder({ size: 64 }), (bytes) => bytes);
1692
+ }
1693
+ function getCompiledTransactionDecoder() {
1694
+ return getStructDecoder(
1695
+ [
1696
+ [
1697
+ "signatures",
1698
+ getArrayDecoder(getSignatureDecoder(), {
1699
+ description: signaturesDescription,
1700
+ size: getShortU16Decoder()
1701
+ })
1702
+ ],
1703
+ ["compiledMessage", getCompiledMessageDecoder()]
1704
+ ],
1705
+ {
1706
+ description: transactionDescription
1707
+ }
1708
+ );
1709
+ }
1710
+ function getTransactionEncoder() {
1711
+ return mapEncoder(getCompiledTransactionEncoder(), getCompiledTransaction);
1712
+ }
1713
+ function getTransactionDecoder(lastValidBlockHeight) {
1714
+ return mapDecoder(
1715
+ getCompiledTransactionDecoder(),
1716
+ (compiledTransaction) => decompileTransaction(compiledTransaction, lastValidBlockHeight)
1717
+ );
1718
+ }
1719
+ function getTransactionCodec(lastValidBlockHeight) {
1720
+ return combineCodec(getTransactionEncoder(), getTransactionDecoder(lastValidBlockHeight));
1721
+ }
1722
+
1723
+ // ../keys/dist/index.browser.js
1724
+ async function signBytes(key, data) {
1725
+ await assertSigningCapabilityIsAvailable();
1726
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
1727
+ return new Uint8Array(signedData);
1728
+ }
1729
+
1730
+ // src/signatures.ts
1731
+ function assertIsTransactionSignature(putativeTransactionSignature) {
1732
+ try {
1733
+ if (
1734
+ // Lowest value (64 bytes of zeroes)
1735
+ putativeTransactionSignature.length < 64 || // Highest value (64 bytes of 255)
1736
+ putativeTransactionSignature.length > 88
1737
+ ) {
1738
+ throw new Error("Expected input string to decode to a byte array of length 64.");
1739
+ }
1740
+ const bytes = base58.serialize(putativeTransactionSignature);
1741
+ const numBytes = bytes.byteLength;
1742
+ if (numBytes !== 64) {
1743
+ throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
1744
+ }
1745
+ } catch (e2) {
1746
+ throw new Error(`\`${putativeTransactionSignature}\` is not a transaction signature`, {
1747
+ cause: e2
1748
+ });
1749
+ }
1750
+ }
1751
+ function isTransactionSignature(putativeTransactionSignature) {
1752
+ if (
1753
+ // Lowest value (64 bytes of zeroes)
1754
+ putativeTransactionSignature.length < 64 || // Highest value (64 bytes of 255)
1755
+ putativeTransactionSignature.length > 88
1756
+ ) {
1757
+ return false;
1758
+ }
1759
+ const bytes = base58.serialize(putativeTransactionSignature);
1760
+ const numBytes = bytes.byteLength;
1761
+ if (numBytes !== 64) {
1762
+ return false;
1763
+ }
1764
+ return true;
1765
+ }
1766
+ function getSignatureFromTransaction(transaction) {
1767
+ const signatureBytes = transaction.signatures[transaction.feePayer];
1768
+ if (!signatureBytes) {
1769
+ throw new Error(
1770
+ "Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer."
1771
+ );
1772
+ }
1773
+ const transactionSignature2 = base58.deserialize(signatureBytes)[0];
1774
+ return transactionSignature2;
1775
+ }
1776
+ async function signTransaction(keyPairs, transaction) {
1777
+ const compiledMessage = compileMessage(transaction);
1778
+ const nextSignatures = "signatures" in transaction ? { ...transaction.signatures } : {};
1779
+ const wireMessageBytes = getCompiledMessageEncoder().encode(compiledMessage);
1780
+ const publicKeySignaturePairs = await Promise.all(
1781
+ keyPairs.map(
1782
+ (keyPair) => Promise.all([getAddressFromPublicKey(keyPair.publicKey), signBytes(keyPair.privateKey, wireMessageBytes)])
1783
+ )
1784
+ );
1785
+ for (const [signerPublicKey, signature] of publicKeySignaturePairs) {
1786
+ nextSignatures[signerPublicKey] = signature;
1787
+ }
1788
+ const out = {
1789
+ ...transaction,
1790
+ signatures: nextSignatures
1791
+ };
73
1792
  Object.freeze(out);
74
1793
  return out;
75
1794
  }
1795
+ function transactionSignature(putativeTransactionSignature) {
1796
+ assertIsTransactionSignature(putativeTransactionSignature);
1797
+ return putativeTransactionSignature;
1798
+ }
1799
+ function assertTransactionIsFullySigned(transaction) {
1800
+ const signerAddressesFromInstructions = transaction.instructions.flatMap((i) => i.accounts?.filter((a) => isSignerRole(a.role)) ?? []).map((a) => a.address);
1801
+ const requiredSigners = /* @__PURE__ */ new Set([transaction.feePayer, ...signerAddressesFromInstructions]);
1802
+ requiredSigners.forEach((address2) => {
1803
+ if (!transaction.signatures[address2]) {
1804
+ throw new Error(`Transaction is missing signature for address \`${address2}\``);
1805
+ }
1806
+ });
1807
+ }
1808
+
1809
+ // src/wire-transaction.ts
1810
+ function getBase64EncodedWireTransaction(transaction) {
1811
+ const wireTransactionBytes = getTransactionEncoder().encode(transaction);
1812
+ {
1813
+ return btoa(String.fromCharCode(...wireTransactionBytes));
1814
+ }
1815
+ }
76
1816
 
77
1817
  exports.appendTransactionInstruction = appendTransactionInstruction;
1818
+ exports.assertIsBlockhash = assertIsBlockhash;
1819
+ exports.assertIsDurableNonceTransaction = assertIsDurableNonceTransaction;
1820
+ exports.assertIsTransactionSignature = assertIsTransactionSignature;
1821
+ exports.assertTransactionIsFullySigned = assertTransactionIsFullySigned;
78
1822
  exports.createTransaction = createTransaction;
1823
+ exports.getBase64EncodedWireTransaction = getBase64EncodedWireTransaction;
1824
+ exports.getSignatureFromTransaction = getSignatureFromTransaction;
1825
+ exports.getTransactionCodec = getTransactionCodec;
1826
+ exports.getTransactionDecoder = getTransactionDecoder;
1827
+ exports.getTransactionEncoder = getTransactionEncoder;
1828
+ exports.isAdvanceNonceAccountInstruction = isAdvanceNonceAccountInstruction;
1829
+ exports.isTransactionSignature = isTransactionSignature;
79
1830
  exports.prependTransactionInstruction = prependTransactionInstruction;
80
1831
  exports.setTransactionFeePayer = setTransactionFeePayer;
1832
+ exports.setTransactionLifetimeUsingBlockhash = setTransactionLifetimeUsingBlockhash;
1833
+ exports.setTransactionLifetimeUsingDurableNonce = setTransactionLifetimeUsingDurableNonce;
1834
+ exports.signTransaction = signTransaction;
1835
+ exports.transactionSignature = transactionSignature;
81
1836
 
82
1837
  return exports;
83
1838