const privateKeyStr = "";
const privateKey = new Buffer(privateKeyStr, 'hex');
const contractAddress = '0x';
const COO = '0x';
let contractAddress = '0x';
let myContract = ...;
//some other articles told use getData method , but getData is undefined. so is use request instead.
let payloadData = myContract.contractMethodName.request(methodParams).params[0].data;
let rawTx = {
nonce: web3.toHex(web3.eth.getTransactionCount(fromAccount)),
gas: web3.toHex("21000"),
gasPrice: web3.toHex(web3.eth.gasPrice.toNumber()),
gasLimit: web3.toHex(40000),
from: fromAccount,
to: contractAddress,
data: payloadData
};
var tx = new Tx(rawTx);
tx.sign(privateKey);
var serializedTx = '0x' + tx.serialize().toString('hex');
web3.eth.sendRawTransaction(serializedTx, function(err, hash) {
if (!err){
console.log('transaction hash : ',hash);
process.exit(0);
} else {
console.error('error is ',err);
process.exit(1);
}
});
3 Answers
Try this way.
var data = myContract.contractMethodName.getData(params, {from: senderAddr});
var gasPrice = 0.8; //var gasPrice = web3.eth.gasPrice;
var gasLimit = 3000000;
var rawTransaction = {
"from": senderAddr,
"nonce": web3.toHex(nonce),
"gasPrice": web3.toHex(gasPrice * 1e9),
"gasLimit": web3.toHex(gasLimit),
"to": contractAddress,
"value": "0x00",
"data": data,
"chainId": 4 //change the chainID accordingly
};
var privKey = new Buffer(privateKey, 'hex');
var tx = new Tx(rawTransaction);
tx.sign(privKey);
var serializedTx = tx.serialize();
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
if (!err)
{
console.log('Txn Sent and hash is '+hash);
}
else
{
console.error(err);
}
});
Reading the docs you should do this:
let payloadData = web3.sha3("contractMethodName()").substr(0,10);
Or if you have an argument
var argument = '0';
let payloadData = web3.sha3("contractMethodName(uint256)").substr(0,10);
payloadData += web3.sha3(argument).substr(0,32);
On web3js version 1 it's easy:
const data = contract.methods.contractMethodName(...params).encodeABI();
See the documentation here.
data
param withpayloadData
, instead ofgetData
.