From 99cac64faeff1113657b285f311c79017bc44927 Mon Sep 17 00:00:00 2001 From: pablomendezroyo Date: Wed, 11 Dec 2024 12:46:48 +0100 Subject: [PATCH] Fix block hex parse to number --- .../adapters/execution/execution_adapter.go | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/internal/adapters/execution/execution_adapter.go b/internal/adapters/execution/execution_adapter.go index 940c664..caaa223 100644 --- a/internal/adapters/execution/execution_adapter.go +++ b/internal/adapters/execution/execution_adapter.go @@ -2,9 +2,12 @@ package execution import ( "bytes" + "encoding/binary" "encoding/json" "fmt" "net/http" + + "github.com/ethereum/go-ethereum/common/hexutil" ) // ExecutionAdapter interacts with the Ethereum execution client to fetch block information. @@ -54,13 +57,24 @@ func (e *ExecutionAdapter) GetMostRecentBlockNumber() (uint64, error) { return 0, fmt.Errorf("failed to decode response from execution client: %w", err) } - // Convert the hexadecimal block number to uint64 - var blockNumber uint64 - _, err = fmt.Sscanf(result.Result, "0x%x", &blockNumber) + // Convert the hexadecimal block number to uint64 using hexutil.Decode + decodedBytes, err := hexutil.Decode(result.Result) if err != nil { - return 0, fmt.Errorf("failed to parse block number from result %s: %w", result.Result, err) + return 0, fmt.Errorf("failed to decode block number from result %s: %w", result.Result, err) + } + + // Ensure the decoded byte slice does not exceed 8 bytes for uint64 + if len(decodedBytes) > 8 { + return 0, fmt.Errorf("block number too large to fit in uint64: length %d bytes", len(decodedBytes)) } + // Convert the byte slice to uint64 + var blockNumber uint64 + // If the byte slice is less than 8 bytes, pad it with leading zeros + paddedBytes := make([]byte, 8) + copy(paddedBytes[8-len(decodedBytes):], decodedBytes) + blockNumber = binary.BigEndian.Uint64(paddedBytes) + return blockNumber, nil }