Skip to content

Instantly share code, notes, and snippets.

@haidoan
Created September 16, 2019 15:00
Show Gist options
  • Save haidoan/fb6729e2a2d5978bbaadfcea2dbc55a0 to your computer and use it in GitHub Desktop.
Save haidoan/fb6729e2a2d5978bbaadfcea2dbc55a0 to your computer and use it in GitHub Desktop.
const Web3 = require("web3");
const Tx = require("ethereumjs-tx");
const acct = "";
const receiver = "";
const chainId = 42;
const privateKey = new Buffer(
"PRIVATE_KEY",
"hex"
);
const web3 = new Web3(
new Web3.providers.HttpProvider(
"https://kovan.infura.io"
)
);
const sendRawTx = async function(_rawTx) {
return new Promise(function(resolve, reject) {
let tx = new Tx(_rawTx);
tx.sign(privateKey);
let serializedTx = tx.serialize();
console.log("send raw now");
web3.eth.sendSignedTransaction(
"0x" + serializedTx.toString("hex"),
(err, res) => {
if (!err) {
resolve(res);
} else {
if (
err.message ===
"Transaction with the same hash was already imported."
)
reject(
"Please wait for the recent transaction being mined before make another transaction"
);
else reject("Cant sendRawTrasaction, message : " + err.message);
}
}
);
});
};
const getTransactionCount = async function(address) {
return new Promise(function(resolve, reject) {
web3.eth.getTransactionCount(address, "latest", (err, res) => {
if (err) {
reject(err.message);
} else {
resolve(res);
}
});
});
};
async function sendEth(_toAddress, _amount, gasChosen) {
let txCount;
try {
txCount = await getTransactionCount(acct);
console.log('txCount :', txCount);
} catch (error) {
console.log("getTransactionCount fail:", txCount, error);
return {
error: error
};
}
// console.log('res ether :', txCount, _amount);
var rawTransaction = {
from: acct,
nonce: web3.utils.toHex(txCount),
gasPrice: parseInt(gasChosen),
gasLimit: 100000,
to: _toAddress,
value: _amount,
chainId
};
// console.log('rawTransaction: ', rawTransaction);
let withDrawEtherTx;
try {
withDrawEtherTx = await sendRawTx(rawTransaction);
console.log("withDrawEtherTx success:", withDrawEtherTx);
return withDrawEtherTx;
} catch (error) {
console.log("withDrawEtherTx fail:", withDrawEtherTx, error);
return {
error: error
};
}
}
const gas = 5 10 * 9;
function main() {
sendEth(receiver, 0, gas);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment