-
Notifications
You must be signed in to change notification settings - Fork 0
/
Flashbot.go
307 lines (255 loc) · 8.02 KB
/
Flashbot.go
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package flashbot
import (
"bytes"
"crypto/ecdsa"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
const (
// `eth_sendBundle` can be used to send your bundles to the Flashbots builder.
MethodSendBundle = "eth_sendBundle"
// eth_callBundle can be used to simulate a bundle against a specific block number,
// including simulating a bundle at the top of the next block.
MethodCallBundle = "eth_callBundle"
// `eth_sendPrivateTransaction` used to send a single transaction to Flashbots.
MethodSendPrivateTransaction = "eth_sendPrivateTransaction"
// `eth_cancelPrivateTransaction` Method stops private
// transactions from being submitted for future blocks.
MethodCancelPrivateTransaction = "eth_cancelPrivateTransaction"
MethodEstimateGasBundle = "eth_estimateGasBundle"
MethodGetUserStats = "flashbots_getUserStats"
MethodGetBundleStats = "flashbots_getBundleStats"
)
var (
errorTransaction = errors.New("nil")
)
type FlashbotLaunch struct {
Rpc string
PrivateKey *ecdsa.PrivateKey
}
type metaRequestParams struct {
JsonRPC string `json:"jsonrpc"`
Id int `json:"id"`
Method string `json:"method"`
Params interface{} `json:"params"`
}
// ############
// sendBundle
// ############
type SendBundleParams struct {
Transactions []string `json:"txs"`
BlockNumber string `json:"blockNumber"`
MinTimestamp int64 `json:"minTimestamp,omitempty"`
MaxTimestamp int64 `json:"maxTimestamp,omitempty"`
RevertingTxHashes []string `json:"revertingTxHashes,omitempty"`
}
type SendBundleResponse struct {
ID uint `json:"id"`
Version string `json:"jsonrpc"`
Result *bundleResult `json:"result"`
}
// ############
// callBundle
// ############
type CallBundleParams struct {
Transactions []string `json:"txs"`
BlockNumber string `json:"blockNumber"`
StateBlockNumber string `json:"stateBlockNumber"`
Timestamp int64 `json:"timestamp,omitempty"`
}
type CallBundleResponse struct {
ID uint `json:"id"`
Version string `json:"jsonrpc"`
Result *callResult `json:"result"`
Error *errorResult `json:"error"`
Raw string
StatusCode int
}
// ####################
// PrivateTransaction
// ####################
type SendPrivateTx struct {
Transaction string `json:"txs"`
MaxBlockNumber string `json:"maxBlockNumber"`
Preferences map[string]bool `json:"preferences"`
}
type SendPrivateTxResponse struct {
JsonRPC string `json:"jsonrpc"`
Id int `json:"id"`
Result string `json:"result"`
}
// ###########
// userStats
// ###########
type UserStatsResponse struct {
ID uint `json:"id"`
Version string `json:"jsonrpc"`
Result *userStats `json:"result"`
}
type userStats struct {
IsHighPriority bool `json:"is_high_priority"`
AllTimeMinerPayments string `json:"all_time_miner_payments"`
AllTimeGasSimulated string `json:"all_time_gas_simulated"`
Last7dMinerPayments string `json:"last_7d_miner_payments"`
Last7dGasSimulated string `json:"last_7d_gas_simulated"`
Last1dMinerPayments string `json:"last_1d_miner_payments"`
Last1dGasSimulated string `json:"last_1d_gas_simulated"`
}
type errorResult struct {
Code int64 `json:"code"`
Message string `json:"message"`
}
type bundleResult struct {
BundleHash string `json:"bundleHash"`
}
// ###################
// transaction Result
// ###################
type txResult struct {
CoinbaseDiff string `json:"coinbaseDiff"`
EthSentToCoinbase string `json:"ethSentToCoinbase"`
FromAddress string `json:"fromAddress"`
GasFees string `json:"gasFees"`
GasPrice string `json:"gasPrice"`
GasUsed uint64 `json:"gasUsed"`
ToAddress string `json:"toAddress"`
TxHash string `json:"txHash"`
Value string `json:"value"`
Error string `json:"error,omitempty"`
}
type callResult struct {
BundleGasPrice string `json:"bundleGasPrice"`
BundleHash string `json:"bundleHash"`
CoinbaseDiff string `json:"coinbaseDiff"`
EthSentToCoinbase string `json:"ethSentToCoinbase"`
GasFees string `json:"gasFees"`
Results []txResult `json:"results"`
StateBlockNumber uint64 `json:"stateBlockNumber"`
TotalGasUsed uint64 `json:"totalGasUsed"`
}
func New(relayRPC string) *FlashbotLaunch {
rpc, _ := RelayDefaultRPC(relayRPC)
privateKey := os.Getenv("PRIVATE_KEY")
if privateKey == "" {
log.Fatal("The PrivateKey is nil, please export it !")
}
return &FlashbotLaunch{
Rpc: rpc,
PrivateKey: HexToECDSA(privateKey),
}
}
func (f *FlashbotLaunch) SendBundle(transactions []string, blockNumber uint64) (*SendBundleResponse, error) {
if len(transactions) < 1 {
return nil, errorTransaction
}
args := SendBundleParams{
Transactions: transactions,
BlockNumber: HextoBlockNumber(blockNumber),
}
resp := f.requestRPC(MethodSendBundle, args)
sendBundleResp := new(SendBundleResponse)
if err := json.Unmarshal(resp, sendBundleResp); err != nil {
return nil, err
}
return sendBundleResp, nil
}
func (f *FlashbotLaunch) CallBundle(transaction []string, blockNumber uint64) (*CallBundleResponse, error) {
if len(transaction) < 1 {
return nil, errorTransaction
}
args := CallBundleParams{
Transactions: transaction,
BlockNumber: HextoBlockNumber(blockNumber),
StateBlockNumber: "latest",
Timestamp: 1615920932,
}
resp := f.requestRPC(MethodCallBundle, args)
callBUndleResp := new(CallBundleResponse)
if err := json.Unmarshal(resp, callBUndleResp); err != nil {
return nil, err
}
return callBUndleResp, nil
}
func (f *FlashbotLaunch) SendPrivateTransaction(tx string, maxBlockNumber string) (*SendPrivateTxResponse, error) {
args := SendPrivateTx{
Transaction: tx,
MaxBlockNumber: maxBlockNumber,
}
resp := f.requestRPC(MethodSendPrivateTransaction, args)
transactionResp := new(SendPrivateTxResponse)
if err := json.Unmarshal(resp, transactionResp); err != nil {
return nil, err
}
return transactionResp, nil
}
func (f *FlashbotLaunch) GetUserStats(blockNumber uint64) (*UserStatsResponse, error) {
resp := f.requestRPC(MethodGetUserStats, blockNumber)
userStatusResp := new(UserStatsResponse)
if err := json.Unmarshal(resp, userStatusResp); err != nil {
return nil, err
}
return userStatusResp, nil
}
func (f *FlashbotLaunch) requestRPC(Method string, params ...interface{}) []byte {
requestArgs := metaRequestParams{
JsonRPC: "2.0",
Id: 1,
Method: Method,
Params: append(params, params...),
}
client := &http.Client{Timeout: 20 * time.Second}
payload, err := json.Marshal(requestArgs)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest("POST", f.Rpc, bytes.NewBuffer(payload))
if err != nil {
log.Fatal(err)
}
headerReady, _ := crypto.Sign(
accounts.TextHash([]byte(hexutil.Encode(crypto.Keccak256(payload)))),
f.PrivateKey,
)
signature := flashbotHeader(headerReady, f.PrivateKey)
req.Header.Add("content-type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("X-Flashbots-Signature", signature)
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
res, _ := ioutil.ReadAll(resp.Body)
return res
}
func flashbotHeader(signature []byte, privateKey *ecdsa.PrivateKey) string {
return crypto.PubkeyToAddress(privateKey.PublicKey).Hex() + ":" + hexutil.Encode(signature)
}
func HexToECDSA(privateKey string) *ecdsa.PrivateKey {
key, err := crypto.HexToECDSA(privateKey)
if err != nil {
log.Fatal(err)
}
return key
}
func HextoBlockNumber(blockNumber uint64) string {
return hexutil.EncodeUint64(blockNumber)
}
func RelayDefaultRPC(netType string) (string, error) {
switch netType {
case "mainnet":
return "https://relay.flashbots.net", nil
case "goerli":
return "https://relay-goerli.flashbots.net", nil
default:
return "", fmt.Errorf("The netType is wrong!:", netType)
}
}