-
-
Save denniswon/1241bf6772196f21844e81ffc350565b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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