【问题标题】:How to add account to web3 object?如何将帐户添加到 web3 对象?
【发布时间】:2022-01-03 08:35:21
【问题描述】:

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

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 中?

【问题讨论】:

    标签: solidity web3js binance binance-smart-chain bsc


    【解决方案1】:

    在这里:

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

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

    【讨论】:

    • 其实我不是,只是编辑了那部分:D 感谢您的回答
    猜你喜欢
    • 2018-01-14
    • 1970-01-01
    • 2014-09-14
    • 2023-01-19
    • 2014-06-28
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    相关资源
    最近更新 更多