6

Trying to send a transaction with web3 on ropsten. The code runs on Remix, but now I'm trying to send it via the node console. It connects fine too(web3 works), but for some reason the transaction never gets sent. I'd love some feedback on my code

const Web3 = require("web3");
const solc = require("solc");
const Tx = require('ethereumjs-tx')
const web3 = new Web3(new 
    Web3.providers.HttpProvider("https://ropsten.infura.io"));


    var account1= "0xE5078b80b08bD7036fc0f7973f667b6aa9B4ddBE";
    var key1 = new Buffer('xxxx_validprivatekey_xxxx', 'hex')

var abi = huge_abi
var bytecode = huge_bytecode


var Contract = web3.eth.contract(abi)

const gasPrice = web3.eth.gasPrice;
const gasPriceHex = web3.toHex(gasPrice);
const gasLimitHex = web3.toHex(3000000);

var nonceval = '0x' + new Date().getTime();

var fTx = {
    nonce: nonceval,
    gasPrice: gasPriceHex,
    gasLimit: gasLimitHex,
    data: bytecode,
    from: account1
};

var txx = new Tx(fTx);
txx.sign(key1);

var sTx =txx.serialize();


web3.eth.sendRawTransaction('0x' + sTx.toString('hex'), (err, hash) => {
    if (err) { console.log(err); return; }

    // Log the tx, you can explore status manually with eth.getTransaction()
    console.log('contract creation tx: ' + hash);
});
  • 1
    The nonce of a transaction is equal to the numbers of transactions of the from account, use const nonceval = web3.eth.getTransactionCount(account). – Ismael Aug 6 '17 at 9:09
  • Any chance your code allows to send a signed tx to deploy a smart contract? I'm having a lot of trouble to create the data property (put the parameter of the contructor). – Florian Castelain Jan 16 '18 at 11:33
  • It should work the same way. But this way works really well too: github.com/ethereum/wiki/wiki/JavaScript-API#web3ethcontract – thefett Jan 16 '18 at 20:15
6

As outlined here a nonce

"is just a sequential number tied to every transaction that represents the number of transactions the sender account has made on the network"

.

You have used an arbitrary value defined by yourself, and thus the transaction signature will be invalid. The transaction will thus not be mined.

As mentioned by Ismael, you can use web3.eth.getTransactionCount(0xaddress) to get the current transaction count/nonce value.

If there are further issues, what response (if any) do you get?

  • Thanks, works now. I don't know where I cut that nonceval thing from, but I guess actually understanding it would have been a better way to go – thefett Aug 8 '17 at 1:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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