Playground
codespan_test.gno
package streaks
import (
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
// The not-found branch echoes the visitor's URL path into a code span. Built by
// hand, a backtick in the path closed the span early and everything after it
// rendered as markdown on a gno.land page. md.InlineCode sizes the fence past
// any backtick run in the content, so the payload must come back wrapped in a
// DOUBLE fence, with the backtick intact inside it. Asserting on the payload
// itself rather than on any double fence in the page: an earlier version of
// this test passed on an unrelated span elsewhere in the output.
func TestRenderPathCannotEscapeItsCodeSpan(t *testing.T) {
out := Render("/a`b")
fenced := strings.Contains(out, "``a`b``") || strings.Contains(out, "``/a`b``")
uassert.True(t, fenced,
"the fence did not outscan the caller's backtick, so the span closes early")
}
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/streaks/v1" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914308 max_deposit = "6000000ugnot"
streaks.gno
// Package streaks is an on-chain habit-streak tracker. Call CheckIn() again
// within graceBlocks of your last check-in and the streak keeps growing; let
// the gap run past that and it resets to zero on your next check-in. Gno has
// no wall clock, so "again soon enough" is measured in blocks rather than
// calendar days — graceBlocks is the tunable stand-in for "before tomorrow".
package streaks
import (
"sort"
"strconv"
"chain/runtime"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
"gno.land/p/nt/avl/v0"
)
// graceBlocks is the max block gap between two check-ins that still counts
// as consecutive. A gap larger than this lapses the streak.
const graceBlocks int64 = 100
// record is the persisted streak state for one address.
type record struct {
owner address
current int64
longest int64
total int64
lastHeight int64
}
var streaks avl.Tree // owner address string -> *record
func get(owner address) (*record, bool) {
v, ok := streaks.Get(owner.String()).(*record)
return v, ok
}
// project reports the record's current streak as of height without
// mutating it: once the gap since lastHeight exceeds graceBlocks the streak
// reads as lapsed, even though the stored value only resets on the next
// actual check-in.
func project(r *record, height int64) (current int64, alive bool) {
if height-r.lastHeight > graceBlocks {
return 0, false
}
return r.current, true
}
// checkin is the non-crossing core of CheckIn, kept separate so unit tests
// can drive it directly by address and height.
func checkin(owner address, height int64) string {
r, ok := get(owner)
if !ok {
r = &record{owner: owner}
streaks.Set(owner.String(), r)
} else {
if height <= r.lastHeight {
panic("already checked in at this block height")
}
if height-r.lastHeight > graceBlocks {
r.current = 0
}
}
r.current++
if r.current > r.longest {
r.longest = r.current
}
r.lastHeight = height
r.total++
return "checked in — current streak: " + strconv.FormatInt(r.current, 10) + " 🔥"
}
// CheckIn records a check-in for the caller at the current block height.
func CheckIn(cur realm) string {
if !cur.IsCurrent() {
panic("spoofed realm")
}
return checkin(cur.Previous().Address(), runtime.ChainHeight())
}
// CurrentStreak returns addr's live current streak, 0 if it has lapsed or
// addr has never checked in.
func CurrentStreak(addr string) int64 {
r, ok := get(address(addr))
if !ok {
return 0
}
current, _ := project(r, runtime.ChainHeight())
return current
}
// LongestStreak returns addr's best streak ever, 0 if it has never checked in.
func LongestStreak(addr string) int64 {
r, ok := get(address(addr))
if !ok {
return 0
}
return r.longest
}
// byRank orders the leaderboard by longest streak, then current streak, then
// owner address — fully deterministic regardless of avl iteration order.
type byRank []*record
func (b byRank) Len() int { return len(b) }
func (b byRank) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b byRank) Less(i, j int) bool {
if b[i].longest != b[j].longest {
return b[i].longest > b[j].longest
}
if b[i].current != b[j].current {
return b[i].current > b[j].current
}
return b[i].owner.String() < b[j].owner.String()
}
func renderDetail(r *record, height int64) string {
current, alive := project(r, height)
status := "🔥 active"
if !alive {
status = "💤 lapsed"
}
out := "## " + ui.Addr(r.owner) + "\n\n"
out += "- Status: " + status + "\n"
out += "- Current streak: " + strconv.FormatInt(current, 10) + "\n"
out += "- Longest streak: " + strconv.FormatInt(r.longest, 10) + "\n"
out += "- Total check-ins: " + strconv.FormatInt(r.total, 10) + "\n"
out += "- Last check-in at block " + strconv.FormatInt(r.lastHeight, 10) + "\n"
return out
}
// Render shows either the full leaderboard (path == "") or a single
// address's detail card when path is a bech32 address.
func Render(path string) string {
height := runtime.ChainHeight()
out := "# 🔥 Streaks\n\n"
out += "An on-chain habit-streak tracker. Call `CheckIn()` again within " +
strconv.FormatInt(graceBlocks, 10) + " blocks of your last check-in to keep it alive; " +
"wait longer than that and it resets to zero on your next check-in.\n\n"
if path != "" {
r, ok := get(address(path))
if !ok {
return out + "_No check-ins yet for " + md.InlineCode(path) + "._\n"
}
return out + renderDetail(r, height)
}
var rows []*record
streaks.Iterate("", "", func(_ string, v any) bool {
rows = append(rows, v.(*record))
return false
})
if len(rows) == 0 {
out += "_Nobody has checked in yet. Be the first!_\n"
return out
}
sort.Stable(byRank(rows))
out += "| Rank | Address | Status | Current | Longest | Total |\n"
out += "| ---: | :--- | :--- | ---: | ---: | ---: |\n"
for i, r := range rows {
current, alive := project(r, height)
status := "🔥"
if !alive {
status = "💤"
}
out += "| " + strconv.Itoa(i+1) + " | " + ui.Addr(r.owner) + " | " + status +
" | " + strconv.FormatInt(current, 10) + " | " + strconv.FormatInt(r.longest, 10) +
" | " + strconv.FormatInt(r.total, 10) + " |\n"
}
out += "\n_View a single address at `?<address>`._\n"
return out
}
streaks_test.gno
package streaks
import (
"strings"
"testing"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
)
func resetState() {
streaks = avl.Tree{}
}
func TestCheckinFirstTimeStartsStreak(t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
checkin(alice, 100)
r, ok := get(alice)
if !ok {
t.Fatal("expected a record after first check-in")
}
if r.current != 1 || r.longest != 1 || r.total != 1 {
t.Fatalf("expected current=1 longest=1 total=1, got current=%d longest=%d total=%d", r.current, r.longest, r.total)
}
}
func TestCheckinWithinGraceExtendsStreak(t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
checkin(alice, 100)
checkin(alice, 150) // gap of 50 <= graceBlocks(100)
checkin(alice, 200) // gap of 50 again
r, _ := get(alice)
if r.current != 3 {
t.Fatalf("expected streak of 3, got %d", r.current)
}
if r.longest != 3 {
t.Fatalf("expected longest of 3, got %d", r.longest)
}
}
func TestCheckinAfterGraceResetsStreak(t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
checkin(alice, 100)
checkin(alice, 150)
checkin(alice, 400) // gap of 250 > graceBlocks(100): lapsed
r, _ := get(alice)
if r.current != 1 {
t.Fatalf("expected streak reset to 1, got %d", r.current)
}
if r.longest != 2 {
t.Fatalf("expected longest to stay at 2, got %d", r.longest)
}
if r.total != 3 {
t.Fatalf("expected total check-ins of 3, got %d", r.total)
}
}
func TestCheckinSameOrEarlierHeightPanics(t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
checkin(alice, 100)
defer func() {
if r := recover(); r == nil {
t.Fatal("expected panic checking in at a non-later height")
}
}()
checkin(alice, 100)
}
func TestProjectReportsLapsedWithoutMutating(t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
checkin(alice, 100)
r, _ := get(alice)
current, alive := project(r, 100+graceBlocks+1)
if alive || current != 0 {
t.Fatalf("expected lapsed projection (0, false), got (%d, %v)", current, alive)
}
// Stored state must be untouched by a read-only projection.
if r.current != 1 {
t.Fatalf("project must not mutate stored state, got current=%d", r.current)
}
}
func TestCurrentStreakAndLongestStreakQueries(t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
checkin(alice, 100)
checkin(alice, 150)
if got := LongestStreak(alice.String()); got != 2 {
t.Fatalf("LongestStreak() = %d, want 2", got)
}
if got := LongestStreak(testutils.TestAddress("bob").String()); got != 0 {
t.Fatalf("LongestStreak() for unknown address = %d, want 0", got)
}
}
func TestRenderShowsEmptyThenLeaderboardThenDetail(t *testing.T) {
resetState()
if !strings.Contains(Render(""), "Nobody has checked in yet") {
t.Fatal("expected empty-state placeholder")
}
alice := testutils.TestAddress("alice")
checkin(alice, 100)
out := Render("")
if !strings.Contains(out, "Rank") {
t.Fatal("expected leaderboard table in root render")
}
detail := Render(alice.String())
if !strings.Contains(detail, "Current streak") {
t.Fatal("expected detail card to show current streak")
}
if !strings.Contains(Render(testutils.TestAddress("bob").String()), "No check-ins yet") {
t.Fatal("expected placeholder for an address with no check-ins")
}
}
// TestCheckInViaCrossingCall smoke-tests the exported, realm-crossing entry
// point end to end (as an on-chain caller would invoke it).
func TestCheckInViaCrossingCall(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
testing.SetRealm(testing.NewUserRealm(alice))
msg := CheckIn(cross(cur))
if !strings.Contains(msg, "checked in") {
t.Fatalf("expected check-in confirmation, got %q", msg)
}
if _, ok := get(alice); !ok {
t.Fatal("expected a record to be persisted for caller")
}
}