From 1bd9b02904610707935953780113ee4bfc19b771 Mon Sep 17 00:00:00 2001 From: Sayantan Karmakar Date: Tue, 26 Apr 2022 14:52:40 +0530 Subject: [PATCH] added FileKeypair class --- ts/scripts/keypair.ts | 8 ++++++++ ts/src/fileKeypair.ts | 42 ++++++++++++++++++++++++++++++++++++++++++ ts/src/index.ts | 1 + 3 files changed, 51 insertions(+) create mode 100644 ts/scripts/keypair.ts create mode 100644 ts/src/fileKeypair.ts diff --git a/ts/scripts/keypair.ts b/ts/scripts/keypair.ts new file mode 100644 index 0000000..e6eed6b --- /dev/null +++ b/ts/scripts/keypair.ts @@ -0,0 +1,8 @@ +import { FileKeypair } from "../src"; + +const main = async () => { + const keypair = FileKeypair.loadOrGenerate("./test.json"); + console.log(keypair.keypair.publicKey.toString()); +}; + +main(); diff --git a/ts/src/fileKeypair.ts b/ts/src/fileKeypair.ts new file mode 100644 index 0000000..a490831 --- /dev/null +++ b/ts/src/fileKeypair.ts @@ -0,0 +1,42 @@ +import { Keypair } from "@solana/web3.js"; +import fs from "fs"; + +export class FileKeypair { + public filePath: string; + public keypair: Keypair; + + constructor(filePath: string, keypair: Keypair) { + this.filePath = filePath; + this.keypair = keypair; + } + + static load(filePath: string): FileKeypair { + const fileBuffer = fs.readFileSync(filePath); + const secretKey: number[] = JSON.parse(fileBuffer.toString()); + const keypair = Keypair.fromSecretKey(Uint8Array.from(secretKey)); + return new FileKeypair(filePath, keypair); + } + + static generate(filepath: string): FileKeypair { + const keypair = Keypair.generate(); + const secretKey = Array.from(keypair.secretKey); + fs.writeFileSync(filepath, JSON.stringify(secretKey)); + return new FileKeypair(filepath, keypair); + } + + static loadOrGenerate(filePath: string): FileKeypair { + let keypair: Keypair; + let secretKey: number[]; + try { + const fileBuffer = fs.readFileSync(filePath); + secretKey = JSON.parse(fileBuffer.toString()); + keypair = Keypair.fromSecretKey(Uint8Array.from(secretKey)); + } catch (e) { + keypair = Keypair.generate(); + secretKey = Array.from(keypair.secretKey); + fs.writeFileSync(filePath, JSON.stringify(secretKey)); + } + + return new FileKeypair(filePath, keypair); + } +} diff --git a/ts/src/index.ts b/ts/src/index.ts index 810219a..8e86045 100644 --- a/ts/src/index.ts +++ b/ts/src/index.ts @@ -1,3 +1,4 @@ export * from "./dex"; export * from "./coin"; export * from "./market"; +export * from "./fileKeypair";