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,140 @@
1
+ import {AccountKeysFromLookups} from '../message/account-keys';
2
+ import assert from '../utils/assert';
3
+ import {toBuffer} from '../utils/to-buffer';
4
+ import {Blockhash} from '../blockhash';
5
+ import {Message, MessageV0, VersionedMessage} from '../message';
6
+ import {PublicKey} from '../publickey';
7
+ import {AddressLookupTableAccount} from '../programs';
8
+ import {AccountMeta, TransactionInstruction} from './legacy';
9
+
10
+ export type TransactionMessageArgs = {
11
+ payerKey: PublicKey;
12
+ instructions: Array<TransactionInstruction>;
13
+ recentBlockhash: Blockhash;
14
+ };
15
+
16
+ export type DecompileArgs =
17
+ | {
18
+ accountKeysFromLookups: AccountKeysFromLookups;
19
+ }
20
+ | {
21
+ addressLookupTableAccounts: AddressLookupTableAccount[];
22
+ };
23
+
24
+ export class TransactionMessage {
25
+ payerKey: PublicKey;
26
+ instructions: Array<TransactionInstruction>;
27
+ recentBlockhash: Blockhash;
28
+
29
+ constructor(args: TransactionMessageArgs) {
30
+ this.payerKey = args.payerKey;
31
+ this.instructions = args.instructions;
32
+ this.recentBlockhash = args.recentBlockhash;
33
+ }
34
+
35
+ static decompile(
36
+ message: VersionedMessage,
37
+ args?: DecompileArgs,
38
+ ): TransactionMessage {
39
+ const {header, compiledInstructions, recentBlockhash} = message;
40
+
41
+ const {
42
+ numRequiredSignatures,
43
+ numReadonlySignedAccounts,
44
+ numReadonlyUnsignedAccounts,
45
+ } = header;
46
+
47
+ const numWritableSignedAccounts =
48
+ numRequiredSignatures - numReadonlySignedAccounts;
49
+ assert(numWritableSignedAccounts > 0, 'Message header is invalid');
50
+
51
+ const numWritableUnsignedAccounts =
52
+ message.staticAccountKeys.length -
53
+ numRequiredSignatures -
54
+ numReadonlyUnsignedAccounts;
55
+ assert(numWritableUnsignedAccounts >= 0, 'Message header is invalid');
56
+
57
+ const accountKeys = message.getAccountKeys(args);
58
+ const payerKey = accountKeys.get(0);
59
+ if (payerKey === undefined) {
60
+ throw new Error(
61
+ 'Failed to decompile message because no account keys were found',
62
+ );
63
+ }
64
+
65
+ const instructions: TransactionInstruction[] = [];
66
+ for (const compiledIx of compiledInstructions) {
67
+ const keys: AccountMeta[] = [];
68
+
69
+ for (const keyIndex of compiledIx.accountKeyIndexes) {
70
+ const pubkey = accountKeys.get(keyIndex);
71
+ if (pubkey === undefined) {
72
+ throw new Error(
73
+ `Failed to find key for account key index ${keyIndex}`,
74
+ );
75
+ }
76
+
77
+ const isSigner = keyIndex < numRequiredSignatures;
78
+
79
+ let isWritable;
80
+ if (isSigner) {
81
+ isWritable = keyIndex < numWritableSignedAccounts;
82
+ } else if (keyIndex < accountKeys.staticAccountKeys.length) {
83
+ isWritable =
84
+ keyIndex - numRequiredSignatures < numWritableUnsignedAccounts;
85
+ } else {
86
+ isWritable =
87
+ keyIndex - accountKeys.staticAccountKeys.length <
88
+ // accountKeysFromLookups cannot be undefined because we already found a pubkey for this index above
89
+ accountKeys.accountKeysFromLookups!.writable.length;
90
+ }
91
+
92
+ keys.push({
93
+ pubkey,
94
+ isSigner: keyIndex < header.numRequiredSignatures,
95
+ isWritable,
96
+ });
97
+ }
98
+
99
+ const programId = accountKeys.get(compiledIx.programIdIndex);
100
+ if (programId === undefined) {
101
+ throw new Error(
102
+ `Failed to find program id for program id index ${compiledIx.programIdIndex}`,
103
+ );
104
+ }
105
+
106
+ instructions.push(
107
+ new TransactionInstruction({
108
+ programId,
109
+ data: toBuffer(compiledIx.data),
110
+ keys,
111
+ }),
112
+ );
113
+ }
114
+
115
+ return new TransactionMessage({
116
+ payerKey,
117
+ instructions,
118
+ recentBlockhash,
119
+ });
120
+ }
121
+
122
+ compileToLegacyMessage(): Message {
123
+ return Message.compile({
124
+ payerKey: this.payerKey,
125
+ recentBlockhash: this.recentBlockhash,
126
+ instructions: this.instructions,
127
+ });
128
+ }
129
+
130
+ compileToV0Message(
131
+ addressLookupTableAccounts?: AddressLookupTableAccount[],
132
+ ): MessageV0 {
133
+ return MessageV0.compile({
134
+ payerKey: this.payerKey,
135
+ recentBlockhash: this.recentBlockhash,
136
+ instructions: this.instructions,
137
+ addressLookupTableAccounts,
138
+ });
139
+ }
140
+ }
@@ -0,0 +1,127 @@
1
+ import * as BufferLayout from '@solana/buffer-layout';
2
+
3
+ import {Signer} from '../keypair';
4
+ import assert from '../utils/assert';
5
+ import {VersionedMessage} from '../message/versioned';
6
+ import {SIGNATURE_LENGTH_IN_BYTES} from './constants';
7
+ import * as shortvec from '../utils/shortvec-encoding';
8
+ import * as Layout from '../layout';
9
+ import {sign} from '../utils/ed25519';
10
+ import {PublicKey} from '../publickey';
11
+ import {guardedSplice} from '../utils/guarded-array-utils';
12
+
13
+ export type TransactionVersion = 'legacy' | 0;
14
+
15
+ /**
16
+ * Versioned transaction class
17
+ */
18
+ export class VersionedTransaction {
19
+ signatures: Array<Uint8Array>;
20
+ message: VersionedMessage;
21
+
22
+ get version(): TransactionVersion {
23
+ return this.message.version;
24
+ }
25
+
26
+ constructor(message: VersionedMessage, signatures?: Array<Uint8Array>) {
27
+ if (signatures !== undefined) {
28
+ assert(
29
+ signatures.length === message.header.numRequiredSignatures,
30
+ 'Expected signatures length to be equal to the number of required signatures',
31
+ );
32
+ this.signatures = signatures;
33
+ } else {
34
+ const defaultSignatures = [];
35
+ for (let i = 0; i < message.header.numRequiredSignatures; i++) {
36
+ defaultSignatures.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES));
37
+ }
38
+ this.signatures = defaultSignatures;
39
+ }
40
+ this.message = message;
41
+ }
42
+
43
+ serialize(): Uint8Array {
44
+ const serializedMessage = this.message.serialize();
45
+
46
+ const encodedSignaturesLength = Array<number>();
47
+ shortvec.encodeLength(encodedSignaturesLength, this.signatures.length);
48
+
49
+ const transactionLayout = BufferLayout.struct<{
50
+ encodedSignaturesLength: Uint8Array;
51
+ signatures: Array<Uint8Array>;
52
+ serializedMessage: Uint8Array;
53
+ }>([
54
+ BufferLayout.blob(
55
+ encodedSignaturesLength.length,
56
+ 'encodedSignaturesLength',
57
+ ),
58
+ BufferLayout.seq(
59
+ Layout.signature(),
60
+ this.signatures.length,
61
+ 'signatures',
62
+ ),
63
+ BufferLayout.blob(serializedMessage.length, 'serializedMessage'),
64
+ ]);
65
+
66
+ const serializedTransaction = new Uint8Array(2048);
67
+ const serializedTransactionLength = transactionLayout.encode(
68
+ {
69
+ encodedSignaturesLength: new Uint8Array(encodedSignaturesLength),
70
+ signatures: this.signatures,
71
+ serializedMessage,
72
+ },
73
+ serializedTransaction,
74
+ );
75
+
76
+ return serializedTransaction.slice(0, serializedTransactionLength);
77
+ }
78
+
79
+ static deserialize(serializedTransaction: Uint8Array): VersionedTransaction {
80
+ let byteArray = [...serializedTransaction];
81
+
82
+ const signatures = [];
83
+ const signaturesLength = shortvec.decodeLength(byteArray);
84
+ for (let i = 0; i < signaturesLength; i++) {
85
+ signatures.push(
86
+ new Uint8Array(guardedSplice(byteArray, 0, SIGNATURE_LENGTH_IN_BYTES)),
87
+ );
88
+ }
89
+
90
+ const message = VersionedMessage.deserialize(new Uint8Array(byteArray));
91
+ return new VersionedTransaction(message, signatures);
92
+ }
93
+
94
+ sign(signers: Array<Signer>) {
95
+ const messageData = this.message.serialize();
96
+ const signerPubkeys = this.message.staticAccountKeys.slice(
97
+ 0,
98
+ this.message.header.numRequiredSignatures,
99
+ );
100
+ for (const signer of signers) {
101
+ const signerIndex = signerPubkeys.findIndex(pubkey =>
102
+ pubkey.equals(signer.publicKey),
103
+ );
104
+ assert(
105
+ signerIndex >= 0,
106
+ `Cannot sign with non signer key ${signer.publicKey.toBase58()}`,
107
+ );
108
+ this.signatures[signerIndex] = sign(messageData, signer.secretKey);
109
+ }
110
+ }
111
+
112
+ addSignature(publicKey: PublicKey, signature: Uint8Array) {
113
+ assert(signature.byteLength === 64, 'Signature must be 64 bytes long');
114
+ const signerPubkeys = this.message.staticAccountKeys.slice(
115
+ 0,
116
+ this.message.header.numRequiredSignatures,
117
+ );
118
+ const signerIndex = signerPubkeys.findIndex(pubkey =>
119
+ pubkey.equals(publicKey),
120
+ );
121
+ assert(
122
+ signerIndex >= 0,
123
+ `Can not add signature; \`${publicKey.toBase58()}\` is not required to sign this transaction`,
124
+ );
125
+ this.signatures[signerIndex] = signature;
126
+ }
127
+ }
@@ -0,0 +1,8 @@
1
+ export default function (
2
+ condition: unknown,
3
+ message?: string,
4
+ ): asserts condition {
5
+ if (!condition) {
6
+ throw new Error(message || 'Assertion failed');
7
+ }
8
+ }
@@ -0,0 +1,24 @@
1
+ import {Buffer} from 'buffer';
2
+ import {blob, Layout} from '@solana/buffer-layout';
3
+ import {getU64Codec} from '@solana/codecs-numbers';
4
+
5
+ export function u64(property?: string): Layout<bigint> {
6
+ const layout = blob(8 /* bytes */, property);
7
+ const decode = layout.decode.bind(layout);
8
+ const encode = layout.encode.bind(layout);
9
+
10
+ const bigIntLayout = layout as Layout<unknown> as Layout<bigint>;
11
+ const codec = getU64Codec();
12
+
13
+ bigIntLayout.decode = (buffer: Buffer, offset: number) => {
14
+ const src = decode(buffer as Uint8Array, offset);
15
+ return codec.decode(src);
16
+ };
17
+
18
+ bigIntLayout.encode = (bigInt: bigint, buffer: Buffer, offset: number) => {
19
+ const src = codec.encode(bigInt) as Uint8Array;
20
+ return encode(src, buffer as Uint8Array, offset);
21
+ };
22
+
23
+ return bigIntLayout;
24
+ }
@@ -0,0 +1,38 @@
1
+ import {Buffer} from 'buffer';
2
+ import {serialize, deserialize, deserializeUnchecked} from 'borsh';
3
+
4
+ // Class wrapping a plain object
5
+ export class Struct {
6
+ constructor(properties: any) {
7
+ Object.assign(this, properties);
8
+ }
9
+
10
+ encode(): Buffer {
11
+ return Buffer.from(serialize(SOLANA_SCHEMA, this));
12
+ }
13
+
14
+ static decode(data: Buffer): any {
15
+ return deserialize(SOLANA_SCHEMA, this, data);
16
+ }
17
+
18
+ static decodeUnchecked(data: Buffer): any {
19
+ return deserializeUnchecked(SOLANA_SCHEMA, this, data);
20
+ }
21
+ }
22
+
23
+ // Class representing a Rust-compatible enum, since enums are only strings or
24
+ // numbers in pure JS
25
+ export class Enum extends Struct {
26
+ enum: string = '';
27
+ constructor(properties: any) {
28
+ super(properties);
29
+ if (Object.keys(properties).length !== 1) {
30
+ throw new Error('Enum can only take single value');
31
+ }
32
+ Object.keys(properties).map(key => {
33
+ this.enum = key;
34
+ });
35
+ }
36
+ }
37
+
38
+ export const SOLANA_SCHEMA: Map<Function, any> = new Map();
@@ -0,0 +1,35 @@
1
+ const endpoint = {
2
+ http: {
3
+ devnet: 'http://api.devnet.solana.com',
4
+ testnet: 'http://api.testnet.solana.com',
5
+ 'mainnet-beta': 'http://api.mainnet-beta.solana.com/',
6
+ },
7
+ https: {
8
+ devnet: 'https://api.devnet.solana.com',
9
+ testnet: 'https://api.testnet.solana.com',
10
+ 'mainnet-beta': 'https://api.mainnet-beta.solana.com/',
11
+ },
12
+ };
13
+
14
+ export type Cluster = 'devnet' | 'testnet' | 'mainnet-beta';
15
+
16
+ /**
17
+ * Retrieves the RPC API URL for the specified cluster
18
+ * @param {Cluster} [cluster="devnet"] - The cluster name of the RPC API URL to use. Possible options: 'devnet' | 'testnet' | 'mainnet-beta'
19
+ * @param {boolean} [tls="http"] - Use TLS when connecting to cluster.
20
+ *
21
+ * @returns {string} URL string of the RPC endpoint
22
+ */
23
+ export function clusterApiUrl(cluster?: Cluster, tls?: boolean): string {
24
+ const key = tls === false ? 'http' : 'https';
25
+
26
+ if (!cluster) {
27
+ return endpoint[key]['devnet'];
28
+ }
29
+
30
+ const url = endpoint[key][cluster];
31
+ if (!url) {
32
+ throw new Error(`Unknown ${key} cluster: ${cluster}`);
33
+ }
34
+ return url;
35
+ }
@@ -0,0 +1,43 @@
1
+ import {ed25519} from '@noble/curves/ed25519';
2
+
3
+ /**
4
+ * A 64 byte secret key, the first 32 bytes of which is the
5
+ * private scalar and the last 32 bytes is the public key.
6
+ * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/
7
+ */
8
+ type Ed25519SecretKey = Uint8Array;
9
+
10
+ /**
11
+ * Ed25519 Keypair
12
+ */
13
+ export interface Ed25519Keypair {
14
+ publicKey: Uint8Array;
15
+ secretKey: Ed25519SecretKey;
16
+ }
17
+
18
+ export const generatePrivateKey = ed25519.utils.randomPrivateKey;
19
+ export const generateKeypair = (): Ed25519Keypair => {
20
+ const privateScalar = ed25519.utils.randomPrivateKey();
21
+ const publicKey = getPublicKey(privateScalar);
22
+ const secretKey = new Uint8Array(64);
23
+ secretKey.set(privateScalar);
24
+ secretKey.set(publicKey, 32);
25
+ return {
26
+ publicKey,
27
+ secretKey,
28
+ };
29
+ };
30
+ export const getPublicKey = ed25519.getPublicKey;
31
+ export function isOnCurve(publicKey: Uint8Array): boolean {
32
+ try {
33
+ ed25519.ExtendedPoint.fromHex(publicKey);
34
+ return true;
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+ export const sign = (
40
+ message: Parameters<typeof ed25519.sign>[0],
41
+ secretKey: Ed25519SecretKey,
42
+ ) => ed25519.sign(message, secretKey.slice(0, 32));
43
+ export const verify = ed25519.verify;
@@ -0,0 +1,34 @@
1
+ const END_OF_BUFFER_ERROR_MESSAGE = 'Reached end of buffer unexpectedly';
2
+
3
+ /**
4
+ * Delegates to `Array#shift`, but throws if the array is zero-length.
5
+ */
6
+ export function guardedShift<T>(byteArray: T[]): T {
7
+ if (byteArray.length === 0) {
8
+ throw new Error(END_OF_BUFFER_ERROR_MESSAGE);
9
+ }
10
+ return byteArray.shift() as T;
11
+ }
12
+
13
+ /**
14
+ * Delegates to `Array#splice`, but throws if the section being spliced out extends past the end of
15
+ * the array.
16
+ */
17
+ export function guardedSplice<T>(
18
+ byteArray: T[],
19
+ ...args:
20
+ | [start: number, deleteCount?: number]
21
+ | [start: number, deleteCount: number, ...items: T[]]
22
+ ): T[] {
23
+ const [start] = args;
24
+ if (
25
+ args.length === 2 // Implies that `deleteCount` was supplied
26
+ ? start + (args[1] ?? 0) > byteArray.length
27
+ : start >= byteArray.length
28
+ ) {
29
+ throw new Error(END_OF_BUFFER_ERROR_MESSAGE);
30
+ }
31
+ return byteArray.splice(
32
+ ...(args as Parameters<typeof Array.prototype.splice>),
33
+ );
34
+ }
@@ -0,0 +1,5 @@
1
+ export * from './borsh-schema';
2
+ export * from './cluster';
3
+ export type {Ed25519Keypair} from './ed25519';
4
+ export * from './send-and-confirm-raw-transaction';
5
+ export * from './send-and-confirm-transaction';
@@ -0,0 +1,26 @@
1
+ const URL_RE = /^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;
2
+
3
+ export function makeWebsocketUrl(endpoint: string) {
4
+ const matches = endpoint.match(URL_RE);
5
+ if (matches == null) {
6
+ throw TypeError(`Failed to validate endpoint URL \`${endpoint}\``);
7
+ }
8
+ const [
9
+ _, // eslint-disable-line @typescript-eslint/no-unused-vars
10
+ hostish,
11
+ portWithColon,
12
+ rest,
13
+ ] = matches;
14
+ const protocol = endpoint.startsWith('https:') ? 'wss:' : 'ws:';
15
+ const startPort =
16
+ portWithColon == null ? null : parseInt(portWithColon.slice(1), 10);
17
+ const websocketPort =
18
+ // Only shift the port by +1 as a convention for ws(s) only if given endpoint
19
+ // is explicitly specifying the endpoint port (HTTP-based RPC), assuming
20
+ // we're directly trying to connect to agave-validator's ws listening port.
21
+ // When the endpoint omits the port, we're connecting to the protocol
22
+ // default ports: http(80) or https(443) and it's assumed we're behind a reverse
23
+ // proxy which manages WebSocket upgrade and backend port redirection.
24
+ startPort == null ? '' : `:${startPort + 1}`;
25
+ return `${protocol}//${hostish}${websocketPort}${rest}`;
26
+ }
@@ -0,0 +1,14 @@
1
+ export function promiseTimeout<T>(
2
+ promise: Promise<T>,
3
+ timeoutMs: number,
4
+ ): Promise<T | null> {
5
+ let timeoutId: ReturnType<typeof setTimeout>;
6
+ const timeoutPromise: Promise<null> = new Promise(resolve => {
7
+ timeoutId = setTimeout(() => resolve(null), timeoutMs);
8
+ });
9
+
10
+ return Promise.race([promise, timeoutPromise]).then((result: T | null) => {
11
+ clearTimeout(timeoutId);
12
+ return result;
13
+ });
14
+ }
@@ -0,0 +1,11 @@
1
+ import {secp256k1} from '@noble/curves/secp256k1';
2
+
3
+ export const ecdsaSign = (
4
+ msgHash: Parameters<typeof secp256k1.sign>[0],
5
+ privKey: Parameters<typeof secp256k1.sign>[1],
6
+ ) => {
7
+ const signature = secp256k1.sign(msgHash, privKey);
8
+ return [signature.toCompactRawBytes(), signature.recovery!] as const;
9
+ };
10
+ export const isValidPrivateKey = secp256k1.utils.isValidPrivateKey;
11
+ export const publicKeyCreate = secp256k1.getPublicKey;
@@ -0,0 +1,110 @@
1
+ import type {Buffer} from 'buffer';
2
+
3
+ import {
4
+ BlockheightBasedTransactionConfirmationStrategy,
5
+ Connection,
6
+ DurableNonceTransactionConfirmationStrategy,
7
+ TransactionConfirmationStrategy,
8
+ } from '../connection';
9
+ import type {TransactionSignature} from '../transaction';
10
+ import type {ConfirmOptions} from '../connection';
11
+ import {SendTransactionError} from '../errors';
12
+
13
+ /**
14
+ * Send and confirm a raw transaction
15
+ *
16
+ * If `commitment` option is not specified, defaults to 'max' commitment.
17
+ *
18
+ * @param {Connection} connection
19
+ * @param {Buffer} rawTransaction
20
+ * @param {TransactionConfirmationStrategy} confirmationStrategy
21
+ * @param {ConfirmOptions} [options]
22
+ * @returns {Promise<TransactionSignature>}
23
+ */
24
+ export async function sendAndConfirmRawTransaction(
25
+ connection: Connection,
26
+ rawTransaction: Buffer,
27
+ confirmationStrategy: TransactionConfirmationStrategy,
28
+ options?: ConfirmOptions,
29
+ ): Promise<TransactionSignature>;
30
+
31
+ /**
32
+ * @deprecated Calling `sendAndConfirmRawTransaction()` without a `confirmationStrategy`
33
+ * is no longer supported and will be removed in a future version.
34
+ */
35
+ // eslint-disable-next-line no-redeclare
36
+ export async function sendAndConfirmRawTransaction(
37
+ connection: Connection,
38
+ rawTransaction: Buffer,
39
+ options?: ConfirmOptions,
40
+ ): Promise<TransactionSignature>;
41
+
42
+ // eslint-disable-next-line no-redeclare
43
+ export async function sendAndConfirmRawTransaction(
44
+ connection: Connection,
45
+ rawTransaction: Buffer,
46
+ confirmationStrategyOrConfirmOptions:
47
+ | TransactionConfirmationStrategy
48
+ | ConfirmOptions
49
+ | undefined,
50
+ maybeConfirmOptions?: ConfirmOptions,
51
+ ): Promise<TransactionSignature> {
52
+ let confirmationStrategy: TransactionConfirmationStrategy | undefined;
53
+ let options: ConfirmOptions | undefined;
54
+ if (
55
+ confirmationStrategyOrConfirmOptions &&
56
+ Object.prototype.hasOwnProperty.call(
57
+ confirmationStrategyOrConfirmOptions,
58
+ 'lastValidBlockHeight',
59
+ )
60
+ ) {
61
+ confirmationStrategy =
62
+ confirmationStrategyOrConfirmOptions as BlockheightBasedTransactionConfirmationStrategy;
63
+ options = maybeConfirmOptions;
64
+ } else if (
65
+ confirmationStrategyOrConfirmOptions &&
66
+ Object.prototype.hasOwnProperty.call(
67
+ confirmationStrategyOrConfirmOptions,
68
+ 'nonceValue',
69
+ )
70
+ ) {
71
+ confirmationStrategy =
72
+ confirmationStrategyOrConfirmOptions as DurableNonceTransactionConfirmationStrategy;
73
+ options = maybeConfirmOptions;
74
+ } else {
75
+ options = confirmationStrategyOrConfirmOptions as
76
+ | ConfirmOptions
77
+ | undefined;
78
+ }
79
+ const sendOptions = options && {
80
+ skipPreflight: options.skipPreflight,
81
+ preflightCommitment: options.preflightCommitment || options.commitment,
82
+ minContextSlot: options.minContextSlot,
83
+ };
84
+
85
+ const signature = await connection.sendRawTransaction(
86
+ rawTransaction,
87
+ sendOptions,
88
+ );
89
+
90
+ const commitment = options && options.commitment;
91
+ const confirmationPromise = confirmationStrategy
92
+ ? connection.confirmTransaction(confirmationStrategy, commitment)
93
+ : connection.confirmTransaction(signature, commitment);
94
+ const status = (await confirmationPromise).value;
95
+
96
+ if (status.err) {
97
+ if (signature != null) {
98
+ throw new SendTransactionError({
99
+ action: sendOptions?.skipPreflight ? 'send' : 'simulate',
100
+ signature: signature,
101
+ transactionMessage: `Status: (${JSON.stringify(status)})`,
102
+ });
103
+ }
104
+ throw new Error(
105
+ `Raw transaction ${signature} failed (${JSON.stringify(status)})`,
106
+ );
107
+ }
108
+
109
+ return signature;
110
+ }