Skip to content

Commit

Permalink
fix imports
Browse files Browse the repository at this point in the history
  • Loading branch information
Tofel committed Aug 23, 2024
1 parent e38eb7e commit 2a6138d
Show file tree
Hide file tree
Showing 13 changed files with 91 additions and 78 deletions.
52 changes: 26 additions & 26 deletions seth/abi_finder.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,36 +98,36 @@ func (a *ABIFinder) FindABIByMethod(address string, signature []byte) (ABIFinder
result.DuplicateCount = 0 // we know the exact contract, so the duplicates here do not matter

return result, nil
} else {
// if we do not know what contract is at given address we need to iterate over all known ABIs
// and check if any of them has a method with the given signature (this might gave false positives,
// when more than one contract has the same method signature, but we can't do anything about it)
// In any case this should happen only when we did not deploy the contract via Seth (as otherwise we
// know the address of the contract and can map it to the correct ABI instance).
// If there are duplicates we will use the first ABI that matched.
for abiName, abiInstanceCandidate := range a.ContractStore.ABIs {
methodCandidate, err := abiInstanceCandidate.MethodById(signature)
if err != nil {
L.Trace().
Err(err).
Str("Signature", stringSignature).
Msg("Method not found")
continue
}
}

// if we do not know what contract is at given address we need to iterate over all known ABIs
// and check if any of them has a method with the given signature (this might gave false positives,
// when more than one contract has the same method signature, but we can't do anything about it)
// In any case this should happen only when we did not deploy the contract via Seth (as otherwise we
// know the address of the contract and can map it to the correct ABI instance).
// If there are duplicates we will use the first ABI that matched.
for abiName, abiInstanceCandidate := range a.ContractStore.ABIs {
methodCandidate, err := abiInstanceCandidate.MethodById(signature)
if err != nil {
L.Trace().
Err(err).
Str("Signature", stringSignature).
Msg("Method not found")
continue
}

a.ContractMap.AddContract(address, abiName)
a.ContractMap.AddContract(address, abiName)

result.ABI = abiInstanceCandidate
result.Method = methodCandidate
result.contractName = abiName
result.DuplicateCount = a.getDuplicateCount(signature)
result.ABI = abiInstanceCandidate
result.Method = methodCandidate
result.contractName = abiName
result.DuplicateCount = a.getDuplicateCount(signature)

break
}
break
}

if result.Method == nil {
return ABIFinderResult{}, errors.New(ErrNoABIMethod)
}
if result.Method == nil {
return ABIFinderResult{}, errors.New(ErrNoABIMethod)
}

return result, nil
Expand Down
18 changes: 10 additions & 8 deletions seth/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const (

var (
// Amount of funds that will be left on the root key, when splitting funds between ephemeral addresses
ZeroInt64 int64 = 0
ZeroInt64 int64

TracingLevel_None = "NONE"
TracingLevel_Reverted = "REVERTED"
Expand Down Expand Up @@ -469,19 +469,17 @@ func (m *Client) Decode(tx *types.Transaction, txErr error) (*DecodedTransaction
if replacementErr != nil {
L.Debug().Str("Replacement error", replacementErr.Error()).Str("Current error", retryErr.Error()).Uint("Attempt", i).Msg("Failed to prepare replacement transaction. Retrying without the original one")
return
} else {
L.Debug().Str("Current error", retryErr.Error()).Uint("Attempt", i).Msg("Waiting for transaction to be confirmed after gas bump")
}
L.Debug().Str("Current error", retryErr.Error()).Uint("Attempt", i).Msg("Waiting for transaction to be confirmed after gas bump")
tx = replacementTx
}),
retry.DelayType(retry.FixedDelay),
// unless attempts is at least 1 retry.Do won't execute at all
retry.Attempts(func() uint {
if m.Cfg.GasBumpRetries() == 0 {
return 1
} else {
return m.Cfg.GasBumpRetries()
}
return m.Cfg.GasBumpRetries()
}()),
retry.RetryIf(func(err error) bool {
return m.Cfg.GasBumpRetries() != 0 && errors.Is(err, context.DeadlineExceeded)
Expand Down Expand Up @@ -594,12 +592,16 @@ func (m *Client) TransferETHFromKey(ctx context.Context, fromKeyNum int, to stri
return errors.Wrap(errors.New(ErrNoKeyLoaded), fmt.Sprintf("requested key: %d", fromKeyNum))
}
toAddr := common.HexToAddress(to)
chainID, err := m.Client.NetworkID(context.Background())
ctx, chainCancel := context.WithTimeout(ctx, m.Cfg.Network.TxnTimeout.Duration())
defer chainCancel()

chainID, err := m.Client.NetworkID(ctx)
if err != nil {
return errors.Wrap(err, "failed to get network ID")
}

var gasLimit int64
//nolint
gasLimitRaw, err := m.EstimateGasLimitForFundTransfer(m.Addresses[fromKeyNum], common.HexToAddress(to), value)
if err != nil {
gasLimit = m.Cfg.Network.TransferGasFee
Expand All @@ -624,8 +626,8 @@ func (m *Client) TransferETHFromKey(ctx context.Context, fromKeyNum int, to stri
return errors.Wrap(err, "failed to sign tx")
}

ctx, cancel := context.WithTimeout(ctx, m.Cfg.Network.TxnTimeout.Duration())
defer cancel()
ctx, sendCancel := context.WithTimeout(ctx, m.Cfg.Network.TxnTimeout.Duration())
defer sendCancel()
err = m.Client.SendTransaction(ctx, signedTx)
if err != nil {
return errors.Wrap(err, "failed to send transaction")
Expand Down
3 changes: 1 addition & 2 deletions seth/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,8 @@ func ReadConfig() (*Config, error) {
rootPrivateKey := os.Getenv(ROOT_PRIVATE_KEY_ENV_VAR)
if rootPrivateKey == "" {
return nil, errors.Errorf(ErrEmptyRootPrivateKey, ROOT_PRIVATE_KEY_ENV_VAR)
} else {
cfg.Network.PrivateKeys = append(cfg.Network.PrivateKeys, rootPrivateKey)
}
cfg.Network.PrivateKeys = append(cfg.Network.PrivateKeys, rootPrivateKey)
if cfg.Network.DialTimeout == nil {
cfg.Network.DialTimeout = &Duration{D: DefaultDialTimeout}
}
Expand Down
3 changes: 2 additions & 1 deletion seth/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ func (m *Client) decodeTransaction(l zerolog.Logger, tx *types.Transaction, rece
return defaultTxn, errors.Wrap(err, ErrDecodeInput)
}

var txIndex uint = 0
var txIndex uint

if receipt != nil {
l.Trace().Interface("Receipt", receipt).Msg("TX receipt")
Expand Down Expand Up @@ -213,6 +213,7 @@ func (m *Client) printDecodedTXData(l zerolog.Logger, ptx *DecodedTransaction) {

// DecodeCustomABIErr decodes typed Solidity errors
func (m *Client) DecodeCustomABIErr(txErr error) (string, error) {
//nolint
cerr, ok := txErr.(rpc.DataError)
if !ok {
return "", errors.New(ErrRPCJSONCastError)
Expand Down
8 changes: 6 additions & 2 deletions seth/dot_graph.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package seth

import (
//we use it only to generate hash that's used to identify a node in graph, so we don't care about this function being weak
//nolint
"crypto/sha1"
"encoding/hex"
"encoding/json"
Expand Down Expand Up @@ -284,12 +286,12 @@ func (t *Tracer) generateDotGraph(txHash string, calls []*DecodedCall, revertErr

f, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("Error creating file: %v\n", err)
return fmt.Errorf("error creating file: %v", err)
}
defer func() { _ = f.Close() }()

if _, err := f.WriteString(g.String()); err != nil {
return fmt.Errorf("Error writing to file: %v\n", err)
return fmt.Errorf("error writing to file: %v", err)
}

L.Debug().Msgf("DOT graph saved to %s", filePath)
Expand Down Expand Up @@ -353,6 +355,8 @@ func formatMapForLabel(m map[string]interface{}, truncateTo int) string {
}

func hashCall(call *DecodedCall) string {
//we use it only to generate hash that's used to identify a node in graph, so we don't care about this function being weak
//nolint
h := sha1.New()
h.Write([]byte(fmt.Sprintf("%v", call)))
return hex.EncodeToString(h.Sum(nil))
Expand Down
46 changes: 25 additions & 21 deletions seth/gas_adjuster.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ func (m *Client) GetSuggestedEIP1559Fees(ctx context.Context, priority string) (

// Fetch the baseline historical base fee and tip for the selected priority
var baseFee64, historicalSuggestedTip64 float64
//nolint
baseFee64, historicalSuggestedTip64, err = m.HistoricalFeeData(priority)
if err != nil {
return
Expand Down Expand Up @@ -266,6 +267,7 @@ func (m *Client) GetSuggestedEIP1559Fees(ctx context.Context, priority string) (

// between 0 and 1 (empty blocks - full blocks)
var congestionMetric float64
//nolint
congestionMetric, err = m.CalculateNetworkCongestionMetric(m.Cfg.Network.GasPriceEstimationBlocks, CongestionStrategy_NewestFirst)
if err == nil {
congestionClassification := classifyCongestion(congestionMetric)
Expand Down Expand Up @@ -366,6 +368,7 @@ func (m *Client) GetSuggestedLegacyFees(ctx context.Context, priority string) (a

// between 0 and 1 (empty blocks - full blocks)
var congestionMetric float64
//nolint
congestionMetric, err = m.CalculateNetworkCongestionMetric(m.Cfg.Network.GasPriceEstimationBlocks, CongestionStrategy_NewestFirst)
if err == nil {
congestionClassification := classifyCongestion(congestionMetric)
Expand Down Expand Up @@ -464,28 +467,29 @@ func (m *Client) HistoricalFeeData(priority string) (baseFee float64, historical
Msg("Failed to get fee history. Skipping automation gas estimation")

return
} else {
switch priority {
case Priority_Degen:
baseFee = stats.GasPrice.Max
historicalGasTipCap = stats.TipCap.Max
case Priority_Fast:
baseFee = stats.GasPrice.Perc99
historicalGasTipCap = stats.TipCap.Perc99
case Priority_Standard:
baseFee = stats.GasPrice.Perc50
historicalGasTipCap = stats.TipCap.Perc50
case Priority_Slow:
baseFee = stats.GasPrice.Perc25
historicalGasTipCap = stats.TipCap.Perc25
default:
err = fmt.Errorf("unknown priority: %s", priority)
L.Error().
Str("Priority", priority).
Msg("Unknown priority. Skipping automation gas estimation")
}

switch priority {
case Priority_Degen:
baseFee = stats.GasPrice.Max
historicalGasTipCap = stats.TipCap.Max
case Priority_Fast:
baseFee = stats.GasPrice.Perc99
historicalGasTipCap = stats.TipCap.Perc99
case Priority_Standard:
baseFee = stats.GasPrice.Perc50
historicalGasTipCap = stats.TipCap.Perc50
case Priority_Slow:
baseFee = stats.GasPrice.Perc25
historicalGasTipCap = stats.TipCap.Perc25
default:
err = fmt.Errorf("unknown priority: %s", priority)
L.Error().
Str("Priority", priority).
Msg("Unknown priority. Skipping automation gas estimation")

return

return
}
}

return baseFee, historicalGasTipCap, err
Expand Down
2 changes: 1 addition & 1 deletion seth/gas_bump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
)

var oneEth = big.NewInt(1000000000000000000)
var zero int64 = 0
var zero int64

func TestGasBumping_Contract_Deployment_Legacy_SufficientBumping(t *testing.T) {
c := newClient(t)
Expand Down
2 changes: 1 addition & 1 deletion seth/header_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func (c *LFUHeaderCache) Set(header *types.Header) error {

// evict removes the least frequently used item from the cache. If more than one item has the same frequency, the oldest is evicted.
func (c *LFUHeaderCache) evict() {
var leastFreq int = int(^uint(0) >> 1)
var leastFreq = int(^uint(0) >> 1)
var evictKey int64
oldestBlockNumber := ^uint64(0)
for key, item := range c.cache {
Expand Down
2 changes: 2 additions & 0 deletions seth/http_logging_transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,14 @@ func NewLoggingTransport() http.RoundTripper {
return &LoggingTransport{
// TODO: GAP, add proper certificates
Transport: &http.Transport{
//nolint
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
}

return &http.Transport{
//nolint
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
10 changes: 5 additions & 5 deletions seth/keyfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,16 @@ func ReturnFunds(c *Client, toAddr string) error {
for i := 1; i < len(c.Addresses); i++ {
idx := i
eg.Go(func() error {
balance, err := c.Client.BalanceAt(context.Background(), c.Addresses[idx], nil)
ctx, balanceCancel := context.WithTimeout(egCtx, c.Cfg.Network.TxnTimeout.Duration())
balance, err := c.Client.BalanceAt(ctx, c.Addresses[idx], nil)
balanceCancel()
if err != nil {
L.Error().Err(err).Msg("Error getting balance")
return err
}

var gasLimit int64
//nolint
gasLimitRaw, err := c.EstimateGasLimitForFundTransfer(c.Addresses[idx], common.HexToAddress(toAddr), balance)
if err != nil {
gasLimit = c.Cfg.Network.TransferGasFee
Expand Down Expand Up @@ -98,9 +101,6 @@ func ReturnFunds(c *Client, toAddr string) error {
)
})
}
if err := eg.Wait(); err != nil {
return err
}

return nil
return eg.Wait()
}
15 changes: 8 additions & 7 deletions seth/nonce.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,15 @@ func (m *NonceManager) anySyncedKey() int {
Nonce: nonce,
}
return nil
} else {
L.Trace().
Interface("KeyNum", keyData.KeyNum).
Uint64("Nonce", nonce).
Int("Expected nonce", int(keyData.Nonce+1)).
Interface("Address", m.Addresses[keyData.KeyNum]).
Msg("Key NOT synced")
}

L.Trace().
Interface("KeyNum", keyData.KeyNum).
Uint64("Nonce", nonce).
Int("Expected nonce", int(keyData.Nonce+1)).
Interface("Address", m.Addresses[keyData.KeyNum]).
Msg("Key NOT synced")

return errors.New(ErrKeySync)
},
retry.Attempts(m.cfg.KeySyncRetries),
Expand Down
4 changes: 2 additions & 2 deletions seth/test_utils/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ import (
"github.com/smartcontractkit/chainlink-testing-framework/seth"
)

var zero int64

// NewClientWithEphemeralAddresses creates a new Seth client with the given number of addresses. Each address is funded with the
// calculated with the amount of ETH calculated by dividing the total balance of root key by the number of addresses (minus root key buffer amount).
func NewClientWithEphemeralAddresses(t *testing.T, addressCount int) *seth.Client {
cfg, err := seth.ReadConfig()
require.NoError(t, err, "failed to read config")

var zero int64 = 0
cfg.EphemeralAddrs = &zero

c, err := seth.NewClientWithConfig(cfg)
Expand Down Expand Up @@ -72,7 +73,6 @@ func NewClientWithAddresses(t *testing.T, addressCount int, funding *big.Int) *s
cfg, err := seth.ReadConfig()
require.NoError(t, err, "failed to read config")

var zero int64 = 0
cfg.EphemeralAddrs = &zero

c, err := seth.NewClientWithConfig(cfg)
Expand Down
4 changes: 2 additions & 2 deletions seth/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func (m *Client) CalculateSubKeyFunding(addrs, gasPrice, rooKeyBuffer int64) (*F
Msg("Root key balance")

if freeBalance.Cmp(big.NewInt(0)) < 0 {
return nil, errors.New(fmt.Sprintf(ErrInsufficientRootKeyBalance, freeBalance.String()))
return nil, fmt.Errorf(ErrInsufficientRootKeyBalance, freeBalance.String())
}

addrFunding := new(big.Int).Div(freeBalance, big.NewInt(addrs))
Expand All @@ -91,7 +91,7 @@ func (m *Client) CalculateSubKeyFunding(addrs, gasPrice, rooKeyBuffer int64) (*F
Msg("Using hardcoded ephemeral funding")

if freeBalance.Cmp(requiredBalance) < 0 {
return nil, errors.New(fmt.Sprintf(ErrInsufficientRootKeyBalance, freeBalance.String()))
return nil, fmt.Errorf(ErrInsufficientRootKeyBalance, freeBalance.String())
}

bd := &FundingDetails{
Expand Down

0 comments on commit 2a6138d

Please sign in to comment.