-
Notifications
You must be signed in to change notification settings - Fork 40
/
client_builder.go
431 lines (390 loc) · 16.6 KB
/
client_builder.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package seth
import (
"fmt"
"time"
"github.com/pkg/errors"
)
const (
NoPkForRpcHealthCheckErr = "you need to provide at least one private key to check the RPC health"
NoPkForNonceProtection = "you need to provide at least one private key to enable nonce protection"
NoPkForEphemeralKeys = "you need to provide at least one private key to generate and fund ephemeral addresses"
NoPkForGasPriceEstimation = "you need to provide at least one private key to enable gas price estimations"
)
type ClientBuilder struct {
config *Config
readonly bool
errors []error
}
// NewClientBuilder creates a new ClientBuilder with reasonable default values. You only need to pass private key(s) and RPC URL to build a usable config.
func NewClientBuilder() *ClientBuilder {
network := &Network{
Name: DefaultNetworkName,
EIP1559DynamicFees: true,
TxnTimeout: MustMakeDuration(5 * time.Minute),
DialTimeout: MustMakeDuration(DefaultDialTimeout),
TransferGasFee: DefaultTransferGasFee,
GasPriceEstimationEnabled: true,
GasPriceEstimationBlocks: 200,
GasPriceEstimationTxPriority: Priority_Standard,
GasPrice: DefaultGasPrice,
GasFeeCap: DefaultGasFeeCap,
GasTipCap: DefaultGasTipCap,
}
return &ClientBuilder{
config: &Config{
ArtifactsDir: "seth_artifacts",
EphemeralAddrs: &ZeroInt64,
RootKeyFundsBuffer: &ZeroInt64,
Network: network,
Networks: []*Network{network},
TracingLevel: TracingLevel_Reverted,
TraceOutputs: []string{TraceOutput_Console, TraceOutput_DOT},
ExperimentsEnabled: []string{},
CheckRpcHealthOnStart: true,
BlockStatsConfig: &BlockStatsConfig{RPCRateLimit: 10},
NonceManager: &NonceManagerCfg{KeySyncRateLimitSec: 10, KeySyncRetries: 3, KeySyncTimeout: MustMakeDuration(60 * time.Second), KeySyncRetryDelay: MustMakeDuration(5 * time.Second)},
GasBump: &GasBumpConfig{
Retries: 0, // bumping disabled by default
},
},
}
}
// NewClientBuilderWithConfig creates a new ClientBuilder with a provided config. If it doesn't have the network set, remember to set it with `UseNetworkWithName(name string)`
// or `WithSelectedNetworkWithChainId(chainId uint64)`, before calling any of the methods that modify the Network.
func NewClientBuilderWithConfig(config *Config) *ClientBuilder {
return &ClientBuilder{
config: config,
}
}
// WithRpcUrl sets the RPC URL for the config.
// Default value is an empty string (which is an incorrect value).
func (c *ClientBuilder) WithRpcUrl(url string) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.URLs = []string{url}
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.URLs = []string{url}
}
return c
}
// UseNetworkWithName sets the network to use by name. If the network with the provided name is not found in the `Networks` slice, config will fail on build.
// There is no default value.
func (c *ClientBuilder) UseNetworkWithName(name string) *ClientBuilder {
for _, network := range c.config.Networks {
if network.Name == name {
c.config.Network = network
return c
}
}
// if the network is not found, we will try to use the default network
for _, network := range c.config.Networks {
if network.Name == DefaultNetworkName {
c.config.Network = network
return c
}
}
c.errors = append(c.errors, fmt.Errorf("network with name '%s' not found", name))
return c
}
// UseNetworkWithChainId sets the network to use by chain ID. If the network with the provided chain ID is not found in the `Networks` slice, config will fail on build.
// There is no default value.
func (c *ClientBuilder) UseNetworkWithChainId(chainId uint64) *ClientBuilder {
for _, network := range c.config.Networks {
if network.ChainID == chainId {
c.config.Network = network
return c
}
}
// if the network is not found, we will try to use the default network
for _, network := range c.config.Networks {
if network.Name == DefaultNetworkName {
c.config.Network = network
return c
}
}
c.errors = append(c.errors, fmt.Errorf("network with chainId '%d' not found", chainId))
return c
}
// WithPrivateKeys sets the private keys for the config. At least one is required to build a valid config.
// Default value is an empty slice (which is an incorrect value).
func (c *ClientBuilder) WithPrivateKeys(pks []string) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.PrivateKeys = pks
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.PrivateKeys = pks
}
return c
}
// WithNetworkName sets the network name, useful mostly for debugging and logging.
// Default value is "default".
func (c *ClientBuilder) WithNetworkName(name string) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.Name = name
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.Name = name
}
return c
}
// WithNetworkChainId sets the network chainID. If no value is set, we will ask the RPC node for the chainID.
// There is no default value.
func (c *ClientBuilder) WithNetworkChainId(chainId uint64) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.ChainID = chainId
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.ChainID = chainId
}
return c
}
// WithGasPriceEstimations enables or disables gas price estimations, sets the number of blocks to use for estimation or transaction priority.
// Even with estimations enabled you should still either set legacy gas price with `WithLegacyGasPrice()` or EIP-1559 dynamic fees with `WithDynamicGasPrices()`
// ss they will be used as fallback values, if the estimations fail.
// Following priorities are supported: "slow", "standard" and "fast"
// Default values are true for enabled, 200 blocks for estimation and "standard" for priority.
func (c *ClientBuilder) WithGasPriceEstimations(enabled bool, estimationBlocks uint64, txPriority string) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.GasPriceEstimationEnabled = enabled
c.config.Network.GasPriceEstimationBlocks = estimationBlocks
c.config.Network.GasPriceEstimationTxPriority = txPriority
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.GasPriceEstimationEnabled = enabled
net.GasPriceEstimationBlocks = estimationBlocks
net.GasPriceEstimationTxPriority = txPriority
}
return c
}
// WithEIP1559DynamicFees enables or disables EIP-1559 dynamic fees. If enabled, you should set gas fee cap and gas tip cap with `WithDynamicGasPrices()`
// Default value is true.
func (c *ClientBuilder) WithEIP1559DynamicFees(enabled bool) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.EIP1559DynamicFees = enabled
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.EIP1559DynamicFees = enabled
}
return c
}
// WithLegacyGasPrice sets the gas price for legacy transactions that will be used only if EIP-1559 dynamic fees are disabled.
// Default value is 1 gwei.
func (c *ClientBuilder) WithLegacyGasPrice(gasPrice int64) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.GasPrice = gasPrice
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.GasPrice = gasPrice
}
return c
}
// WithDynamicGasPrices sets the gas fee cap and gas tip cap for EIP-1559 dynamic fees. These values will be used only if EIP-1559 dynamic fees are enabled.
// Default values are 150 gwei for gas fee cap and 50 gwei for gas tip cap.
func (c *ClientBuilder) WithDynamicGasPrices(gasFeeCap, gasTipCap int64) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.GasFeeCap = gasFeeCap
c.config.Network.GasTipCap = gasTipCap
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.GasFeeCap = gasFeeCap
net.GasTipCap = gasTipCap
}
return c
}
// WithTransferGasFee sets the gas fee for transfer transactions. This value is used, when sending funds to ephemeral keys or returning funds to root private key.
// Default value is 21_000 wei.
func (c *ClientBuilder) WithTransferGasFee(transferGasFee int64) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.TransferGasFee = transferGasFee
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.TransferGasFee = transferGasFee
}
return c
}
// WithGasBumping sets the number of retries for gas bumping and max gas price. You can also provide a custom bumping strategy. If the transaction is not mined within this number of retries, it will be considered failed.
// If the gas price is bumped to a value higher than max gas price, no more gas bumping will be attempted and previous gas price will be used by all subsequent attempts. If set to 0 max price is not checked.
// Default value is 0 retries. If you want to use default bumping strategy (where gas increase % based on gas_price_estimation_tx_priority), pass `nil` as the customBumpingStrategy.
func (c *ClientBuilder) WithGasBumping(retries uint, maxGasPrice int64, customBumpingStrategy GasBumpStrategyFn) *ClientBuilder {
c.config.GasBump = &GasBumpConfig{
Retries: retries,
MaxGasPrice: maxGasPrice,
StrategyFn: customBumpingStrategy,
}
return c
}
// WithTransactionTimeout sets the timeout for transactions. If the transaction is not mined within this time, it will be considered failed.
// Default value is 5 minutes.
func (c *ClientBuilder) WithTransactionTimeout(timeout time.Duration) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.TxnTimeout = MustMakeDuration(timeout)
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.TxnTimeout = MustMakeDuration(timeout)
}
return c
}
// WithRpcDialTimeout sets the timeout for dialing the RPC server. If the connection is not established within this time, it will be considered failed.
// Default value is 1 minute.
func (c *ClientBuilder) WithRpcDialTimeout(timeout time.Duration) *ClientBuilder {
if !c.checkIfNetworkIsSet() {
return c
}
c.config.Network.DialTimeout = MustMakeDuration(timeout)
// defensive programming
if len(c.config.Networks) == 0 {
c.config.Networks = append(c.config.Networks, c.config.Network)
} else if net := c.config.findNetworkByName(c.config.Network.Name); net != nil {
net.DialTimeout = MustMakeDuration(timeout)
}
return c
}
// WithEphemeralAddresses sets the number of ephemeral addresses to generate and the amount of funds to keep in the root private key.
// Default values are 0 for ephemeral addresses and 0 for root key funds buffer.
func (c *ClientBuilder) WithEphemeralAddresses(ephemeralAddressCount, rootKeyBufferAmount int64) *ClientBuilder {
c.config.EphemeralAddrs = &ephemeralAddressCount
c.config.RootKeyFundsBuffer = &rootKeyBufferAmount
return c
}
// WithTracing sets the tracing level and outputs. Tracing level can be one of: "all", "reverted", "none". Outputs can be one or more of: "console", "dot" or "json".
// Default values are "reverted" and ["console", "dot"].
func (c *ClientBuilder) WithTracing(level string, outputs []string) *ClientBuilder {
c.config.TracingLevel = level
c.config.TraceOutputs = outputs
return c
}
// WithProtections enables or disables nonce protection (fails, when key has a pending transaction, and you try to submit another one) and node health check on startup.
// Default values are false for nonce protection, true for node health check and 1 minute timeout.
func (c *ClientBuilder) WithProtections(pendingNonceProtectionEnabled, nodeHealthStartupCheck bool, pendingNonceProtectionTimeout *Duration) *ClientBuilder {
c.config.PendingNonceProtectionEnabled = pendingNonceProtectionEnabled
c.config.CheckRpcHealthOnStart = nodeHealthStartupCheck
c.config.PendingNonceProtectionTimeout = pendingNonceProtectionTimeout
return c
}
// WithArtifactsFolder sets the folder where the Seth artifacts such as DOT graphs or JSON will be saved.
// Default value is "seth_artifacts".
func (c *ClientBuilder) WithArtifactsFolder(folder string) *ClientBuilder {
c.config.ArtifactsDir = folder
return c
}
// WithGethWrappersFolders sets list of folders where the Geth wrappers are stored. Seth will load ABIs from all wrappers it finds in theses folders (including subfolders).
// Default value is an empty string (= loading disabled).
func (c *ClientBuilder) WithGethWrappersFolders(folders []string) *ClientBuilder {
c.config.GethWrappersDirs = folders
return c
}
// WithNonceManager sets the rate limit for key sync, number of retries, timeout and retry delay.
// Default values are 10 calls per second, 3 retires, 60s timeout and 5s retry delay.
func (c *ClientBuilder) WithNonceManager(rateLimitSec int, retries uint, timeout, retryDelay time.Duration) *ClientBuilder {
c.config.NonceManager = &NonceManagerCfg{
KeySyncRateLimitSec: rateLimitSec,
KeySyncRetries: retries,
KeySyncTimeout: MustMakeDuration(timeout),
KeySyncRetryDelay: MustMakeDuration(retryDelay),
}
return c
}
// WithReadOnlyMode sets the client to read-only mode. It removes all private keys from all Networks and disables nonce protection and ephemeral addresses.
func (c *ClientBuilder) WithReadOnlyMode() *ClientBuilder {
c.readonly = true
return c
}
// Build creates a new Client from the builder.
func (c *ClientBuilder) Build() (*Client, error) {
config, err := c.BuildConfig()
if err != nil {
return nil, err
}
return NewClientWithConfig(config)
}
// BuildConfig returns the config from the builder.
func (c *ClientBuilder) BuildConfig() (*Config, error) {
c.handleReadOnlyMode()
c.validateConfig()
if len(c.errors) > 0 {
var concatenatedErrors string
for _, err := range c.errors {
concatenatedErrors = fmt.Sprintf("%s\n%s", concatenatedErrors, err.Error())
}
return nil, fmt.Errorf("errors occurred during building the config:%s", concatenatedErrors)
}
return c.config, nil
}
func (c *ClientBuilder) handleReadOnlyMode() {
if c.readonly {
c.config.PendingNonceProtectionEnabled = false
c.config.CheckRpcHealthOnStart = false
c.config.EphemeralAddrs = nil
c.readonly = true
if c.config.Network != nil {
c.config.Network.GasPriceEstimationEnabled = false
c.config.Network.PrivateKeys = []string{}
}
for i := range c.config.Networks {
c.config.Networks[i].PrivateKeys = []string{}
}
}
}
func (c *ClientBuilder) validateConfig() {
if c.config.Network != nil {
if len(c.config.Network.PrivateKeys) == 0 && c.config.CheckRpcHealthOnStart {
c.errors = append(c.errors, errors.New(NoPkForRpcHealthCheckErr))
}
if len(c.config.Network.PrivateKeys) == 0 && c.config.PendingNonceProtectionEnabled {
c.errors = append(c.errors, errors.New(NoPkForNonceProtection))
}
if len(c.config.Network.PrivateKeys) == 0 && c.config.EphemeralAddrs != nil && *c.config.EphemeralAddrs > 0 {
c.errors = append(c.errors, errors.New(NoPkForEphemeralKeys))
}
if len(c.config.Network.PrivateKeys) == 0 && c.config.Network.GasPriceEstimationEnabled {
c.errors = append(c.errors, errors.New(NoPkForGasPriceEstimation))
}
}
}
func (c *ClientBuilder) checkIfNetworkIsSet() bool {
if c.config.Network == nil {
c.errors = append(c.errors, errors.New("at least one method that required network to be set was called, but network is nil"))
return false
}
return true
}