Package Exports
- @solana-developers/helpers
- @solana-developers/helpers/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@solana-developers/helpers) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Solana helpers
The helpers package contains Solana helper functions, for use in the browser and/or node.js, made by the Solana Foundation Developer Ecosystem team.
Eventually most of these will end up in @solana/web3.js.
What can I do with this module?
Make multiple keypairs at once
Resolve a custom error message
Get an airdrop if your balance is below some amount, and wait until it's confirmed
Get a Solana Explorer link for a transaction, address, or block
Confirm a transaction (includes getting a recent blockhash)
Get a keypair from a keypair file (like id.json)
Get a keypair from an environment variable
Add a new keypair to an env file
Installation
npm i @solana-developers/helpershelpers for the browser and node.js
makeKeypairs
In some situations - like making tests for your on-chain 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.
const [sender, recipient] = makeKeypairs(2);getCustomErrorMessage
Sometimes Solana transactions throw an error with a message like:
failed to send transaction: Transaction simulation failed: Error processing Instruction 0: custom program error: 0x10
getCustomErrorMessage() allows you to turn this message into a more readable message from the custom program, like:
This token mint cannot freeze accounts
Just:
Get the errors from the specific program's
error.rsfile - for example, there are the errors for the Token ProgramSave the errors into an array
// Token program errors
// https://github.com/solana-labs/solana-program-library/blob/master/token/program/src/error.rs
const tokenProgramErrors = [
"Lamport balance below rent-exempt threshold",
"Insufficient funds",
"Invalid Mint",
"Account not associated with this Mint",
"Owner does not match",
"Fixed supply",
"Already in use",
"Invalid number of provided signers",
"Invalid number of required signers",
"State is unititialized",
"Instruction does not support native tokens",
"Non-native account can only be closed if its balance is zero",
"Invalid instruction",
"State is invalid for requested operation",
"Operation overflowed",
"Account does not support specified authority type",
"This token mint cannot freeze accounts",
"Account is frozen",
"The provided decimals value different from the Mint decimals",
"Instruction does not support non-native tokens",
];Then run:
const errorMessage = getCustomErrorMessage(
tokenProgramErrors,
"failed to send transaction: Transaction simulation failed: Error processing Instruction 0: custom program error: 0x10",
);And errorMessage will now be:
"This token mint cannot freeze accounts";airdropIfRequired
Request and confirm an airdrop in one step. As soon as the await returns, the airdropped tokens will be ready in the address, and the new balance of tokens is 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.
To ask for 0.5 SOL, if the balance is below 1 SOL, use:
const newBalance = await airdropIfRequired(
connection,
keypair.publicKey,
0.5 * LAMPORTS_PER_SOL,
1 * LAMPORTS_PER_SOL,
);getExplorerLink
Get an explorer link for an address, block or transaction (tx works too).
getExplorerLink(
"address",
"dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8",
"mainnet-beta",
);Will return "https://explorer.solana.com/address/dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8". The cluster name isn't included since mainnet-beta is the default.
getExplorerLink(
"address",
"dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8",
"devnet",
);Will return "https://explorer.solana.com/address/dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8?cluster=devnet"
getExplorerLink("block", "241889720", "mainnet-beta");Will return "https://explorer.solana.com/block/241889720"
makeKeypairs
Particularly in tests, Solana developers often need to make multiple keypairs at once. So just:
const [alice, bob, tokenA, tokenB] = makeKeypairs(4);And you'll now have alice, bob, tokenA and tokenB as distinct keypairs.
confirmTransaction
Confirm a transaction, and also gets the recent blockhash required to confirm it.
await confirmTransaction(connection, transaction);getLogs
Get the logs for a transaction signature:
const logs = await getLogs(connection, transaction);The logs will be an array of strings, eg:
[
"Program 11111111111111111111111111111111 invoke [1]",
"Program 11111111111111111111111111111111 success",
];This a good way to assert your onchain programs returned particular logs during unit tests.
node.js specific helpers
getKeypairFromFile
Gets a keypair from a file - the format must be the same as Solana CLI uses, ie, a JSON array of numbers:
To load the default keypair ~/.config/solana/id.json, just run:
const keyPair = await getKeypairFromFile(file);or to load a specific file:
const keyPair = await getKeypairFromFile("somefile.json");or using home dir expansion:
const keyPair = await getKeypairFromFile("~/code/solana/demos/steve.json");getKeypairFromEnvironment
Gets a keypair from a secret key stored in an environment variable. This is typically used to load secret keys from env files.
const keypair = await getKeypairFromEnvironment("SECRET_KEY");addKeypairToEnvFile
Saves a keypair to the environment file.
await addKeypairToEnvFile(testKeypair, "SECRET_KEY");or to specify a file name:
await addKeypairToEnvFile(testKeypair, "SECRET_KEY", ".env.local");This will also reload the env file
Secret key format
Secret keys can be read in either the more compact base58 format (base58.encode(randomKeypair.secretKey);), like:
# A random secret key for demo purposes
SECRET_KEY=QqKYBnj5mcgUsS4vrCeyMczbTyV1SMrr7SjSAPj7JGFtxfrgD8AWU8NciwHNCbmkscbvj4HdeEen42GDBSHCj1NOr the longer, 'array of numbers' format JSON.stringify(Object.values(randomKeypair.secretKey));:
# A random secret key for demo purposes
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]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.
Development
To run tests - open a terminal tab, and run:
solana-test-validatorThen in a different tab, run:
npm run testThe tests use the node native test runner.