Skip to content

Commit 84b86e5

Browse files
committed
docs: readme
1 parent 2f67f00 commit 84b86e5

File tree

3 files changed

+97
-56
lines changed

3 files changed

+97
-56
lines changed

.prettierrc

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"tabWidth": 2,
3+
"useTabs": false,
4+
"singleQuote": false,
5+
"bracketSpacing": true,
6+
"semi": true,
7+
"trailingComma": "all",
8+
"proseWrap": "always",
9+
"arrowParens": "always",
10+
"printWidth": 100
11+
}

.prettierrc.json

Lines changed: 0 additions & 1 deletion
This file was deleted.

README.md

Lines changed: 86 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,17 @@
1-
# Solana helpers
1+
# Solana web3.js v1 helpers
22

3-
The `helpers` 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) and our friends at [Anza](https://anza.xyz), [Turbin3](https://turbin3.com/), [Unboxed Software](https://beunboxed.com/), and [StarAtlas](https://staratlas.com/).
3+
The `@solana-developers/helpers` package contains Solana helper functions, for use in the browser
4+
and/or node.js, made by the Solana Foundation's
5+
[Developer Relations team](https://x.com/solana_devs) and contributions from
6+
[Anza](https://anza.xyz), [Turbin3](https://turbin3.com/),
7+
[Unboxed Software](https://beunboxed.com/), and [StarAtlas](https://staratlas.com/).
8+
9+
> [!IMPORTANT]
10+
> `@solana-developers/helpers` is for Solana web3.js version 1. The updated version of this package
11+
> which is compatible with Solana web3.js version 2 is called `gill`. Learn more here:
12+
>
13+
> - npm registry - https://www.npmjs.com/package/gill
14+
> - source repository - https://github.com/solana-foundation/gill
415
516
## What can I do with this module?
617

@@ -33,6 +44,7 @@ The `helpers` package contains Solana helper functions, for use in the browser a
3344
[Get an airdrop if your balance is below some amount](#get-an-airdrop-if-your-balance-is-below-some-amount)
3445

3546
### Error Handling & Utilities:
47+
3648
[Resolve a custom error message](#resolve-a-custom-error-message)
3749

3850
[Get a Solana Explorer link for a transaction, address, or block](#get-a-solana-explorer-link-for-a-transaction-address-or-block)
@@ -53,9 +65,11 @@ npm i @solana-developers/helpers
5365

5466
## Contributing
5567

56-
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!
68+
PRs are very much welcome! Read the
69+
[CONTRIBUTING guidelines for the Solana course](https://github.com/Unboxed-Software/solana-course/blob/main/CONTRIBUTING.md#code)
70+
then send a PR!
5771

58-
## helpers for the browser and node.js
72+
## Helpers for the browser and node.js
5973

6074
### Make multiple keypairs at once
6175

@@ -65,17 +79,22 @@ Usage:
6579
makeKeypairs(amount);
6680
```
6781

68-
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.
82+
In some situations - like making tests for your onchain programs - you might need to make lots of
83+
keypairs at once. You can use `makeKeypairs()` combined with JS destructuring to quickly create
84+
multiple variables with distinct keypairs.
6985

7086
```typescript
7187
const [sender, recipient] = makeKeypairs(2);
7288
```
7389

7490
### Make a token mint with metadata
7591

76-
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!
92+
The `makeTokenMint` makes a new token mint. A token mint is effectively the factory that produces
93+
token of a particular type. So if you want to make a new token, this is the right function for you!
7794

78-
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!
95+
Unlike older tools, the function uses Token Extensions Metadata and Metadata Pointer to put all
96+
metadata into the Mint Account, without needing an external Metadata account. If you don't know what
97+
that means, just know that things are simpler than they used to be!
7998

8099
Parameters
81100

@@ -85,7 +104,8 @@ Parameters
85104
- `symbol`: string, like a ticker symbol. Usually in all-caps.
86105
- `decimals`: number, how many decimal places the new token will have.
87106
- `uri`: string, URI to a JSON file containing at minimum a value for `image`.
88-
- `additionalMetadata`: additional metadata as either `Record<string, string>` or `Array<[string, string]>`(optional).
107+
- `additionalMetadata`: additional metadata as either `Record<string, string>` or
108+
`Array<[string, string]>`(optional).
89109
- `updateAuthority`: PublicKey (optional) - public key of the account that can update the token.
90110
- `freezeAuthority`: PublicKey (optional) - public key of the freeze account, default to `null`
91111

@@ -102,7 +122,10 @@ const mintAddress = await makeTokenMint(
102122

103123
### Create users, mints and token accounts in a single step
104124

105-
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.
125+
Frequently, tests for onchain programs need to make not just users with SOL, but also token mints
126+
and give each user some balance of each token. To save this boilerplate,
127+
`createAccountsMintsAndTokenAccounts()` handles making user keypairs, giving them SOL, making mints,
128+
creating associated token accounts, and minting tokens directly to the associated token accounts.
106129

107130
Eg, to make two new users, and two tokens:
108131

@@ -133,7 +156,8 @@ The returned `usersMintsAndTokenAccounts` will be an object of the form:
133156
}
134157
```
135158

136-
tokenAccounts are indexed by the user, then the mint. Eg, the ATA of `user[0]` for `mint[0]` is `tokenAccounts[0][0]`.
159+
tokenAccounts are indexed by the user, then the mint. Eg, the ATA of `user[0]` for `mint[0]` is
160+
`tokenAccounts[0][0]`.
137161

138162
### Resolve a custom error message
139163

@@ -145,7 +169,8 @@ getCustomErrorMessage(programErrors, errorMessage);
145169

146170
Sometimes Solana transactions throw an error with a message like:
147171

148-
> failed to send transaction: Transaction simulation failed: Error processing Instruction 0: custom program error: 0x10
172+
> failed to send transaction: Transaction simulation failed: Error processing Instruction 0: custom
173+
> program error: 0x10
149174
150175
Usage:
151176

@@ -159,7 +184,8 @@ Allows you to turn this message into a more readable message from the custom pro
159184
160185
Just:
161186

162-
- 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)
187+
- Get the errors from the specific program's `error.rs` file - for example, there are
188+
[the errors for the Token Program](https://github.com/solana-labs/solana-program-library/blob/master/token/program/src/error.rs)
163189

164190
- Save the errors into an array
165191

@@ -213,7 +239,10 @@ Usage:
213239
airdropIfRequired(connection, publicKey, lamports, maximumBalance);
214240
```
215241

216-
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.
242+
Request and confirm an airdrop in one step. As soon as the `await` returns, the airdropped tokens
243+
will be ready to use, and the new balance of tokens will be returned. The `maximumBalance` is used
244+
to avoid errors caused by unnecessarily asking for SOL when there's already enough in the account,
245+
and makes `airdropIfRequired()` very handy in scripts that run repeatedly.
217246

218247
To ask for 0.5 SOL, if the balance is below 1 SOL, use:
219248

@@ -237,24 +266,18 @@ getExplorerLink(type, identifier, clusterName);
237266
Get an explorer link for an `address`, `block` or `transaction` (`tx` works too).
238267

239268
```typescript
240-
getExplorerLink(
241-
"address",
242-
"dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8",
243-
"mainnet-beta",
244-
);
269+
getExplorerLink("address", "dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8", "mainnet-beta");
245270
```
246271

247-
Will return `"https://explorer.solana.com/address/dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8"`. The cluster name isn't included since mainnet-beta is the default.
272+
Will return `"https://explorer.solana.com/address/dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8"`. The
273+
cluster name isn't included since mainnet-beta is the default.
248274

249275
```typescript
250-
getExplorerLink(
251-
"address",
252-
"dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8",
253-
"devnet",
254-
);
276+
getExplorerLink("address", "dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8", "devnet");
255277
```
256278

257-
Will return `"https://explorer.solana.com/address/dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8?cluster=devnet"`
279+
Will return
280+
`"https://explorer.solana.com/address/dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8?cluster=devnet"`
258281

259282
```typescript
260283
getExplorerLink("block", "241889720", "mainnet-beta");
@@ -322,14 +345,13 @@ const sendSol = SystemProgram.transfer({
322345
Then use `getSimulationComputeUnits` to get the number of compute units the instructions will use:
323346

324347
```typescript
325-
const units = await getSimulationComputeUnits(
326-
connection,
327-
[sendSol],
328-
payer.publicKey,
329-
);
348+
const units = await getSimulationComputeUnits(connection, [sendSol], payer.publicKey);
330349
```
331350

332-
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.
351+
You can then use `ComputeBudgetProgram.setComputeUnitLimit({ units })` as the first instruction in
352+
your transaction. See
353+
[How to Request Optimal Compute Budget](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute)
354+
for more information on compute units.
333355

334356
### `addComputeInstructions`
335357

@@ -358,7 +380,7 @@ This function:
358380
3. Adds compute unit limit instruction with buffer
359381
4. Returns the updated instructions array
360382

361-
## node.js specific helpers
383+
## Node.js specific helpers
362384

363385
### Get a keypair from a keypair file
364386

@@ -368,7 +390,8 @@ Usage:
368390
getKeypairFromFile(filename);
369391
```
370392

371-
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:
393+
Gets a keypair from a file - the format must be the same as
394+
[Solana CLI](https://docs.anza.xyz/cli/wallets/file-system) uses, ie, a JSON array of numbers:
372395

373396
To load the default keypair `~/.config/solana/id.json`, just run:
374397

@@ -396,7 +419,9 @@ Usage:
396419
getKeypairFromEnvironment(environmentVariable);
397420
```
398421

399-
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).
422+
Gets a keypair from a secret key stored in an environment variable. This is typically used to load
423+
secret keys from
424+
[env files](https://stackoverflow.com/questions/68267862/what-is-an-env-or-dotenv-file-exactly).
400425

401426
```typescript
402427
const keypair = await getKeypairFromEnvironment("SECRET_KEY");
@@ -446,11 +471,15 @@ interface initializeKeypairOptions {
446471
}
447472
```
448473

449-
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`.
474+
By default, the keypair will be retrieved from the `.env` file. If a `.env` file does not exist,
475+
this function will create one with a new keypair under the optional `envVariableName`.
450476

451-
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.
477+
To load the keypair from the filesystem, pass in the `keypairPath`. When set, loading a keypair from
478+
the filesystem will take precedence over loading from the `.env` file.
452479

453-
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`.
480+
If `airdropAmount` amount is set to something other than `null` or `0`, this function will then
481+
check the account's balance. If the balance is below the `minimumBalance`, it will airdrop the
482+
account `airdropAmount`.
454483

455484
To initialize a keypair from the `.env` file, and airdrop it 1 sol if it's beneath 0.5 sol:
456485

@@ -485,7 +514,8 @@ const DEFAULT_ENV_KEYPAIR_VARIABLE_NAME = "PRIVATE_KEY";
485514

486515
## Secret key format
487516

488-
Secret keys can be read in either the more compact base58 format (`base58.encode(randomKeypair.secretKey);`), like:
517+
Secret keys can be read in either the more compact base58 format
518+
(`base58.encode(randomKeypair.secretKey);`), like:
489519

490520
```bash
491521
# A random secret key for demo purposes
@@ -499,7 +529,8 @@ Or the longer, 'array of numbers' format `JSON.stringify(Object.values(randomKey
499529
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]
500530
```
501531

502-
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.
532+
We always save keys using the 'array of numbers' format, since most other Solana apps (like the CLI
533+
SDK and Rust tools) use the 'array of numbers' format.
503534

504535
## Development
505536

@@ -515,7 +546,8 @@ Then in a different tab, run:
515546
npm run test
516547
```
517548

518-
The tests use the [node native test runner](https://blog.logrocket.com/exploring-node-js-native-test-runner/).
549+
The tests use the
550+
[node native test runner](https://blog.logrocket.com/exploring-node-js-native-test-runner/).
519551

520552
If you'd like to run a single test, use:
521553

@@ -569,8 +601,10 @@ The function will:
569601
For RPC providers that support priority fees:
570602

571603
- Helius: minimum 10000 microLamports
572-
- Triton: see their [priority fee API](https://docs.triton.one/chains/solana/improved-priority-fees-api)
573-
- Quicknode: see their [priority fee estimation](https://www.quicknode.com/docs/solana/qn_estimatePriorityFees)
604+
- Triton: see their
605+
[priority fee API](https://docs.triton.one/chains/solana/improved-priority-fees-api)
606+
- Quicknode: see their
607+
[priority fee estimation](https://www.quicknode.com/docs/solana/qn_estimatePriorityFees)
574608

575609
#### `sendVersionedTransaction`
576610

@@ -621,11 +655,11 @@ async function createLookupTable(
621655
Example:
622656

623657
```typescript
624-
const [lookupTableAddress, lookupTableAccount] = await createLookupTable(
625-
connection,
626-
payer,
627-
[account1.publicKey, account2.publicKey, account3.publicKey],
628-
);
658+
const [lookupTableAddress, lookupTableAccount] = await createLookupTable(connection, payer, [
659+
account1.publicKey,
660+
account2.publicKey,
661+
account3.publicKey,
662+
]);
629663
// Can either cache the lookup table address and lookup table account for reuse, or use them directly
630664
const signature = await sendVersionedTransaction(
631665
connection,
@@ -671,17 +705,13 @@ Usage:
671705

672706
```typescript
673707
const idl = await getIdlByProgramId(programId, connection);
674-
const data = await getIdlParsedAccountData(
675-
idl,
676-
"counter",
677-
accountAddress,
678-
connection,
679-
);
708+
const data = await getIdlParsedAccountData(idl, "counter", accountAddress, connection);
680709

681710
// Decoded Data: { count: <BN: 2> }
682711
```
683712

684-
Fetches and parses an account's data using an Anchor IDL file. This is useful when you need to decode account data from Anchor programs.
713+
Fetches and parses an account's data using an Anchor IDL file. This is useful when you need to
714+
decode account data from Anchor programs.
685715

686716
### Parse Transaction Events
687717

@@ -698,7 +728,8 @@ const events = await parseAnchorTransactionEvents(idl, signature, connection);
698728
// }
699729
```
700730

701-
Parses all Anchor events emitted in a transaction. This helps you track and verify program events after transaction execution.
731+
Parses all Anchor events emitted in a transaction. This helps you track and verify program events
732+
after transaction execution.
702733

703734
### Decode Anchor Transaction
704735

0 commit comments

Comments
 (0)