@solana/web3.js 1.57.0 → 1.58.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solana/web3.js",
3
- "version": "1.57.0",
3
+ "version": "1.58.0",
4
4
  "description": "Solana Javascript API",
5
5
  "keywords": [
6
6
  "api",
package/src/connection.ts CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  Transaction,
37
37
  TransactionStatus,
38
38
  TransactionVersion,
39
+ VersionedTransaction,
39
40
  } from './transaction';
40
41
  import {Message, MessageHeader, MessageV0, VersionedMessage} from './message';
41
42
  import {AddressLookupTableAccount} from './programs/address-lookup-table/state';
@@ -801,6 +802,22 @@ export type TransactionReturnData = {
801
802
  data: [string, TransactionReturnDataEncoding];
802
803
  };
803
804
 
805
+ export type SimulateTransactionConfig = {
806
+ /** Optional parameter used to enable signature verification before simulation */
807
+ sigVerify?: boolean;
808
+ /** Optional parameter used to replace the simulated transaction's recent blockhash with the latest blockhash */
809
+ replaceRecentBlockhash?: boolean;
810
+ /** Optional parameter used to set the commitment level when selecting the latest block */
811
+ commitment?: Commitment;
812
+ /** Optional parameter used to specify a list of account addresses to return post simulation state for */
813
+ accounts?: {
814
+ encoding: 'base64';
815
+ addresses: string[];
816
+ };
817
+ /** Optional parameter used to specify the minimum block slot that can be used for simulation */
818
+ minContextSlot?: number;
819
+ };
820
+
804
821
  export type SimulatedTransactionResponse = {
805
822
  err: TransactionError | string | null;
806
823
  logs: Array<string> | null;
@@ -4625,12 +4642,58 @@ export class Connection {
4625
4642
 
4626
4643
  /**
4627
4644
  * Simulate a transaction
4645
+ *
4646
+ * @deprecated Instead, call {@link simulateTransaction} with {@link
4647
+ * VersionedTransaction} and {@link SimulateTransactionConfig} parameters
4628
4648
  */
4629
- async simulateTransaction(
4649
+ simulateTransaction(
4630
4650
  transactionOrMessage: Transaction | Message,
4631
4651
  signers?: Array<Signer>,
4632
4652
  includeAccounts?: boolean | Array<PublicKey>,
4653
+ ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>>;
4654
+
4655
+ /**
4656
+ * Simulate a transaction
4657
+ */
4658
+ // eslint-disable-next-line no-dupe-class-members
4659
+ simulateTransaction(
4660
+ transaction: VersionedTransaction,
4661
+ config?: SimulateTransactionConfig,
4662
+ ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>>;
4663
+
4664
+ /**
4665
+ * Simulate a transaction
4666
+ */
4667
+ // eslint-disable-next-line no-dupe-class-members
4668
+ async simulateTransaction(
4669
+ transactionOrMessage: VersionedTransaction | Transaction | Message,
4670
+ configOrSigners?: SimulateTransactionConfig | Array<Signer>,
4671
+ includeAccounts?: boolean | Array<PublicKey>,
4633
4672
  ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>> {
4673
+ if ('message' in transactionOrMessage) {
4674
+ const versionedTx = transactionOrMessage;
4675
+ const wireTransaction = versionedTx.serialize();
4676
+ const encodedTransaction =
4677
+ Buffer.from(wireTransaction).toString('base64');
4678
+ if (Array.isArray(configOrSigners) || includeAccounts !== undefined) {
4679
+ throw new Error('Invalid arguments');
4680
+ }
4681
+
4682
+ const config: any = configOrSigners || {};
4683
+ config.encoding = 'base64';
4684
+ if (!('commitment' in config)) {
4685
+ config.commitment = this.commitment;
4686
+ }
4687
+
4688
+ const args = [encodedTransaction, config];
4689
+ const unsafeRes = await this._rpcRequest('simulateTransaction', args);
4690
+ const res = create(unsafeRes, SimulatedTransactionResponseStruct);
4691
+ if ('error' in res) {
4692
+ throw new Error('failed to simulate transaction: ' + res.error.message);
4693
+ }
4694
+ return res.result;
4695
+ }
4696
+
4634
4697
  let transaction;
4635
4698
  if (transactionOrMessage instanceof Transaction) {
4636
4699
  let originalTx: Transaction = transactionOrMessage;
@@ -4645,6 +4708,11 @@ export class Connection {
4645
4708
  transaction._message = transaction._json = undefined;
4646
4709
  }
4647
4710
 
4711
+ if (configOrSigners !== undefined && !Array.isArray(configOrSigners)) {
4712
+ throw new Error('Invalid arguments');
4713
+ }
4714
+
4715
+ const signers = configOrSigners;
4648
4716
  if (transaction.nonceInfo && signers) {
4649
4717
  transaction.sign(...signers);
4650
4718
  } else {
@@ -4731,12 +4799,48 @@ export class Connection {
4731
4799
 
4732
4800
  /**
4733
4801
  * Sign and send a transaction
4802
+ *
4803
+ * @deprecated Instead, call {@link sendTransaction} with a {@link
4804
+ * VersionedTransaction}
4734
4805
  */
4735
- async sendTransaction(
4806
+ sendTransaction(
4736
4807
  transaction: Transaction,
4737
4808
  signers: Array<Signer>,
4738
4809
  options?: SendOptions,
4810
+ ): Promise<TransactionSignature>;
4811
+
4812
+ /**
4813
+ * Send a signed transaction
4814
+ */
4815
+ // eslint-disable-next-line no-dupe-class-members
4816
+ sendTransaction(
4817
+ transaction: VersionedTransaction,
4818
+ options?: SendOptions,
4819
+ ): Promise<TransactionSignature>;
4820
+
4821
+ /**
4822
+ * Sign and send a transaction
4823
+ */
4824
+ // eslint-disable-next-line no-dupe-class-members
4825
+ async sendTransaction(
4826
+ transaction: VersionedTransaction | Transaction,
4827
+ signersOrOptions?: Array<Signer> | SendOptions,
4828
+ options?: SendOptions,
4739
4829
  ): Promise<TransactionSignature> {
4830
+ if ('message' in transaction) {
4831
+ if (signersOrOptions && Array.isArray(signersOrOptions)) {
4832
+ throw new Error('Invalid arguments');
4833
+ }
4834
+
4835
+ const wireTransaction = transaction.serialize();
4836
+ return await this.sendRawTransaction(wireTransaction, options);
4837
+ }
4838
+
4839
+ if (signersOrOptions === undefined || !Array.isArray(signersOrOptions)) {
4840
+ throw new Error('Invalid arguments');
4841
+ }
4842
+
4843
+ const signers = signersOrOptions;
4740
4844
  if (transaction.nonceInfo) {
4741
4845
  transaction.sign(...signers);
4742
4846
  } else {
@@ -13,6 +13,9 @@ import {
13
13
  MessageAddressTableLookup,
14
14
  MessageCompiledInstruction,
15
15
  } from './index';
16
+ import {TransactionInstruction} from '../transaction';
17
+ import {CompiledKeys} from './compiled-keys';
18
+ import {MessageAccountKeys} from './account-keys';
16
19
 
17
20
  /**
18
21
  * An instruction to execute by a program
@@ -37,13 +40,19 @@ export type MessageArgs = {
37
40
  /** The message header, identifying signed and read-only `accountKeys` */
38
41
  header: MessageHeader;
39
42
  /** All the account keys used by this transaction */
40
- accountKeys: string[];
43
+ accountKeys: string[] | PublicKey[];
41
44
  /** The hash of a recent ledger block */
42
45
  recentBlockhash: Blockhash;
43
46
  /** Instructions that will be executed in sequence and committed in one atomic transaction if all succeed. */
44
47
  instructions: CompiledInstruction[];
45
48
  };
46
49
 
50
+ export type CompileLegacyArgs = {
51
+ payerKey: PublicKey;
52
+ instructions: Array<TransactionInstruction>;
53
+ recentBlockhash: Blockhash;
54
+ };
55
+
47
56
  /**
48
57
  * List of instructions to be processed atomically
49
58
  */
@@ -93,6 +102,29 @@ export class Message {
93
102
  return [];
94
103
  }
95
104
 
105
+ getAccountKeys(): MessageAccountKeys {
106
+ return new MessageAccountKeys(this.staticAccountKeys);
107
+ }
108
+
109
+ static compile(args: CompileLegacyArgs): Message {
110
+ const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);
111
+ const [header, staticAccountKeys] = compiledKeys.getMessageComponents();
112
+ const accountKeys = new MessageAccountKeys(staticAccountKeys);
113
+ const instructions = accountKeys.compileInstructions(args.instructions).map(
114
+ (ix: MessageCompiledInstruction): CompiledInstruction => ({
115
+ programIdIndex: ix.programIdIndex,
116
+ accounts: ix.accountKeyIndexes,
117
+ data: bs58.encode(ix.data),
118
+ }),
119
+ );
120
+ return new Message({
121
+ header,
122
+ accountKeys: staticAccountKeys,
123
+ recentBlockhash: args.recentBlockhash,
124
+ instructions,
125
+ });
126
+ }
127
+
96
128
  isAccountSigner(index: number): boolean {
97
129
  return index < this.header.numRequiredSignatures;
98
130
  }
@@ -250,7 +282,7 @@ export class Message {
250
282
  for (let i = 0; i < accountCount; i++) {
251
283
  const account = byteArray.slice(0, PUBLIC_KEY_LENGTH);
252
284
  byteArray = byteArray.slice(PUBLIC_KEY_LENGTH);
253
- accountKeys.push(bs58.encode(Buffer.from(account)));
285
+ accountKeys.push(new PublicKey(Buffer.from(account)));
254
286
  }
255
287
 
256
288
  const recentBlockhash = byteArray.slice(0, PUBLIC_KEY_LENGTH);
package/src/message/v0.ts CHANGED
@@ -40,6 +40,14 @@ export type CompileV0Args = {
40
40
  addressLookupTableAccounts?: Array<AddressLookupTableAccount>;
41
41
  };
42
42
 
43
+ export type GetAccountKeysArgs =
44
+ | {
45
+ accountKeysFromLookups: AccountKeysFromLookups;
46
+ }
47
+ | {
48
+ addressLookupTableAccounts: AddressLookupTableAccount[];
49
+ };
50
+
43
51
  export class MessageV0 {
44
52
  header: MessageHeader;
45
53
  staticAccountKeys: Array<PublicKey>;
@@ -59,6 +67,88 @@ export class MessageV0 {
59
67
  return 0;
60
68
  }
61
69
 
70
+ get numAccountKeysFromLookups(): number {
71
+ let count = 0;
72
+ for (const lookup of this.addressTableLookups) {
73
+ count += lookup.readonlyIndexes.length + lookup.writableIndexes.length;
74
+ }
75
+ return count;
76
+ }
77
+
78
+ getAccountKeys(args?: GetAccountKeysArgs): MessageAccountKeys {
79
+ let accountKeysFromLookups: AccountKeysFromLookups | undefined;
80
+ if (args && 'accountKeysFromLookups' in args) {
81
+ if (
82
+ this.numAccountKeysFromLookups !=
83
+ args.accountKeysFromLookups.writable.length +
84
+ args.accountKeysFromLookups.readonly.length
85
+ ) {
86
+ throw new Error(
87
+ 'Failed to get account keys because of a mismatch in the number of account keys from lookups',
88
+ );
89
+ }
90
+ accountKeysFromLookups = args.accountKeysFromLookups;
91
+ } else if (args && 'addressLookupTableAccounts' in args) {
92
+ accountKeysFromLookups = this.resolveAddressTableLookups(
93
+ args.addressLookupTableAccounts,
94
+ );
95
+ } else if (this.addressTableLookups.length > 0) {
96
+ throw new Error(
97
+ 'Failed to get account keys because address table lookups were not resolved',
98
+ );
99
+ }
100
+ return new MessageAccountKeys(
101
+ this.staticAccountKeys,
102
+ accountKeysFromLookups,
103
+ );
104
+ }
105
+
106
+ resolveAddressTableLookups(
107
+ addressLookupTableAccounts: AddressLookupTableAccount[],
108
+ ): AccountKeysFromLookups {
109
+ const accountKeysFromLookups: AccountKeysFromLookups = {
110
+ writable: [],
111
+ readonly: [],
112
+ };
113
+
114
+ for (const tableLookup of this.addressTableLookups) {
115
+ const tableAccount = addressLookupTableAccounts.find(account =>
116
+ account.key.equals(tableLookup.accountKey),
117
+ );
118
+ if (!tableAccount) {
119
+ throw new Error(
120
+ `Failed to find address lookup table account for table key ${tableLookup.accountKey.toBase58()}`,
121
+ );
122
+ }
123
+
124
+ for (const index of tableLookup.writableIndexes) {
125
+ if (index < tableAccount.state.addresses.length) {
126
+ accountKeysFromLookups.writable.push(
127
+ tableAccount.state.addresses[index],
128
+ );
129
+ } else {
130
+ throw new Error(
131
+ `Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`,
132
+ );
133
+ }
134
+ }
135
+
136
+ for (const index of tableLookup.readonlyIndexes) {
137
+ if (index < tableAccount.state.addresses.length) {
138
+ accountKeysFromLookups.readonly.push(
139
+ tableAccount.state.addresses[index],
140
+ );
141
+ } else {
142
+ throw new Error(
143
+ `Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`,
144
+ );
145
+ }
146
+ }
147
+ }
148
+
149
+ return accountKeysFromLookups;
150
+ }
151
+
62
152
  static compile(args: CompileV0Args): MessageV0 {
63
153
  const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);
64
154
 
@@ -1,4 +1,5 @@
1
1
  export * from './constants';
2
2
  export * from './expiry-custom-errors';
3
3
  export * from './legacy';
4
+ export * from './message';
4
5
  export * from './versioned';
@@ -0,0 +1,147 @@
1
+ import {
2
+ AccountKeysFromLookups,
3
+ MessageAccountKeys,
4
+ } from '../message/account-keys';
5
+ import assert from '../utils/assert';
6
+ import {toBuffer} from '../utils/to-buffer';
7
+ import {Blockhash} from '../blockhash';
8
+ import {Message, MessageV0, VersionedMessage} from '../message';
9
+ import {AddressLookupTableAccount} from '../programs';
10
+ import {AccountMeta, TransactionInstruction} from './legacy';
11
+
12
+ export type TransactionMessageArgs = {
13
+ accountKeys: MessageAccountKeys;
14
+ instructions: Array<TransactionInstruction>;
15
+ recentBlockhash: Blockhash;
16
+ };
17
+
18
+ export type DecompileArgs =
19
+ | {
20
+ accountKeysFromLookups: AccountKeysFromLookups;
21
+ }
22
+ | {
23
+ addressLookupTableAccounts: AddressLookupTableAccount[];
24
+ };
25
+
26
+ export class TransactionMessage {
27
+ accountKeys: MessageAccountKeys;
28
+ instructions: Array<TransactionInstruction>;
29
+ recentBlockhash: Blockhash;
30
+
31
+ constructor(args: TransactionMessageArgs) {
32
+ this.accountKeys = args.accountKeys;
33
+ this.instructions = args.instructions;
34
+ this.recentBlockhash = args.recentBlockhash;
35
+ }
36
+
37
+ static decompile(
38
+ message: VersionedMessage,
39
+ args?: DecompileArgs,
40
+ ): TransactionMessage {
41
+ const {header, compiledInstructions, recentBlockhash} = message;
42
+
43
+ const {
44
+ numRequiredSignatures,
45
+ numReadonlySignedAccounts,
46
+ numReadonlyUnsignedAccounts,
47
+ } = header;
48
+
49
+ const numWritableSignedAccounts =
50
+ numRequiredSignatures - numReadonlySignedAccounts;
51
+ assert(numWritableSignedAccounts > 0, 'Message header is invalid');
52
+
53
+ const numWritableUnsignedAccounts =
54
+ message.staticAccountKeys.length - numReadonlyUnsignedAccounts;
55
+ assert(numWritableUnsignedAccounts >= 0, 'Message header is invalid');
56
+
57
+ const accountKeys = message.getAccountKeys(args);
58
+ const instructions: TransactionInstruction[] = [];
59
+ for (const compiledIx of compiledInstructions) {
60
+ const keys: AccountMeta[] = [];
61
+
62
+ for (const keyIndex of compiledIx.accountKeyIndexes) {
63
+ const pubkey = accountKeys.get(keyIndex);
64
+ if (pubkey === undefined) {
65
+ throw new Error(
66
+ `Failed to find key for account key index ${keyIndex}`,
67
+ );
68
+ }
69
+
70
+ const isSigner = keyIndex < numRequiredSignatures;
71
+
72
+ let isWritable;
73
+ if (isSigner) {
74
+ isWritable = keyIndex < numWritableSignedAccounts;
75
+ } else if (keyIndex < accountKeys.staticAccountKeys.length) {
76
+ isWritable =
77
+ keyIndex - numRequiredSignatures < numWritableUnsignedAccounts;
78
+ } else {
79
+ isWritable =
80
+ keyIndex - accountKeys.staticAccountKeys.length <
81
+ // accountKeysFromLookups cannot be undefined because we already found a pubkey for this index above
82
+ accountKeys.accountKeysFromLookups!.writable.length;
83
+ }
84
+
85
+ keys.push({
86
+ pubkey,
87
+ isSigner: keyIndex < header.numRequiredSignatures,
88
+ isWritable,
89
+ });
90
+ }
91
+
92
+ const programId = accountKeys.get(compiledIx.programIdIndex);
93
+ if (programId === undefined) {
94
+ throw new Error(
95
+ `Failed to find program id for program id index ${compiledIx.programIdIndex}`,
96
+ );
97
+ }
98
+
99
+ instructions.push(
100
+ new TransactionInstruction({
101
+ programId,
102
+ data: toBuffer(compiledIx.data),
103
+ keys,
104
+ }),
105
+ );
106
+ }
107
+
108
+ return new TransactionMessage({
109
+ accountKeys,
110
+ instructions,
111
+ recentBlockhash,
112
+ });
113
+ }
114
+
115
+ compileToLegacyMessage(): Message {
116
+ const payerKey = this.accountKeys.get(0);
117
+ if (payerKey === undefined) {
118
+ throw new Error(
119
+ 'Failed to compile message because no account keys were found',
120
+ );
121
+ }
122
+
123
+ return Message.compile({
124
+ payerKey,
125
+ recentBlockhash: this.recentBlockhash,
126
+ instructions: this.instructions,
127
+ });
128
+ }
129
+
130
+ compileToV0Message(
131
+ addressLookupTableAccounts?: AddressLookupTableAccount[],
132
+ ): MessageV0 {
133
+ const payerKey = this.accountKeys.get(0);
134
+ if (payerKey === undefined) {
135
+ throw new Error(
136
+ 'Failed to compile message because no account keys were found',
137
+ );
138
+ }
139
+
140
+ return MessageV0.compile({
141
+ payerKey,
142
+ recentBlockhash: this.recentBlockhash,
143
+ instructions: this.instructions,
144
+ addressLookupTableAccounts,
145
+ });
146
+ }
147
+ }