I'm developing a very simple React application wherein a user clicks a button and some ether gets sent from one account to another. Currently, the onClick sendEther function crafts a proper signed serialized transaction and (oftentimes) returns a transaction hash. However, the transaction never actually goes through to the Rinkeby test network (as accessed via Etherscan).
My hunch is that that I'm misusing infura (which I set up in my DOMContentLoaded event, see below).
//1. Set up
document.addEventListener('DOMContentLoaded', () => {
const endpoint = 'https://rinkeby.infura.io/APIKEY';
window.web3 = new Web3(new Web3.providers.HttpProvider(endpoint));
});
//2. React front end component.
sendEther() {
const fromAccount = **acct1**;
const toAccount = **acct2**;
const rawTransaction = this.makeRawTransaction(fromAccount, toAccount);
const signedTransaction = this.makeSignedTransaction(rawTransaction);
const serializedTransaction = `0x${signedTransaction.serialize().toString('hex')}`;
window.web3.eth.sendSignedTransaction(serializedTransaction, (error, result) => {
if(!error) {
console.log(`Transaction hash is: ${result}`);
this.setState({
etherscanUrl: `https://rinkeby.etherscan.io/tx/${result}`,
error: null
});
} else {
this.setState({ error: error.message })
console.error(error);
}
});
}
makeSignedTransaction(rawTransaction) {
const privateKey = '**************';
const privateKeyX = new Buffer(privateKey, 'hex');
const transaction = new EthTx(rawTransaction);
transaction.sign(privateKeyX);
return transaction;
}
makeRawTransaction(fromAccount, toAccount) {
const { exchangeRate } = this.props;
const amount = (1 / exchangeRate) * 5;
return ({
nonce: window.web3.utils.toHex(window.web3.eth.getTransactionCount(fromAccount)),
to: toAccount,
gasPrice: window.web3.utils.toHex(100000000000),
gasLimit: window.web3.utils.toHex(100000),
value: window.web3.utils.toHex(window.web3.utils.toWei(`${amount}`, 'ether')),
data: ''
});
}