Skip to content

Instantly share code, notes, and snippets.

@sanjukurian
Created January 31, 2019 07:11
Show Gist options
  • Save sanjukurian/642f03bb660b4f6d0f8978b25237e7a8 to your computer and use it in GitHub Desktop.
Save sanjukurian/642f03bb660b4f6d0f8978b25237e7a8 to your computer and use it in GitHub Desktop.
Create ETH wallet, make transaction, get balance etc using infura
import Web3 from 'Web3'
var Tx = require('ethereumjs-tx');
const web3 = new Web3(`https://rinkeby.infura.io/v3/` + config.infura_api_key);
const createWallet = async () => {
try {
web3.eth.accounts.create((err, createdAcc) => {
if (err === null)
return {success: true, data: {
addr: createdAcc.address,
privateKey1: createdAcc.privateKey.substr(2),
privateKey2: createdAcc.privateKey.substr(2)
}};
else throw {success: false, error: {message: "Wallet not created", stack: err}};
})
} catch (e) {
console.log(e);
return e;
}
};
const getWallet = async (walletId) => {
try {
web3.eth.getBalance(walletId, (err, balance) => {
if (err === null)
return {success: true, data: {balance: web3.utils.fromWei(balance, 'ether'), address: walletId}};
else throw {success: false, error: {message: "Unable to fetch Balance", stack: err}}
});
} catch (ex) {
console.log(ex);
return ex;
}
};
const send = async (address, receiver, amount, pvKey) => {
try {
var privateKey = Buffer.from(pvKey, 'hex');
web3.eth.getTransactionCount(address, (err, txnCount) => {
if (!err) {
const txObject = {
nonce: web3.utils.toHex(txnCount),
to: receiver,
value: web3.utils.toHex(web3.utils.toWei(amount, 'ether')),
gasLimit: web3.utils.toHex(21000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
};
const tx = new Tx(txObject);
tx.sign(privateKey);
const serializedTx = tx.serialize();
const raw = '0x' + serializedTx.toString('hex');
web3.eth.sendSignedTransaction(raw, (err, txnHash) => {
if (!err)
return {success: true, data: {txn: txnHash}};
else throw {success: false, error: {message: "Unable to transfer", stack: err}}
})
} else throw {success: false, error: {message: "Unable to get nounce", stack: err}}
});
} catch (ex) {
console.error(ex);
return ex;
}
};
const getTxnDetails = async (txn) => {
try {
web3.eth.getTransactionReceipt(txn, (err, reciept) =>{
if(!err)
return {success: true, data:{receipt:reciept}};
else throw {success: false, error:{message: "Unable to find transaction", stack:err}}
})
} catch (ex) {
console.log(ex);
return ex;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment