Skip to content

Commit

Permalink
added importWallet() using privatekey
Browse files Browse the repository at this point in the history
  • Loading branch information
CaptainLEVI-XXX committed Dec 5, 2023
1 parent b5ec9dc commit dc74834
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 5 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
- Added method to sign Typed Data (EIP-712)
- Added importWallet() to import account using privateKey.
36 changes: 32 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down Expand Up @@ -463,7 +491,7 @@ class KeyringController extends EventEmitter {
throw err
}
}

}

module.exports = { KeyringController}
module.exports = { KeyringController }
7 changes: 7 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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")
})
})

0 comments on commit dc74834

Please sign in to comment.