@solana/transactions 2.0.0-experimental.6cedd3a → 2.0.0-experimental.71b920d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,11 @@
1
1
  'use strict';
2
2
 
3
+ var keys = require('@solana/keys');
4
+ var umiSerializers = require('@metaplex-foundation/umi-serializers');
5
+
6
+ // ../build-scripts/env-shim.ts
7
+ var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
8
+
3
9
  // src/create-transaction.ts
4
10
  function createTransaction({
5
11
  version
@@ -72,7 +78,560 @@ function prependTransactionInstruction(instruction, transaction) {
72
78
  return out;
73
79
  }
74
80
 
81
+ // ../instructions/dist/index.browser.js
82
+ var AccountRole = /* @__PURE__ */ ((AccountRole2) => {
83
+ AccountRole2[AccountRole2["WRITABLE_SIGNER"] = /* 3 */
84
+ 3] = "WRITABLE_SIGNER";
85
+ AccountRole2[AccountRole2["READONLY_SIGNER"] = /* 2 */
86
+ 2] = "READONLY_SIGNER";
87
+ AccountRole2[AccountRole2["WRITABLE"] = /* 1 */
88
+ 1] = "WRITABLE";
89
+ AccountRole2[AccountRole2["READONLY"] = /* 0 */
90
+ 0] = "READONLY";
91
+ return AccountRole2;
92
+ })(AccountRole || {});
93
+ var IS_WRITABLE_BITMASK = 1;
94
+ function isSignerRole(role) {
95
+ return role >= 2;
96
+ }
97
+ function isWritableRole(role) {
98
+ return (role & IS_WRITABLE_BITMASK) !== 0;
99
+ }
100
+ function mergeRoles(roleA, roleB) {
101
+ return roleA | roleB;
102
+ }
103
+ function upsert(addressMap, address, update) {
104
+ addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });
105
+ }
106
+ var TYPE = Symbol("AddressMapTypeProperty");
107
+ function getAddressMapFromInstructions(feePayer, instructions) {
108
+ const addressMap = {
109
+ [feePayer]: { [TYPE]: 0 /* FEE_PAYER */, role: AccountRole.WRITABLE_SIGNER }
110
+ };
111
+ const addressesOfInvokedPrograms = /* @__PURE__ */ new Set();
112
+ for (const instruction of instructions) {
113
+ upsert(addressMap, instruction.programAddress, (entry) => {
114
+ addressesOfInvokedPrograms.add(instruction.programAddress);
115
+ if (TYPE in entry) {
116
+ if (isWritableRole(entry.role)) {
117
+ switch (entry[TYPE]) {
118
+ case 0 /* FEE_PAYER */:
119
+ throw new Error(
120
+ `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and set as the fee payer. Program addresses may not pay fees.`
121
+ );
122
+ default:
123
+ throw new Error(
124
+ `This transaction includes an address (\`${instruction.programAddress}\`) which is both invoked and marked writable. Program addresses may not be writable.`
125
+ );
126
+ }
127
+ }
128
+ if (entry[TYPE] === 2 /* STATIC */) {
129
+ return entry;
130
+ }
131
+ }
132
+ return { [TYPE]: 2 /* STATIC */, role: AccountRole.READONLY };
133
+ });
134
+ let addressComparator;
135
+ if (!instruction.accounts) {
136
+ continue;
137
+ }
138
+ for (const account of instruction.accounts) {
139
+ upsert(addressMap, account.address, (entry) => {
140
+ const {
141
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
142
+ address: _,
143
+ ...accountMeta
144
+ } = account;
145
+ if (TYPE in entry) {
146
+ switch (entry[TYPE]) {
147
+ case 0 /* FEE_PAYER */:
148
+ return entry;
149
+ case 1 /* LOOKUP_TABLE */: {
150
+ const nextRole = mergeRoles(entry.role, accountMeta.role);
151
+ if ("lookupTableAddress" in accountMeta) {
152
+ const shouldReplaceEntry = (
153
+ // Consider using the new LOOKUP_TABLE if its address is different...
154
+ entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
155
+ (addressComparator || (addressComparator = keys.getBase58EncodedAddressComparator()))(
156
+ accountMeta.lookupTableAddress,
157
+ entry.lookupTableAddress
158
+ ) < 0
159
+ );
160
+ if (shouldReplaceEntry) {
161
+ return {
162
+ [TYPE]: 1 /* LOOKUP_TABLE */,
163
+ ...accountMeta,
164
+ role: nextRole
165
+ };
166
+ }
167
+ } else if (isSignerRole(accountMeta.role)) {
168
+ return {
169
+ [TYPE]: 2 /* STATIC */,
170
+ role: nextRole
171
+ };
172
+ }
173
+ if (entry.role !== nextRole) {
174
+ return {
175
+ ...entry,
176
+ role: nextRole
177
+ };
178
+ } else {
179
+ return entry;
180
+ }
181
+ }
182
+ case 2 /* STATIC */: {
183
+ const nextRole = mergeRoles(entry.role, accountMeta.role);
184
+ if (
185
+ // Check to see if this address represents a program that is invoked
186
+ // in this transaction.
187
+ addressesOfInvokedPrograms.has(account.address)
188
+ ) {
189
+ if (isWritableRole(accountMeta.role)) {
190
+ throw new Error(
191
+ `This transaction includes an address (\`${account.address}\`) which is both invoked and marked writable. Program addresses may not be writable.`
192
+ );
193
+ }
194
+ if (entry.role !== nextRole) {
195
+ return {
196
+ ...entry,
197
+ role: nextRole
198
+ };
199
+ } else {
200
+ return entry;
201
+ }
202
+ } else if ("lookupTableAddress" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as
203
+ // long as they are not require to sign the transaction.
204
+ !isSignerRole(entry.role)) {
205
+ return {
206
+ ...accountMeta,
207
+ [TYPE]: 1 /* LOOKUP_TABLE */,
208
+ role: nextRole
209
+ };
210
+ } else {
211
+ if (entry.role !== nextRole) {
212
+ return {
213
+ ...entry,
214
+ role: nextRole
215
+ };
216
+ } else {
217
+ return entry;
218
+ }
219
+ }
220
+ }
221
+ }
222
+ }
223
+ if ("lookupTableAddress" in accountMeta) {
224
+ return {
225
+ ...accountMeta,
226
+ [TYPE]: 1 /* LOOKUP_TABLE */
227
+ };
228
+ } else {
229
+ return {
230
+ ...accountMeta,
231
+ [TYPE]: 2 /* STATIC */
232
+ };
233
+ }
234
+ });
235
+ }
236
+ }
237
+ return addressMap;
238
+ }
239
+ function getOrderedAccountsFromAddressMap(addressMap) {
240
+ let addressComparator;
241
+ const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {
242
+ if (leftEntry[TYPE] !== rightEntry[TYPE]) {
243
+ if (leftEntry[TYPE] === 0 /* FEE_PAYER */) {
244
+ return -1;
245
+ } else if (rightEntry[TYPE] === 0 /* FEE_PAYER */) {
246
+ return 1;
247
+ } else if (leftEntry[TYPE] === 2 /* STATIC */) {
248
+ return -1;
249
+ } else if (rightEntry[TYPE] === 2 /* STATIC */) {
250
+ return 1;
251
+ }
252
+ }
253
+ const leftIsSigner = isSignerRole(leftEntry.role);
254
+ if (leftIsSigner !== isSignerRole(rightEntry.role)) {
255
+ return leftIsSigner ? -1 : 1;
256
+ }
257
+ const leftIsWritable = isWritableRole(leftEntry.role);
258
+ if (leftIsWritable !== isWritableRole(rightEntry.role)) {
259
+ return leftIsWritable ? -1 : 1;
260
+ }
261
+ addressComparator || (addressComparator = keys.getBase58EncodedAddressComparator());
262
+ if (leftEntry[TYPE] === 1 /* LOOKUP_TABLE */ && rightEntry[TYPE] === 1 /* LOOKUP_TABLE */ && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
263
+ return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
264
+ } else {
265
+ return addressComparator(leftAddress, rightAddress);
266
+ }
267
+ }).map(([address, addressMeta]) => ({
268
+ address,
269
+ ...addressMeta
270
+ }));
271
+ return orderedAccounts;
272
+ }
273
+ function getCompiledAddressTableLookups(orderedAccounts) {
274
+ var _a;
275
+ const index = {};
276
+ for (const account of orderedAccounts) {
277
+ if (!("lookupTableAddress" in account)) {
278
+ continue;
279
+ }
280
+ const entry = index[_a = account.lookupTableAddress] || (index[_a] = {
281
+ readableIndices: [],
282
+ writableIndices: []
283
+ });
284
+ if (account.role === AccountRole.WRITABLE) {
285
+ entry.writableIndices.push(account.addressIndex);
286
+ } else {
287
+ entry.readableIndices.push(account.addressIndex);
288
+ }
289
+ }
290
+ return Object.keys(index).sort(keys.getBase58EncodedAddressComparator()).map((lookupTableAddress) => ({
291
+ lookupTableAddress,
292
+ ...index[lookupTableAddress]
293
+ }));
294
+ }
295
+
296
+ // src/compile-header.ts
297
+ function getCompiledMessageHeader(orderedAccounts) {
298
+ let numReadonlyNonSignerAccounts = 0;
299
+ let numReadonlySignerAccounts = 0;
300
+ let numSignerAccounts = 0;
301
+ for (const account of orderedAccounts) {
302
+ if ("lookupTableAddress" in account) {
303
+ break;
304
+ }
305
+ const accountIsWritable = isWritableRole(account.role);
306
+ if (isSignerRole(account.role)) {
307
+ numSignerAccounts++;
308
+ if (!accountIsWritable) {
309
+ numReadonlySignerAccounts++;
310
+ }
311
+ } else if (!accountIsWritable) {
312
+ numReadonlyNonSignerAccounts++;
313
+ }
314
+ }
315
+ return {
316
+ numReadonlyNonSignerAccounts,
317
+ numReadonlySignerAccounts,
318
+ numSignerAccounts
319
+ };
320
+ }
321
+
322
+ // src/compile-instructions.ts
323
+ function getAccountIndex(orderedAccounts) {
324
+ const out = {};
325
+ for (const [index, account] of orderedAccounts.entries()) {
326
+ out[account.address] = index;
327
+ }
328
+ return out;
329
+ }
330
+ function getCompiledInstructions(instructions, orderedAccounts) {
331
+ const accountIndex = getAccountIndex(orderedAccounts);
332
+ return instructions.map(({ accounts, data, programAddress }) => {
333
+ return {
334
+ programAddressIndex: accountIndex[programAddress],
335
+ ...accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null,
336
+ ...data ? { data } : null
337
+ };
338
+ });
339
+ }
340
+
341
+ // src/compile-lifetime-token.ts
342
+ function getCompiledLifetimeToken(lifetimeConstraint) {
343
+ if ("nonce" in lifetimeConstraint) {
344
+ return lifetimeConstraint.nonce;
345
+ }
346
+ return lifetimeConstraint.blockhash;
347
+ }
348
+
349
+ // src/compile-static-accounts.ts
350
+ function getCompiledStaticAccounts(orderedAccounts) {
351
+ const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account);
352
+ const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);
353
+ return orderedStaticAccounts.map(({ address }) => address);
354
+ }
355
+
356
+ // src/message.ts
357
+ function compileMessage(transaction) {
358
+ const addressMap = getAddressMapFromInstructions(transaction.feePayer, transaction.instructions);
359
+ const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);
360
+ return {
361
+ ...transaction.version !== "legacy" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null,
362
+ header: getCompiledMessageHeader(orderedAccounts),
363
+ instructions: getCompiledInstructions(transaction.instructions, orderedAccounts),
364
+ lifetimeToken: getCompiledLifetimeToken(transaction.lifetimeConstraint),
365
+ staticAccounts: getCompiledStaticAccounts(orderedAccounts),
366
+ version: transaction.version
367
+ };
368
+ }
369
+ function getAddressTableLookupCodec() {
370
+ return umiSerializers.struct(
371
+ [
372
+ [
373
+ "lookupTableAddress",
374
+ keys.getBase58EncodedAddressCodec(
375
+ __DEV__ ? {
376
+ description: "The address of the address lookup table account from which instruction addresses should be looked up"
377
+ } : void 0
378
+ )
379
+ ],
380
+ [
381
+ "writableIndices",
382
+ umiSerializers.array(umiSerializers.u8(), {
383
+ ...__DEV__ ? {
384
+ description: "The indices of the accounts in the lookup table that should be loaded as writeable"
385
+ } : null,
386
+ size: umiSerializers.shortU16()
387
+ })
388
+ ],
389
+ [
390
+ "readableIndices",
391
+ umiSerializers.array(umiSerializers.u8(), {
392
+ ...__DEV__ ? {
393
+ description: "The indices of the accounts in the lookup table that should be loaded as read-only"
394
+ } : void 0,
395
+ size: umiSerializers.shortU16()
396
+ })
397
+ ]
398
+ ],
399
+ __DEV__ ? {
400
+ description: "A pointer to the address of an address lookup table, along with the readonly/writeable indices of the addresses that should be loaded from it"
401
+ } : void 0
402
+ );
403
+ }
404
+ function getMessageHeaderCodec() {
405
+ return umiSerializers.struct(
406
+ [
407
+ [
408
+ "numSignerAccounts",
409
+ umiSerializers.u8(
410
+ __DEV__ ? {
411
+ description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction"
412
+ } : void 0
413
+ )
414
+ ],
415
+ [
416
+ "numReadonlySignerAccounts",
417
+ umiSerializers.u8(
418
+ __DEV__ ? {
419
+ description: "The expected number of addresses in the static address list belonging to accounts that are required to sign this transaction, but may not be writable"
420
+ } : void 0
421
+ )
422
+ ],
423
+ [
424
+ "numReadonlyNonSignerAccounts",
425
+ umiSerializers.u8(
426
+ __DEV__ ? {
427
+ description: "The expected number of addresses in the static address list belonging to accounts that are neither signers, nor writable"
428
+ } : void 0
429
+ )
430
+ ]
431
+ ],
432
+ __DEV__ ? {
433
+ description: "The transaction message header containing counts of the signer, readonly-signer, and readonly-nonsigner account addresses"
434
+ } : void 0
435
+ );
436
+ }
437
+ function getInstructionCodec() {
438
+ return umiSerializers.mapSerializer(
439
+ umiSerializers.struct([
440
+ [
441
+ "programAddressIndex",
442
+ umiSerializers.u8(
443
+ __DEV__ ? {
444
+ description: "The index of the program being called, according to the well-ordered accounts list for this transaction"
445
+ } : void 0
446
+ )
447
+ ],
448
+ [
449
+ "addressIndices",
450
+ umiSerializers.array(
451
+ umiSerializers.u8({
452
+ description: __DEV__ ? "The index of an account, according to the well-ordered accounts list for this transaction" : ""
453
+ }),
454
+ {
455
+ description: __DEV__ ? "An optional list of account indices, according to the well-ordered accounts list for this transaction, in the order in which the program being called expects them" : "",
456
+ size: umiSerializers.shortU16()
457
+ }
458
+ )
459
+ ],
460
+ [
461
+ "data",
462
+ umiSerializers.bytes({
463
+ description: __DEV__ ? "An optional buffer of data passed to the instruction" : "",
464
+ size: umiSerializers.shortU16()
465
+ })
466
+ ]
467
+ ]),
468
+ (value) => {
469
+ if (value.addressIndices !== void 0 && value.data !== void 0) {
470
+ return value;
471
+ }
472
+ return {
473
+ ...value,
474
+ addressIndices: value.addressIndices ?? [],
475
+ data: value.data ?? new Uint8Array(0)
476
+ };
477
+ },
478
+ (value) => {
479
+ if (value.addressIndices.length && value.data.byteLength) {
480
+ return value;
481
+ }
482
+ const { addressIndices, data, ...rest } = value;
483
+ return {
484
+ ...rest,
485
+ ...addressIndices.length ? { addressIndices } : null,
486
+ ...data.byteLength ? { data } : null
487
+ };
488
+ }
489
+ );
490
+ }
491
+
492
+ // src/serializers/unimplemented.ts
493
+ function getError(type, name) {
494
+ const functionSuffix = name + type[0].toUpperCase() + type.slice(1);
495
+ return new Error(
496
+ `No ${type} exists for ${name}. Use \`get${functionSuffix}()\` if you need a ${type}, and \`get${name}Codec()\` if you need to both encode and decode ${name}`
497
+ );
498
+ }
499
+ function getUnimplementedDecoder(name) {
500
+ return () => {
501
+ throw getError("decoder", name);
502
+ };
503
+ }
504
+
505
+ // src/serializers/transaction-version.ts
506
+ var VERSION_FLAG_MASK = 128;
507
+ var BASE_CONFIG = {
508
+ description: __DEV__ ? "A single byte that encodes the version of the transaction" : "",
509
+ fixedSize: null,
510
+ maxSize: 1
511
+ };
512
+ function deserialize(bytes2, offset = 0) {
513
+ const firstByte = bytes2[offset];
514
+ if ((firstByte & VERSION_FLAG_MASK) === 0) {
515
+ return ["legacy", offset];
516
+ } else {
517
+ const version = firstByte ^ VERSION_FLAG_MASK;
518
+ return [version, offset + 1];
519
+ }
520
+ }
521
+ function serialize(value) {
522
+ if (value === "legacy") {
523
+ return new Uint8Array();
524
+ }
525
+ if (value < 0 || value > 127) {
526
+ throw new Error(`Transaction version must be in the range [0, 127]. \`${value}\` given.`);
527
+ }
528
+ return new Uint8Array([value | VERSION_FLAG_MASK]);
529
+ }
530
+ function getTransactionVersionCodec() {
531
+ return {
532
+ ...BASE_CONFIG,
533
+ deserialize,
534
+ serialize
535
+ };
536
+ }
537
+
538
+ // src/serializers/message.ts
539
+ var BASE_CONFIG2 = {
540
+ description: __DEV__ ? "The wire format of a Solana transaction message" : "",
541
+ fixedSize: null,
542
+ maxSize: null
543
+ };
544
+ function serialize2(compiledMessage) {
545
+ if (compiledMessage.version === "legacy") {
546
+ return umiSerializers.struct(getPreludeStructSerializerTuple()).serialize(compiledMessage);
547
+ } else {
548
+ return umiSerializers.mapSerializer(
549
+ umiSerializers.struct([
550
+ ...getPreludeStructSerializerTuple(),
551
+ ["addressTableLookups", getAddressTableLookupsSerializer()]
552
+ ]),
553
+ (value) => {
554
+ if (value.version === "legacy") {
555
+ return value;
556
+ }
557
+ return {
558
+ ...value,
559
+ addressTableLookups: value.addressTableLookups ?? []
560
+ };
561
+ }
562
+ ).serialize(compiledMessage);
563
+ }
564
+ }
565
+ function getPreludeStructSerializerTuple() {
566
+ return [
567
+ ["version", getTransactionVersionCodec()],
568
+ ["header", getMessageHeaderCodec()],
569
+ [
570
+ "staticAccounts",
571
+ umiSerializers.array(keys.getBase58EncodedAddressCodec(), {
572
+ description: __DEV__ ? "A compact-array of static account addresses belonging to this transaction" : "",
573
+ size: umiSerializers.shortU16()
574
+ })
575
+ ],
576
+ [
577
+ "lifetimeToken",
578
+ umiSerializers.string({
579
+ description: __DEV__ ? "A 32-byte token that specifies the lifetime of this transaction (eg. a recent blockhash, or a durable nonce)" : "",
580
+ encoding: umiSerializers.base58,
581
+ size: 32
582
+ })
583
+ ],
584
+ [
585
+ "instructions",
586
+ umiSerializers.array(getInstructionCodec(), {
587
+ description: __DEV__ ? "A compact-array of instructions belonging to this transaction" : "",
588
+ size: umiSerializers.shortU16()
589
+ })
590
+ ]
591
+ ];
592
+ }
593
+ function getAddressTableLookupsSerializer() {
594
+ return umiSerializers.array(getAddressTableLookupCodec(), {
595
+ ...__DEV__ ? { description: "A compact array of address table lookups belonging to this transaction" } : null,
596
+ size: umiSerializers.shortU16()
597
+ });
598
+ }
599
+ function getCompiledMessageEncoder() {
600
+ return {
601
+ ...BASE_CONFIG2,
602
+ deserialize: getUnimplementedDecoder("CompiledMessage"),
603
+ serialize: serialize2
604
+ };
605
+ }
606
+
607
+ // src/signatures.ts
608
+ async function getCompiledMessageSignature(message, secretKey) {
609
+ const wireMessageBytes = getCompiledMessageEncoder().serialize(message);
610
+ const signature = await keys.signBytes(secretKey, wireMessageBytes);
611
+ return signature;
612
+ }
613
+ async function signTransaction(keyPair, transaction) {
614
+ const compiledMessage = compileMessage(transaction);
615
+ const [signerPublicKey, signature] = await Promise.all([
616
+ keys.getBase58EncodedAddressFromPublicKey(keyPair.publicKey),
617
+ getCompiledMessageSignature(compiledMessage, keyPair.privateKey)
618
+ ]);
619
+ const nextSignatures = {
620
+ ..."signatures" in transaction ? transaction.signatures : null,
621
+ ...{ [signerPublicKey]: signature }
622
+ };
623
+ const out = {
624
+ ...transaction,
625
+ signatures: nextSignatures
626
+ };
627
+ Object.freeze(out);
628
+ return out;
629
+ }
630
+
75
631
  exports.appendTransactionInstruction = appendTransactionInstruction;
76
632
  exports.createTransaction = createTransaction;
77
633
  exports.prependTransactionInstruction = prependTransactionInstruction;
78
634
  exports.setTransactionFeePayer = setTransactionFeePayer;
635
+ exports.signTransaction = signTransaction;
636
+ //# sourceMappingURL=out.js.map
637
+ //# sourceMappingURL=index.browser.cjs.map