I'm trying to write a script that takes as input a JSON array where each element of the array has an address and a corresponding private key. I'd like to have a function that iterates through this array, checking the balance of each account and subsequently emptying it into an arbitrary external account.
However, when I run this function below, an error with no contents (undefined error) is returned. How can I figure out what's going wrong?
Here's my code, including sample input:
var Tx = require('ethereumjs-tx');
var wallets = [
{ _id: 5b898c5cda06f4c58c8aa59c,
address: '0x107396c9f484666d0C43F227FEd9f3d258576F37',
key:
'0x4482be4e4e36d5521d70dafa57818eed38a4d0c69562bffebf24901c3199b271' },
{ _id: 5b89a45918f5dbce22e9115f,
address: '0xB6125B6F5854547da1CF3B2CDe831cBEB7Ea31c0',
key:
'0x62305fc1c775f69603b1f378b5cd72815c102fb77d549d3364df7c9b53a0b444' } ]
var counter = 0;
var to = "0xa1cc63e76dc8dde54abf848810abd2680617b900";
var updatedBalance = 0;
var txHashes = [];
function iterateAndEmptyWallets(counter, wallets, updatedBalance, txHashes, to) {
if (counter >= wallets.length) {
return [updatedBalance, txHashes]
}
var addr = wallets[counter].address;
var key = wallets[counter].key;
web3.eth.getBalance(addr).then( (result) => {
result = parseInt(result, 10);
var gasLimit = 25000;
web3.eth.getGasPrice()
.then((gasPrice) => {
web3.eth.getTransactionCount(addr).then( (nonce) => {
var nonce = nonce.toString();
var valAfterGas = result - (gasPrice * gasLimit)
key = key.slice(2);
var rawTransaction = {
"from": addr,
"nonce": web3.utils.toHex(nonce),
"gasPrice": web3.utils.toHex(gasPrice),
"gasLimit": web3.utils.toHex(gasLimit),
"to": to,
"value": valAfterGas,
};
var privKey = Buffer.from(key, 'hex');
var tx = new Tx(rawTransaction);
tx.sign(privKey);
var serializedTx = tx.serialize();
updatedBalance += valAfterGas;
var transaction = web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
transaction.on('receipt', receipt => {
txHashes.push(receipt.transactionHash);
counter++;
iterateAndEmptyWallets(counter, wallets, updatedBalance, txHashes, to);
});
transaction.on('error', error => {
return error
});
});
});
});
}