7

This is the code i'm using to send payment from one address to another. But why do i get this error? TypeError: web3.eth.sendRawTransaction is not a function

Here is the code im using

var Web3 = require('web3');
var Tx = require('ethereumjs-tx');
// Show Web3 where it needs to look for a connection to Ethereum.
//web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545'));
web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/N6IIa2HvDYOovtgmPbhD'));
var gasPrice = "2";//or get with web3.eth.gasPrice
var gasLimit = 3000000;
var addr = "0x......................";
var toAddress = "0x..............................";
var amountToSend = "0.00192823123348952"; //$1
var nonce = web3.eth.getTransactionCount(addr); //211;
var rawTransaction = {
"from": addr,
"nonce": web3.utils.toHex(nonce),
"gasPrice": web3.utils.toHex(gasPrice * 1e9),
"gasLimit": web3.utils.toHex(gasLimit),
"to": toAddress,
"value": amountToSend ,
"chainId": 1 //remember to change this
};
var privateKey = ".........................................................";
var privKey = new Buffer(privateKey, 'hex');
console.log("privKey  : ", privKey);
var tx = new Tx(rawTransaction);
tx.sign(privKey);
var serializedTx = tx.serialize();
console.log('serializedTx : '+serializedTx);
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
if (!err)
{
console.log('Txn Sent and hash is '+hash);
}
else
{
console.error(err);
}
});
shawn
  • 399
  • 2
  • 8
  • 14

1 Answers1

15

You are using web3 v1.0. The method was renamed to sendSignedTransaction.

const tx = new Tx(rawTx);
tx.sign(privateKey);

const serializedTx = `0x${tx.serialize().toString('hex')}`;

web3.eth.sendSignedTransaction(serializedTx);
Ismael
  • 30,570
  • 21
  • 53
  • 96
  • 1
    why do i get this error? (node:27384) UnhandledPromiseRejectionWarning: Error: Returned error: invalid sender – shawn Mar 25 '18 at 07:02
  • if i change chainId to 1 then i get this error Error: Returned error: insufficient funds for gas * price + value – shawn Mar 25 '18 at 07:15
  • @shawn It is better to create a new question for these other issues. – Ismael Mar 25 '18 at 14:58
  • Thank you very much Ismael, I posted a new question as you suggested :-) – shawn Mar 26 '18 at 09:20
  • 1
    @shawn have u got the answer for that error if yes please send the link where u have asked that question because i also have the same problem. – veeresh kumbar Apr 14 '18 at 07:29
  • @veereshkumbar If you are still in same problem, i can give you working code that is working fine for me – shawn May 16 '18 at 13:11
  • @veereshkumbar If you have a problem try searching in the responses, or if you found none try asking a new question adding all the relevant information like the code you used, sometimes the error is very small like a missing '0x' and without the code is hard to find. – Ismael May 16 '18 at 18:18