Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/leaderboard/v1"
gno = "0.9"
private = true

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 914308
  max_deposit = "5000000ugnot"

leaderboard.gno

// Package leaderboard is an on-chain score leaderboard realm.
//
// Any account can accumulate points via AddPoints and (optionally) attach a
// display name with SetName. Render produces a ranked Markdown table sorted by
// points descending, with medals for the top three players.
package leaderboard

import (
	"sort"
	"strconv"

	"chain/runtime/unsafe"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
	"gno.land/p/nt/avl/v0"
)

// player holds the accumulated state for a single address.
type player struct {
	addr   address
	name   string
	points int
}

// players maps address string -> *player. An avl.Tree gives deterministic
// iteration (unlike a Go map) so Render output is stable across nodes.
var players avl.Tree

// get returns the stored *player for addr, creating one if absent.
func get(addr address) *player {
	key := addr.String()
	if v := players.Get(key); v != nil {
		return v.(*player)
	}
	p := &player{addr: addr}
	players.Set(key, p)
	return p
}

// caller returns the address of the account that invoked the current tx.
// unsafe.PreviousRealm() is the origin user for a MsgCall entry point.
func caller() address {
	return unsafe.PreviousRealm().Address()
}

// AddPoints adds n points to the caller's total. n must be positive.
//
// Crossing function: MsgCall dispatches only to crossing functions, and the
// cur.IsCurrent() check authenticates the live call frame before we trust the
// caller identity derived from it.
func AddPoints(cur realm, n int) {
	if !cur.IsCurrent() {
		panic("spoofed realm")
	}
	if n <= 0 {
		panic("points must be positive")
	}
	p := get(caller())
	p.points += n
}

// SetName attaches a display name (max 32 bytes) to the caller. Passing an
// empty string clears the name and falls back to the address in Render.
func SetName(cur realm, name string) {
	if !cur.IsCurrent() {
		panic("spoofed realm")
	}
	if len(name) > 32 {
		panic("name too long (max 32)")
	}
	get(caller()).name = name
}

// display returns the player's name, or a shortened address if unnamed.
func (p *player) display() string {
	if p.name != "" {
		return p.name
	}
	s := p.addr.String()
	if len(s) > 12 {
		return s[:8] + "…" + s[len(s)-4:]
	}
	return s
}

// byRank implements sort.Interface, ranking players by points descending with
// ties broken by address so the order is deterministic across nodes. The gno
// sort package exposes Sort/Stable over an Interface — there is no sort.Slice.
type byRank []*player

func (r byRank) Len() int      { return len(r) }
func (r byRank) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r byRank) Less(i, j int) bool {
	if r[i].points != r[j].points {
		return r[i].points > r[j].points
	}
	return r[i].addr.String() < r[j].addr.String()
}

// snapshot collects all players into a slice ranked by points descending.
func snapshot() []*player {
	out := make([]*player, 0, players.Size())
	players.Iterate("", "", func(_ string, v any) bool {
		out = append(out, v.(*player))
		return false
	})
	sort.Stable(byRank(out))
	return out
}

// Render produces the Markdown leaderboard. It is NOT a crossing function
// (read-only view, no cur realm parameter).
func Render(path string) string {
	ranked := snapshot()

	out := "# 🏆 Leaderboard\n\n"
	if len(ranked) == 0 {
		out += "_No players yet. Call `AddPoints(n)` to get on the board._\n"
		return out
	}

	out += "Total players: **" + strconv.Itoa(len(ranked)) + "**\n\n"
	out += "| Rank | Player | Points |\n"
	out += "| ---: | :--- | ---: |\n"
	for i, p := range ranked {
		rankCell := ui.Podium(i)
		if rankCell == "" {
			rankCell = strconv.Itoa(i + 1)
		}
		out += "| " + rankCell +
			" | " + p.display() +
			" | " + strconv.Itoa(p.points) + " |\n"
	}
	return out
}

leaderboard_test.gno

package leaderboard

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

// resetState clears package globals between tests. Global-state reset belongs
// in a helper; realm setup (SetRealm) must NOT — it only affects its own frame.
func resetState() {
	keys := []string{}
	players.Iterate("", "", func(key string, _ any) bool {
		keys = append(keys, key)
		return false
	})
	for _, k := range keys {
		players.Remove(k)
	}
}

const (
	alice = "g1alice00000000000000000000000000000000"
	bob   = "g1bob0000000000000000000000000000000000"
	carol = "g1carol00000000000000000000000000000000"
)

// Crossing test: takes `cur realm` so it can call crossing functions via
// cross(cur). SetRealm is called directly in this frame (never via a helper).
func TestAddPointsAccumulatesAndRanks(cur realm, t *testing.T) {
	resetState()

	testing.SetRealm(testing.NewUserRealm(address(alice)))
	AddPoints(cross(cur), 10)
	AddPoints(cross(cur), 5) // accumulates -> 15

	testing.SetRealm(testing.NewUserRealm(address(bob)))
	AddPoints(cross(cur), 20)

	uassert.Equal(t, 15, get(address(alice)).points, "alice points")
	uassert.Equal(t, 20, get(address(bob)).points, "bob points")

	// Ranking: bob (20) outranks alice (15).
	ranked := snapshot()
	uassert.Equal(t, 2, len(ranked), "player count")
	uassert.Equal(t, bob, ranked[0].addr.String(), "rank 1 is bob")
	uassert.Equal(t, alice, ranked[1].addr.String(), "rank 2 is alice")
}

func TestRenderTableWithMedalsAndName(cur realm, t *testing.T) {
	resetState()

	// Empty board.
	uassert.True(t, strings.Contains(Render(""), "No players yet"), "empty placeholder")

	testing.SetRealm(testing.NewUserRealm(address(alice)))
	AddPoints(cross(cur), 30)
	SetName(cross(cur), "Alice")

	testing.SetRealm(testing.NewUserRealm(address(bob)))
	AddPoints(cross(cur), 20)

	testing.SetRealm(testing.NewUserRealm(address(carol)))
	AddPoints(cross(cur), 10)

	out := Render("")

	uassert.True(t, strings.Contains(out, "| 🥇 | Alice | 30 |"), "Alice gold row")
	uassert.True(t, strings.Contains(out, "🥈"), "silver medal present")
	uassert.True(t, strings.Contains(out, "🥉"), "bronze medal present")
	uassert.True(t, strings.Contains(out, "Total players: **3**"), "total players count")
}

func TestSetNameTooLongPanics(cur realm, t *testing.T) {
	resetState()
	testing.SetRealm(testing.NewUserRealm(address(alice)))
	uassert.AbortsWithMessage(t, cur, "name too long (max 32)", func() {
		SetName(cross(cur), strings.Repeat("x", 33))
	})
}

func TestAddPointsRejectsNonPositive(cur realm, t *testing.T) {
	resetState()
	testing.SetRealm(testing.NewUserRealm(address(alice)))
	uassert.AbortsWithMessage(t, cur, "points must be positive", func() {
		AddPoints(cross(cur), 0)
	})
}

render_example_test.gno

package leaderboard

// ExampleRender pins the realm's Render output as a testable example.
func ExampleRender() {
	print(Render(""))
	// Output:
	// # 🏆 Leaderboard
	//
	// _No players yet. Call `AddPoints(n)` to get on the board._
}