added FileKeypair class

This commit is contained in:
Sayantan Karmakar 2022-04-26 14:52:40 +05:30
parent 3c3bb578f4
commit 1bd9b02904
3 changed files with 51 additions and 0 deletions

8
ts/scripts/keypair.ts Normal file
View File

@ -0,0 +1,8 @@
import { FileKeypair } from "../src";
const main = async () => {
const keypair = FileKeypair.loadOrGenerate("./test.json");
console.log(keypair.keypair.publicKey.toString());
};
main();

42
ts/src/fileKeypair.ts Normal file
View File

@ -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);
}
}

View File

@ -1,3 +1,4 @@
export * from "./dex";
export * from "./coin";
export * from "./market";
export * from "./fileKeypair";