Skip to content

Commit aec6319

Browse files
committed
wrap error correctly
1 parent 112f3c4 commit aec6319

File tree

5 files changed

+69
-53
lines changed

5 files changed

+69
-53
lines changed

seth/abi_finder.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ func (a *ABIFinder) FindABIByMethod(address string, signature []byte) (ABIFinder
6161
Str("Contract", contractName).
6262
Str("Address", address).
6363
Msg("ABI not found for known contract")
64-
return ABIFinderResult{}, err
64+
return ABIFinderResult{}, fmt.Errorf("%w: %v", ErrNoABIMethod, err)
6565
}
6666

6767
methodCandidate, err := abiInstanceCandidate.MethodById(signature)
@@ -99,7 +99,7 @@ func (a *ABIFinder) FindABIByMethod(address string, signature []byte) (ABIFinder
9999
Str("Supposed address", address).
100100
Msg("Method not found in known ABI instance. This should not happen. Contract map might be corrupted")
101101

102-
return ABIFinderResult{}, err
102+
return ABIFinderResult{}, fmt.Errorf("%w: %v", ErrNoABIMethod, err)
103103
}
104104

105105
result.Method = methodCandidate
@@ -137,7 +137,7 @@ func (a *ABIFinder) FindABIByMethod(address string, signature []byte) (ABIFinder
137137
}
138138

139139
if result.Method == nil {
140-
return ABIFinderResult{}, fmt.Errorf("no ABI found with method signature %s for contract at address %s.\n"+
140+
err := fmt.Errorf("no ABI found with method signature %s for contract at address %s.\n"+
141141
"Checked %d ABIs but none matched.\n"+
142142
"Possible causes:\n"+
143143
" 1. Contract ABI not loaded (check abi_dir and contract_map_file)\n"+
@@ -151,6 +151,8 @@ func (a *ABIFinder) FindABIByMethod(address string, signature []byte) (ABIFinder
151151
" 4. Review contract_map_file for address-to-name mappings\n"+
152152
" 5. Use ContractStore.AddABI() to manually add the ABI",
153153
stringSignature, address, len(a.ContractStore.ABIs))
154+
155+
return ABIFinderResult{}, fmt.Errorf("%w: %v", ErrNoABIMethod, err)
154156
}
155157

156158
return result, nil

seth/client.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -987,7 +987,7 @@ func (m *Client) CalculateGasEstimations(request GasEstimationRequest) GasEstima
987987
defer cancel()
988988

989989
var disableEstimationsIfNeeded = func(err error) {
990-
if strings.Contains(err.Error(), ZeroGasSuggestedErr) {
990+
if errors.Is(err, GasEstimationErr) {
991991
L.Warn().Msg("Received incorrect gas estimations. Disabling them and reverting to hardcoded values. Remember to update your config!")
992992
m.Cfg.Network.GasPriceEstimationEnabled = false
993993
}
@@ -1469,7 +1469,7 @@ func (m *Client) decodeContractLogs(l zerolog.Logger, logs []types.Log, allABIs
14691469
for i, topic := range lo.Topics {
14701470
topics[i] = topic.Hex()
14711471
}
1472-
1472+
14731473
decodeError := EventDecodingError{
14741474
Signature: eventSig,
14751475
LogIndex: lo.Index,
@@ -1478,12 +1478,12 @@ func (m *Client) decodeContractLogs(l zerolog.Logger, logs []types.Log, allABIs
14781478
Errors: decodeAttempts,
14791479
}
14801480
decodeErrors = append(decodeErrors, decodeError)
1481-
1481+
14821482
abiNames := make([]string, len(decodeAttempts))
14831483
for i, attempt := range decodeAttempts {
14841484
abiNames[i] = attempt.ABIName
14851485
}
1486-
1486+
14871487
l.Warn().
14881488
Str("Signature", eventSig).
14891489
Uint("LogIndex", lo.Index).
@@ -1522,13 +1522,13 @@ func (m *Client) findABIName(targetABI *abi.ABI) string {
15221522
if m.ContractStore == nil {
15231523
return "unknown"
15241524
}
1525-
1525+
15261526
for name, storedABI := range m.ContractStore.ABIs {
15271527
if reflect.DeepEqual(storedABI, *targetABI) {
15281528
return strings.TrimSuffix(name, ".abi")
15291529
}
15301530
}
1531-
1531+
15321532
return "unknown"
15331533
}
15341534

seth/decode.go

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,45 +20,40 @@ import (
2020
"github.com/rs/zerolog"
2121
)
2222

23-
const (
24-
ErrDecodeInput = "failed to decode transaction input"
25-
ErrDecodeOutput = "failed to decode transaction output"
26-
ErrDecodeLog = "failed to decode log"
27-
ErrDecodedLogNonIndexed = "failed to decode non-indexed log data"
28-
ErrDecodeILogIndexed = "failed to decode indexed log data"
29-
ErrTooShortTxData = "tx data is less than 4 bytes, can't decode"
30-
ErrRPCJSONCastError = "failed to cast CallMsg error as rpc.DataError"
31-
ErrUnableToDecode = "unable to decode revert reason"
23+
var (
24+
ErrNoABIMethod = errors.New("no ABI method found")
25+
)
3226

27+
const (
3328
WarnNoContractStore = "ContractStore is nil, use seth.NewContractStore(...) to decode transactions"
3429
)
3530

3631
// DecodedTransaction decoded transaction
3732
type DecodedTransaction struct {
3833
CommonData
39-
Index uint `json:"index"`
40-
Hash string `json:"hash,omitempty"`
41-
Protected bool `json:"protected,omitempty"`
42-
Transaction *types.Transaction `json:"transaction,omitempty"`
43-
Receipt *types.Receipt `json:"receipt,omitempty"`
44-
Events []DecodedTransactionLog `json:"events,omitempty"`
34+
Index uint `json:"index"`
35+
Hash string `json:"hash,omitempty"`
36+
Protected bool `json:"protected,omitempty"`
37+
Transaction *types.Transaction `json:"transaction,omitempty"`
38+
Receipt *types.Receipt `json:"receipt,omitempty"`
39+
Events []DecodedTransactionLog `json:"events,omitempty"`
4540
EventDecodingErrors []EventDecodingError `json:"event_decoding_errors,omitempty"`
4641
}
4742

4843
// EventDecodingError represents a failed event decode attempt
4944
type EventDecodingError struct {
50-
Signature string `json:"signature"`
51-
LogIndex uint `json:"log_index"`
52-
Address string `json:"address"`
53-
Topics []string `json:"topics,omitempty"`
54-
Errors []ABIDecodingError `json:"errors,omitempty"`
45+
Signature string `json:"signature"`
46+
LogIndex uint `json:"log_index"`
47+
Address string `json:"address"`
48+
Topics []string `json:"topics,omitempty"`
49+
Errors []ABIDecodingError `json:"errors,omitempty"`
5550
}
5651

5752
// ABIDecodingError represents a single ABI decode attempt failure
5853
type ABIDecodingError struct {
59-
ABIName string `json:"abi_name"`
60-
EventName string `json:"event_name"`
61-
Error string `json:"error"`
54+
ABIName string `json:"abi_name"`
55+
EventName string `json:"event_name"`
56+
Error string `json:"error"`
6257
}
6358

6459
type CommonData struct {
@@ -196,7 +191,7 @@ func (m *Client) DecodeTx(tx *types.Transaction) (*DecodedTransaction, error) {
196191
Msg("No post-decode hook found. Skipping")
197192
}
198193

199-
if decodeErr != nil && errors.Is(decodeErr, errors.New(ErrNoABIMethod)) {
194+
if decodeErr != nil && errors.Is(decodeErr, ErrNoABIMethod) {
200195
m.handleTxDecodingError(l, *decoded, decodeErr)
201196
return decoded, revertErr
202197
}
@@ -524,21 +519,21 @@ func (m *Client) printDecodedTXData(l zerolog.Logger, ptx *DecodedTransaction) {
524519
Interface("Data", e.EventData).
525520
Msg("Event emitted")
526521
}
527-
522+
528523
// Print event decoding errors separately
529524
if len(ptx.EventDecodingErrors) > 0 {
530525
l.Warn().
531526
Int("Failed event decodes", len(ptx.EventDecodingErrors)).
532527
Msg("Some events could not be decoded")
533-
528+
534529
for _, decodeErr := range ptx.EventDecodingErrors {
535530
abiNames := make([]string, len(decodeErr.Errors))
536531
errorMsgs := make([]string, len(decodeErr.Errors))
537532
for i, abiErr := range decodeErr.Errors {
538533
abiNames[i] = abiErr.ABIName
539534
errorMsgs[i] = fmt.Sprintf("%s.%s: %s", abiErr.ABIName, abiErr.EventName, abiErr.Error)
540535
}
541-
536+
542537
l.Warn().
543538
Str("Signature", decodeErr.Signature).
544539
Uint("LogIndex", decodeErr.LogIndex).

seth/gas_adjuster.go

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"math"
88
"math/big"
99
"slices"
10-
"strings"
1110
"sync"
1211
"time"
1312

@@ -37,17 +36,19 @@ const (
3736
)
3837

3938
var (
40-
ZeroGasSuggestedErr = "either base fee or suggested tip is 0"
41-
BlockFetchingErr = "failed to fetch enough block headers for congestion calculation"
39+
GasEstimationErr = errors.New("incorrect gas data received from node. Skipping gas estimation")
40+
BlockFetchingErr = errors.New("failed to fetch enough block headers for congestion calculation")
4241
)
4342

4443
// CalculateNetworkCongestionMetric calculates a simple congestion metric based on the last N blocks
4544
// according to selected strategy.
4645
func (m *Client) CalculateNetworkCongestionMetric(blocksNumber uint64, strategy string) (float64, error) {
4746
if m.HeaderCache == nil {
48-
return 0, fmt.Errorf("header cache is not initialized. " +
47+
err := fmt.Errorf("header cache is not initialized. " +
4948
"This is an internal error that shouldn't happen. " +
5049
"If you see this, please open a GitHub issue at https://github.com/smartcontractkit/chainlink-testing-framework/issues with your configuration details")
50+
err = fmt.Errorf("%w: %v", BlockFetchingErr, err)
51+
return 0, err
5152
}
5253
var getHeaderData = func(bn *big.Int) (*types.Header, error) {
5354
if bn == nil {
@@ -80,13 +81,15 @@ func (m *Client) CalculateNetworkCongestionMetric(blocksNumber uint64, strategy
8081
defer cancel()
8182
lastBlockNumber, err := m.Client.BlockNumber(ctx)
8283
if err != nil {
84+
err = fmt.Errorf("%w: %v", BlockFetchingErr, err)
8385
return 0, err
8486
}
8587

8688
L.Trace().Msgf("Block range for gas calculation: %d - %d", lastBlockNumber-blocksNumber, lastBlockNumber)
8789

8890
lastBlock, err := getHeaderData(big.NewInt(mustSafeInt64(lastBlockNumber)))
8991
if err != nil {
92+
err = fmt.Errorf("%w: %v", BlockFetchingErr, err)
9093
return 0, err
9194
}
9295

@@ -133,7 +136,7 @@ func (m *Client) CalculateNetworkCongestionMetric(blocksNumber uint64, strategy
133136

134137
minBlockCount := int(float64(blocksNumber) * 0.8)
135138
if len(headers) < minBlockCount {
136-
return 0, fmt.Errorf("failed to fetch sufficient block headers for gas estimation. "+
139+
err := fmt.Errorf("failed to fetch sufficient block headers for gas estimation. "+
137140
"Needed at least %d blocks, but only got %d (%.1f%% success rate).\n"+
138141
"This usually indicates:\n"+
139142
" 1. RPC node is experiencing high latency or load\n"+
@@ -145,6 +148,9 @@ func (m *Client) CalculateNetworkCongestionMetric(blocksNumber uint64, strategy
145148
" 3. Disable gas estimation: set gas_price_estimation_enabled = false\n"+
146149
" 4. Reduce gas_price_estimation_blocks to fetch fewer blocks",
147150
minBlockCount, len(headers), float64(len(headers))/float64(blocksNumber)*100)
151+
err = fmt.Errorf("%w: %v", BlockFetchingErr, err)
152+
153+
return 0, err
148154
}
149155

150156
switch strategy {
@@ -153,10 +159,12 @@ func (m *Client) CalculateNetworkCongestionMetric(blocksNumber uint64, strategy
153159
case CongestionStrategy_NewestFirst:
154160
return calculateNewestFirstNetworkCongestionMetric(headers), nil
155161
default:
156-
return 0, fmt.Errorf("unknown network congestion strategy '%s'. "+
162+
err := fmt.Errorf("unknown network congestion strategy '%s'. "+
157163
"Valid strategies are: 'simple' (equal weight) or 'newest_first' (recent blocks weighted more).\n"+
158164
"This is likely a configuration error. Check your gas estimation settings",
159165
strategy)
166+
err = fmt.Errorf("%w: %v", BlockFetchingErr, err)
167+
return 0, err
160168
}
161169
}
162170

@@ -209,13 +217,15 @@ func (m *Client) GetSuggestedEIP1559Fees(ctx context.Context, priority string) (
209217
// fallback to current fees if historical fetching fails
210218
baseFee, currentGasTip, err = m.currentIP1559Fees(ctx)
211219
if err != nil {
220+
err = fmt.Errorf("%w: %v", GasEstimationErr, err)
212221
return
213222
}
214223
L.Debug().Msg("Falling back to current EIP-1559 fees for gas estimation")
215224
}
216225
} else {
217226
baseFee, currentGasTip, err = m.currentIP1559Fees(ctx)
218227
if err != nil {
228+
err = fmt.Errorf("%w: %v", GasEstimationErr, err)
219229
return
220230
}
221231
}
@@ -227,6 +237,7 @@ func (m *Client) GetSuggestedEIP1559Fees(ctx context.Context, priority string) (
227237
" 1. Use a different RPC endpoint\n" +
228238
" 2. Disable gas estimation: set gas_price_estimation_enabled = false in config\n" +
229239
" 3. Set explicit gas values: gas_price, gas_fee_cap, and gas_tip_cap (in your config (seth.toml or ClientBuilder)")
240+
err = fmt.Errorf("%w: %v", GasEstimationErr, err)
230241
return
231242
}
232243

@@ -267,6 +278,7 @@ func (m *Client) GetSuggestedEIP1559Fees(ctx context.Context, priority string) (
267278
Int64("SuggestedTip", currentGasTip.Int64()).
268279
Msgf("Incorrect gas data received from node: base fee was 0. Skipping gas estimation")
269280
err = errors.New("incorrect gas data received from node: base fee was 0. Skipping gas estimation")
281+
err = fmt.Errorf("%w: %v", GasEstimationErr, err)
270282
return
271283
}
272284

@@ -283,6 +295,7 @@ func (m *Client) GetSuggestedEIP1559Fees(ctx context.Context, priority string) (
283295
var adjustmentFactor float64
284296
adjustmentFactor, err = getAdjustmentFactor(priority)
285297
if err != nil {
298+
err = fmt.Errorf("%w: %v", GasEstimationErr, err)
286299
return
287300
}
288301

@@ -315,6 +328,7 @@ func (m *Client) GetSuggestedEIP1559Fees(ctx context.Context, priority string) (
315328
var bufferAdjustment float64
316329
bufferAdjustment, err = getCongestionFactor(congestionClassification)
317330
if err != nil {
331+
err = fmt.Errorf("%w: %v", GasEstimationErr, err)
318332
return
319333
}
320334

@@ -325,7 +339,8 @@ func (m *Client) GetSuggestedEIP1559Fees(ctx context.Context, priority string) (
325339
// Apply buffer also to the tip
326340
bufferedTipCapFloat := new(big.Float).Mul(new(big.Float).SetInt(adjustedTipCap), big.NewFloat(bufferAdjustment))
327341
adjustedTipCap, _ = bufferedTipCapFloat.Int(nil)
328-
} else if !strings.Contains(err.Error(), BlockFetchingErr) {
342+
} else if !errors.Is(err, BlockFetchingErr) {
343+
err = fmt.Errorf("%w: %v", GasEstimationErr, err)
329344
return
330345
} else {
331346
L.Debug().
@@ -550,7 +565,7 @@ func (m *Client) GetSuggestedLegacyFees(ctx context.Context, priority string) (a
550565
}))
551566

552567
if retryErr != nil {
553-
err = retryErr
568+
err = fmt.Errorf("%w: %v", GasEstimationErr, retryErr)
554569
return
555570
}
556571

@@ -562,6 +577,7 @@ func (m *Client) GetSuggestedLegacyFees(ctx context.Context, priority string) (a
562577
var adjustmentFactor float64
563578
adjustmentFactor, err = getAdjustmentFactor(priority)
564579
if err != nil {
580+
err = fmt.Errorf("%w: %v", GasEstimationErr, err)
565581
return
566582
}
567583

@@ -589,13 +605,15 @@ func (m *Client) GetSuggestedLegacyFees(ctx context.Context, priority string) (a
589605
var bufferAdjustment float64
590606
bufferAdjustment, err = getCongestionFactor(congestionClassification)
591607
if err != nil {
608+
err = fmt.Errorf("%w: %v", GasEstimationErr, err)
592609
return
593610
}
594611

595612
// Calculate and apply the buffer.
596613
bufferedGasPriceFloat := new(big.Float).Mul(new(big.Float).SetInt(adjustedGasPrice), big.NewFloat(bufferAdjustment))
597614
adjustedGasPrice, _ = bufferedGasPriceFloat.Int(nil)
598-
} else if !strings.Contains(err.Error(), BlockFetchingErr) {
615+
} else if !errors.Is(err, BlockFetchingErr) {
616+
err = fmt.Errorf("%w: %v", GasEstimationErr, err)
599617
return
600618
} else {
601619
L.Debug().

0 commit comments

Comments
 (0)