Skip to content

Refactor: clean up getBalance archival balance resolution logic #5193

Description

@bootcodes

Problem

Context

During #5146 (migration of eth_getBalance to a worker thread), several pre-existing issues in the balance resolution logic were identified but intentionally left unaddressed to keep the migration PR focused.
This issue tracks the follow-up cleanup.

Problems

1. Opaque control flow in archival balance resolution

The method that resolves whether a block identifier refers to the chain tip or a historical block (extractBlockNumberAndTimestamp) is difficult to follow. The core logic is:

if block tag is pending/latest → return null (not archival)
resolve block identifier → block number
if block is within tip tolerance → return null (not archival)
return balance at historical block ?? 0

This is buried under nested conditionals and a mutable blockNumberOrTagOrHash variable that is promoted to constants.BLOCK_LATEST inside the function - a hidden state change that is non-obvious to callers.

2. Double blockTagIsLatestOrPending check

blockTagIsLatestOrPending is called twice with the same key before and after extractBlockNumberAndTimestamp. The second check is necessary because the function can promote blockNumberOrTagOrHash to BLOCK_LATEST internally - but this is
invisible from the call site. A discriminated return type would make this explicit and eliminate the second check.

3. Magic number for block tip tolerance

The tolerance of 1 block used to determine whether a request targets the chain tip is an inline magic number with no explanation. It should be a named constant with documentation explaining why that value was chosen.

Solution

  • Refactor extractBlockNumberAndTimestamp to return a discriminated union ({ isLatest: true, latestBlock } | { isLatest: false, latestBlock, blockNumberOrTagOrHash }) so callers do not need to inspect the returned blockNumberOrTagOrHash to
    determine routing
  • Extract the tip tolerance to constants.LATEST_BLOCK_TOLERANCE with a comment explaining the value
  • Restructure the nested conditionals into a flat, readable sequence matching the logic description above

Alternatives

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Team PromotedIssues to be triaged and discussed by committers, maintainers, to be worked on the following sprintenhancementNew feature or request

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions