Created
September 29, 2023 17:08
-
-
Save 0xdeepmehta/8be9713fc14587a4576c9c4d96ae65ff to your computer and use it in GitHub Desktop.
Read and write keypair in jsonfile anchor solana
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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