-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
399 lines (356 loc) · 12.4 KB
/
main.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package main
import (
"context"
"fmt"
"log/slog"
"math"
"math/big"
"math/rand"
"net/url"
"os"
"strings"
"time"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
ee "github.com/primev/preconf_blob_bidder/internal/eth"
bb "github.com/primev/preconf_blob_bidder/internal/mevcommit"
"github.com/urfave/cli/v2"
)
const (
FlagEnv = "env"
FlagBidderAddress = "bidder-address"
FlagUsePayload = "use-payload"
FlagRpcEndpoint = "rpc-endpoint"
FlagWsEndpoint = "ws-endpoint"
FlagPrivateKey = "private-key"
FlagOffset = "offset"
FlagBidAmount = "bid-amount"
FlagBidAmountStdDevPercentage = "bid-amount-std-dev-percentage"
FlagNumBlob = "num-blob"
FlagDefaultTimeout = "default-timeout"
FlagRunDurationMinutes = "run-duration-minutes"
)
func promptForInput(prompt string) string {
fmt.Printf("%s: ", prompt)
var input string
if _, err := fmt.Scanln(&input); err != nil {
slog.Warn("Error reading input", "error", err)
}
return input
}
func validateWebSocketURL(input string) (string, error) {
if input == "" {
return "", fmt.Errorf("endpoint cannot be empty")
}
if !strings.Contains(input, "://") {
input = "ws://" + input
}
parsedURL, err := url.Parse(input)
if err != nil {
return "", fmt.Errorf("invalid URL format: %v", err)
}
if parsedURL.Scheme != "ws" && parsedURL.Scheme != "wss" {
return "", fmt.Errorf("invalid scheme: %s (only ws:// or wss:// are supported)", parsedURL.Scheme)
}
if parsedURL.Host == "" {
return "", fmt.Errorf("URL must include a host")
}
return parsedURL.String(), nil
}
func validatePrivateKey(input string) error {
if len(input) != 64 {
return fmt.Errorf("private key must be 64 hex characters")
}
return nil
}
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
Level: slog.LevelInfo,
AddSource: true,
}))
slog.SetDefault(logger)
app := &cli.App{
Name: "Preconf Bidder",
Usage: "A tool for bidding in mev-commit preconfirmation auctions for blobs and transactions.",
Action: func(c *cli.Context) error {
fmt.Println("-----------------------------------------------------------------------------------------------")
fmt.Println("Welcome to Preconf Bidder!")
fmt.Println("")
fmt.Println("This is a quickstart tool to make preconf bids on mev-commit chain.")
fmt.Println("")
fmt.Println("If you already know what you're doing, you can skip the prompts by providing flags upfront.")
fmt.Println("For example:")
fmt.Println(" ./biddercli --private-key <your_64_char_hex_key> --ws-endpoint wss://your-node.com/ws")
fmt.Println("")
fmt.Println("Available flags include:")
fmt.Println(" --private-key Your private key for signing transactions (64 hex chars)")
fmt.Println(" --ws-endpoint The WebSocket endpoint for your Ethereum node")
fmt.Println(" --rpc-endpoint The RPC endpoint if not using payload")
fmt.Println(" --bid-amount The amount to bid (in ETH), default 0.001")
fmt.Println(" --bid-amount-std-dev-percentage Std dev percentage of bid amount, default 100.0")
fmt.Println(" --num-blob Number of blob transactions to send, default 0 makes the tx an eth transfer")
fmt.Println(" --default-timeout Default timeout in seconds, default 15")
fmt.Println(" --run-duration-minutes Duration to run the bidder in minutes (0 for infinite)")
fmt.Println("")
fmt.Println("You can also set environment variables like WS_ENDPOINT and PRIVATE_KEY.")
fmt.Println("For more details, check the documentation: https://docs.primev.xyz/get-started/bidders/best-practices")
fmt.Println("-----------------------------------------------------------------------------------------------")
fmt.Println()
wsEndpoint := c.String(FlagWsEndpoint)
privateKeyHex := c.String(FlagPrivateKey)
if wsEndpoint == "" {
fmt.Println("First, we need the WebSocket endpoint for your Ethereum node.")
fmt.Println("This is where we'll connect to receive real-time blockchain updates.")
fmt.Println("For example: wss://your-node-provider.com/ws")
fmt.Println()
var err error
for {
wsEndpoint = promptForInput("Please enter your WebSocket endpoint")
wsEndpoint, err = validateWebSocketURL(wsEndpoint)
if err == nil {
break
}
fmt.Printf("Error: %s\nPlease try again.\n\n", err)
}
fmt.Println()
}
if privateKeyHex == "" {
fmt.Println("A private key is needed to sign transactions.")
fmt.Println("A private key is a 64-character hexadecimal string.")
fmt.Println()
var err error
for {
privateKeyHex = promptForInput("Please enter your private key")
err = validatePrivateKey(privateKeyHex)
if err == nil {
break
}
fmt.Printf("Error: %s\nPlease try again.\n\n", err)
}
fmt.Println()
}
bidderAddress := c.String(FlagBidderAddress)
usePayload := c.Bool(FlagUsePayload)
rpcEndpoint := c.String(FlagRpcEndpoint)
offset := c.Uint64(FlagOffset)
bidAmount := c.Float64(FlagBidAmount)
stdDevPercentage := c.Float64(FlagBidAmountStdDevPercentage)
numBlob := c.Uint(FlagNumBlob)
defaultTimeoutSeconds := c.Uint(FlagDefaultTimeout)
defaultTimeout := time.Duration(defaultTimeoutSeconds) * time.Second
runDurationMinutes := c.Uint(FlagRunDurationMinutes)
var endTime time.Time
if runDurationMinutes > 0 {
endTime = time.Now().Add(time.Duration(runDurationMinutes) * time.Minute)
slog.Info("Bidder will run until", "endTime", endTime)
} else {
slog.Info("Bidder will run indefinitely")
}
fmt.Println("Great! Here's what we have:")
fmt.Printf(" - WebSocket Endpoint: %s\n", wsEndpoint)
fmt.Printf(" - Private Key: Provided (hidden)\n")
fmt.Printf(" - Bidder Address: %s\n", bidderAddress)
fmt.Printf(" - Use Payload: %v\n", usePayload)
fmt.Printf(" - Bid Amount: %f ETH\n", bidAmount)
fmt.Printf(" - Standard Deviation: %f%%\n", stdDevPercentage)
fmt.Printf(" - Number of Blobs: %d\n", numBlob)
fmt.Printf(" - Default Timeout: %d seconds\n", defaultTimeoutSeconds)
if runDurationMinutes > 0 {
fmt.Printf(" - Run Duration: %d minutes\n", runDurationMinutes)
} else {
fmt.Printf(" - Run Duration: infinite\n")
}
fmt.Println()
fmt.Println("We will now connect to the blockchain and start sending transactions.")
fmt.Println("Please wait...")
fmt.Println()
slog.Info("Configuration values",
"bidderAddress", bidderAddress,
"rpcEndpoint", bb.MaskEndpoint(rpcEndpoint),
"wsEndpoint", bb.MaskEndpoint(wsEndpoint),
"offset", offset,
"usePayload", usePayload,
"bidAmount", bidAmount,
"stdDevPercentage", stdDevPercentage,
"numBlob", numBlob,
"privateKeyProvided", privateKeyHex != "",
"defaultTimeoutSeconds", defaultTimeoutSeconds,
)
cfg := bb.BidderConfig{
ServerAddress: bidderAddress,
}
bidderClient, err := bb.NewBidderClient(cfg)
if err != nil {
slog.Error("Failed to connect to mev-commit bidder API", "error", err)
return fmt.Errorf("failed to connect to mev-commit bidder API: %w", err)
}
slog.Info("Connected to mev-commit client")
timeout := defaultTimeout
var rpcClient *ethclient.Client
if !usePayload {
rpcClient = bb.ConnectRPCClientWithRetries(rpcEndpoint, 5, timeout)
if rpcClient == nil {
slog.Error("Failed to connect to RPC client", "rpcEndpoint", bb.MaskEndpoint(rpcEndpoint))
} else {
slog.Info("Geth client connected (rpc)",
"endpoint", bb.MaskEndpoint(rpcEndpoint),
)
}
}
wsClient, err := bb.ConnectWSClient(wsEndpoint)
if err != nil {
slog.Error("Failed to connect to WebSocket client", "error", err)
return fmt.Errorf("failed to connect to WebSocket client: %w", err)
}
slog.Info("Geth client connected (ws)",
"endpoint", bb.MaskEndpoint(wsEndpoint),
)
headers := make(chan *types.Header)
sub, err := wsClient.SubscribeNewHead(context.Background(), headers)
if err != nil {
slog.Error("Failed to subscribe to new blocks", "error", err)
return fmt.Errorf("failed to subscribe to new blocks: %w", err)
}
authAcct, err := bb.AuthenticateAddress(privateKeyHex, wsClient)
if err != nil {
slog.Error("Failed to authenticate private key", "error", err)
return fmt.Errorf("failed to authenticate private key: %w", err)
}
for {
if runDurationMinutes > 0 && time.Now().After(endTime) {
slog.Info("Run duration reached, shutting down")
return nil
}
select {
case err := <-sub.Err():
slog.Warn("Subscription error", "error", err)
wsClient, sub = bb.ReconnectWSClient(wsEndpoint, headers)
continue
case header := <-headers:
var signedTx *types.Transaction
var blockNumber uint64
if numBlob == 0 {
// Perform ETH Transfer
amount := big.NewInt(1e15)
signedTx, blockNumber, err = ee.SelfETHTransfer(wsClient, authAcct, amount, offset)
} else {
// Execute Blob Transaction
signedTx, blockNumber, err = ee.ExecuteBlobTransaction(wsClient, authAcct, int(numBlob), offset)
}
if signedTx == nil {
slog.Error("Transaction was not signed or created.")
} else {
slog.Info("Transaction sent successfully")
}
if err != nil {
slog.Error("Failed to execute transaction", "error", err)
}
slog.Info("New block received",
"blockNumber", header.Number.Uint64(),
"timestamp", header.Time,
"hash", header.Hash().String(),
)
stdDev := bidAmount * stdDevPercentage / 100.0
randomEthAmount := rand.NormFloat64()*stdDev + bidAmount
randomEthAmount = math.Max(randomEthAmount, bidAmount)
if usePayload {
bb.SendPreconfBid(bidderClient, signedTx, int64(blockNumber), randomEthAmount)
} else {
_, err = ee.SendBundle(rpcEndpoint, signedTx, blockNumber)
if err != nil {
slog.Error("Failed to send transaction",
"rpcEndpoint", bb.MaskEndpoint(rpcEndpoint),
"error", err,
)
}
bb.SendPreconfBid(bidderClient, signedTx.Hash().String(), int64(blockNumber), randomEthAmount)
}
if err != nil {
slog.Error("Failed to execute transaction", "error", err)
continue
}
}
}
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: FlagEnv,
Usage: "Path to .env file",
EnvVars: []string{"ENV_FILE"},
},
&cli.StringFlag{
Name: FlagBidderAddress,
Usage: "Address of the bidder",
EnvVars: []string{"BIDDER_ADDRESS"},
Value: "localhost:13524",
},
&cli.BoolFlag{
Name: FlagUsePayload,
Usage: "Use payload for transactions",
EnvVars: []string{"USE_PAYLOAD"},
Value: true,
},
&cli.StringFlag{
Name: FlagRpcEndpoint,
Usage: "RPC endpoint when use-payload is false",
EnvVars: []string{"RPC_ENDPOINT"},
Required: false,
},
&cli.StringFlag{
Name: FlagWsEndpoint,
Usage: "WebSocket endpoint for transactions",
EnvVars: []string{"WS_ENDPOINT"},
Value: "wss://ethereum-holesky-rpc.publicnode.com",
Required: false,
},
&cli.StringFlag{
Name: FlagPrivateKey,
Usage: "Private key for signing transactions",
EnvVars: []string{"PRIVATE_KEY"},
Required: false,
Hidden: true,
TakesFile: false,
},
&cli.Uint64Flag{
Name: FlagOffset,
Usage: "Offset value for transactions",
EnvVars: []string{"OFFSET"},
Value: 1,
},
&cli.Float64Flag{
Name: FlagBidAmount,
Usage: "Amount to bid",
EnvVars: []string{"BID_AMOUNT"},
Value: 0.001,
},
&cli.Float64Flag{
Name: FlagBidAmountStdDevPercentage,
Usage: "Standard deviation percentage for bid amount",
EnvVars: []string{"BID_AMOUNT_STD_DEV_PERCENTAGE"},
Value: 100.0,
},
&cli.UintFlag{
Name: FlagNumBlob,
Usage: "Number of blobs to send (0 for ETH transfer)",
EnvVars: []string{"NUM_BLOB"},
Value: 0,
},
&cli.UintFlag{
Name: FlagDefaultTimeout,
Usage: "Default timeout in seconds",
EnvVars: []string{"DEFAULT_TIMEOUT"},
Value: 15,
},
&cli.UintFlag{
Name: FlagRunDurationMinutes,
Usage: "Duration to run the bidder in minutes (0 for infinite)",
EnvVars: []string{"RUN_DURATION_MINUTES"},
Value: 0,
},
},
}
if err := app.Run(os.Args); err != nil {
slog.Error("Application error", "error", err)
os.Exit(1)
}
}