I am new to learning Solana development. Is there any way to retrieve the keypair from a Filesystem path? I am doing a tutorial and I want to use the same keypair to sign transactions, instead of creating each time a new one.
1 Answer
Here's a reference that you can adapt. It generates a .env
file with a new keypair if one does not already exist, otherwise it creates the keypair from the file.
export async function initializeKeypair(
connection: web3.Connection
): Promise<web3.Keypair> {
if (!process.env.PRIVATE_KEY) {
console.log("Creating .env file")
const signer = web3.Keypair.generate()
fs.writeFileSync(".env", `PRIVATE_KEY=[${signer.secretKey.toString()}]`)
await airdropSolIfNeeded(signer, connection)
return signer
}
const secret = JSON.parse(process.env.PRIVATE_KEY ?? "") as number[]
const secretKey = Uint8Array.from(secret)
const keypairFromSecretKey = web3.Keypair.fromSecretKey(secretKey)
await airdropSolIfNeeded(keypairFromSecretKey, connection)
return keypairFromSecretKey
}
airdropSolIfNeeded
is just a helper function to airdrop devnet SOL
async function airdropSolIfNeeded(
signer: web3.Keypair,
connection: web3.Connection
) {
const balance = await connection.getBalance(signer.publicKey)
console.log("Current balance is", balance / web3.LAMPORTS_PER_SOL)
if (balance < web3.LAMPORTS_PER_SOL) {
console.log("Airdropping 1 SOL...")
const airdropSignature = await connection.requestAirdrop(
signer.publicKey,
web3.LAMPORTS_PER_SOL
)
const latestBlockHash = await connection.getLatestBlockhash()
await connection.confirmTransaction(
{
blockhash: latestBlockHash.blockhash,
lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
signature: airdropSignature,
},
"finalized"
)
const newBalance = await connection.getBalance(signer.publicKey)
console.log("New balance is", newBalance / web3.LAMPORTS_PER_SOL)
}
}
From this template: https://github.com/Unboxed-Software/solana-npx-client-template/tree/with-keypair-env