solana-web3-fork 1.0.0

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 (78) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +14 -0
  3. package/lib/index.browser.cjs.js +10564 -0
  4. package/lib/index.browser.cjs.js.map +1 -0
  5. package/lib/index.browser.esm.js +10463 -0
  6. package/lib/index.browser.esm.js.map +1 -0
  7. package/lib/index.cjs.js +11351 -0
  8. package/lib/index.cjs.js.map +1 -0
  9. package/lib/index.d.ts +4025 -0
  10. package/lib/index.esm.js +11246 -0
  11. package/lib/index.esm.js.map +1 -0
  12. package/lib/index.iife.js +26085 -0
  13. package/lib/index.iife.js.map +1 -0
  14. package/lib/index.iife.min.js +20 -0
  15. package/lib/index.iife.min.js.map +1 -0
  16. package/lib/index.native.js +10564 -0
  17. package/lib/index.native.js.map +1 -0
  18. package/package.json +87 -0
  19. package/src/__forks__/browser/fetch-impl.ts +4 -0
  20. package/src/__forks__/react-native/fetch-impl.ts +4 -0
  21. package/src/account-data.ts +39 -0
  22. package/src/account.ts +55 -0
  23. package/src/blockhash.ts +4 -0
  24. package/src/bpf-loader-deprecated.ts +5 -0
  25. package/src/bpf-loader.ts +50 -0
  26. package/src/connection.ts +6961 -0
  27. package/src/epoch-schedule.ts +102 -0
  28. package/src/errors.ts +133 -0
  29. package/src/fee-calculator.ts +18 -0
  30. package/src/fetch-impl.ts +16 -0
  31. package/src/index.ts +24 -0
  32. package/src/instruction.ts +58 -0
  33. package/src/keypair.ts +102 -0
  34. package/src/layout.ts +188 -0
  35. package/src/loader.ts +267 -0
  36. package/src/message/account-keys.ts +79 -0
  37. package/src/message/compiled-keys.ts +165 -0
  38. package/src/message/index.ts +47 -0
  39. package/src/message/legacy.ts +323 -0
  40. package/src/message/v0.ts +513 -0
  41. package/src/message/versioned.ts +36 -0
  42. package/src/nonce-account.ts +82 -0
  43. package/src/programs/address-lookup-table/index.ts +438 -0
  44. package/src/programs/address-lookup-table/state.ts +84 -0
  45. package/src/programs/compute-budget.ts +281 -0
  46. package/src/programs/ed25519.ts +157 -0
  47. package/src/programs/index.ts +7 -0
  48. package/src/programs/secp256k1.ts +228 -0
  49. package/src/programs/stake.ts +952 -0
  50. package/src/programs/system.ts +1048 -0
  51. package/src/programs/vote.ts +586 -0
  52. package/src/publickey.ts +259 -0
  53. package/src/rpc-websocket.ts +75 -0
  54. package/src/sysvar.ts +37 -0
  55. package/src/timing.ts +23 -0
  56. package/src/transaction/constants.ts +12 -0
  57. package/src/transaction/expiry-custom-errors.ts +48 -0
  58. package/src/transaction/index.ts +5 -0
  59. package/src/transaction/legacy.ts +970 -0
  60. package/src/transaction/message.ts +140 -0
  61. package/src/transaction/versioned.ts +127 -0
  62. package/src/utils/assert.ts +8 -0
  63. package/src/utils/bigint.ts +24 -0
  64. package/src/utils/borsh-schema.ts +38 -0
  65. package/src/utils/cluster.ts +35 -0
  66. package/src/utils/ed25519.ts +43 -0
  67. package/src/utils/guarded-array-utils.ts +34 -0
  68. package/src/utils/index.ts +5 -0
  69. package/src/utils/makeWebsocketUrl.ts +26 -0
  70. package/src/utils/promise-timeout.ts +14 -0
  71. package/src/utils/secp256k1.ts +11 -0
  72. package/src/utils/send-and-confirm-raw-transaction.ts +110 -0
  73. package/src/utils/send-and-confirm-transaction.ts +106 -0
  74. package/src/utils/shortvec-encoding.ts +28 -0
  75. package/src/utils/sleep.ts +4 -0
  76. package/src/utils/to-buffer.ts +11 -0
  77. package/src/validator-info.ts +108 -0
  78. package/src/vote-account.ts +236 -0
@@ -0,0 +1,970 @@
1
+ import bs58 from 'bs58';
2
+ import {Buffer} from 'buffer';
3
+
4
+ import {PACKET_DATA_SIZE, SIGNATURE_LENGTH_IN_BYTES} from './constants';
5
+ import {Connection} from '../connection';
6
+ import {Message} from '../message';
7
+ import {PublicKey} from '../publickey';
8
+ import * as shortvec from '../utils/shortvec-encoding';
9
+ import {toBuffer} from '../utils/to-buffer';
10
+ import invariant from '../utils/assert';
11
+ import type {Signer} from '../keypair';
12
+ import type {Blockhash} from '../blockhash';
13
+ import type {CompiledInstruction} from '../message';
14
+ import {sign, verify} from '../utils/ed25519';
15
+ import {guardedSplice} from '../utils/guarded-array-utils';
16
+
17
+ /** @internal */
18
+ type MessageSignednessErrors = {
19
+ invalid?: PublicKey[];
20
+ missing?: PublicKey[];
21
+ };
22
+
23
+ /**
24
+ * Transaction signature as base-58 encoded string
25
+ */
26
+ export type TransactionSignature = string;
27
+
28
+ export const enum TransactionStatus {
29
+ BLOCKHEIGHT_EXCEEDED,
30
+ PROCESSED,
31
+ TIMED_OUT,
32
+ NONCE_INVALID,
33
+ }
34
+
35
+ /**
36
+ * Default (empty) signature
37
+ */
38
+ const DEFAULT_SIGNATURE = Buffer.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0);
39
+
40
+ /**
41
+ * Account metadata used to define instructions
42
+ */
43
+ export type AccountMeta = {
44
+ /** An account's public key */
45
+ pubkey: PublicKey;
46
+ /** True if an instruction requires a transaction signature matching `pubkey` */
47
+ isSigner: boolean;
48
+ /** True if the `pubkey` can be loaded as a read-write account. */
49
+ isWritable: boolean;
50
+ };
51
+
52
+ /**
53
+ * List of TransactionInstruction object fields that may be initialized at construction
54
+ */
55
+ export type TransactionInstructionCtorFields = {
56
+ keys: Array<AccountMeta>;
57
+ programId: PublicKey;
58
+ data?: Buffer;
59
+ };
60
+
61
+ /**
62
+ * Configuration object for Transaction.serialize()
63
+ */
64
+ export type SerializeConfig = {
65
+ /** Require all transaction signatures be present (default: true) */
66
+ requireAllSignatures?: boolean;
67
+ /** Verify provided signatures (default: true) */
68
+ verifySignatures?: boolean;
69
+ };
70
+
71
+ /**
72
+ * @internal
73
+ */
74
+ export interface TransactionInstructionJSON {
75
+ keys: {
76
+ pubkey: string;
77
+ isSigner: boolean;
78
+ isWritable: boolean;
79
+ }[];
80
+ programId: string;
81
+ data: number[];
82
+ }
83
+
84
+ /**
85
+ * Transaction Instruction class
86
+ */
87
+ export class TransactionInstruction {
88
+ /**
89
+ * Public keys to include in this transaction
90
+ * Boolean represents whether this pubkey needs to sign the transaction
91
+ */
92
+ keys: Array<AccountMeta>;
93
+
94
+ /**
95
+ * Program Id to execute
96
+ */
97
+ programId: PublicKey;
98
+
99
+ /**
100
+ * Program input
101
+ */
102
+ data: Buffer = Buffer.alloc(0);
103
+
104
+ constructor(opts: TransactionInstructionCtorFields) {
105
+ this.programId = opts.programId;
106
+ this.keys = opts.keys;
107
+ if (opts.data) {
108
+ this.data = opts.data;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * @internal
114
+ */
115
+ toJSON(): TransactionInstructionJSON {
116
+ return {
117
+ keys: this.keys.map(({pubkey, isSigner, isWritable}) => ({
118
+ pubkey: pubkey.toJSON(),
119
+ isSigner,
120
+ isWritable,
121
+ })),
122
+ programId: this.programId.toJSON(),
123
+ data: [...this.data],
124
+ };
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Pair of signature and corresponding public key
130
+ */
131
+ export type SignaturePubkeyPair = {
132
+ signature: Buffer | null;
133
+ publicKey: PublicKey;
134
+ };
135
+
136
+ /**
137
+ * List of Transaction object fields that may be initialized at construction
138
+ */
139
+ export type TransactionCtorFields_DEPRECATED = {
140
+ /** Optional nonce information used for offline nonce'd transactions */
141
+ nonceInfo?: NonceInformation | null;
142
+ /** The transaction fee payer */
143
+ feePayer?: PublicKey | null;
144
+ /** One or more signatures */
145
+ signatures?: Array<SignaturePubkeyPair>;
146
+ /** A recent blockhash */
147
+ recentBlockhash?: Blockhash;
148
+ };
149
+
150
+ // For backward compatibility; an unfortunate consequence of being
151
+ // forced to over-export types by the documentation generator.
152
+ // See https://github.com/solana-labs/solana/pull/25820
153
+ export type TransactionCtorFields = TransactionCtorFields_DEPRECATED;
154
+
155
+ /**
156
+ * Blockhash-based transactions have a lifetime that are defined by
157
+ * the blockhash they include. Any transaction whose blockhash is
158
+ * too old will be rejected.
159
+ */
160
+ export type TransactionBlockhashCtor = {
161
+ /** The transaction fee payer */
162
+ feePayer?: PublicKey | null;
163
+ /** One or more signatures */
164
+ signatures?: Array<SignaturePubkeyPair>;
165
+ /** A recent blockhash */
166
+ blockhash: Blockhash;
167
+ /** the last block chain can advance to before tx is declared expired */
168
+ lastValidBlockHeight: number;
169
+ };
170
+
171
+ /**
172
+ * Use these options to construct a durable nonce transaction.
173
+ */
174
+ export type TransactionNonceCtor = {
175
+ /** The transaction fee payer */
176
+ feePayer?: PublicKey | null;
177
+ minContextSlot: number;
178
+ nonceInfo: NonceInformation;
179
+ /** One or more signatures */
180
+ signatures?: Array<SignaturePubkeyPair>;
181
+ };
182
+
183
+ /**
184
+ * Nonce information to be used to build an offline Transaction.
185
+ */
186
+ export type NonceInformation = {
187
+ /** The current blockhash stored in the nonce */
188
+ nonce: Blockhash;
189
+ /** AdvanceNonceAccount Instruction */
190
+ nonceInstruction: TransactionInstruction;
191
+ };
192
+
193
+ /**
194
+ * @internal
195
+ */
196
+ export interface TransactionJSON {
197
+ recentBlockhash: string | null;
198
+ feePayer: string | null;
199
+ nonceInfo: {
200
+ nonce: string;
201
+ nonceInstruction: TransactionInstructionJSON;
202
+ } | null;
203
+ instructions: TransactionInstructionJSON[];
204
+ signers: string[];
205
+ }
206
+
207
+ /**
208
+ * Transaction class
209
+ */
210
+ export class Transaction {
211
+ /**
212
+ * Signatures for the transaction. Typically created by invoking the
213
+ * `sign()` method
214
+ */
215
+ signatures: Array<SignaturePubkeyPair> = [];
216
+
217
+ /**
218
+ * The first (payer) Transaction signature
219
+ *
220
+ * @returns {Buffer | null} Buffer of payer's signature
221
+ */
222
+ get signature(): Buffer | null {
223
+ if (this.signatures.length > 0) {
224
+ return this.signatures[0].signature;
225
+ }
226
+ return null;
227
+ }
228
+
229
+ /**
230
+ * The transaction fee payer
231
+ */
232
+ feePayer?: PublicKey;
233
+
234
+ /**
235
+ * The instructions to atomically execute
236
+ */
237
+ instructions: Array<TransactionInstruction> = [];
238
+
239
+ /**
240
+ * A recent transaction id. Must be populated by the caller
241
+ */
242
+ recentBlockhash?: Blockhash;
243
+
244
+ /**
245
+ * the last block chain can advance to before tx is declared expired
246
+ * */
247
+ lastValidBlockHeight?: number;
248
+
249
+ /**
250
+ * Optional Nonce information. If populated, transaction will use a durable
251
+ * Nonce hash instead of a recentBlockhash. Must be populated by the caller
252
+ */
253
+ nonceInfo?: NonceInformation;
254
+
255
+ /**
256
+ * If this is a nonce transaction this represents the minimum slot from which
257
+ * to evaluate if the nonce has advanced when attempting to confirm the
258
+ * transaction. This protects against a case where the transaction confirmation
259
+ * logic loads the nonce account from an old slot and assumes the mismatch in
260
+ * nonce value implies that the nonce has been advanced.
261
+ */
262
+ minNonceContextSlot?: number;
263
+
264
+ /**
265
+ * @internal
266
+ */
267
+ _message?: Message;
268
+
269
+ /**
270
+ * @internal
271
+ */
272
+ _json?: TransactionJSON;
273
+
274
+ // Construct a transaction with a blockhash and lastValidBlockHeight
275
+ constructor(opts?: TransactionBlockhashCtor);
276
+
277
+ // Construct a transaction using a durable nonce
278
+ constructor(opts?: TransactionNonceCtor);
279
+
280
+ /**
281
+ * @deprecated `TransactionCtorFields` has been deprecated and will be removed in a future version.
282
+ * Please supply a `TransactionBlockhashCtor` instead.
283
+ */
284
+ constructor(opts?: TransactionCtorFields_DEPRECATED);
285
+
286
+ /**
287
+ * Construct an empty Transaction
288
+ */
289
+ constructor(
290
+ opts?:
291
+ | TransactionBlockhashCtor
292
+ | TransactionNonceCtor
293
+ | TransactionCtorFields_DEPRECATED,
294
+ ) {
295
+ if (!opts) {
296
+ return;
297
+ }
298
+ if (opts.feePayer) {
299
+ this.feePayer = opts.feePayer;
300
+ }
301
+ if (opts.signatures) {
302
+ this.signatures = opts.signatures;
303
+ }
304
+ if (Object.prototype.hasOwnProperty.call(opts, 'nonceInfo')) {
305
+ const {minContextSlot, nonceInfo} = opts as TransactionNonceCtor;
306
+ this.minNonceContextSlot = minContextSlot;
307
+ this.nonceInfo = nonceInfo;
308
+ } else if (
309
+ Object.prototype.hasOwnProperty.call(opts, 'lastValidBlockHeight')
310
+ ) {
311
+ const {blockhash, lastValidBlockHeight} =
312
+ opts as TransactionBlockhashCtor;
313
+ this.recentBlockhash = blockhash;
314
+ this.lastValidBlockHeight = lastValidBlockHeight;
315
+ } else {
316
+ const {recentBlockhash, nonceInfo} =
317
+ opts as TransactionCtorFields_DEPRECATED;
318
+ if (nonceInfo) {
319
+ this.nonceInfo = nonceInfo;
320
+ }
321
+ this.recentBlockhash = recentBlockhash;
322
+ }
323
+ }
324
+
325
+ /**
326
+ * @internal
327
+ */
328
+ toJSON(): TransactionJSON {
329
+ return {
330
+ recentBlockhash: this.recentBlockhash || null,
331
+ feePayer: this.feePayer ? this.feePayer.toJSON() : null,
332
+ nonceInfo: this.nonceInfo
333
+ ? {
334
+ nonce: this.nonceInfo.nonce,
335
+ nonceInstruction: this.nonceInfo.nonceInstruction.toJSON(),
336
+ }
337
+ : null,
338
+ instructions: this.instructions.map(instruction => instruction.toJSON()),
339
+ signers: this.signatures.map(({publicKey}) => {
340
+ return publicKey.toJSON();
341
+ }),
342
+ };
343
+ }
344
+
345
+ /**
346
+ * Add one or more instructions to this Transaction
347
+ *
348
+ * @param {Array< Transaction | TransactionInstruction | TransactionInstructionCtorFields >} items - Instructions to add to the Transaction
349
+ */
350
+ add(
351
+ ...items: Array<
352
+ Transaction | TransactionInstruction | TransactionInstructionCtorFields
353
+ >
354
+ ): Transaction {
355
+ if (items.length === 0) {
356
+ throw new Error('No instructions');
357
+ }
358
+
359
+ items.forEach((item: any) => {
360
+ if ('instructions' in item) {
361
+ this.instructions = this.instructions.concat(item.instructions);
362
+ } else if ('data' in item && 'programId' in item && 'keys' in item) {
363
+ this.instructions.push(item);
364
+ } else {
365
+ this.instructions.push(new TransactionInstruction(item));
366
+ }
367
+ });
368
+ return this;
369
+ }
370
+
371
+ /**
372
+ * Compile transaction data
373
+ */
374
+ compileMessage(): Message {
375
+ if (
376
+ this._message &&
377
+ JSON.stringify(this.toJSON()) === JSON.stringify(this._json)
378
+ ) {
379
+ return this._message;
380
+ }
381
+
382
+ let recentBlockhash;
383
+ let instructions: TransactionInstruction[];
384
+ if (this.nonceInfo) {
385
+ recentBlockhash = this.nonceInfo.nonce;
386
+ if (this.instructions[0] != this.nonceInfo.nonceInstruction) {
387
+ instructions = [this.nonceInfo.nonceInstruction, ...this.instructions];
388
+ } else {
389
+ instructions = this.instructions;
390
+ }
391
+ } else {
392
+ recentBlockhash = this.recentBlockhash;
393
+ instructions = this.instructions;
394
+ }
395
+ if (!recentBlockhash) {
396
+ throw new Error('Transaction recentBlockhash required');
397
+ }
398
+
399
+ if (instructions.length < 1) {
400
+ console.warn('No instructions provided');
401
+ }
402
+
403
+ let feePayer: PublicKey;
404
+ if (this.feePayer) {
405
+ feePayer = this.feePayer;
406
+ } else if (this.signatures.length > 0 && this.signatures[0].publicKey) {
407
+ // Use implicit fee payer
408
+ feePayer = this.signatures[0].publicKey;
409
+ } else {
410
+ throw new Error('Transaction fee payer required');
411
+ }
412
+
413
+ for (let i = 0; i < instructions.length; i++) {
414
+ if (instructions[i].programId === undefined) {
415
+ throw new Error(
416
+ `Transaction instruction index ${i} has undefined program id`,
417
+ );
418
+ }
419
+ }
420
+
421
+ const programIds: string[] = [];
422
+ const accountMetas: AccountMeta[] = [];
423
+ instructions.forEach(instruction => {
424
+ instruction.keys.forEach(accountMeta => {
425
+ accountMetas.push({...accountMeta});
426
+ });
427
+
428
+ const programId = instruction.programId.toString();
429
+ if (!programIds.includes(programId)) {
430
+ programIds.push(programId);
431
+ }
432
+ });
433
+
434
+ // Append programID account metas
435
+ programIds.forEach(programId => {
436
+ accountMetas.push({
437
+ pubkey: new PublicKey(programId),
438
+ isSigner: false,
439
+ isWritable: false,
440
+ });
441
+ });
442
+
443
+ // Cull duplicate account metas
444
+ const uniqueMetas: AccountMeta[] = [];
445
+ accountMetas.forEach(accountMeta => {
446
+ const pubkeyString = accountMeta.pubkey.toString();
447
+ const uniqueIndex = uniqueMetas.findIndex(x => {
448
+ return x.pubkey.toString() === pubkeyString;
449
+ });
450
+ if (uniqueIndex > -1) {
451
+ uniqueMetas[uniqueIndex].isWritable =
452
+ uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable;
453
+ uniqueMetas[uniqueIndex].isSigner =
454
+ uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner;
455
+ } else {
456
+ uniqueMetas.push(accountMeta);
457
+ }
458
+ });
459
+
460
+ // Sort. Prioritizing first by signer, then by writable
461
+ uniqueMetas.sort(function (x, y) {
462
+ if (x.isSigner !== y.isSigner) {
463
+ // Signers always come before non-signers
464
+ return x.isSigner ? -1 : 1;
465
+ }
466
+ if (x.isWritable !== y.isWritable) {
467
+ // Writable accounts always come before read-only accounts
468
+ return x.isWritable ? -1 : 1;
469
+ }
470
+ // Otherwise, sort by pubkey, stringwise.
471
+ const options = {
472
+ localeMatcher: 'best fit',
473
+ usage: 'sort',
474
+ sensitivity: 'variant',
475
+ ignorePunctuation: false,
476
+ numeric: false,
477
+ caseFirst: 'lower',
478
+ } as Intl.CollatorOptions;
479
+ return x.pubkey
480
+ .toBase58()
481
+ .localeCompare(y.pubkey.toBase58(), 'en', options);
482
+ });
483
+
484
+ // Move fee payer to the front
485
+ const feePayerIndex = uniqueMetas.findIndex(x => {
486
+ return x.pubkey.equals(feePayer);
487
+ });
488
+ if (feePayerIndex > -1) {
489
+ const [payerMeta] = uniqueMetas.splice(feePayerIndex, 1);
490
+ payerMeta.isSigner = true;
491
+ payerMeta.isWritable = true;
492
+ uniqueMetas.unshift(payerMeta);
493
+ } else {
494
+ uniqueMetas.unshift({
495
+ pubkey: feePayer,
496
+ isSigner: true,
497
+ isWritable: true,
498
+ });
499
+ }
500
+
501
+ // Disallow unknown signers
502
+ for (const signature of this.signatures) {
503
+ const uniqueIndex = uniqueMetas.findIndex(x => {
504
+ return x.pubkey.equals(signature.publicKey);
505
+ });
506
+ if (uniqueIndex > -1) {
507
+ if (!uniqueMetas[uniqueIndex].isSigner) {
508
+ uniqueMetas[uniqueIndex].isSigner = true;
509
+ console.warn(
510
+ 'Transaction references a signature that is unnecessary, ' +
511
+ 'only the fee payer and instruction signer accounts should sign a transaction. ' +
512
+ 'This behavior is deprecated and will throw an error in the next major version release.',
513
+ );
514
+ }
515
+ } else {
516
+ throw new Error(`unknown signer: ${signature.publicKey.toString()}`);
517
+ }
518
+ }
519
+
520
+ let numRequiredSignatures = 0;
521
+ let numReadonlySignedAccounts = 0;
522
+ let numReadonlyUnsignedAccounts = 0;
523
+
524
+ // Split out signing from non-signing keys and count header values
525
+ const signedKeys: string[] = [];
526
+ const unsignedKeys: string[] = [];
527
+ uniqueMetas.forEach(({pubkey, isSigner, isWritable}) => {
528
+ if (isSigner) {
529
+ signedKeys.push(pubkey.toString());
530
+ numRequiredSignatures += 1;
531
+ if (!isWritable) {
532
+ numReadonlySignedAccounts += 1;
533
+ }
534
+ } else {
535
+ unsignedKeys.push(pubkey.toString());
536
+ if (!isWritable) {
537
+ numReadonlyUnsignedAccounts += 1;
538
+ }
539
+ }
540
+ });
541
+
542
+ const accountKeys = signedKeys.concat(unsignedKeys);
543
+ const compiledInstructions: CompiledInstruction[] = instructions.map(
544
+ instruction => {
545
+ const {data, programId} = instruction;
546
+ return {
547
+ programIdIndex: accountKeys.indexOf(programId.toString()),
548
+ accounts: instruction.keys.map(meta =>
549
+ accountKeys.indexOf(meta.pubkey.toString()),
550
+ ),
551
+ data: bs58.encode(data),
552
+ };
553
+ },
554
+ );
555
+
556
+ compiledInstructions.forEach(instruction => {
557
+ invariant(instruction.programIdIndex >= 0);
558
+ instruction.accounts.forEach(keyIndex => invariant(keyIndex >= 0));
559
+ });
560
+
561
+ return new Message({
562
+ header: {
563
+ numRequiredSignatures,
564
+ numReadonlySignedAccounts,
565
+ numReadonlyUnsignedAccounts,
566
+ },
567
+ accountKeys,
568
+ recentBlockhash,
569
+ instructions: compiledInstructions,
570
+ });
571
+ }
572
+
573
+ /**
574
+ * @internal
575
+ */
576
+ _compile(): Message {
577
+ const message = this.compileMessage();
578
+ const signedKeys = message.accountKeys.slice(
579
+ 0,
580
+ message.header.numRequiredSignatures,
581
+ );
582
+
583
+ if (this.signatures.length === signedKeys.length) {
584
+ const valid = this.signatures.every((pair, index) => {
585
+ return signedKeys[index].equals(pair.publicKey);
586
+ });
587
+
588
+ if (valid) return message;
589
+ }
590
+
591
+ this.signatures = signedKeys.map(publicKey => ({
592
+ signature: null,
593
+ publicKey,
594
+ }));
595
+
596
+ return message;
597
+ }
598
+
599
+ /**
600
+ * Get a buffer of the Transaction data that need to be covered by signatures
601
+ */
602
+ serializeMessage(): Buffer {
603
+ return this._compile().serialize();
604
+ }
605
+
606
+ /**
607
+ * Get the estimated fee associated with a transaction
608
+ *
609
+ * @param {Connection} connection Connection to RPC Endpoint.
610
+ *
611
+ * @returns {Promise<number | null>} The estimated fee for the transaction
612
+ */
613
+ async getEstimatedFee(connection: Connection): Promise<number | null> {
614
+ return (await connection.getFeeForMessage(this.compileMessage())).value;
615
+ }
616
+
617
+ /**
618
+ * Specify the public keys which will be used to sign the Transaction.
619
+ * The first signer will be used as the transaction fee payer account.
620
+ *
621
+ * Signatures can be added with either `partialSign` or `addSignature`
622
+ *
623
+ * @deprecated Deprecated since v0.84.0. Only the fee payer needs to be
624
+ * specified and it can be set in the Transaction constructor or with the
625
+ * `feePayer` property.
626
+ */
627
+ setSigners(...signers: Array<PublicKey>) {
628
+ if (signers.length === 0) {
629
+ throw new Error('No signers');
630
+ }
631
+
632
+ const seen = new Set();
633
+ this.signatures = signers
634
+ .filter(publicKey => {
635
+ const key = publicKey.toString();
636
+ if (seen.has(key)) {
637
+ return false;
638
+ } else {
639
+ seen.add(key);
640
+ return true;
641
+ }
642
+ })
643
+ .map(publicKey => ({signature: null, publicKey}));
644
+ }
645
+
646
+ /**
647
+ * Sign the Transaction with the specified signers. Multiple signatures may
648
+ * be applied to a Transaction. The first signature is considered "primary"
649
+ * and is used identify and confirm transactions.
650
+ *
651
+ * If the Transaction `feePayer` is not set, the first signer will be used
652
+ * as the transaction fee payer account.
653
+ *
654
+ * Transaction fields should not be modified after the first call to `sign`,
655
+ * as doing so may invalidate the signature and cause the Transaction to be
656
+ * rejected.
657
+ *
658
+ * The Transaction must be assigned a valid `recentBlockhash` before invoking this method
659
+ *
660
+ * @param {Array<Signer>} signers Array of signers that will sign the transaction
661
+ */
662
+ sign(...signers: Array<Signer>) {
663
+ if (signers.length === 0) {
664
+ throw new Error('No signers');
665
+ }
666
+
667
+ // Dedupe signers
668
+ const seen = new Set();
669
+ const uniqueSigners = [];
670
+ for (const signer of signers) {
671
+ const key = signer.publicKey.toString();
672
+ if (seen.has(key)) {
673
+ continue;
674
+ } else {
675
+ seen.add(key);
676
+ uniqueSigners.push(signer);
677
+ }
678
+ }
679
+
680
+ this.signatures = uniqueSigners.map(signer => ({
681
+ signature: null,
682
+ publicKey: signer.publicKey,
683
+ }));
684
+
685
+ const message = this._compile();
686
+ this._partialSign(message, ...uniqueSigners);
687
+ }
688
+
689
+ /**
690
+ * Partially sign a transaction with the specified accounts. All accounts must
691
+ * correspond to either the fee payer or a signer account in the transaction
692
+ * instructions.
693
+ *
694
+ * All the caveats from the `sign` method apply to `partialSign`
695
+ *
696
+ * @param {Array<Signer>} signers Array of signers that will sign the transaction
697
+ */
698
+ partialSign(...signers: Array<Signer>) {
699
+ if (signers.length === 0) {
700
+ throw new Error('No signers');
701
+ }
702
+
703
+ // Dedupe signers
704
+ const seen = new Set();
705
+ const uniqueSigners = [];
706
+ for (const signer of signers) {
707
+ const key = signer.publicKey.toString();
708
+ if (seen.has(key)) {
709
+ continue;
710
+ } else {
711
+ seen.add(key);
712
+ uniqueSigners.push(signer);
713
+ }
714
+ }
715
+
716
+ const message = this._compile();
717
+ this._partialSign(message, ...uniqueSigners);
718
+ }
719
+
720
+ /**
721
+ * @internal
722
+ */
723
+ _partialSign(message: Message, ...signers: Array<Signer>) {
724
+ const signData = message.serialize();
725
+ signers.forEach(signer => {
726
+ const signature = sign(signData, signer.secretKey);
727
+ this._addSignature(signer.publicKey, toBuffer(signature));
728
+ });
729
+ }
730
+
731
+ /**
732
+ * Add an externally created signature to a transaction. The public key
733
+ * must correspond to either the fee payer or a signer account in the transaction
734
+ * instructions.
735
+ *
736
+ * @param {PublicKey} pubkey Public key that will be added to the transaction.
737
+ * @param {Buffer} signature An externally created signature to add to the transaction.
738
+ */
739
+ addSignature(pubkey: PublicKey, signature: Buffer) {
740
+ this._compile(); // Ensure signatures array is populated
741
+ this._addSignature(pubkey, signature);
742
+ }
743
+
744
+ /**
745
+ * @internal
746
+ */
747
+ _addSignature(pubkey: PublicKey, signature: Buffer) {
748
+ invariant(signature.length === 64);
749
+
750
+ const index = this.signatures.findIndex(sigpair =>
751
+ pubkey.equals(sigpair.publicKey),
752
+ );
753
+ if (index < 0) {
754
+ throw new Error(`unknown signer: ${pubkey.toString()}`);
755
+ }
756
+
757
+ this.signatures[index].signature = Buffer.from(signature);
758
+ }
759
+
760
+ /**
761
+ * Verify signatures of a Transaction
762
+ * Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one.
763
+ * If no boolean is provided, we expect a fully signed Transaction by default.
764
+ *
765
+ * @param {boolean} [requireAllSignatures=true] Require a fully signed Transaction
766
+ */
767
+ verifySignatures(requireAllSignatures: boolean = true): boolean {
768
+ const signatureErrors = this._getMessageSignednessErrors(
769
+ this.serializeMessage(),
770
+ requireAllSignatures,
771
+ );
772
+ return !signatureErrors;
773
+ }
774
+
775
+ /**
776
+ * @internal
777
+ */
778
+ _getMessageSignednessErrors(
779
+ message: Uint8Array,
780
+ requireAllSignatures: boolean,
781
+ ): MessageSignednessErrors | undefined {
782
+ const errors: MessageSignednessErrors = {};
783
+ for (const {signature, publicKey} of this.signatures) {
784
+ if (signature === null) {
785
+ if (requireAllSignatures) {
786
+ (errors.missing ||= []).push(publicKey);
787
+ }
788
+ } else {
789
+ if (!verify(signature, message, publicKey.toBytes())) {
790
+ (errors.invalid ||= []).push(publicKey);
791
+ }
792
+ }
793
+ }
794
+ return errors.invalid || errors.missing ? errors : undefined;
795
+ }
796
+
797
+ /**
798
+ * Serialize the Transaction in the wire format.
799
+ *
800
+ * @param {Buffer} [config] Config of transaction.
801
+ *
802
+ * @returns {Buffer} Signature of transaction in wire format.
803
+ */
804
+ serialize(config?: SerializeConfig): Buffer {
805
+ const {requireAllSignatures, verifySignatures} = Object.assign(
806
+ {requireAllSignatures: true, verifySignatures: true},
807
+ config,
808
+ );
809
+
810
+ const signData = this.serializeMessage();
811
+ if (verifySignatures) {
812
+ const sigErrors = this._getMessageSignednessErrors(
813
+ signData,
814
+ requireAllSignatures,
815
+ );
816
+ if (sigErrors) {
817
+ let errorMessage = 'Signature verification failed.';
818
+ if (sigErrors.invalid) {
819
+ errorMessage += `\nInvalid signature for public key${
820
+ sigErrors.invalid.length === 1 ? '' : '(s)'
821
+ } [\`${sigErrors.invalid.map(p => p.toBase58()).join('`, `')}\`].`;
822
+ }
823
+ if (sigErrors.missing) {
824
+ errorMessage += `\nMissing signature for public key${
825
+ sigErrors.missing.length === 1 ? '' : '(s)'
826
+ } [\`${sigErrors.missing.map(p => p.toBase58()).join('`, `')}\`].`;
827
+ }
828
+ throw new Error(errorMessage);
829
+ }
830
+ }
831
+
832
+ return this._serialize(signData);
833
+ }
834
+
835
+ /**
836
+ * @internal
837
+ */
838
+ _serialize(signData: Buffer): Buffer {
839
+ const {signatures} = this;
840
+ const signatureCount: number[] = [];
841
+ shortvec.encodeLength(signatureCount, signatures.length);
842
+ const transactionLength =
843
+ signatureCount.length + signatures.length * 64 + signData.length;
844
+ const wireTransaction = Buffer.alloc(transactionLength);
845
+ invariant(signatures.length < 256);
846
+ Buffer.from(signatureCount).copy(wireTransaction, 0);
847
+ signatures.forEach(({signature}, index) => {
848
+ if (signature !== null) {
849
+ invariant(signature.length === 64, `signature has invalid length`);
850
+ Buffer.from(signature).copy(
851
+ wireTransaction,
852
+ signatureCount.length + index * 64,
853
+ );
854
+ }
855
+ });
856
+ signData.copy(
857
+ wireTransaction,
858
+ signatureCount.length + signatures.length * 64,
859
+ );
860
+ invariant(
861
+ wireTransaction.length <= PACKET_DATA_SIZE,
862
+ `Transaction too large: ${wireTransaction.length} > ${PACKET_DATA_SIZE}`,
863
+ );
864
+ return wireTransaction;
865
+ }
866
+
867
+ /**
868
+ * Deprecated method
869
+ * @internal
870
+ */
871
+ get keys(): Array<PublicKey> {
872
+ invariant(this.instructions.length === 1);
873
+ return this.instructions[0].keys.map(keyObj => keyObj.pubkey);
874
+ }
875
+
876
+ /**
877
+ * Deprecated method
878
+ * @internal
879
+ */
880
+ get programId(): PublicKey {
881
+ invariant(this.instructions.length === 1);
882
+ return this.instructions[0].programId;
883
+ }
884
+
885
+ /**
886
+ * Deprecated method
887
+ * @internal
888
+ */
889
+ get data(): Buffer {
890
+ invariant(this.instructions.length === 1);
891
+ return this.instructions[0].data;
892
+ }
893
+
894
+ /**
895
+ * Parse a wire transaction into a Transaction object.
896
+ *
897
+ * @param {Buffer | Uint8Array | Array<number>} buffer Signature of wire Transaction
898
+ *
899
+ * @returns {Transaction} Transaction associated with the signature
900
+ */
901
+ static from(buffer: Buffer | Uint8Array | Array<number>): Transaction {
902
+ // Slice up wire data
903
+ let byteArray = [...buffer];
904
+
905
+ const signatureCount = shortvec.decodeLength(byteArray);
906
+ let signatures = [];
907
+ for (let i = 0; i < signatureCount; i++) {
908
+ const signature = guardedSplice(byteArray, 0, SIGNATURE_LENGTH_IN_BYTES);
909
+ signatures.push(bs58.encode(Buffer.from(signature)));
910
+ }
911
+
912
+ return Transaction.populate(Message.from(byteArray), signatures);
913
+ }
914
+
915
+ /**
916
+ * Populate Transaction object from message and signatures
917
+ *
918
+ * @param {Message} message Message of transaction
919
+ * @param {Array<string>} signatures List of signatures to assign to the transaction
920
+ *
921
+ * @returns {Transaction} The populated Transaction
922
+ */
923
+ static populate(
924
+ message: Message,
925
+ signatures: Array<string> = [],
926
+ ): Transaction {
927
+ const transaction = new Transaction();
928
+ transaction.recentBlockhash = message.recentBlockhash;
929
+ if (message.header.numRequiredSignatures > 0) {
930
+ transaction.feePayer = message.accountKeys[0];
931
+ }
932
+ signatures.forEach((signature, index) => {
933
+ const sigPubkeyPair = {
934
+ signature:
935
+ signature == bs58.encode(DEFAULT_SIGNATURE)
936
+ ? null
937
+ : bs58.decode(signature),
938
+ publicKey: message.accountKeys[index],
939
+ };
940
+ transaction.signatures.push(sigPubkeyPair);
941
+ });
942
+
943
+ message.instructions.forEach(instruction => {
944
+ const keys = instruction.accounts.map(account => {
945
+ const pubkey = message.accountKeys[account];
946
+ return {
947
+ pubkey,
948
+ isSigner:
949
+ transaction.signatures.some(
950
+ keyObj => keyObj.publicKey.toString() === pubkey.toString(),
951
+ ) || message.isAccountSigner(account),
952
+ isWritable: message.isAccountWritable(account),
953
+ };
954
+ });
955
+
956
+ transaction.instructions.push(
957
+ new TransactionInstruction({
958
+ keys,
959
+ programId: message.accountKeys[instruction.programIdIndex],
960
+ data: bs58.decode(instruction.data),
961
+ }),
962
+ );
963
+ });
964
+
965
+ transaction._message = message;
966
+ transaction._json = transaction.toJSON();
967
+
968
+ return transaction;
969
+ }
970
+ }