UNPKG

hardhat-secure-accounts

Version:
68 lines 2.87 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSecureAccounts = getSecureAccounts; exports.getSecureAccount = getSecureAccount; exports.accountExists = accountExists; exports.encryptAccount = encryptAccount; exports.decryptAccount = decryptAccount; exports.unlockAccount = unlockAccount; const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const ethers_1 = require("ethers"); const logger_1 = require("../helpers/logger"); const error_1 = require("../helpers/error"); const ask_1 = require("../helpers/ask"); function getSecureAccounts(accountsDir) { if (!fs_1.default.existsSync(accountsDir)) { return []; } return fs_1.default.readdirSync(accountsDir).map((a) => ({ name: path_1.default.parse(a).name, filename: path_1.default.join(accountsDir, a), json: fs_1.default.readFileSync(path_1.default.join(accountsDir, a), 'utf8'), })); } function getSecureAccount(accountsDir, name) { const accounts = getSecureAccounts(accountsDir); return accounts.find((a) => a.name === name); } function accountExists(accountsDir, name) { return getSecureAccount(accountsDir, name) !== undefined; } async function encryptAccount(accountsDir, name, password, mnemonic) { const wallet = mnemonic.length === 0 ? ethers_1.Wallet.createRandom() : ethers_1.Wallet.fromPhrase(mnemonic); const encrypted = await wallet.encrypt(password); if (!fs_1.default.existsSync(accountsDir)) { fs_1.default.mkdirSync(accountsDir); (0, logger_1.logDebug)(`Created accounts directory: ${accountsDir}`); } const fileName = path_1.default.join(accountsDir, `${name}.json`); fs_1.default.writeFileSync(fileName, encrypted, 'utf8'); (0, logger_1.logDebug)(`Saved account to ${fileName}`); return { name: name, filename: fileName, json: encrypted, }; } async function decryptAccount(account, password) { const wallet = await ethers_1.Wallet.fromEncryptedJson(account.json, password); (0, logger_1.logDebug)(`Account unlocked: ${wallet.address}`); if (!isHDNodeWallet(wallet) || wallet.mnemonic === null) { throw new error_1.SecureAccountsPluginError('Decrypted account is not valid!'); } return wallet.mnemonic.phrase; } async function unlockAccount(accountsDir, accountName, accountPassword) { const account = await (0, ask_1.getAccountOrAsk)(accountName, accountsDir); const password = await (0, ask_1.getPasswordOrAsk)(accountPassword); return await decryptAccount(account, password); } // typeguard function isHDNodeWallet(wallet) { return wallet.mnemonic !== undefined; } //# sourceMappingURL=account.js.map