ethersService.js
1 import { ethers } from "ethers"; 2 import crypto from "crypto"; 3 4 export class EthersService { 5 constructor(fsService, configService, osService, shellService) { 6 this.fs = fsService; 7 this.configService = configService; 8 this.os = osService; 9 this.shell = shellService; 10 } 11 12 getOrCreateEthKey = () => { 13 const paths = this.configService.getEthFilePaths(); 14 15 if (!this.fs.isFile(paths.key)) { 16 this.generateAndSaveKey(paths); 17 } 18 19 const address = this.fs.readFile(paths.address); 20 21 return { 22 privateKeyFilePath: paths.key, 23 addressFilePath: paths.address, 24 address: address, 25 }; 26 }; 27 28 generateAndSaveKey = async (paths) => { 29 const keys = this.generateKey(); 30 this.fs.writeFile(paths.key, keys.key); 31 this.fs.writeFile(paths.address, keys.address); 32 33 if (this.os.isWindows()) { 34 const username = this.os.getUsername(); 35 this.shell.run(`icacls ${paths.key} /inheritance:r >nul 2>&1`); 36 this.shell.run(`icacls ${paths.key} /grant:r ${username}:F >nul 2>&1`); 37 this.shell.run(`icacls ${paths.key} /remove SYSTEM >nul 2>&1`); 38 this.shell.run(`icacls ${paths.key} /remove Administrators >nul 2>&1`); 39 } else { 40 this.shell.run(`chmod 600 "${paths.key}"`); 41 } 42 }; 43 44 generateKey = () => { 45 var id = crypto.randomBytes(32).toString("hex"); 46 var privateKey = "0x" + id; 47 var wallet = new ethers.Wallet(privateKey); 48 return { 49 key: privateKey, 50 address: wallet.address, 51 }; 52 }; 53 }