Skip to content

fix: replace reverting, quadratic on-chain leaderboard - #13

Open
Xaxxoo wants to merge 1 commit into
DogStark:mainfrom
Xaxxoo:fix/issue-8-leaderboard-revert-and-quadratic
Open

fix: replace reverting, quadratic on-chain leaderboard#13
Xaxxoo wants to merge 1 commit into
DogStark:mainfrom
Xaxxoo:fix/issue-8-leaderboard-revert-and-quadratic

Conversation

@Xaxxoo

@Xaxxoo Xaxxoo commented Aug 22, 2026

Copy link
Copy Markdown

Summary

Fixes #8

  • Fixed underflow revert: getLeaderboard() now returns an empty array when registeredPlayers.length == 0 or topN == 0, instead of reverting with an arithmetic panic from the unchecked total - 1 expression.
  • Replaced O(n²) bubble sort with O(n × K) partial selection sort: Only the top K entries are selected, avoiding full-array sorting. Gas and RPC performance no longer grows quadratically with player count.
  • Deterministic tie-breaking: When two players have equal totalScore, the one with the higher streak is ranked first; if streaks are also equal, earlier registration order (lower array index) wins.
  • Oversized topN handled safely: topN > playerCount is clamped to playerCount, never reverts.

Test coverage added

Case Result
0 registered players Returns []
topN = 0 Returns []
topN > playerCount Returns all players, no revert
Single player Returns correctly
Tie-breaking by streak Higher streak ranked first
Standard sorted board Highest score first

All 17 tests pass.

Test plan

  • npx hardhat test — all tests pass
  • Verify getLeaderboard(10) on empty contract returns [] (no revert)
  • Verify getLeaderboard(0) always returns []
  • Verify topN > playerCount returns correct subset
  • Verify tie-breaking is deterministic

🤖 Generated with Claude Code

- Return empty array when registeredPlayers.length == 0 or topN == 0,
  fixing the arithmetic underflow panic on empty leaderboard
- Replace O(n²) bubble sort with O(n * topN) partial selection sort,
  eliminating quadratic gas growth for view calls
- Add deterministic tie-breaking: higher streak first, then earlier
  registration order
- Cap topN to actual player count so oversized requests never revert
- Add tests for 0-player, topN=0, single-player, oversized topN, and
  tie-breaking edge cases

Closes DogStark#8

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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 this pull request may close these issues.

Replace reverting, quadratic on-chain leaderboard implementation

1 participant