Skip to content

Instantly share code, notes, and snippets.

@0xDeeep
Created September 29, 2023 17:08
Show Gist options
  • Select an option

  • Save 0xDeeep/8be9713fc14587a4576c9c4d96ae65ff to your computer and use it in GitHub Desktop.

Select an option

Save 0xDeeep/8be9713fc14587a4576c9c4d96ae65ff to your computer and use it in GitHub Desktop.

Revisions

  1. 0xDeeep created this gist Sep 29, 2023.
    29 changes: 29 additions & 0 deletions keypair_utils.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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}`);
    }
    };