@solana/web3.js 1.57.0 → 1.59.1

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.59.1",
4
4
  "description": "Solana Javascript API",
5
5
  "keywords": [
6
6
  "api",
@@ -69,7 +69,6 @@
69
69
  "buffer": "6.0.1",
70
70
  "fast-stable-stringify": "^1.0.0",
71
71
  "jayson": "^3.4.4",
72
- "js-sha3": "^0.8.0",
73
72
  "node-fetch": "2",
74
73
  "rpc-websockets": "^7.5.0",
75
74
  "superstruct": "^0.14.2"
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 {
package/src/layout.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import {Buffer} from 'buffer';
2
2
  import * as BufferLayout from '@solana/buffer-layout';
3
3
 
4
+ import {VoteAuthorizeWithSeedArgs} from './programs/vote';
5
+
4
6
  /**
5
7
  * Layout for a public key
6
8
  */
@@ -141,6 +143,23 @@ export const voteInit = (property: string = 'voteInit') => {
141
143
  );
142
144
  };
143
145
 
146
+ /**
147
+ * Layout for a VoteAuthorizeWithSeedArgs object
148
+ */
149
+ export const voteAuthorizeWithSeedArgs = (
150
+ property: string = 'voteAuthorizeWithSeedArgs',
151
+ ) => {
152
+ return BufferLayout.struct<VoteAuthorizeWithSeedArgs>(
153
+ [
154
+ BufferLayout.u32('voteAuthorizationType'),
155
+ publicKey('currentAuthorityDerivedKeyOwnerPubkey'),
156
+ rustString('currentAuthorityDerivedKeySeed'),
157
+ publicKey('newAuthorized'),
158
+ ],
159
+ property,
160
+ );
161
+ };
162
+
144
163
  export function getAlloc(type: any, fields: any): number {
145
164
  const getItemAlloc = (item: any): number => {
146
165
  if (item.span >= 0) {
@@ -152,6 +171,9 @@ export function getAlloc(type: any, fields: any): number {
152
171
  if (Array.isArray(field)) {
153
172
  return field.length * getItemAlloc(item.elementLayout);
154
173
  }
174
+ } else if ('fields' in item) {
175
+ // This is a `Structure` whose size needs to be recursively measured.
176
+ return getAlloc({layout: item}, fields[item.property]);
155
177
  }
156
178
  // Couldn't determine allocated size of layout
157
179
  return 0;
@@ -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,6 +1,6 @@
1
1
  import {Buffer} from 'buffer';
2
2
  import * as BufferLayout from '@solana/buffer-layout';
3
- import sha3 from 'js-sha3';
3
+ import {keccak_256} from '@noble/hashes/sha3';
4
4
 
5
5
  import {PublicKey} from '../publickey';
6
6
  import {TransactionInstruction} from '../transaction';
@@ -98,9 +98,9 @@ export class Secp256k1Program {
98
98
  );
99
99
 
100
100
  try {
101
- return Buffer.from(
102
- sha3.keccak_256.update(toBuffer(publicKey)).digest(),
103
- ).slice(-ETHEREUM_ADDRESS_BYTES);
101
+ return Buffer.from(keccak_256(toBuffer(publicKey))).slice(
102
+ -ETHEREUM_ADDRESS_BYTES,
103
+ );
104
104
  } catch (error) {
105
105
  throw new Error(`Error constructing Ethereum address: ${error}`);
106
106
  }
@@ -211,9 +211,7 @@ export class Secp256k1Program {
211
211
  privateKey,
212
212
  false /* isCompressed */,
213
213
  ).slice(1); // throw away leading byte
214
- const messageHash = Buffer.from(
215
- sha3.keccak_256.update(toBuffer(message)).digest(),
216
- );
214
+ const messageHash = Buffer.from(keccak_256(toBuffer(message)));
217
215
  const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);
218
216
 
219
217
  return this.createInstructionWithPublicKey({
@@ -65,6 +65,18 @@ export type AuthorizeVoteParams = {
65
65
  voteAuthorizationType: VoteAuthorizationType;
66
66
  };
67
67
 
68
+ /**
69
+ * AuthorizeWithSeed instruction params
70
+ */
71
+ export type AuthorizeVoteWithSeedParams = {
72
+ currentAuthorityDerivedKeyBasePubkey: PublicKey;
73
+ currentAuthorityDerivedKeyOwnerPubkey: PublicKey;
74
+ currentAuthorityDerivedKeySeed: string;
75
+ newAuthorizedPubkey: PublicKey;
76
+ voteAuthorizationType: VoteAuthorizationType;
77
+ votePubkey: PublicKey;
78
+ };
79
+
68
80
  /**
69
81
  * Withdraw from vote account transaction params
70
82
  */
@@ -160,6 +172,41 @@ export class VoteInstruction {
160
172
  };
161
173
  }
162
174
 
175
+ /**
176
+ * Decode an authorize instruction and retrieve the instruction params.
177
+ */
178
+ static decodeAuthorizeWithSeed(
179
+ instruction: TransactionInstruction,
180
+ ): AuthorizeVoteWithSeedParams {
181
+ this.checkProgramId(instruction.programId);
182
+ this.checkKeyLength(instruction.keys, 3);
183
+
184
+ const {
185
+ voteAuthorizeWithSeedArgs: {
186
+ currentAuthorityDerivedKeyOwnerPubkey,
187
+ currentAuthorityDerivedKeySeed,
188
+ newAuthorized,
189
+ voteAuthorizationType,
190
+ },
191
+ } = decodeData(
192
+ VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,
193
+ instruction.data,
194
+ );
195
+
196
+ return {
197
+ currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey,
198
+ currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(
199
+ currentAuthorityDerivedKeyOwnerPubkey,
200
+ ),
201
+ currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,
202
+ newAuthorizedPubkey: new PublicKey(newAuthorized),
203
+ voteAuthorizationType: {
204
+ index: voteAuthorizationType,
205
+ },
206
+ votePubkey: instruction.keys[0].pubkey,
207
+ };
208
+ }
209
+
163
210
  /**
164
211
  * Decode a withdraw instruction and retrieve the instruction params.
165
212
  */
@@ -211,13 +258,23 @@ export type VoteInstructionType =
211
258
  // It would be preferable for this type to be `keyof VoteInstructionInputData`
212
259
  // but Typedoc does not transpile `keyof` expressions.
213
260
  // See https://github.com/TypeStrong/typedoc/issues/1894
214
- 'Authorize' | 'InitializeAccount' | 'Withdraw';
215
-
261
+ 'Authorize' | 'AuthorizeWithSeed' | 'InitializeAccount' | 'Withdraw';
262
+
263
+ /** @internal */
264
+ export type VoteAuthorizeWithSeedArgs = Readonly<{
265
+ currentAuthorityDerivedKeyOwnerPubkey: Uint8Array;
266
+ currentAuthorityDerivedKeySeed: string;
267
+ newAuthorized: Uint8Array;
268
+ voteAuthorizationType: number;
269
+ }>;
216
270
  type VoteInstructionInputData = {
217
271
  Authorize: IInstructionInputData & {
218
272
  newAuthorized: Uint8Array;
219
273
  voteAuthorizationType: number;
220
274
  };
275
+ AuthorizeWithSeed: IInstructionInputData & {
276
+ voteAuthorizeWithSeedArgs: VoteAuthorizeWithSeedArgs;
277
+ };
221
278
  InitializeAccount: IInstructionInputData & {
222
279
  voteInit: Readonly<{
223
280
  authorizedVoter: Uint8Array;
@@ -258,6 +315,13 @@ const VOTE_INSTRUCTION_LAYOUTS = Object.freeze<{
258
315
  BufferLayout.ns64('lamports'),
259
316
  ]),
260
317
  },
318
+ AuthorizeWithSeed: {
319
+ index: 10,
320
+ layout: BufferLayout.struct<VoteInstructionInputData['AuthorizeWithSeed']>([
321
+ BufferLayout.u32('instruction'),
322
+ Layout.voteAuthorizeWithSeedArgs(),
323
+ ]),
324
+ },
261
325
  });
262
326
 
263
327
  /**
@@ -390,6 +454,49 @@ export class VoteProgram {
390
454
  });
391
455
  }
392
456
 
457
+ /**
458
+ * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account
459
+ * where the current Voter or Withdrawer authority is a derived key.
460
+ */
461
+ static authorizeWithSeed(params: AuthorizeVoteWithSeedParams): Transaction {
462
+ const {
463
+ currentAuthorityDerivedKeyBasePubkey,
464
+ currentAuthorityDerivedKeyOwnerPubkey,
465
+ currentAuthorityDerivedKeySeed,
466
+ newAuthorizedPubkey,
467
+ voteAuthorizationType,
468
+ votePubkey,
469
+ } = params;
470
+
471
+ const type = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;
472
+ const data = encodeData(type, {
473
+ voteAuthorizeWithSeedArgs: {
474
+ currentAuthorityDerivedKeyOwnerPubkey: toBuffer(
475
+ currentAuthorityDerivedKeyOwnerPubkey.toBuffer(),
476
+ ),
477
+ currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,
478
+ newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),
479
+ voteAuthorizationType: voteAuthorizationType.index,
480
+ },
481
+ });
482
+
483
+ const keys = [
484
+ {pubkey: votePubkey, isSigner: false, isWritable: true},
485
+ {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},
486
+ {
487
+ pubkey: currentAuthorityDerivedKeyBasePubkey,
488
+ isSigner: true,
489
+ isWritable: false,
490
+ },
491
+ ];
492
+
493
+ return new Transaction().add({
494
+ keys,
495
+ programId: this.programId,
496
+ data,
497
+ });
498
+ }
499
+
393
500
  /**
394
501
  * Generate a transaction to withdraw from a Vote account.
395
502
  */
@@ -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';