-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathfrontrun.js
73 lines (64 loc) · 2.78 KB
/
frontrun.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// provider.on("pending", listener)
import { ethers, utils } from "ethers";
// 1. 创建provider
var url = "http://127.0.0.1:8545";
const provider = new ethers.providers.WebSocketProvider(url);
let network = provider.getNetwork()
network.then(res => console.log(`[${(new Date).toLocaleTimeString()}] 连接到 chain ID ${res.chainId}`));
// 2. 创建interface对象,用于解码交易详情。
const iface = new utils.Interface([
"function mint() external",
])
// 3. 创建钱包,用于发送抢跑交易
const privateKey = '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a'
const wallet = new ethers.Wallet(privateKey, provider)
const main = async () => {
// 4. 监听pending的mint交易,获取交易详情,然后解码。
console.log("\n4. 监听pending交易,获取txHash,并输出交易详情。")
provider.on("pending", async (txHash) => {
if (txHash) {
// 获取tx详情
let tx = await provider.getTransaction(txHash);
if (tx) {
// filter pendingTx.data
if (tx.data.indexOf(iface.getSighash("mint")) !== -1 && tx.from != wallet.address ) {
// 打印txHash
console.log(`\n[${(new Date).toLocaleTimeString()}] 监听Pending交易: ${txHash} \r`);
// 打印解码的交易详情
let parsedTx = iface.parseTransaction(tx)
console.log("pending交易详情解码:")
console.log(parsedTx);
// Input data解码
console.log("raw transaction")
console.log(tx);
// 构建抢跑tx
const txFrontrun = {
to: tx.to,
value: tx.value,
maxPriorityFeePerGas: tx.maxPriorityFeePerGas * 1.2,
maxFeePerGas: tx.maxFeePerGas * 1.2,
gasLimit: tx.gasLimit * 2,
data: tx.data
}
// 发送抢跑交易
var txResponse = await wallet.sendTransaction(txFrontrun)
console.log(`正在frontrun交易`)
await txResponse.wait()
console.log(`frontrun 交易成功`)
}
}
}
});
provider._websocket.on("error", async () => {
console.log(`Unable to connect to ${ep.subdomain} retrying in 3s...`);
setTimeout(init, 3000);
});
provider._websocket.on("close", async (code) => {
console.log(
`Connection lost with code ${code}! Attempting reconnect in 3s...`
);
provider._websocket.terminate();
setTimeout(init, 3000);
});
};
main()