I am trying to send some test ether on Ropsten network using Infura but I can not make a transaction. Code works locally with testrpc but not with Infura
var Web3 = require('web3');
var util = require('ethereumjs-util');
var tx = require('ethereumjs-tx');
var lightwallet = require('eth-lightwallet');
var txutils = lightwallet.txutils;
var web3 = new Web3(
new Web3.providers.HttpProvider('https://ropsten.infura.io/<token>')
//new Web3.providers.HttpProvider('http://localhost:8545')
);
var address = '0xadaD904F70ec8323fEd1734614d78D2145222322';
var address2 = '0x5858599f16c46fa33238313A412eE9f0491EBef3';
var key = '<KEY>';
var key2 = '<KEY>';
var amount = web3.toWei(1, "ether");
var balance = web3.eth.getBalance(address);
var value = web3.fromWei(balance, 'ether');
console.log(value);
function sendRaw(rawTx) {
var privateKey = new Buffer(key, 'hex');
var transaction = new tx(rawTx);
transaction.sign(privateKey);
var serializedTx = transaction.serialize().toString('hex');
web3.eth.sendRawTransaction(
'0x' + serializedTx, function(err, result) {
if(err) {
console.log('error');
console.log(err);
} else {
console.log('success');
console.log(result);
}
});
}
var rawTx = {
nonce: web3.toHex(web3.eth.getTransactionCount(address)),
gasLimit: web3.toHex(21000),
to: address2,
from:address,
value: web3.toHex(web3.toBigNumber(amount))
}
sendRaw(rawTx);
As you can notice I am logging ether on address but no matter how many times I send the transaction it stays eq to 1eth.
Any ideas what I am doing wrong?
Best Answer
This looks mostly correct, but there are a couple optional tx parameters that might make the difference:
Also, the
nonce
may need to be converted to hexadecimal. ThegetTransactionCount
method returns a javascript number, so you might need to convert that to hex first.I'd recommend also logging the parameters before you send it out. If you're connecting to a node that is not synchronized, your nonce could be wrong, and that would also fail these transactions.
I see you got one tx out, so that makes me think a wrong nonce could be blocking you. https://testnet.etherscan.io/tx/0x17c6e7e318a181cc729207ebe2bc203b4df71657b845aaf551892f20de42bc62