Last active
January 30, 2022 05:46
-
-
Save VagrantPi/fb373c909c118fb642483fdce739dde7 to your computer and use it in GitHub Desktop.
監聽 ETH 錢包,有錢轉進來,立馬轉走
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require("log-timestamp"); | |
const ethers = require("ethers"); | |
// mainnet | |
chainId = 1 | |
// Infura apikey | |
apikey = "" | |
fromPrivateKey = "" | |
fromAddress = "" | |
toAddress = "" | |
const privateKey = (fromPrivateKey).toString('hex'); | |
const wallet = new ethers.Wallet(privateKey); | |
const address = wallet.address; | |
const init = async function () { | |
const provider = new ethers.providers.InfuraWebSocketProvider(chainId, apikey); | |
filter = { | |
address: toAddress | |
} | |
provider.on("block", async(blockNumber) => { | |
console.log("blockNumber", blockNumber); | |
block = await provider.getBlock(blockNumber) | |
for (let i = 0; i < block.transactions.length; i++) { | |
const txhash = block.transactions[i]; | |
provider.getTransaction(txhash).then(async (transaction) => { | |
if (transaction.to == fromAddress) { | |
console.log(`fromAddress ${transaction.to} receive ${transaction.value.toString()}`); | |
allBalance = await provider.getBalance(fromAddress); | |
console.log('allBalance', allBalance); | |
let nonce = await provider.getTransactionCount(address); | |
let feeData = await provider.getFeeData(); | |
console.log("Fee Data:", feeData); | |
gasLimit = await provider.estimateGas({ | |
to: toAddress, | |
// `function deposit() payable` | |
data: "0xd0e30db0", | |
}); | |
price = feeData.maxFeePerGas.mul(gasLimit) | |
const tx = { | |
type: 2, | |
nonce: nonce, | |
to: toAddress, // Address to send to | |
maxPriorityFeePerGas: feeData["maxPriorityFeePerGas"], // Recommended maxPriorityFeePerGas | |
maxFeePerGas: feeData["maxFeePerGas"], // Recommended maxFeePerGas | |
value: allBalance.sub(price), | |
gasLimit, // basic transaction costs exactly 21000 | |
chainId, | |
}; | |
console.log("Transaction Data:", tx); | |
const signedTx = await wallet.signTransaction(tx); | |
console.log("Signed Transaction:", signedTx); | |
const txHash = ethers.utils.keccak256(signedTx); | |
console.log("Precomputed txHash:", txHash); | |
console.log(`https://etherscan.io/tx/${txHash}`); | |
provider.sendTransaction(signedTx) | |
.then(console.log) | |
.catch(e => { | |
console.log('e', e); | |
}) | |
} | |
}); | |
} | |
}) | |
}; | |
init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment