Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

epoch_from_block_number improvement suggestions #4036

Open
Ayiga opened this issue Jan 17, 2025 · 0 comments · May be fixed by #4037
Open

epoch_from_block_number improvement suggestions #4036

Ayiga opened this issue Jan 17, 2025 · 0 comments · May be fixed by #4037

Comments

@Ayiga
Copy link
Member

Ayiga commented Jan 17, 2025

In inspecting the implementation of epoch_from_block_number as it currently exists:

/// Returns an epoch number given a block number and an epoch height
#[must_use]
pub fn epoch_from_block_number(block_number: u64, epoch_height: u64) -> u64 {
if epoch_height == 0 {
0
} else if block_number % epoch_height == 0 {
block_number / epoch_height
} else {
block_number / epoch_height + 1
}
}

It seems that there is room for improvement on this implementation in terms of readability. Specifically the parameter epoch_height seems slightly confusing, as we tend to use the term height when applied to other parameters interchangeably with the position of that element. For example, we use "block height" to refer to the same thing that this function calls "block number". As a result, the term epoch_height would tend to similarly indicate the current position of the epoch. However, since the point of this function is to compute the epoch based on the block number / height, a more indicative parameter name that would better capture the intent of this parameter might be blocks_per_epoch.

In terms of the implementation itself, we have 3 separate branches of return path for this single function that seem a little confusing upon first glance, until we realize what's meant to be happening. Essentially we want to return block_number / epoch_height, which seems plane. However, we want to ensure that for block_number 0, we want to return 0, and as a result for every whole number division of the epoch_height, we want to return the previous epoch number.

Realizing this, It's clear that we could actually implement this without the conditional branches:

(block_height + epoch_height - 1) / epoch_height

This achieves the same result without the conditionals, and still passes all of the same tests.

@Ayiga Ayiga linked a pull request Jan 17, 2025 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant