From dc748343948846042006421fc1aaa2075577b3c4 Mon Sep 17 00:00:00 2001 From: saurabh Date: Tue, 5 Dec 2023 18:57:47 +0530 Subject: [PATCH] added importWallet() using privatekey --- CHANGELOG.md | 3 ++- src/index.js | 36 ++++++++++++++++++++++++++++++++---- test/index.js | 7 +++++++ 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93c4f9b..bec81c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,4 +8,5 @@ - Added method to export the private key of an address - Added method to sign a transaction - Added method to sign a message -- Added method to sign Typed Data (EIP-712) \ No newline at end of file +- Added method to sign Typed Data (EIP-712) +- Added importWallet() to import account using privateKey. \ No newline at end of file diff --git a/src/index.js b/src/index.js index 51b13b6..ddd9d84 100644 --- a/src/index.js +++ b/src/index.js @@ -225,13 +225,41 @@ class KeyringController extends EventEmitter { } catch (e) { return Promise.reject(e) } - } + } + /** + * + * @param {string} _privateKey - Private key of the account to be imported + * @returns {string} - Address of the imported account + */ + importWallet(_privateKey) { + try { + if (_privateKey.startsWith('0x')) { + _privateKey = _privateKey.slice(2) + } + const privateKey = Buffer.from(_privateKey, 'hex') + if (!ethUtil.isValidPrivate(privateKey)) + throw "Enter a valid private key" + + const address = ethUtil.bufferToHex(ethUtil.privateToAddress(privateKey)) + this.importedWallets.push(address); + return address + } catch (e) { + return Promise.reject(e) + } + } // // SIGNING METHODS // - + async sign(rawTx, privateKey, web3) { + let signedTx; + if (typeof rawTx === 'string') + signedTx = await web3.eth.accounts.sign(rawTx, privateKey); + else + signedTx = await web3.eth.accounts.signTransaction({ ...rawTx, gas: await web3.eth.estimateGas(rawTx) }, privateKey) + return signedTx + } /** * Sign Message * @@ -463,7 +491,7 @@ class KeyringController extends EventEmitter { throw err } } - + } -module.exports = { KeyringController} \ No newline at end of file +module.exports = { KeyringController } \ No newline at end of file diff --git a/test/index.js b/test/index.js index f18985b..bfc7a7d 100644 --- a/test/index.js +++ b/test/index.js @@ -88,4 +88,11 @@ describe('Initialize wallet ', () => { const acc = await baseKeyring.getAccounts() console.log("acc ", acc) }) + + it("Should import correct account ", async () => { + const address = await baseKeyring.importWallet(EXTERNAL_ACCOUNT_PRIVATE_KEY) + console.log("address : ",address); + assert(address.toLowerCase() === EXTERNAL_ACCOUNT_ADDRESS.toLowerCase(), "Wrong address") + assert(baseKeyring.importedWallets.length === 1, "Should have 1 imported wallet") + }) })