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/guestbook/v1"
gno = "0.9"
private = true

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

guestbook.gno

// Package guestbook is a public, on-chain guestbook realm for gno.land.
//
// Anyone can sign the guestbook with a short message via the Sign crossing
// function. Every entry records the caller's address, the message, and the
// block height at which it was signed. Render lists all entries newest-first
// as a Markdown table.
//
// v1 renders through [p/moul/kit/ui](/p/moul/kit/ui/v0) instead of the
// hand-rolled shortAddr and escapeCell helpers v0 carried. The escaping is the
// substantive change: v0 replaced four characters, while ui.Cell also strips
// bidi and zero-width characters, which a message can otherwise use to reorder
// how the rest of the row reads.
package guestbook

import (
	"strconv"
	"strings"

	"chain"
	"chain/markdown"
	"chain/runtime"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
)

// Entry is a single signed guestbook line. It carries no ID field: the id
// belongs to the store, which hands it back on lookup and iteration.
type Entry struct {
	Author  string // bech32 address of the signer
	Message string // the message left by the signer
	Height  int64  // block height at which the entry was signed
}

const maxMessageLen = 280

// entries assigns the sequence numbers. v1 kept its own count plus a seqKey()
// that zero-padded to width 16, the widest of the six hand-rolled variants in
// this repo and still a ceiling; the store key has none.
var entries = store.Named("guestbook: entry")

// Sign appends a new entry to the guestbook attributed to the immediate caller.
//
// It is a crossing function (gno 0.9 interrealm convention): callers invoke it
// as Sign(cross(cur), "hello"). The cur.IsCurrent() guard is the authentication
// primitive — without it a stale/forged realm value could spoof the author.
func Sign(cur realm, message string) {
	if !cur.IsCurrent() {
		panic("guestbook: spoofed realm; Sign must be called via cross(cur)")
	}

	author := cur.Previous().Address().String()
	id, e := addEntry(author, message, runtime.ChainHeight())

	chain.Emit("Signed",
		"id", id.String(),
		"author", e.Author,
		"height", strconv.FormatInt(e.Height, 10),
	)
}

// addEntry validates the message and appends an entry. Non-crossing internal
// helper so the append/validation logic is unit-testable without a realm frame.
// Panics (aborting the tx, reverting state) on an invalid message.
func addEntry(author, message string, height int64) (store.ID, *Entry) {
	msg := strings.TrimSpace(message)
	if strings.TrimSpace(markdown.StripBidiAndZeroWidth(msg)) == "" {
		panic("guestbook: message must not be empty")
	}
	if len(msg) > maxMessageLen {
		panic("guestbook: message too long (max " + strconv.Itoa(maxMessageLen) + " bytes)")
	}

	e := &Entry{
		Author:  author,
		Message: msg,
		Height:  height,
	}
	return entries.Add(e), e
}

// Count returns the total number of signatures. Read-only, non-crossing.
func Count() int {
	return entries.Len()
}

// Render lists every entry newest-first as a Markdown table plus a total count.
func Render(path string) string {
	if entries.Len() == 0 {
		return "# Guestbook\n\n" + ui.Empty("No one has signed yet. Be the first!")
	}

	t := ui.NewTable("#", "Who", "Message", "Height")
	// Ids ascend with signing, so reverse iteration is newest-first.
	entries.EachReverse(func(id store.ID, v any) {
		e := v.(*Entry)
		t.Row(
			id.String(),
			ui.AddrOf(e.Author),
			ui.Cell(e.Message),
			strconv.FormatInt(e.Height, 10),
		)
	})

	return "# Guestbook\n\n**Total signatures:** " + strconv.Itoa(entries.Len()) + "\n\n" + t.String()
}

guestbook_test.gno

package guestbook

import (
	"strings"
	"testing"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
)

// resetState clears package globals between tests (globals persist across
// test functions in the same package binary).
func resetState() {
	entries = store.Named("guestbook: entry")
}

func TestAddEntryAppendsAndCounts(t *testing.T) {
	resetState()

	addEntry("g1alice", "hello world", 100)
	addEntry("g1bob", "second entry", 101)

	if got := Count(); got != 2 {
		t.Fatalf("Count() = %d, want 2", got)
	}

	out := Render("")
	if !strings.Contains(out, "**Total signatures:** 2") {
		t.Errorf("Render missing total; got:\n%s", out)
	}
	if !strings.Contains(out, "hello world") {
		t.Errorf("Render missing first message; got:\n%s", out)
	}
	if !strings.Contains(out, "second entry") {
		t.Errorf("Render missing second message; got:\n%s", out)
	}
	if !strings.Contains(out, "100") || !strings.Contains(out, "101") {
		t.Errorf("Render missing heights; got:\n%s", out)
	}
}

func TestRenderNewestFirst(t *testing.T) {
	resetState()

	addEntry("g1alice", "AAA oldest", 1)
	addEntry("g1alice", "BBB newest", 2)

	out := Render("")
	iNew := strings.Index(out, "BBB newest")
	iOld := strings.Index(out, "AAA oldest")
	if iNew < 0 || iOld < 0 {
		t.Fatalf("both messages must appear; got:\n%s", out)
	}
	if iNew > iOld {
		t.Errorf("newest entry should render before oldest; got:\n%s", out)
	}
}

func TestRenderEmpty(t *testing.T) {
	resetState()

	out := Render("")
	if !strings.Contains(out, "No one has signed yet") {
		t.Errorf("empty render should invite signing; got:\n%s", out)
	}
}

func TestEmptyMessagePanics(t *testing.T) {
	resetState()

	defer func() {
		if r := recover(); r == nil {
			t.Errorf("signing an empty message should panic")
		}
	}()
	addEntry("g1alice", "   ", 1)
}

// A message must not be able to break out of its table cell. The escaping now
// lives in ui.Cell, so this asserts the realm's rendered output rather than a
// local helper.
func TestRenderEscapesMessage(t *testing.T) {
	resetState()
	defer resetState()
	addEntry("g1manfred47kzduec920z88wfr64ylksmdcedlf5", "a|b", 1)
	out := Render("")
	if strings.Contains(out, "| a|b |") {
		t.Errorf("an unescaped pipe would open a column:\n%s", out)
	}
	if !strings.Contains(out, `a\|b`) {
		t.Errorf("message should appear escaped:\n%s", out)
	}
}

// v1 asserted that its own seqKey() ordered numerically. That held only below
// its width of 16: seqKey(10^16) is 17 characters and sorts before
// seqKey(10^16-1). The store key is 8 bytes for every id, so there is no
// ceiling to reach.
func TestSeqKeyOrders(t *testing.T) {
	if a, b := store.ID(2).Key(), store.ID(10).Key(); !(a < b) {
		t.Error("id 2 should sort before id 10")
	}
	if a, b := store.ID(9999999999999999).Key(), store.ID(10000000000000000).Key(); !(a < b) {
		t.Error("ordering should survive one past v1's width-16 ceiling")
	}
}

render_example_test.gno

package guestbook

// ExampleRender pins the realm's Render output as a testable example.
func ExampleRender() {
	print(Render(""))
	// Output:
	// # Guestbook
	//
	// *No one has signed yet. Be the first!*
}

zz_zerowidth_test.gno

package guestbook

import (
	"testing"
)

// zwBlank holds one input per rune range chain/markdown.StripBidiAndZeroWidth
// removes (U+200B..U+200F, U+202A..U+202E, U+2066..U+2069, U+FEFF), plus a mix
// with real spaces. strings.TrimSpace keeps every one of them and the render
// strips them all, so each must be refused.
var zwBlank = []string{
	"\u200b\u200b\u200b", // ZWSP
	"\u200d",             // ZWJ
	"\u200e",             // LRM
	"\u202e",             // RLO
	"\u2066\u2069",       // LRI PDI
	"\ufeff",             // BOM
	" \u200b \u200b ",    // mixed with real spaces
}

// zwOK must stay accepted: the stripper removes the marks and leaves text.
var zwOK = []string{"a", "a\u200bb", "  padded  "}

func zwPanics(f func()) (p bool) {
	defer func() {
		if recover() != nil {
			p = true
		}
	}()
	f()
	return false
}

func TestZeroWidthMessageIsRefused(t *testing.T) {
	resetState()
	defer resetState()
	for _, s := range zwBlank {
		if !zwPanics(func() { addEntry("g1alice", s, 1) }) {
			t.Errorf("addEntry(%q) accepted a message the render strips to blank", s)
		}
	}
	for _, s := range zwOK {
		if zwPanics(func() { addEntry("g1alice", s, 1) }) {
			t.Errorf("addEntry(%q) refused a message that renders as text", s)
		}
	}
	if Count() != len(zwOK) {
		t.Errorf("Count = %d, want %d", Count(), len(zwOK))
	}
}