Skip to content

Instantly share code, notes, and snippets.

@nodlAndHodl
Created January 31, 2022 03:53
Show Gist options
  • Save nodlAndHodl/45fd144730209bea630abc52833ea780 to your computer and use it in GitHub Desktop.
Save nodlAndHodl/45fd144730209bea630abc52833ea780 to your computer and use it in GitHub Desktop.
const Web3 = require('web3');
const url = 'http://localhost:8545'; //ganache-cli rpc
let web3 = new Web3(new Web3.providers.HttpProvider(url));
const EthereumTx = require('ethereumjs-tx').Transaction
web3.eth.getAccounts().then(accounts => {
//sending eth using the sendTransaction.
web3.eth.personal.sendTransaction({
from: accounts[1],
gasPrice: "20000000000",
gas: "21000",
to: accounts[3],
value: "1000000000000000000",
data: ""
}, ).then(
web3.eth.getBalance(accounts[3]).then(balance => {
console.log(web3.utils.fromWei(balance, 'ether'));
})
);
});
let sendingAddress = '0x810614B66497f9Cf4788e50e27E690C6f4c3ab90';
let receivingAddress = '0xf293d70BDF8d2370f7Bd150c4EcAf76d977A5928';
let privKeySender = '32f95d7667f9b4a0a8bc8bd94e74c1a8b863114167431737ba1d26f50be9bc6f';
//sending a signed transaction using the private key from address.
web3.eth.accounts.signTransaction({
nonce: web3.eth.getTransactionCount(sendingAddress),
to: receivingAddress,
value: '1000000000',
gas: 2000000
}, privKeySender )
.then(data =>{console.log('data', data)});
//Using the Ethereum-tx library to sign and send transaction. Raw txn details are in hex vals
let privKeySenderHex = new Buffer.from(privKeySender, 'hex');
const rawTxn = {
nonce: '0x9',
gasPrice: '0x4a717c800',
gasLimit: '0xc340',
to: receivingAddress,
value: '0x2386f26fc10000',
data: '0x'
};
var txn = new EthereumTx(rawTxn)
txn.sign(privKeySenderHex);
const serializedTxn = txn.serialize();
web3.eth.sendSignedTransaction(serializedTxn);
web3.eth.getBalance(receivingAddress).then(balance => {
console.log(web3.utils.fromWei(balance, 'ether'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment