Skip to content

Instantly share code, notes, and snippets.

@denniswon
Created September 21, 2019 20:43
Show Gist options
  • Save denniswon/1241bf6772196f21844e81ffc350565b to your computer and use it in GitHub Desktop.
Save denniswon/1241bf6772196f21844e81ffc350565b to your computer and use it in GitHub Desktop.
async sendTransaction(contractAddress, privateKey, from, to, amount, callback) {
let sendAmount = web3.utils.toWei(amount.toString(), 'ether')
const consumerContract = new web3.eth.Contract(config.erc20ABI, contractAddress);
const myData = consumerContract.methods.transfer(to, sendAmount).encodeABI();
const gasPriceGwei = 3;
const gasLimit = 3000000;
const [chainId, nonce] = await Promise.all([web3.eth.net.getId(), web3.eth.getTransactionCount(from, 'pending')]);
console.log('chainId: ' + chainId + ', nonce: ' + nonce);
const tx = {
from,
to: contractAddress,
gasPrice: web3.utils.toHex(gasPriceGwei * 1e9),
gasLimit: web3.utils.toHex(gasLimit),
value: '0x0',
gas: 0,
chainId: chainId,
nonce: nonce,
data: myData
}
const rawTx = new Tx.Transaction(tx, { chain: 'mainnet', hardfork: 'petersburg' });
const privKey = Buffer.from(privateKey, 'hex');
rawTx.sign(privKey);
const serializedTx = rawTx.serialize();
console.log(`Attempting to send signed tx: ${serializedTx.toString('hex')}\n------------------------`);
const receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'),
function (err, hash) {
if (err) {
callback(err, null)
}
callback(null, hash.toString())
})
console.log(receipt)
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment