Skip to content

Instantly share code, notes, and snippets.

@afope
Last active June 6, 2020 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afope/74254f8300f6d9e90120bc7f6095f29a to your computer and use it in GitHub Desktop.
Save afope/74254f8300f6d9e90120bc7f6095f29a to your computer and use it in GitHub Desktop.
Send a transaction
// require dependencies
const Web3 = require('web3');
const EthTx = require('ethereumjs-tx').Transaction;
// assign address and private key to account
const account = {
address: 'YOUR_ETHEREUM_ADDRESS_GOES_HERE', // Your address goes here
privateKey: 'YOUR_PRIVATE_KEY_GOES_HERE' // Your private key goes here
};
const rpcURL = 'YOUR_URL_GOES_HERE'; // Your RPC URL goes here
const username = 'YOUR_USERNAME_GOES_HERE'; // your BLOCKCHAIN GATEWAY username goes here
const password = 'YOUR_PASSWORD_GOES_HERE'; // your BLOCKCHAIN GATEWAY password goes here
let creds = username + ':' + password;
const secURL = 'https://' + creds + '@' + rpcURL;
const provider = new Web3.providers.HttpProvider(secURL);
const web3 = new Web3(provider);
const transact = async () => {
const txnCount = await web3.eth.getTransactionCount(account.address);
const rawTx = {
nonce: web3.utils.toHex(txnCount),
gasLimit: web3.utils.toHex(21008),
gasPrice: web3.utils.toHex(web3.utils.toWei('100', 'gwei')),
to: account.address,
value: '0x00'
};
// sign and serialize the transaction
const tx = new EthTx(rawTx, {chain: 'ropsten'});
const privKey = Buffer.from(account.privateKey, 'hex');
tx.sign(privKey);
let serializedTx = tx.serialize();
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.once('transactionHash', console.log)
.on('receipt', console.log)
.on('error', err => console.error(err))
.catch((err) => console.log);
};
transact();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment