@solana/web3.js 1.24.2 → 1.28.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/lib/index.d.ts CHANGED
@@ -18,6 +18,9 @@ declare module '@solana/web3.js' {
18
18
  * Maximum length of derived pubkey seed
19
19
  */
20
20
  export const MAX_SEED_LENGTH = 32;
21
+ /**
22
+ * Value to be converted into public key
23
+ */
21
24
  export type PublicKeyInitData =
22
25
  | number
23
26
  | string
@@ -25,6 +28,9 @@ declare module '@solana/web3.js' {
25
28
  | Uint8Array
26
29
  | Array<number>
27
30
  | PublicKeyData;
31
+ /**
32
+ * JSON object representation of PublicKey class
33
+ */
28
34
  export type PublicKeyData = {};
29
35
  /**
30
36
  * A public key
@@ -296,8 +302,13 @@ declare module '@solana/web3.js' {
296
302
  accountKeys: PublicKey[];
297
303
  recentBlockhash: Blockhash;
298
304
  instructions: CompiledInstruction[];
305
+ private indexToProgramIds;
299
306
  constructor(args: MessageArgs);
307
+ isAccountSigner(index: number): boolean;
300
308
  isAccountWritable(index: number): boolean;
309
+ isProgramId(index: number): boolean;
310
+ programIds(): PublicKey[];
311
+ nonProgramIds(): PublicKey[];
301
312
  serialize(): Buffer;
302
313
  /**
303
314
  * Decode a compiled message into a Message object.
@@ -499,7 +510,7 @@ declare module '@solana/web3.js' {
499
510
  /**
500
511
  * Populate Transaction object from message and signatures
501
512
  */
502
- static populate(message: Message, signatures: Array<string>): Transaction;
513
+ static populate(message: Message, signatures?: Array<string>): Transaction;
503
514
  }
504
515
 
505
516
  export type TokenAccountsFilter =
@@ -714,9 +725,23 @@ declare module '@solana/web3.js' {
714
725
  'solana-core': string;
715
726
  'feature-set'?: number;
716
727
  };
728
+ export type SimulatedTransactionAccountInfo = {
729
+ /** `true` if this account's data contains a loaded program */
730
+ executable: boolean;
731
+ /** Identifier of the program that owns the account */
732
+ owner: string;
733
+ /** Number of lamports assigned to the account */
734
+ lamports: number;
735
+ /** Optional data assigned to the account */
736
+ data: string[];
737
+ /** Optional rent epoch info for account */
738
+ rentEpoch?: number;
739
+ };
717
740
  export type SimulatedTransactionResponse = {
718
741
  err: TransactionError | string | null;
719
742
  logs: Array<string> | null;
743
+ accounts?: SimulatedTransactionAccountInfo[] | null;
744
+ unitsConsumed?: number;
720
745
  };
721
746
  export type ParsedInnerInstruction = {
722
747
  index: number;
@@ -1166,6 +1191,8 @@ declare module '@solana/web3.js' {
1166
1191
  lamports: number;
1167
1192
  /** Optional data assigned to the account */
1168
1193
  data: T;
1194
+ /** Optional rent epoch infor for account */
1195
+ rentEpoch?: number;
1169
1196
  };
1170
1197
  /**
1171
1198
  * Account information identified by pubkey
@@ -1328,6 +1355,8 @@ declare module '@solana/web3.js' {
1328
1355
  fetchMiddleware?: FetchMiddleware;
1329
1356
  /** Optional Disable retring calls when server responds with HTTP 429 (Too Many Requests) */
1330
1357
  disableRetryOnRateLimit?: boolean;
1358
+ /** time to allow for the server to initially process a transaction (in milliseconds) */
1359
+ confirmTransactionInitialTimeout?: number;
1331
1360
  };
1332
1361
  /**
1333
1362
  * A connection to a fullnode JSON RPC endpoint
@@ -1624,6 +1653,10 @@ declare module '@solana/web3.js' {
1624
1653
  * Fetch the node version
1625
1654
  */
1626
1655
  getVersion(): Promise<Version>;
1656
+ /**
1657
+ * Fetch the genesis hash
1658
+ */
1659
+ getGenesisHash(): Promise<string>;
1627
1660
  /**
1628
1661
  * Fetch a processed block from the cluster.
1629
1662
  */
@@ -1757,8 +1790,9 @@ declare module '@solana/web3.js' {
1757
1790
  * Simulate a transaction
1758
1791
  */
1759
1792
  simulateTransaction(
1760
- transaction: Transaction,
1793
+ transactionOrMessage: Transaction | Message,
1761
1794
  signers?: Array<Signer>,
1795
+ includeAccounts?: boolean | Array<PublicKey>,
1762
1796
  ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>>;
1763
1797
  /**
1764
1798
  * Sign and send a transaction
@@ -1952,6 +1986,45 @@ declare module '@solana/web3.js' {
1952
1986
  ): Promise<boolean>;
1953
1987
  }
1954
1988
 
1989
+ /**
1990
+ * Params for creating an ed25519 instruction using a public key
1991
+ */
1992
+ export type CreateEd25519InstructionWithPublicKeyParams = {
1993
+ publicKey: Uint8Array;
1994
+ message: Uint8Array;
1995
+ signature: Uint8Array;
1996
+ instructionIndex?: number;
1997
+ };
1998
+ /**
1999
+ * Params for creating an ed25519 instruction using a private key
2000
+ */
2001
+ export type CreateEd25519InstructionWithPrivateKeyParams = {
2002
+ privateKey: Uint8Array;
2003
+ message: Uint8Array;
2004
+ instructionIndex?: number;
2005
+ };
2006
+ export class Ed25519Program {
2007
+ /**
2008
+ * Public key that identifies the ed25519 program
2009
+ */
2010
+ static programId: PublicKey;
2011
+ /**
2012
+ * Create an ed25519 instruction with a public key and signature. The
2013
+ * public key must be a buffer that is 32 bytes long, and the signature
2014
+ * must be a buffer of 64 bytes.
2015
+ */
2016
+ static createInstructionWithPublicKey(
2017
+ params: CreateEd25519InstructionWithPublicKeyParams,
2018
+ ): TransactionInstruction;
2019
+ /**
2020
+ * Create an ed25519 instruction with a private key. The private key
2021
+ * must be a buffer that is 64 bytes long.
2022
+ */
2023
+ static createInstructionWithPrivateKey(
2024
+ params: CreateEd25519InstructionWithPrivateKeyParams,
2025
+ ): TransactionInstruction;
2026
+ }
2027
+
1955
2028
  /**
1956
2029
  * Program loader interface
1957
2030
  */
package/lib/index.esm.js CHANGED
@@ -7,7 +7,7 @@ import bs58 from 'bs58';
7
7
  import { sha256 } from 'crypto-hash';
8
8
  import { serialize, deserialize, deserializeUnchecked } from 'borsh';
9
9
  import * as BufferLayout from '@solana/buffer-layout';
10
- import fetch from 'node-fetch';
10
+ import fetch from 'cross-fetch';
11
11
  import { coerce, instance, string, tuple, literal, unknown, union, type, optional, any, number, array, nullable, create, boolean, record, assert as assert$1 } from 'superstruct';
12
12
  import { Client } from 'rpc-websockets';
13
13
  import RpcClient from 'jayson/lib/client/browser';
@@ -69,6 +69,9 @@ const SOLANA_SCHEMA = new Map();
69
69
  */
70
70
 
71
71
  const MAX_SEED_LENGTH = 32;
72
+ /**
73
+ * Value to be converted into public key
74
+ */
72
75
 
73
76
  function isPublicKeyData(value) {
74
77
  return value._bn !== undefined;
@@ -458,16 +461,35 @@ class Message {
458
461
 
459
462
  _defineProperty(this, "instructions", void 0);
460
463
 
464
+ _defineProperty(this, "indexToProgramIds", new Map());
465
+
461
466
  this.header = args.header;
462
467
  this.accountKeys = args.accountKeys.map(account => new PublicKey(account));
463
468
  this.recentBlockhash = args.recentBlockhash;
464
469
  this.instructions = args.instructions;
470
+ this.instructions.forEach(ix => this.indexToProgramIds.set(ix.programIdIndex, this.accountKeys[ix.programIdIndex]));
471
+ }
472
+
473
+ isAccountSigner(index) {
474
+ return index < this.header.numRequiredSignatures;
465
475
  }
466
476
 
467
477
  isAccountWritable(index) {
468
478
  return index < this.header.numRequiredSignatures - this.header.numReadonlySignedAccounts || index >= this.header.numRequiredSignatures && index < this.accountKeys.length - this.header.numReadonlyUnsignedAccounts;
469
479
  }
470
480
 
481
+ isProgramId(index) {
482
+ return this.indexToProgramIds.has(index);
483
+ }
484
+
485
+ programIds() {
486
+ return [...this.indexToProgramIds.values()];
487
+ }
488
+
489
+ nonProgramIds() {
490
+ return this.accountKeys.filter((_, index) => !this.isProgramId(index));
491
+ }
492
+
471
493
  serialize() {
472
494
  const numKeys = this.accountKeys.length;
473
495
  let keyCount = [];
@@ -1182,7 +1204,7 @@ class Transaction {
1182
1204
  */
1183
1205
 
1184
1206
 
1185
- static populate(message, signatures) {
1207
+ static populate(message, signatures = []) {
1186
1208
  const transaction = new Transaction();
1187
1209
  transaction.recentBlockhash = message.recentBlockhash;
1188
1210
 
@@ -1202,7 +1224,7 @@ class Transaction {
1202
1224
  const pubkey = message.accountKeys[account];
1203
1225
  return {
1204
1226
  pubkey,
1205
- isSigner: transaction.signatures.some(keyObj => keyObj.publicKey.toString() === pubkey.toString()),
1227
+ isSigner: transaction.signatures.some(keyObj => keyObj.publicKey.toString() === pubkey.toString()) || message.isAccountSigner(account),
1206
1228
  isWritable: message.isAccountWritable(account)
1207
1229
  };
1208
1230
  });
@@ -2634,7 +2656,15 @@ const VersionResult = type({
2634
2656
  });
2635
2657
  const SimulatedTransactionResponseStruct = jsonRpcResultAndContext(type({
2636
2658
  err: nullable(union([type({}), string()])),
2637
- logs: nullable(array(string()))
2659
+ logs: nullable(array(string())),
2660
+ accounts: optional(nullable(array(type({
2661
+ executable: boolean(),
2662
+ owner: string(),
2663
+ lamports: number(),
2664
+ data: array(string()),
2665
+ rentEpoch: optional(number())
2666
+ })))),
2667
+ unitsConsumed: optional(number())
2638
2668
  }));
2639
2669
 
2640
2670
  function createRpcClient(url, useHttps, httpHeaders, fetchMiddleware, disableRetryOnRateLimit) {
@@ -3366,6 +3396,8 @@ class Connection {
3366
3396
 
3367
3397
  /** @internal */
3368
3398
 
3399
+ /** @internal */
3400
+
3369
3401
  /**
3370
3402
  * Establish a JSON RPC connection
3371
3403
  *
@@ -3375,6 +3407,8 @@ class Connection {
3375
3407
  constructor(endpoint, commitmentOrConfig) {
3376
3408
  _defineProperty(this, "_commitment", void 0);
3377
3409
 
3410
+ _defineProperty(this, "_confirmTransactionInitialTimeout", void 0);
3411
+
3378
3412
  _defineProperty(this, "_rpcEndpoint", void 0);
3379
3413
 
3380
3414
  _defineProperty(this, "_rpcWsEndpoint", void 0);
@@ -3443,6 +3477,7 @@ class Connection {
3443
3477
  this._commitment = commitmentOrConfig;
3444
3478
  } else if (commitmentOrConfig) {
3445
3479
  this._commitment = commitmentOrConfig.commitment;
3480
+ this._confirmTransactionInitialTimeout = commitmentOrConfig.confirmTransactionInitialTimeout;
3446
3481
  wsEndpoint = commitmentOrConfig.wsEndpoint;
3447
3482
  httpHeaders = commitmentOrConfig.httpHeaders;
3448
3483
  fetchMiddleware = commitmentOrConfig.fetchMiddleware;
@@ -3902,7 +3937,7 @@ class Connection {
3902
3937
  reject(err);
3903
3938
  }
3904
3939
  });
3905
- let timeoutMs = 60 * 1000;
3940
+ let timeoutMs = this._confirmTransactionInitialTimeout || 60 * 1000;
3906
3941
 
3907
3942
  switch (subscriptionCommitment) {
3908
3943
  case 'processed':
@@ -3911,7 +3946,7 @@ class Connection {
3911
3946
  case 'confirmed':
3912
3947
  case 'singleGossip':
3913
3948
  {
3914
- timeoutMs = 30 * 1000;
3949
+ timeoutMs = this._confirmTransactionInitialTimeout || 30 * 1000;
3915
3950
  break;
3916
3951
  }
3917
3952
  }
@@ -4283,6 +4318,21 @@ class Connection {
4283
4318
 
4284
4319
  return res.result;
4285
4320
  }
4321
+ /**
4322
+ * Fetch the genesis hash
4323
+ */
4324
+
4325
+
4326
+ async getGenesisHash() {
4327
+ const unsafeRes = await this._rpcRequest('getGenesisHash', []);
4328
+ const res = create(unsafeRes, jsonRpcResult(string()));
4329
+
4330
+ if ('error' in res) {
4331
+ throw new Error('failed to get genesis hash: ' + res.error.message);
4332
+ }
4333
+
4334
+ return res.result;
4335
+ }
4286
4336
  /**
4287
4337
  * Fetch a processed block from the cluster.
4288
4338
  */
@@ -4683,7 +4733,15 @@ class Connection {
4683
4733
  */
4684
4734
 
4685
4735
 
4686
- async simulateTransaction(transaction, signers) {
4736
+ async simulateTransaction(transactionOrMessage, signers, includeAccounts) {
4737
+ let transaction;
4738
+
4739
+ if (transactionOrMessage instanceof Transaction) {
4740
+ transaction = transactionOrMessage;
4741
+ } else {
4742
+ transaction = Transaction.populate(transactionOrMessage);
4743
+ }
4744
+
4687
4745
  if (transaction.nonceInfo && signers) {
4688
4746
  transaction.sign(...signers);
4689
4747
  } else {
@@ -4716,7 +4774,9 @@ class Connection {
4716
4774
  }
4717
4775
  }
4718
4776
 
4719
- const signData = transaction.serializeMessage();
4777
+ const message = transaction._compile();
4778
+
4779
+ const signData = message.serialize();
4720
4780
 
4721
4781
  const wireTransaction = transaction._serialize(signData);
4722
4782
 
@@ -4726,6 +4786,14 @@ class Connection {
4726
4786
  commitment: this.commitment
4727
4787
  };
4728
4788
 
4789
+ if (includeAccounts) {
4790
+ const addresses = (Array.isArray(includeAccounts) ? includeAccounts : message.nonProgramIds()).map(key => key.toBase58());
4791
+ config['accounts'] = {
4792
+ encoding: 'base64',
4793
+ addresses
4794
+ };
4795
+ }
4796
+
4729
4797
  if (signers) {
4730
4798
  config.sigVerify = true;
4731
4799
  }
@@ -5606,6 +5674,96 @@ class Keypair {
5606
5674
 
5607
5675
  }
5608
5676
 
5677
+ const PRIVATE_KEY_BYTES$1 = 64;
5678
+ const PUBLIC_KEY_BYTES$1 = 32;
5679
+ const SIGNATURE_BYTES = 64;
5680
+ /**
5681
+ * Params for creating an ed25519 instruction using a public key
5682
+ */
5683
+
5684
+ const ED25519_INSTRUCTION_LAYOUT = BufferLayout.struct([BufferLayout.u8('numSignatures'), BufferLayout.u8('padding'), BufferLayout.u16('signatureOffset'), BufferLayout.u16('signatureInstructionIndex'), BufferLayout.u16('publicKeyOffset'), BufferLayout.u16('publicKeyInstructionIndex'), BufferLayout.u16('messageDataOffset'), BufferLayout.u16('messageDataSize'), BufferLayout.u16('messageInstructionIndex')]);
5685
+ class Ed25519Program {
5686
+ /**
5687
+ * @internal
5688
+ */
5689
+ constructor() {}
5690
+ /**
5691
+ * Public key that identifies the ed25519 program
5692
+ */
5693
+
5694
+
5695
+ /**
5696
+ * Create an ed25519 instruction with a public key and signature. The
5697
+ * public key must be a buffer that is 32 bytes long, and the signature
5698
+ * must be a buffer of 64 bytes.
5699
+ */
5700
+ static createInstructionWithPublicKey(params) {
5701
+ const {
5702
+ publicKey,
5703
+ message,
5704
+ signature,
5705
+ instructionIndex
5706
+ } = params;
5707
+ assert(publicKey.length === PUBLIC_KEY_BYTES$1, `Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey.length} bytes`);
5708
+ assert(signature.length === SIGNATURE_BYTES, `Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`);
5709
+ const publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span;
5710
+ const signatureOffset = publicKeyOffset + publicKey.length;
5711
+ const messageDataOffset = signatureOffset + signature.length;
5712
+ const numSignatures = 1;
5713
+ const instructionData = Buffer.alloc(messageDataOffset + message.length);
5714
+ ED25519_INSTRUCTION_LAYOUT.encode({
5715
+ numSignatures,
5716
+ padding: 0,
5717
+ signatureOffset,
5718
+ signatureInstructionIndex: instructionIndex,
5719
+ publicKeyOffset,
5720
+ publicKeyInstructionIndex: instructionIndex,
5721
+ messageDataOffset,
5722
+ messageDataSize: message.length,
5723
+ messageInstructionIndex: instructionIndex
5724
+ }, instructionData);
5725
+ instructionData.fill(publicKey, publicKeyOffset);
5726
+ instructionData.fill(signature, signatureOffset);
5727
+ instructionData.fill(message, messageDataOffset);
5728
+ return new TransactionInstruction({
5729
+ keys: [],
5730
+ programId: Ed25519Program.programId,
5731
+ data: instructionData
5732
+ });
5733
+ }
5734
+ /**
5735
+ * Create an ed25519 instruction with a private key. The private key
5736
+ * must be a buffer that is 64 bytes long.
5737
+ */
5738
+
5739
+
5740
+ static createInstructionWithPrivateKey(params) {
5741
+ const {
5742
+ privateKey,
5743
+ message,
5744
+ instructionIndex
5745
+ } = params;
5746
+ assert(privateKey.length === PRIVATE_KEY_BYTES$1, `Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);
5747
+
5748
+ try {
5749
+ const keypair = Keypair.fromSecretKey(privateKey);
5750
+ const publicKey = keypair.publicKey.toBytes();
5751
+ const signature = nacl__default.sign.detached(message, keypair.secretKey);
5752
+ return this.createInstructionWithPublicKey({
5753
+ publicKey,
5754
+ message,
5755
+ signature,
5756
+ instructionIndex
5757
+ });
5758
+ } catch (error) {
5759
+ throw new Error(`Error creating instruction; ${error}`);
5760
+ }
5761
+ }
5762
+
5763
+ }
5764
+
5765
+ _defineProperty(Ed25519Program, "programId", new PublicKey('Ed25519SigVerify111111111111111111111111111'));
5766
+
5609
5767
  /**
5610
5768
  * Address of the stake config account which configures the rate
5611
5769
  * of stake warmup and cooldown as well as the slashing penalty.
@@ -6738,5 +6896,5 @@ function clusterApiUrl(cluster, tls) {
6738
6896
 
6739
6897
  const LAMPORTS_PER_SOL = 1000000000;
6740
6898
 
6741
- export { Account, Authorized, BLOCKHASH_CACHE_TIMEOUT_MS, BPF_LOADER_DEPRECATED_PROGRAM_ID, BPF_LOADER_PROGRAM_ID, BpfLoader, Connection, Enum, EpochSchedule, FeeCalculatorLayout, Keypair, LAMPORTS_PER_SOL, Loader, Lockup, MAX_SEED_LENGTH, Message, NONCE_ACCOUNT_LENGTH, NonceAccount, PACKET_DATA_SIZE, PublicKey, SOLANA_SCHEMA, STAKE_CONFIG_ID, STAKE_INSTRUCTION_LAYOUTS, SYSTEM_INSTRUCTION_LAYOUTS, SYSVAR_CLOCK_PUBKEY, SYSVAR_INSTRUCTIONS_PUBKEY, SYSVAR_RECENT_BLOCKHASHES_PUBKEY, SYSVAR_RENT_PUBKEY, SYSVAR_REWARDS_PUBKEY, SYSVAR_STAKE_HISTORY_PUBKEY, Secp256k1Program, SendTransactionError, StakeAuthorizationLayout, StakeInstruction, StakeProgram, Struct, SystemInstruction, SystemProgram, Transaction, TransactionInstruction, VALIDATOR_INFO_KEY, VOTE_PROGRAM_ID, ValidatorInfo, VoteAccount, clusterApiUrl, sendAndConfirmRawTransaction, sendAndConfirmTransaction };
6899
+ export { Account, Authorized, BLOCKHASH_CACHE_TIMEOUT_MS, BPF_LOADER_DEPRECATED_PROGRAM_ID, BPF_LOADER_PROGRAM_ID, BpfLoader, Connection, Ed25519Program, Enum, EpochSchedule, FeeCalculatorLayout, Keypair, LAMPORTS_PER_SOL, Loader, Lockup, MAX_SEED_LENGTH, Message, NONCE_ACCOUNT_LENGTH, NonceAccount, PACKET_DATA_SIZE, PublicKey, SOLANA_SCHEMA, STAKE_CONFIG_ID, STAKE_INSTRUCTION_LAYOUTS, SYSTEM_INSTRUCTION_LAYOUTS, SYSVAR_CLOCK_PUBKEY, SYSVAR_INSTRUCTIONS_PUBKEY, SYSVAR_RECENT_BLOCKHASHES_PUBKEY, SYSVAR_RENT_PUBKEY, SYSVAR_REWARDS_PUBKEY, SYSVAR_STAKE_HISTORY_PUBKEY, Secp256k1Program, SendTransactionError, StakeAuthorizationLayout, StakeInstruction, StakeProgram, Struct, SystemInstruction, SystemProgram, Transaction, TransactionInstruction, VALIDATOR_INFO_KEY, VOTE_PROGRAM_ID, ValidatorInfo, VoteAccount, clusterApiUrl, sendAndConfirmRawTransaction, sendAndConfirmTransaction };
6742
6900
  //# sourceMappingURL=index.esm.js.map