Skip to content

Instantly share code, notes, and snippets.

@0xdeepmehta
Created September 29, 2023 17:08
Show Gist options
  • Save 0xdeepmehta/8be9713fc14587a4576c9c4d96ae65ff to your computer and use it in GitHub Desktop.
Save 0xdeepmehta/8be9713fc14587a4576c9c4d96ae65ff to your computer and use it in GitHub Desktop.
Read and write keypair in jsonfile anchor solana
import * as fs from 'fs/promises';
import * as path from 'path';
const writeKeypairToFile = async (sk: Uint8Array, fileName: string): Promise<void> => {
const filePath = path.join('tests/keys', `${fileName}.json`);
try {
await fs.writeFile(filePath, JSON.stringify(Array.from(sk)));
console.log(`Keypair written to file: ${filePath}`);
} catch (error) {
console.error(`Error writing keypair to file: ${(error as Error).message}`);
}
};
const readKeypairToFile = async (fileName: string): Promise<anchor.web3.Keypair | undefined> => {
const filePath = path.join('tests/keys', `${fileName}.json`);
try {
const raw = await fs.readFile(filePath);
const formattedData = JSON.parse(raw.toString());
const keypair = anchor.web3.Keypair.fromSecretKey(Uint8Array.from(formattedData));
console.log(keypair.publicKey.toString());
return keypair
} catch (error) {
console.error(`Error reading keypair from file: ${(error as Error).message}`);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment