i have private key and this is how i access account (Binance Smart Chain network):
const web3 = new Web3('https://bsc-dataseed1.binance.org:443')
const account = await web3.eth.accounts.privateKeyToAccount(pk)
So, i have account object,
{ address: '0x...', privateKey: '0x...', signTransaction: [Function: signTransaction], sign: [Function: sign], encrypt: [Function: encrypt] }
I want to send() method on BEP-20 token address:
const contract = new web3.eth.Contract(ABI, address)
const tx = await contract.methods.transfer(address, amount).send({
from: account.address
})
But i am getting error Error: Returned error: unknown account
Do i have to sign each transaction and then send it?
Maybe there is a way when provider signs transaction for me?
How to do it? How to add account object to web3.eth.accounts ?
In here:
const tx = await contract.methods.transfer(address, amount).send({
from: account.address
})
You are essentially asking the Ethereum node that you're communicating with, to sign the transaction for you.
In order for this to work, you first need to unlock the specified account on that node, by sending an appropriate request.
Alternatively (and probably more securely), you can sign the transaction yourself:
async function signAndSend(web3, account, gasPrice, transaction, value = 0) {
while (true) {
try {
const options = {
to : transaction._parent._address,
data : transaction.encodeABI(),
gas : await transaction.estimateGas({from: account.address, value: value}),
gasPrice: gasPrice,
value : value,
};
const signed = await web3.eth.accounts.signTransaction(options, account.privateKey);
const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
return receipt;
}
catch (error) {
console.log(error.message);
}
}
}
async function yourFunc(web3, account, gasPrice, address, amount) {
const contract = new web3.eth.Contract(ABI, address)
const receipt = await signAndSend(web3, account, gasPrice, contract.methods.transfer(address, amount));
}
BTW, I find it quite odd that you are trying to transfer tokens from your account into the Token contract.