How to use ethereumjs-wallet with web3
Oct 28, 2021
When i was developing Ethereum React Native wallet app, i use web3 to transfer tokens from sender to receiver. I keep getting this error:
“Returned error: unknown account”
The root cause is the wallet account created from ethereumjs-wallet is not recognised by web3.
The solution is to link ethereumjs-wallet account to web3.
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(account);
After that, you can use the ERC20 transfer method to send tokens from sender to receiver.
const amountAdj = (amount * 10 ** contractDecimal).toFixed(0)
const recipientAddr = web3.utils.toChecksumAddress(payee)
const senderAddr = web3.utils.toChecksumAddress(sender)const boolResult = await contract.methods.transfer(
recipientAddr,
amountAdj
)
.send({from: senderAddr, gas: 2000000})
Note:
The below code of adding to wallet will not work because it is not adding the complete account object.
web3.eth.accounts.wallet.add
({
privateKey: pk,
address: addr
});
Alright. Hope it helps.