-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathconsolidate.go
More file actions
350 lines (293 loc) · 10.7 KB
/
Copy pathconsolidate.go
File metadata and controls
350 lines (293 loc) · 10.7 KB
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
package commands
import (
"context"
"fmt"
"math/big"
"github.com/Layr-Labs/eigenlayer-contracts/pkg/bindings/EigenPod"
"github.com/Layr-Labs/eigenpod-proofs-generation/cli/core"
"github.com/Layr-Labs/eigenpod-proofs-generation/cli/core/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
"github.com/fatih/color"
lo "github.com/samber/lo"
)
type ConsolidateBaseCommandArgs struct {
EigenpodAddress string
DisableColor bool
UseJSON bool
SimulateTransaction bool
Node string
BeaconNode string
Sender string
BatchSize uint64
NoPrompt bool
Verbose bool
CheckFee bool
NoWarn bool
FeeOverestimateFactor float64
}
type TConsolidateSwitchCommandArgs struct {
ConsolidateBaseCommandArgs
Validators []uint64
}
type TConsolidateToTargetCommandArgs struct {
ConsolidateBaseCommandArgs
TargetValidator uint64
SourceValidators []uint64
}
func ConsolidateSwitchCommand(args TConsolidateSwitchCommandArgs) error {
ctx := context.Background()
if args.DisableColor {
color.NoColor = true
}
// "verbosity" in this case refers to validator info printouts.
// As long as we don't have UseJSON enabled, we keep logs enabled.
// TODO - we should move to a -v vs -vv vs -vvv system
isVerbose := args.Verbose
enableLogs := true
if args.UseJSON {
isVerbose = false
enableLogs = false
}
if len(args.Validators) == 0 {
return fmt.Errorf("usage: consolidate switch --validators <validatorIndexA>, <validatorIndexB>, ...")
}
eth, beaconClient, chainId, err := utils.GetClients(ctx, args.Node, args.BeaconNode, enableLogs)
utils.PanicOnError("failed to reach ethereum clients", err)
headState, err := utils.GetBeaconHeadState(ctx, beaconClient)
utils.PanicOnError("failed to fetch beacon chain head state", err)
eigenpodValidators, err := utils.GetEigenPodValidatorsByIndex(args.EigenpodAddress, headState)
utils.PanicOnError("failed to fetch validators for eigenpod", err)
// Form requests, filtering duplicates and validators that aren't pointed at the pod
requests := make([]EigenPod.IEigenPodTypesConsolidationRequest, 0)
seen := make(map[uint64]bool)
for _, vIndex := range args.Validators {
if v, exists := eigenpodValidators[vIndex]; !exists {
return fmt.Errorf("validator index %d is not pointed at this eigenpod", vIndex)
} else if seen[vIndex] {
return fmt.Errorf("validator index %d is included twice in input args", vIndex)
} else {
seen[vIndex] = true
requests = append(requests, EigenPod.IEigenPodTypesConsolidationRequest{
SrcPubkey: v.PublicKey[:],
TargetPubkey: v.PublicKey[:],
})
}
}
requestChunks := utils.Chunk(requests, args.BatchSize)
txns := make([]*types.Transaction, 0)
for i, chunk := range requestChunks {
feeInfo, err := utils.GetConsolidationFeeInfoForRequest(eth, chunk, args.FeeOverestimateFactor)
utils.PanicOnError("error getting consolidation fee info", err)
isSimulatedStr := ""
if args.SimulateTransaction {
isSimulatedStr = "[SIMULATED]"
} else {
isSimulatedStr = "[LIVE]"
}
// Prompt the user for consent.
// We prompt for individual chunks because the predeploy includes exponential fee growth depending
// on the size of the queue, and we want to make sure the user is aware of the rising fee.
utils.PanicIfNoConsent(utils.SubmitSwitchRequestConsent(
len(chunk),
feeInfo.CurrentQueueSize,
toPrintableUnits(feeInfo.FeePerRequest),
toPrintableUnits(feeInfo.TotalFee),
toPrintableUnits(feeInfo.OverestimateFee),
isSimulatedStr,
))
if isVerbose {
color.Green("Submitting chunk %d/%d (msg.value: %s)", i+1, len(requestChunks), toPrintableUnits(feeInfo.OverestimateFee))
}
txn, err := core.SubmitConsolidationRequests(
ctx,
args.Sender,
args.EigenpodAddress,
chainId,
eth,
chunk,
feeInfo.OverestimateFee,
args.SimulateTransaction,
isVerbose,
)
// If submission fails, print any successful requests before exiting with the error message
if err != nil {
if len(txns) != 0 {
fmt.Println("Error submitting consolidation request. Printing successful requests:")
printConsolidateTxnsAsJSON(txns)
}
utils.PanicOnError("consolidation request submission failed", err)
} else {
if isVerbose {
color.Green("transaction %d/%d succeeded: %s", i+1, len(requestChunks), txn.Hash().Hex())
}
txns = append(txns, txn)
}
}
if isVerbose {
color.Green("All requests succeeded.")
}
// If all submissions succeeded, print transactions
if args.SimulateTransaction {
printConsolidateTxnsAsJSON(txns)
} else {
for i, txn := range txns {
color.Green("transaction(%d): %s", i, txn.Hash().Hex())
}
}
return nil
}
func ConsolidateToTargetCommand(args TConsolidateToTargetCommandArgs) error {
ctx := context.Background()
if args.DisableColor {
color.NoColor = true
}
// "verbosity" in this case refers to validator info printouts.
// As long as we don't have UseJSON enabled, we keep logs enabled.
// TODO - we should move to a -v vs -vv vs -vvv system
isVerbose := args.Verbose
enableLogs := true
if args.UseJSON {
isVerbose = false
enableLogs = false
}
if len(args.SourceValidators) == 0 {
return fmt.Errorf("usage: consolidate source-to-target --target <validatorIndexA> --sources <validatorIndexB>, <validatorIndexC>, ...")
}
eth, beaconClient, chainId, err := utils.GetClients(ctx, args.Node, args.BeaconNode, enableLogs)
utils.PanicOnError("failed to reach ethereum clients", err)
headState, err := utils.GetBeaconHeadState(ctx, beaconClient)
utils.PanicOnError("failed to fetch beacon chain head state", err)
eigenpodValidators, err := utils.GetEigenPodValidatorsByIndex(args.EigenpodAddress, headState)
utils.PanicOnError("failed to fetch source validators for eigenpod", err)
targetValidator, exists := eigenpodValidators[args.TargetValidator]
if !exists {
return fmt.Errorf("target validator (index %d) is not pointed at this eigenpod", args.TargetValidator)
}
eigenPod, err := EigenPod.NewEigenPod(common.HexToAddress(args.EigenpodAddress), eth)
utils.PanicOnError("failed to locate eigenpod. is your address correct?", err)
status, err := eigenPod.ValidatorStatus(nil, targetValidator.PublicKey[:])
utils.PanicOnError("failed to fetch target validator status", err)
// Target validator must be in ACTIVE state in pod (verified withdrawal credentials; not withdrawn)
if status == utils.ValidatorStatusInactive {
return fmt.Errorf("target validator must have verified withdrawal credentials and be in the ACTIVE status. got status: INACTIVE")
} else if status == utils.ValidatorStatusWithdrawn {
return fmt.Errorf("target validator must have verified withdrawal credentials and be in the ACTIVE status. got status: WITHDRAWN")
}
// Form requests, filtering duplicate source validators and validators that aren't pointed at the pod
requests := make([]EigenPod.IEigenPodTypesConsolidationRequest, 0)
seen := make(map[uint64]bool)
for _, vIndex := range args.SourceValidators {
if v, exists := eigenpodValidators[vIndex]; !exists {
return fmt.Errorf("source validator (index %d) is not pointed at this eigenpod", vIndex)
} else if seen[vIndex] {
return fmt.Errorf("source validator (index %d) is included twice in input args", vIndex)
} else {
seen[vIndex] = true
requests = append(requests, EigenPod.IEigenPodTypesConsolidationRequest{
SrcPubkey: v.PublicKey[:],
TargetPubkey: targetValidator.PublicKey[:],
})
}
}
requestChunks := utils.Chunk(requests, args.BatchSize)
txns := make([]*types.Transaction, 0)
for i, chunk := range requestChunks {
feeInfo, err := utils.GetConsolidationFeeInfoForRequest(eth, chunk, args.FeeOverestimateFactor)
utils.PanicOnError("error getting consolidation fee info", err)
isSimulatedStr := ""
if args.SimulateTransaction {
isSimulatedStr = "[SIMULATED]"
} else {
isSimulatedStr = "[LIVE]"
}
// Prompt the user for consent.
// We prompt for individual chunks because the predeploy includes exponential fee growth depending
// on the size of the queue, and we want to make sure the user is aware of the rising fee.
utils.PanicIfNoConsent(utils.SubmitSourceToTargetRequestConsent(
len(chunk),
feeInfo.CurrentQueueSize,
toPrintableUnits(feeInfo.FeePerRequest),
toPrintableUnits(feeInfo.TotalFee),
toPrintableUnits(feeInfo.OverestimateFee),
args.TargetValidator,
len(args.SourceValidators),
isSimulatedStr,
))
if isVerbose {
color.Green("Submitting chunk %d/%d (msg.value: %s)", i+1, len(requestChunks), toPrintableUnits(feeInfo.OverestimateFee))
}
txn, err := core.SubmitConsolidationRequests(
ctx,
args.Sender,
args.EigenpodAddress,
chainId,
eth,
chunk,
feeInfo.OverestimateFee,
args.SimulateTransaction,
isVerbose,
)
// If submission fails, print any successful requests before exiting with the error message
if err != nil {
if len(txns) != 0 {
fmt.Println("Error submitting consolidation request. Printing successful requests:")
printConsolidateTxnsAsJSON(txns)
}
utils.PanicOnError("consolidation request submission failed", err)
} else {
if isVerbose {
color.Green("transaction %d/%d succeeded: %s", i+1, len(requestChunks), txn.Hash().Hex())
}
txns = append(txns, txn)
}
}
if isVerbose {
color.Green("All requests succeeded.")
}
// If all submissions succeeded, print transactions
if args.SimulateTransaction {
printConsolidateTxnsAsJSON(txns)
} else {
for i, txn := range txns {
color.Green("transaction(%d): %s", i, txn.Hash().Hex())
}
}
return nil
}
// If the amount is greater than 0.0001 ETH, print as ETH
// If amount is less than 100_000 Wei, print as Wei
// Otherwise, print as Gwei
func toPrintableUnits(weiAmt *big.Int) string {
printAsETHThreshhold := new(big.Int).Mul(
big.NewInt(100_000),
big.NewInt(params.GWei),
)
printAsWeiThreshhold := new(big.Int).Mul(
big.NewInt(100_000),
big.NewInt(params.Wei),
)
if weiAmt.Cmp(printAsETHThreshhold) > 0 {
return fmt.Sprintf("%f ETH", utils.IweiToEther(weiAmt))
} else if weiAmt.Cmp(printAsWeiThreshhold) < 0 {
return fmt.Sprintf("%d Wei", weiAmt)
} else {
return fmt.Sprintf("%f Gwei", utils.WeiToGwei(weiAmt))
}
}
func printConsolidateTxnsAsJSON(txns []*types.Transaction) {
printableTxns := lo.Map(txns, func(txn *types.Transaction, _ int) PredeployRequestTransaction {
gas := txn.Gas()
return PredeployRequestTransaction{
Transaction: Transaction{
To: txn.To().Hex(),
CallData: common.Bytes2Hex(txn.Data()),
Type: "consolidation_request",
GasEstimateGwei: &gas,
},
Value: txn.Value(),
}
})
PrintAsJSON(printableTxns)
}