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/nym-moultest123/x/daily/quotes/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186408
  max_deposit = "5000000ugnot"

quotes.gno

// Package quotes is a community "Quote of the Moment" board realm.
//
// Anyone can submit a quote via the exported crossing function AddQuote.
// Each quote records its text, the address of the caller who added it, and
// the block height at submission time. Render deterministically picks a
// "featured" quote by the current block height (a stable index into the
// list), shows it as a blockquote, then lists every quote with its author
// and id below.
package quotes

import (
	"strconv"
	"strings"

	"chain"
	"chain/runtime"
)

// quote is a single board entry. Author is stored as a plain string address
// (realm values are ephemeral and must never be persisted).
type quote struct {
	id     int
	text   string
	author string // bech32 address of the submitter, or "" for seeded quotes
	height int64  // block height at submission (0 for seeded quotes)
}

// board is the persistent realm state. A plain slice is fine here: the list
// only ever grows by append and Render walks it in insertion order, which is
// deterministic.
var board []quote

// init seeds the board so a fresh deploy renders nicely.
func init() {
	seed := []string{
		"The unexamined life is not worth living.",
		"We suffer more often in imagination than in reality.",
		"Waste no more time arguing about what a good person should be. Be one.",
		"He who is brave is free.",
	}
	for _, s := range seed {
		board = append(board, quote{
			id:     len(board),
			text:   s,
			author: "", // seeded
			height: 0,
		})
	}
}

// AddQuote is the exported, state-mutating entry point. It follows the gno 0.9
// interrealm crossing convention: the first parameter is `cur realm`. Callers
// invoke it as AddQuote(cross(cur), "...") over a MsgCall.
func AddQuote(cur realm, text string) {
	// Authentication primitive: reject a stale/forged realm value before
	// deriving any caller identity from it.
	if !cur.IsCurrent() {
		panic("spoofed realm: cur is not the live crossing frame")
	}

	if err := validate(text); err != nil {
		panic(err)
	}

	author := cur.Previous().Address().String()
	h := runtime.ChainHeight()

	board = append(board, quote{
		id:     len(board),
		text:   text,
		author: author,
		height: h,
	})

	chain.Emit("QuoteAdded",
		"id", strconv.Itoa(len(board)-1),
		"author", author,
		"height", strconv.FormatInt(h, 10),
	)
}

// maxQuoteLen caps quote length to keep storage costs bounded and Render tidy.
const maxQuoteLen = 280

// validate enforces basic content rules. Returns an error describing the
// problem, or nil when the text is acceptable.
func validate(text string) error {
	if len(text) == 0 {
		return errEmpty
	}
	if len(text) > maxQuoteLen {
		return errTooLong
	}
	return nil
}

// Sentinel errors for validation. Kept as package-level vars so tests can
// compare against them directly.
var (
	errEmpty   = quoteError("quote text must not be empty")
	errTooLong = quoteError("quote text exceeds " + strconv.Itoa(maxQuoteLen) + " characters")
)

// quoteError is a trivial string-backed error type (the VM has no host
// stdlib errors package convenience beyond this).
type quoteError string

func (e quoteError) Error() string { return string(e) }

// featuredIndex deterministically picks which quote is "of the moment" for a
// given block height. Pure function of (height, count) so it is fully
// deterministic and easy to test.
func featuredIndex(height int64, count int) int {
	if count <= 0 {
		return -1
	}
	// Guard against a negative height (should not happen on-chain, but keeps
	// the modulo well-defined).
	if height < 0 {
		height = -height
	}
	return int(height % int64(count))
}

// Render produces the Markdown page shown in gnoweb. It is NOT a crossing
// function (no `cur realm` parameter) — it is a read-only view.
func Render(path string) string {
	count := len(board)
	if count == 0 {
		return "# Quote of the Moment\n\n_No quotes yet. Be the first to add one._\n"
	}

	h := runtime.ChainHeight()
	idx := featuredIndex(h, count)
	featured := board[idx]

	var b strings.Builder
	b.WriteString("# Quote of the Moment\n\n")

	// Featured quote as a blockquote.
	b.WriteString("> ")
	b.WriteString(featured.text)
	b.WriteString("\n>\n> — ")
	b.WriteString(authorLabel(featured))
	b.WriteString(" (#")
	b.WriteString(strconv.Itoa(featured.id))
	b.WriteString(")\n\n")

	b.WriteString("_Featured pick rotates with block height ")
	b.WriteString(strconv.FormatInt(h, 10))
	b.WriteString(" — index ")
	b.WriteString(strconv.Itoa(idx))
	b.WriteString(" of ")
	b.WriteString(strconv.Itoa(count))
	b.WriteString("._\n\n")

	// Full list.
	b.WriteString("## All quotes (")
	b.WriteString(strconv.Itoa(count))
	b.WriteString(")\n\n")
	for _, q := range board {
		b.WriteString("- **#")
		b.WriteString(strconv.Itoa(q.id))
		b.WriteString("** ")
		b.WriteString(q.text)
		b.WriteString(" — _")
		b.WriteString(authorLabel(q))
		b.WriteString("_\n")
	}

	return b.String()
}

// authorLabel renders a human-friendly author string. Seeded quotes (empty
// author) show as the house account.
func authorLabel(q quote) string {
	if q.author == "" {
		return "the board"
	}
	return q.author
}

quotes_test.gno

package quotes

import (
	"strings"
	"testing"
)

// TestFeaturedIndexDeterministic verifies the rotating pick is a pure,
// deterministic function of (height, count): same inputs -> same index,
// always within [0, count).
func TestFeaturedIndexDeterministic(t *testing.T) {
	tests := []struct {
		name   string
		height int64
		count  int
		want   int
	}{
		{"zero height", 0, 4, 0},
		{"wraps at count", 4, 4, 0},
		{"mid range", 5, 4, 1},
		{"single quote always zero", 12345, 1, 0},
		{"empty list", 100, 0, -1},
		{"negative height normalized", -3, 4, 3},
		{"large height", 1_000_003, 3, 1},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := featuredIndex(tt.height, tt.count)
			if got != tt.want {
				t.Errorf("featuredIndex(%d, %d) = %d, want %d",
					tt.height, tt.count, got, tt.want)
			}
			// For non-empty lists the index must be a valid slot.
			if tt.count > 0 && (got < 0 || got >= tt.count) {
				t.Errorf("featuredIndex(%d, %d) = %d, out of range [0,%d)",
					tt.height, tt.count, got, tt.count)
			}
		})
	}

	// Determinism: repeated calls with identical inputs never diverge.
	for i := 0; i < 5; i++ {
		if featuredIndex(7, 4) != featuredIndex(7, 4) {
			t.Fatal("featuredIndex is not deterministic")
		}
	}
}

// TestValidate covers the content rules enforced before a quote is stored.
func TestValidate(t *testing.T) {
	tests := []struct {
		name    string
		text    string
		wantErr error
	}{
		{"ok short", "hello world", nil},
		{"ok at limit", strings.Repeat("x", maxQuoteLen), nil},
		{"empty", "", errEmpty},
		{"too long", strings.Repeat("x", maxQuoteLen+1), errTooLong},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			err := validate(tt.text)
			if err != tt.wantErr {
				t.Errorf("validate(%q) err = %v, want %v", tt.name, err, tt.wantErr)
			}
		})
	}
}

// TestRenderSeeded checks that a fresh deploy (seeded board) renders the
// expected structure: title, a blockquote featured pick, and the full list
// containing every seeded quote.
func TestRenderSeeded(t *testing.T) {
	out := Render("")

	if !strings.Contains(out, "# Quote of the Moment") {
		t.Error("missing title heading")
	}
	if !strings.Contains(out, "\n> ") {
		t.Error("featured quote is not rendered as a blockquote")
	}
	if !strings.Contains(out, "## All quotes (") {
		t.Error("missing full-list section")
	}

	// Every seeded quote must appear in the listing.
	for _, q := range board {
		if !strings.Contains(out, q.text) {
			t.Errorf("rendered output missing seeded quote: %q", q.text)
		}
	}

	// Seeded quotes have no author and should surface the house label.
	if !strings.Contains(out, "the board") {
		t.Error("seeded quotes should be attributed to \"the board\"")
	}
}

// TestSeededBoard confirms init populated the board and ids are sequential.
func TestSeededBoard(t *testing.T) {
	if len(board) < 3 {
		t.Fatalf("expected at least 3 seeded quotes, got %d", len(board))
	}
	for i, q := range board {
		if q.id != i {
			t.Errorf("quote at position %d has id %d, want %d", i, q.id, i)
		}
	}
}

render_example_test.gno

package quotes

// ExampleRender pins the realm's Render output as a testable example.
func ExampleRender() {
	print(Render(""))
	// Output:
	// # Quote of the Moment
	//
	// > He who is brave is free.
	// >
	// > — the board (#3)
	//
	// _Featured pick rotates with block height 123 — index 3 of 4._
	//
	// ## All quotes (4)
	//
	// - **#0** The unexamined life is not worth living. — _the board_
	// - **#1** We suffer more often in imagination than in reality. — _the board_
	// - **#2** Waste no more time arguing about what a good person should be. Be one. — _the board_
	// - **#3** He who is brave is free. — _the board_
}