0

I need to check the balance of several addresses for the presence of erc20 tokens, if the balance is not empty, send eth there and forward this balance to the resulting address. But in the end, I get an error: private key should be a Buffer on the line transaction.sign (keys [k])

let foreth = ["addr1", "addr2"];
let keys = [Buffer.from('keyaddr1', 'hex'),Buffer.from('keyaddr2', 'hex')]

foreth.forEach(async function(recipient, i) {
    const balance = await contractInstance.methods.balanceOf(recipient).call(function(err, result) {


        if (result > 0) {


                web3.eth.getTransactionCount(fromAddress)
                    .then((count) => {
                        let rawTransaction = {
                            'from': fromAddress,
                            'gasPrice': web3.utils.toHex(20 * 1e9),
                            'gasLimit': web3.utils.toHex(21000),
                            'to': recipient,
                            'value': web3.utils.toHex(web3.utils.toWei("0.0002")),
                            'nonce': web3.utils.toHex(count + i)
                        }

                        let transaction = new Tx(rawTransaction)
                        transaction.sign(privateKey)
                        return new Promise((resolve, reject) => {
                            web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
                                .on('transactionHash', console.log)
                                .on('receipt', resolve)
                                .on('error', reject)
                        })
                    }).then(receipt => {
                        console.log("status success")
                        for (var k = 0; k < keys.length; k++) {
                         web3.eth.getTransactionCount(recipient)
                        .then((count) => {
                            let rawTransaction = {
                                'from': recipient,
                                'gasPrice': web3.utils.toHex(20 * 1e9),
                                'gasLimit': web3.utils.toHex(200000),
                                'to': tokenAddress,
                                'value': 0x0,
                                'data': contract.methods.transfer(fromAddress, web3.utils.toHex(result)).encodeABI(),
                                'nonce': web3.utils.toHex(count+i)
                            }
                            let transaction = new Tx(rawTransaction)
                            transaction.sign(keys[k])
                            web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
                                .on('transactionHash', console.log)

                            .on('error', console.log)   

                        })    
                    }
                    })

        }
    })
})
0

2 Answers 2

1

Change this:

var privateKey = Buffer.from('abcde', 'hex')

let transaction = new Tx(rawTransaction)
transaction.sign(keys[k])
web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
...

To this:

var privateKey ='abcde'

web3.eth.accounts.signTransaction(rawTransaction, privateKey).then(signedTx => {
           web3.eth.sendSignedTransaction(signedTx);
    ...
})
7
  • error: UnhandledPromiseRejectionWarning: TypeError: privateKey.startsWith is not a function
    – Ayurpwnz
    Dec 8, 2019 at 8:35
  • @Ayurpwnz: You should be more specific (also in your question), and indicate exactly which line of code gives you this error. If you're not sure, then please debug your code and find out. The fix that I suggested is for the last part in your code, there could be other fixes required as well. Dec 8, 2019 at 9:10
  • so I wrote: error: private key should be a Buffer on the line transaction.sign (keys [k])
    – Ayurpwnz
    Dec 8, 2019 at 13:24
  • @Ayurpwnz: And I explained that you should get rid of that line. Have you missed that in my answer??? Dec 8, 2019 at 14:50
  • Sorry, I misunderstood you, the error with your fragment is in the modules: (C: \ Users \ Admin \ node_modules \ web3-eth-accounts \ src \ index.js: 220: 28 ) at C: \ Users \ Admin \ node_modules \ web3-eth-accounts \ src \ index.js: 272: 16 at processTicksAndRejections (internal / process / task_queues.js: 93: 5) (node: 9316) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch (). (rejection id: 44)
    – Ayurpwnz
    Dec 8, 2019 at 15:34
0

Change the below

      const Tx = require('ethereumjs-tx').Transaction;

      var transaction_data = {
        "from": myAddress,
        "gasPrice": web3.utils.toHex(20 * 1e9),
        "gasLimit": web3.utils.toHex(210000),
        "to": contractAddress,
        "value": "0x0",
        "data": contract.methods.safeTransferFrom(myAddress, toAddress, tokenId).encodeABI(),
      }

        var privateKey = Buffer.from('abcde', 'hex')

        var transaction = new Tx(transaction_data,{ chain: 'ropsten' , hardfork: 'petersburg' });

        transaction.sign(privateKey);

        web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
            .on('transactionHash', console.log);

to the below

      const Tx = require('ethereumjs-tx').Transaction;

      var transaction_data = {
        "from": myAddress,
        "gasPrice": web3.utils.toHex(20 * 1e9),
        "gasLimit": web3.utils.toHex(210000),
        "to": contractAddress,
        "value": "0x0",
        "data": contract.methods.safeTransferFrom(myAddress, toAddress, tokenId).encodeABI(),
      }

        var privateKey ='abcde'

        web3.eth.accounts.signTransaction(transaction_data, privateKey)
        .then(function(value){
            web3.eth.sendSignedTransaction(value.transaction_data)
            .then(function(response){
              console.log("response:" + JSON.stringify(response, null, ' '));
            })
          })

web3.eth.accounts.signTransaction will take the burden of including the correct chainId and nonce . Reference: https://github.com/ChainSafe/web3.js/issues/1040

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.