如何将帐户添加到 web3 对象?

How to add account to web3 object?

我有私钥,这是我访问账户的方式(币安智能链网络):

const web3 = new Web3('https://bsc-dataseed1.binance.org:443')
const account = await web3.eth.accounts.privateKeyToAccount(pk)

所以,我有帐户对象, { address: '0x...', privateKey: '0x...', signTransaction: [Function: signTransaction], sign: [Function: sign], encrypt: [Function: encrypt] }

我想在 BEP-20 令牌地址上使用 send() 方法:

const contract = new web3.eth.Contract(ABI, address)
const tx = await contract.methods.transfer(address, amount).send({
    from: account.address
})

但是我收到错误消息 Error: Returned error: unknown account

我是否必须在每笔交易上签名然后发送?

也许有一种方法可以让供应商为我签署交易?

怎么做?如何将帐户对象添加到 web3.eth.accounts ?

在这里:

const tx = await contract.methods.transfer(address, amount).send({
    from: account.address
})

您实际上是在请求与您通信的以太坊节点为您签署交易。

为了使其工作,您首先需要通过发送适当的请求解锁该节点上的指定帐户。

或者(可能更安全),您可以自己签署交易:

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));
}

顺便说一句,我觉得你试图将代币从你的账户转移到代币合约中很奇怪。