Skip to Content

BTreeStore leaderboard

Focus: one persistent leaderboard contract that stores score keys in order and reads the highest scores.

Open in Playground 

leaderboard.slx
const BOARD_NS: bytes = "leaderboard".to_bytes() fn score_key(score: u64, player: Address) -> bytes { let key: bytes = score.to_be_bytes() key.extend(player.to_bytes()) return key } entry submit_score(player: Address, score: u64) { let board: BTreeStore = BTreeStore::new(BOARD_NS) board.insert(score_key(score, player), [player, score]) return 0 } entry top(limit: u32) -> any[] { let board: BTreeStore = BTreeStore::new(BOARD_NS) let (cursor, first): (BTreeCursor, optional<Entry>) = board.seek( u64::MAX.to_be_bytes(), BTreeSeekBias::LessOrEqual, false ) let results: any[] = [] let entry: optional<Entry> = first let count: u32 = 0 while count < limit && entry != null { let item: Entry = entry.unwrap() results.push(item.value) entry = cursor.next() count += 1 } return results }

How it works

  • BOARD_NS gives this contract a dedicated persistent tree namespace.
  • score_key(score, player) encodes the score first, then the player address, so keys sort by score.
  • submit_score(player, score) stores one [player, score] value and returns the default success exit code.
  • top(limit) seeks near the maximum possible score and walks backward by passing false for ascending order.
  • top(limit) returns the selected leaderboard entries directly.
Last updated on