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

erratabank.gno

// Package erratabank records corrections, finder credit and book reward escrow.
package erratabank

import (
	"chain"
	"chain/banker"
	"chain/runtime"
	"chain/runtime/unsafe"
	"strconv"
	"strings"
	"unicode/utf8"

	"gno.land/p/g132vz03ycpaagtef4jmxjakstkppgyc5wn3r807/errata/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
)

const (
	Pending   = "Pending"
	Accepted  = "Accepted"
	Rejected  = "Rejected"
	Duplicate = "Duplicate"

	maxAmount  = 1<<63 - 1
	idKeyWidth = 19
)

type Book struct {
	ID               int
	Owner            address
	Title            string
	Edition          string
	Link             string
	RewardPerErratum int64
	Escrow           int64
	Open             bool
	CreatedAt        int64
}

type Erratum struct {
	ID          int
	BookID      int
	Finder      address
	Location    string
	Text        string
	Status      string
	DuplicateOf int
	SubmittedAt int64
	ReviewedAt  int64
	Paid        int64
	Note        string
}

// Each book indexes all reports and each status by submission ID.
type bookRecord struct {
	book      Book
	all       avl.Tree
	pending   avl.Tree
	accepted  avl.Tree
	rejected  avl.Tree
	duplicate avl.Tree
}

func (record *bookRecord) reports(status string) *avl.Tree {
	switch status {
	case "":
		return &record.all
	case Pending:
		return &record.pending
	case Accepted:
		return &record.accepted
	case Rejected:
		return &record.rejected
	case Duplicate:
		return &record.duplicate
	}
	return nil
}

type finderRecord struct {
	paid int64
	ids  avl.Tree
}

var (
	books         = avl.NewTree()
	errataByID    = avl.NewTree()
	finders       = avl.NewTree()
	nextErratumID int
	realmURL      string
)

func init(cur realm) {
	realmURL = strings.TrimPrefix(cur.PkgPath(), "gno.land") + ":"
}

func idKey(id int) string {
	digits := strconv.Itoa(id)
	return strings.Repeat("0", idKeyWidth-len(digits)) + digits
}

func bookByID(id int) *bookRecord {
	if id <= 0 {
		return nil
	}
	book, _ := books.Get(idKey(id)).(*bookRecord)
	return book
}

func reportByID(id int) *Erratum {
	if id <= 0 {
		return nil
	}
	report, _ := errataByID.Get(idKey(id)).(*Erratum)
	return report
}

func requireBook(id int) *bookRecord {
	record := bookByID(id)
	if record == nil {
		panic(errBookMissing)
	}
	return record
}

func requireOwner(record *bookRecord, caller address) {
	if record.book.Owner != caller {
		panic(errOwnerOnly)
	}
}

func requireReview(id int, caller address) (*bookRecord, *Erratum) {
	report := reportByID(id)
	if report == nil {
		panic(errErratumMiss)
	}
	record := requireBook(report.BookID)
	requireOwner(record, caller)
	if report.Status != Pending {
		panic(errPendingOnly)
	}
	return record, report
}

func callerAddress(cur realm) address {
	if !cur.IsCurrent() {
		panic(errCurrentRealm)
	}
	return cur.Previous().Address()
}

// A direct MsgCall credits this realm with the transaction's send before execution.
func inboundUgnot(cur realm) int64 {
	if !cur.Previous().IsUserCall() {
		panic(errDirectCall)
	}
	coins := unsafe.OriginSend()
	if len(coins) == 0 {
		return 0
	}
	if len(coins) != 1 || coins[0].Denom != "ugnot" {
		panic(errPaymentDenom)
	}
	if coins[0].Amount <= 0 {
		panic(errPayment)
	}
	return coins[0].Amount
}

func rejectCoins(cur realm) {
	if cur.Previous().IsUserCall() && len(unsafe.OriginSend()) != 0 {
		panic(errRejectCoins)
	}
}

func addAmount(total, amount int64) int64 {
	if amount > maxAmount-total {
		panic(errOverflow)
	}
	return total + amount
}

func sendUgnot(cur realm, to address, amount int64) {
	b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	b.SendCoins(cur.Address(), to, chain.NewCoins(chain.NewCoin("ugnot", amount)))
}

func requiredText(field, text string, max int) string {
	trimmed := strings.TrimSpace(text)
	if trimmed == "" || !utf8.ValidString(text) || utf8.RuneCountInString(text) > max {
		panic(field + " must contain 1 to " + strconv.Itoa(max) + " characters")
	}
	return trimmed
}

func reviewNote(note string) string {
	if strings.TrimSpace(note) == "" {
		return ""
	}
	return requiredText("review note", note, 300)
}

// CreateBook registers an open book and optionally credits inbound reward escrow.
func CreateBook(cur realm, title, edition, link string, rewardPerErratum int64) int {
	owner := callerAddress(cur)
	escrow := inboundUgnot(cur)
	title = requiredText("title", title, 120)
	edition = requiredText("edition", edition, 120)
	link = requiredText("link", link, 300)
	if sanitize.URL(link) == "" {
		panic("unsupported book link")
	}
	if rewardPerErratum < 0 {
		panic("reward cannot be negative")
	}
	id := books.Size() + 1
	books.Set(idKey(id), &bookRecord{book: Book{
		ID: id, Owner: owner, Title: title, Edition: edition, Link: link,
		RewardPerErratum: rewardPerErratum, Escrow: escrow, Open: true, CreatedAt: runtime.ChainHeight(),
	}})
	chain.Emit("BookCreated", "book", strconv.Itoa(id), "owner", owner.String(),
		"reward", strconv.FormatInt(rewardPerErratum, 10), "escrow", strconv.FormatInt(escrow, 10))
	return id
}

// FundBook credits a book with ugnot supplied by any direct caller.
func FundBook(cur realm, bookID int) {
	caller := callerAddress(cur)
	amount := inboundUgnot(cur)
	if amount == 0 {
		panic(errPayment)
	}
	record := requireBook(bookID)
	record.book.Escrow = addAmount(record.book.Escrow, amount)
	chain.Emit("BookFunded", "book", strconv.Itoa(bookID), "funder", caller.String(),
		"amount", strconv.FormatInt(amount, 10))
}

// Submit records a report. Increasing IDs break ties within a block.
func Submit(cur realm, bookID int, location, text string) int {
	finder := callerAddress(cur)
	rejectCoins(cur)
	record := requireBook(bookID)
	if !record.book.Open {
		panic(errClosed)
	}
	if finder == record.book.Owner {
		panic(errSelfSubmit)
	}
	location = requiredText("location", location, 120)
	text = requiredText("text", text, 1000)
	nextErratumID++
	id := nextErratumID
	key := idKey(id)
	errataByID.Set(key, &Erratum{
		ID: id, BookID: bookID, Finder: finder, Location: location, Text: text,
		Status: Pending, SubmittedAt: runtime.ChainHeight(),
	})
	record.all.Set(key, id)
	record.pending.Set(key, id)
	chain.Emit("ErratumSubmitted", "book", strconv.Itoa(bookID), "erratum", strconv.Itoa(id),
		"finder", finder.String())
	return id
}

func review(record *bookRecord, report *Erratum, status, note string) {
	key := idKey(report.ID)
	record.pending.Remove(key)
	record.reports(status).Set(key, report.ID)
	report.Status = status
	report.ReviewedAt = runtime.ChainHeight()
	report.Note = note
}

// Accept credits the finder and pays the full reward when escrow covers it.
func Accept(cur realm, erratumID int, note string) {
	owner := callerAddress(cur)
	rejectCoins(cur)
	record, report := requireReview(erratumID, owner)
	review(record, report, Accepted, reviewNote(note))

	addr := report.Finder.String()
	finder, ok := finders.Get(addr).(*finderRecord)
	if !ok {
		finder = &finderRecord{}
		finders.Set(addr, finder)
	}
	finder.ids.Set(idKey(erratumID), erratumID)
	reward := record.book.RewardPerErratum
	if reward > 0 && record.book.Escrow >= reward {
		record.book.Escrow -= reward
		report.Paid = reward
		finder.paid = addAmount(finder.paid, reward)
		sendUgnot(cur, report.Finder, reward)
	}
	chain.Emit("ErratumAccepted", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(erratumID),
		"finder", addr, "paid", strconv.FormatInt(report.Paid, 10))
}

// Reject closes a pending submission without finder credit.
func Reject(cur realm, erratumID int, note string) {
	caller := callerAddress(cur)
	rejectCoins(cur)
	record, report := requireReview(erratumID, caller)
	review(record, report, Rejected, reviewNote(note))
	chain.Emit("ErratumRejected", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(erratumID))
}

// MarkDuplicate links a pending report to an earlier accepted report in the same book.
func MarkDuplicate(cur realm, erratumID, originalID int) {
	caller := callerAddress(cur)
	rejectCoins(cur)
	record, report := requireReview(erratumID, caller)
	original := reportByID(originalID)
	if original == nil || original.BookID != report.BookID || original.ID >= report.ID ||
		original.Status != Accepted {
		panic(errDuplicate)
	}
	report.DuplicateOf = originalID
	review(record, report, Duplicate, "")
	chain.Emit("ErratumMarkedDuplicate", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(erratumID),
		"original", strconv.Itoa(originalID))
}

// SetBookOpen controls new submissions. Existing submissions remain reviewable.
func SetBookOpen(cur realm, bookID int, open bool) {
	caller := callerAddress(cur)
	rejectCoins(cur)
	record := requireBook(bookID)
	requireOwner(record, caller)
	record.book.Open = open
	chain.Emit("BookOpenChanged", "book", strconv.Itoa(bookID), "open", strconv.FormatBool(open))
}

// Withdraw returns unused escrow to the book owner.
func Withdraw(cur realm, bookID int, amount int64) {
	caller := callerAddress(cur)
	rejectCoins(cur)
	record := requireBook(bookID)
	requireOwner(record, caller)
	if amount <= 0 || amount > record.book.Escrow {
		panic(errWithdraw)
	}
	record.book.Escrow -= amount
	sendUgnot(cur, caller, amount)
	chain.Emit("BookWithdrawn", "book", strconv.Itoa(bookID), "owner", caller.String(),
		"amount", strconv.FormatInt(amount, 10))
}

func GetBook(id int) (Book, bool) {
	if record := bookByID(id); record != nil {
		return record.book, true
	}
	return Book{}, false
}

func ListBooks(offset, limit int) []Book {
	var result []Book
	if offset < 0 || limit <= 0 || offset >= books.Size() {
		return result
	}
	if remaining := books.Size() - offset; limit > remaining {
		limit = remaining
	}
	books.IterateByOffset(offset, limit, func(_ string, value any) bool {
		result = append(result, value.(*bookRecord).book)
		return false
	})
	return result
}

func GetErratum(id int) (Erratum, bool) {
	if report := reportByID(id); report != nil {
		return *report, true
	}
	return Erratum{}, false
}

func listReports(tree *avl.Tree, offset, limit int) []Erratum {
	var result []Erratum
	if tree == nil || offset < 0 || limit <= 0 || offset >= tree.Size() {
		return result
	}
	if remaining := tree.Size() - offset; limit > remaining {
		limit = remaining
	}
	tree.IterateByOffset(offset, limit, func(_ string, value any) bool {
		report, _ := GetErratum(value.(int))
		result = append(result, report)
		return false
	})
	return result
}

// ListErrata returns reports in submission order. An empty status selects all reports.
func ListErrata(bookID int, status string, offset, limit int) []Erratum {
	if record := bookByID(bookID); record != nil {
		return listReports(record.reports(status), offset, limit)
	}
	return nil
}

func acceptedEntries(reports []Erratum) []errata.Entry {
	var entries []errata.Entry
	for _, report := range reports {
		entries = append(entries, errata.Entry{
			Location: report.Location, Text: report.Text, Finder: report.Finder.String(),
			FoundAt: report.SubmittedAt, Paid: report.Paid, Link: finderURL(report.Finder),
		})
	}
	return entries
}

func AcceptedEntries(bookID int) []errata.Entry {
	return AcceptedEntriesPage(bookID, 0, int(maxAmount))
}

// AcceptedEntriesPage supports integrations that render a bounded page.
func AcceptedEntriesPage(bookID, offset, limit int) []errata.Entry {
	return acceptedEntries(ListErrata(bookID, Accepted, offset, limit))
}

func FinderStats(addr address) (accepted int, paid int64) {
	if finder, ok := finders.Get(addr.String()).(*finderRecord); ok {
		return finder.ids.Size(), finder.paid
	}
	return 0, 0
}

erratabank_test.gno

package erratabank

import (
	"chain"
	"chain/runtime"
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nt/markdown/sanitize/v0"
)

const (
	testOwner  = address("g1dmt3sa5ucvecxuhf3j6ne5r0e3z4x7h6c03xc0")
	testReader = address("g1akeqsvhucjt8gf5yupyzjxsjd29wv8fayng37c")
	testOther  = address("g1juz2yxmdsa6audkp6ep9vfv80c8p5u76e03vvh")
	testLink   = "https://example.org/book"
)

func assertPanic(t *testing.T, got any, want string) {
	t.Helper()
	if got != want {
		t.Fatalf("panic = %v, want %q", got, want)
	}
}

func wantText(t *testing.T, got string, parts ...string) {
	t.Helper()
	for _, part := range parts {
		if !strings.Contains(got, part) {
			t.Errorf("expected %q in %q", part, got)
		}
	}
}

func TestBookValidationAndSubmission(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testOwner))
	assertPanic(t, revive(func() { CreateBook(cross(cur), "", "First", testLink, 0) }),
		"title must contain 1 to 120 characters")
	assertPanic(t, revive(func() { CreateBook(cross(cur), "Book", "", testLink, 0) }),
		"edition must contain 1 to 120 characters")
	assertPanic(t, revive(func() { CreateBook(cross(cur), "Book", "First", strings.Repeat("a", 301), 0) }),
		"link must contain 1 to 300 characters")
	assertPanic(t, revive(func() { CreateBook(cross(cur), "Book", "First", "javascript:bad", 0) }),
		"unsupported book link")
	assertPanic(t, revive(func() { CreateBook(cross(cur), "Book", "First", testLink, -1) }),
		"reward cannot be negative")

	id := CreateBook(cross(cur), "Book", "First", testLink, 0)
	assertPanic(t, revive(func() { Submit(cross(cur), id, "Page 1", "Fix") }), errSelfSubmit)

	testing.SetRealm(testing.NewUserRealm(testReader))
	assertPanic(t, revive(func() { Submit(cross(cur), id, " ", "Fix") }),
		"location must contain 1 to 120 characters")
	assertPanic(t, revive(func() { Submit(cross(cur), id, strings.Repeat("é", 121), "Fix") }),
		"location must contain 1 to 120 characters")
	assertPanic(t, revive(func() { Submit(cross(cur), id, "Page 1", "") }),
		"text must contain 1 to 1000 characters")
	assertPanic(t, revive(func() { Submit(cross(cur), id, "Page 1", strings.Repeat("a", 1001)) }),
		"text must contain 1 to 1000 characters")

	testing.SetRealm(testing.NewUserRealm(testOwner))
	SetBookOpen(cross(cur), id, false)
	testing.SetRealm(testing.NewUserRealm(testReader))
	assertPanic(t, revive(func() { Submit(cross(cur), id, "Page 1", "Fix") }), errClosed)
	testing.SetRealm(testing.NewUserRealm(testOwner))
	SetBookOpen(cross(cur), id, true)

	testing.SkipHeights(2)
	testing.SetRealm(testing.NewUserRealm(testReader))
	reportID := Submit(cross(cur), id, strings.Repeat("é", 120), strings.Repeat("a", 1000))
	report, ok := GetErratum(reportID)
	if !ok || report.Finder != testReader || report.SubmittedAt != runtime.ChainHeight() || report.Status != Pending {
		t.Fatalf("unexpected report %#v", report)
	}
	book, ok := GetBook(id)
	if !ok || book.Owner != testOwner || !book.Open {
		t.Fatalf("unexpected book %#v", book)
	}

	// Cross-realm consumers get detached value data.
	book.Title = "modified"
	report.Status = Accepted
	again, _ := GetBook(id)
	againReport, _ := GetErratum(reportID)
	if again.Title != "Book" || againReport.Status != Pending {
		t.Fatal("editing an exported copy affected realm state")
	}
}

func TestFirstFinderAndPermissions(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testOwner))
	bookID := CreateBook(cross(cur), "Duplicate test", "First", testLink, 0)
	otherBookID := CreateBook(cross(cur), "Another book", "First", testLink, 0)
	testing.SetRealm(testing.NewUserRealm(testReader))
	first := Submit(cross(cur), bookID, "Page 2", "Fix the number.")
	testing.SetRealm(testing.NewUserRealm(testOther))
	second := Submit(cross(cur), bookID, "Page 2", "Fix the number.")
	other := Submit(cross(cur), otherBookID, "Page 2", "Fix the number.")
	rejected := Submit(cross(cur), bookID, "Page 3", "Suggested wording.")
	late := Submit(cross(cur), bookID, "Page 4", "Another suggestion.")
	latest := Submit(cross(cur), bookID, "Page 4", "A later correction.")
	assertPanic(t, revive(func() { Accept(cross(cur), first, "") }), errOwnerOnly)
	assertPanic(t, revive(func() { Reject(cross(cur), first, "") }), errOwnerOnly)
	assertPanic(t, revive(func() { MarkDuplicate(cross(cur), second, first) }), errOwnerOnly)
	assertPanic(t, revive(func() { Withdraw(cross(cur), bookID, 1) }), errOwnerOnly)
	assertPanic(t, revive(func() { SetBookOpen(cross(cur), bookID, false) }), errOwnerOnly)

	original, _ := GetErratum(first)
	later, _ := GetErratum(second)
	if original.SubmittedAt != later.SubmittedAt || first >= second {
		t.Fatal("same-height submissions must retain transaction order")
	}
	testing.SetRealm(testing.NewUserRealm(testOwner))
	assertPanic(t, revive(func() { MarkDuplicate(cross(cur), second, first) }), errDuplicate)
	Accept(cross(cur), first, "Confirmed")
	assertPanic(t, revive(func() { MarkDuplicate(cross(cur), other, first) }), errDuplicate)
	MarkDuplicate(cross(cur), second, first)
	Reject(cross(cur), rejected, "Editorial preference")
	assertPanic(t, revive(func() { MarkDuplicate(cross(cur), late, rejected) }), errDuplicate)
	assertPanic(t, revive(func() { MarkDuplicate(cross(cur), late, second) }), errDuplicate)
	assertPanic(t, revive(func() { Accept(cross(cur), second, "") }), errPendingOnly)
	assertPanic(t, revive(func() { Accept(cross(cur), first, "") }), errPendingOnly)
	assertPanic(t, revive(func() { Reject(cross(cur), rejected, "") }), errPendingOnly)

	duplicate, _ := GetErratum(second)
	entries := AcceptedEntries(bookID)
	count, paid := FinderStats(testReader)
	otherCount, _ := FinderStats(testOther)
	if duplicate.DuplicateOf != first || duplicate.Status != Duplicate ||
		len(entries) != 1 || count != 1 || paid != 0 || otherCount != 0 {
		t.Fatal("duplicate status or finder credit is wrong")
	}
	duplicates := ListErrata(bookID, Duplicate, 0, 10)
	if len(duplicates) != 1 || duplicates[0].ID != second {
		t.Fatal("duplicate index is wrong")
	}

	Accept(cross(cur), latest, "Confirmed")
	assertPanic(t, revive(func() { MarkDuplicate(cross(cur), late, latest) }), errDuplicate)
}

func TestPayableGuards(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testOwner))
	id := CreateBook(cross(cur), "Payment test", "First", testLink, 100)
	assertPanic(t, revive(func() { FundBook(cross(cur), id) }), errPayment)

	testing.SetOriginSend(chain.Coins{{Denom: "utest", Amount: 100}})
	assertPanic(t, revive(func() { FundBook(cross(cur), id) }), errPaymentDenom)
	assertPanic(t, revive(func() { CreateBook(cross(cur), "Payment test", "First", testLink, 100) }), errPaymentDenom)

	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: 0}})
	assertPanic(t, revive(func() { FundBook(cross(cur), id) }), errPayment)
	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: -10}})
	assertPanic(t, revive(func() { FundBook(cross(cur), id) }), errPayment)
	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: 100}})
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/test/paymentcaller"))
	assertPanic(t, revive(func() { FundBook(cross(cur), id) }), errDirectCall)
	assertPanic(t, revive(func() { CreateBook(cross(cur), "Payment test", "First", testLink, 100) }), errDirectCall)
	book, _ := GetBook(id)
	if book.Escrow != 0 {
		t.Fatal("invalid funding was credited")
	}
	testing.SetOriginSend(nil)
}

func TestNonpayableCallsRejectCoins(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testOwner))
	bookID := CreateBook(cross(cur), "Nonpayable calls", "First", testLink, 0)
	testing.SetRealm(testing.NewUserRealm(testReader))
	first := Submit(cross(cur), bookID, "Page 1", "First correction.")
	pending := Submit(cross(cur), bookID, "Page 2", "Second correction.")
	testing.SetRealm(testing.NewUserRealm(testOwner))
	Accept(cross(cur), first, "Confirmed")

	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 1)))
	testing.SetRealm(testing.NewUserRealm(testReader))
	assertPanic(t, revive(func() { Submit(cross(cur), bookID, "Page 3", "Third correction.") }), errRejectCoins)

	testing.SetRealm(testing.NewUserRealm(testOwner))
	assertPanic(t, revive(func() { Accept(cross(cur), pending, "") }), errRejectCoins)
	assertPanic(t, revive(func() { Reject(cross(cur), pending, "") }), errRejectCoins)
	assertPanic(t, revive(func() { MarkDuplicate(cross(cur), pending, first) }), errRejectCoins)
	assertPanic(t, revive(func() { SetBookOpen(cross(cur), bookID, false) }), errRejectCoins)
	assertPanic(t, revive(func() { Withdraw(cross(cur), bookID, 1) }), errRejectCoins)

	// A crossing from another realm does not receive the caller's origin send.
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/test/nonpayablecaller"))
	Submit(cross(cur), bookID, "Page 3", "Third correction.")
	testing.SetOriginSend(nil)
}

func TestRenderAndPagination(cur realm, t *testing.T) {
	hostile := "[x](javascript:bad) *fix* | <img>\n# line"
	testing.SetRealm(testing.NewUserRealm(testOwner))
	bookID := CreateBook(cross(cur), hostile, "First edition", testLink, 0)
	bookPath := "book/" + strconv.Itoa(bookID)

	testing.SetRealm(testing.NewUserRealm(testReader))
	first := Submit(cross(cur), bookID, "Page 1", hostile)
	for i := 2; i <= pageSize+1; i++ {
		Submit(cross(cur), bookID, "Page "+strconv.Itoa(i), "Fix "+strconv.Itoa(i))
	}
	wantText(t, Render(bookPath+"/pending?page=2"), "Page 2 of 2", "Page 21")
	wantText(t, Render(bookPath+"/all?page=2"), "Page 2 of 2", "Page 21")

	testing.SetRealm(testing.NewUserRealm(testOwner))
	Accept(cross(cur), first, hostile)
	wantText(t, Render(""), "# Erratabank", bookURL(bookID), "Started 23 Nov 2026 for Gnome Tavern.")
	out := Render(bookPath)
	wantText(t, out, "## Accepted errata", finderURL(testReader), "Pending (20)", sanitize.TableCell(hostile))
	wantText(t, Render("erratum/"+strconv.Itoa(first)), "Status history", "Pending (submitted)", "Accepted",
		sanitize.InlineText(hostile))
	wantText(t, Render("finder/"+testReader.String()), "Finder account", "Accepted finds:", bookURL(bookID))
	wantText(t, Render("finder/invalid"), "Finder not found")
	wantText(t, Render("unknown"), "Page not found")
	wantText(t, Render(bookPath+"/all?page=3"), "Page not found")
	if strings.Contains(out, "](javascript:") || strings.Contains(out, "<img>") {
		t.Fatalf("unsafe Markdown in book page: %s", out)
	}
}

errors.gno

package erratabank

const (
	errCurrentRealm = "invalid realm context"
	errDirectCall   = "payment requires a direct user call"
	errPaymentDenom = "only ugnot is accepted"
	errPayment      = "payment must be positive"
	errRejectCoins  = "this function does not accept coins"
	errBookMissing  = "book not found"
	errErratumMiss  = "erratum not found"
	errOwnerOnly    = "book owner only"
	errPendingOnly  = "erratum must be pending"
	errClosed       = "book is closed to submissions"
	errSelfSubmit   = "book owners cannot submit to their own book"
	errDuplicate    = "original must be an earlier accepted erratum in the same book"
	errWithdraw     = "withdrawal must be positive and within available escrow"
	errOverflow     = "amount exceeds accounting limit"
)

gnomod.toml

module = "gno.land/r/g132vz03ycpaagtef4jmxjakstkppgyc5wn3r807/erratabank/v0"
gno = "0.9"

[addpkg]
  creator = "g132vz03ycpaagtef4jmxjakstkppgyc5wn3r807"
  height = 1353015
  max_deposit = "10000000ugnot"

render.gno

package erratabank

import (
	"strconv"

	"gno.land/p/g132vz03ycpaagtef4jmxjakstkppgyc5wn3r807/errata/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
	"gno.land/p/nt/mux/v0"
	"gno.land/p/nt/ufmt/v0"
)

const pageSize = 20

var router = mux.NewRouter()

func init() {
	router.HandleFunc("", renderHome)
	router.HandleFunc("book/{id}", renderBook)
	router.HandleFunc("book/{id}/pending", renderPending)
	router.HandleFunc("book/{id}/all", renderAll)
	router.HandleFunc("erratum/{id}", renderErratum)
	router.HandleFunc("finder/{addr}", renderFinder)
	router.SetNotFoundHandler(func(w *mux.ResponseWriter, _ *mux.Request) {
		notFound(w, "Page")
	})
}

// Render is the public Markdown entry point for gnoweb.
func Render(path string) string {
	return router.Render(path)
}

func finderURL(addr address) string {
	return realmURL + "finder/" + addr.String()
}

func bookRoute(id int) string {
	return "book/" + strconv.Itoa(id)
}

func erratumURL(id int) string {
	return realmURL + "erratum/" + strconv.Itoa(id)
}

func bookURL(id int) string {
	return realmURL + bookRoute(id)
}

func pageOffset(req *mux.Request, total int) (int, bool) {
	value := req.Query.Get("page")
	if value == "" {
		return 0, true
	}
	page, err := strconv.Atoi(value)
	if err != nil || page < 1 || (page > 1 && page-1 > (total-1)/pageSize) {
		return 0, false
	}
	return (page - 1) * pageSize, true
}

func pagination(w *mux.ResponseWriter, route string, offset, total int) {
	if total <= pageSize {
		return
	}
	page := offset/pageSize + 1
	last := (total-1)/pageSize + 1
	w.Write(ufmt.Sprintf("\nPage %d of %d", page, last))
	if page > 1 {
		w.Write(ufmt.Sprintf(" · [Previous](%s%s?page=%d)", realmURL, route, page-1))
	}
	if page < last {
		w.Write(ufmt.Sprintf(" · [Next](%s%s?page=%d)", realmURL, route, page+1))
	}
	w.Write("\n")
}

func notFound(w *mux.ResponseWriter, item string) {
	w.Write("# " + item + " not found\n\n[Erratabank home](" + realmURL + ")\n")
}

func renderHome(w *mux.ResponseWriter, req *mux.Request) {
	offset, ok := pageOffset(req, books.Size())
	if !ok {
		notFound(w, "Page")
		return
	}
	w.Write("# Erratabank\n\n")
	w.Write("Erratabank is a public errata page for books, courses, and technical docs.\n\n")
	w.Write("Each accepted correction credits its finder. Authors can escrow a reward for accepted reports.\n\n")
	w.Write("Use the Actions tab to register a book, submit a correction, or review reports for a book you own.\n\n")
	w.Write("## Books\n\n")
	if books.Size() == 0 {
		w.Write("No books registered yet.\n")
	} else {
		w.Write("| Book | Owner | Reward per erratum | Escrow | Accepted |\n")
		w.Write("| --- | --- | ---: | ---: | ---: |\n")
		for _, book := range ListBooks(offset, pageSize) {
			w.Write(ufmt.Sprintf("| [%s](%s) | %s | %s | %s | %d |\n",
				sanitize.TableCell(book.Title), bookURL(book.ID), errata.ShortAddr(book.Owner.String()),
				errata.FormatUgnot(book.RewardPerErratum), errata.FormatUgnot(book.Escrow),
				requireBook(book.ID).accepted.Size()))
		}
		pagination(w, "", offset, books.Size())
	}
	w.Write("\nStarted 23 Nov 2026 for Gnome Tavern.\n")
}

func routeBook(w *mux.ResponseWriter, req *mux.Request) *bookRecord {
	if id, err := strconv.Atoi(req.GetVar("id")); err == nil {
		if record := bookByID(id); record != nil {
			return record
		}
	}
	notFound(w, "Book")
	return nil
}

func renderBook(w *mux.ResponseWriter, req *mux.Request) {
	record := routeBook(w, req)
	if record == nil {
		return
	}
	offset, ok := pageOffset(req, record.accepted.Size())
	if !ok {
		notFound(w, "Page")
		return
	}
	book := record.book
	state := "Closed"
	if book.Open {
		state = "Open"
	}
	w.Write(ufmt.Sprintf("# %s\n\n- Edition: %s\n- Owner: %s\n- Submissions: %s\n- Reward per erratum: %s\n- Escrow left: %s\n",
		sanitize.InlineText(book.Title), sanitize.InlineText(book.Edition), sanitize.InlineCode(book.Owner.String()),
		state, errata.FormatUgnot(book.RewardPerErratum), errata.FormatUgnot(book.Escrow)))
	if url := sanitize.URL(book.Link); url != "" {
		w.Write("- [Read the book](" + url + ")\n")
	}
	w.Write("\n")
	w.Write(errata.RenderSection("Accepted errata", AcceptedEntriesPage(book.ID, offset, pageSize)))
	pagination(w, bookRoute(book.ID), offset, record.accepted.Size())
	w.Write(ufmt.Sprintf("\n[Pending (%d)](%s/pending) · [All reports (%d)](%s/all) · Rejected: %d · Duplicates: %d · [All books](%s)\n",
		record.pending.Size(), bookURL(book.ID), record.all.Size(), bookURL(book.ID),
		record.rejected.Size(), record.duplicate.Size(), realmURL))
}

func renderPending(w *mux.ResponseWriter, req *mux.Request) {
	renderReportList(w, req, Pending, "Pending reports", "/pending")
}

func renderAll(w *mux.ResponseWriter, req *mux.Request) {
	renderReportList(w, req, "", "All reports", "/all")
}

func renderReportList(w *mux.ResponseWriter, req *mux.Request, status, heading, suffix string) {
	record := routeBook(w, req)
	if record == nil {
		return
	}
	tree := record.reports(status)
	offset, ok := pageOffset(req, tree.Size())
	if !ok {
		notFound(w, "Page")
		return
	}
	book := record.book
	w.Write(ufmt.Sprintf("# %s\n\n[Back to %s](%s)\n\n",
		heading, sanitize.InlineText(book.Title), bookURL(book.ID)))
	if tree.Size() == 0 {
		w.Write("No reports here yet.\n")
		return
	}
	w.Write("| Report | Location | Status | Finder | Height found |\n| --- | --- | --- | --- | ---: |\n")
	for _, report := range listReports(tree, offset, pageSize) {
		w.Write(ufmt.Sprintf("| [#%d](%s) | %s | %s | [%s](%s) | %d |\n",
			report.ID, erratumURL(report.ID), sanitize.TableCell(report.Location), report.Status,
			errata.ShortAddr(report.Finder.String()), finderURL(report.Finder), report.SubmittedAt))
	}
	pagination(w, bookRoute(book.ID)+suffix, offset, tree.Size())
}

func renderErratum(w *mux.ResponseWriter, req *mux.Request) {
	id, err := strconv.Atoi(req.GetVar("id"))
	report, ok := GetErratum(id)
	if err != nil || !ok {
		notFound(w, "Erratum")
		return
	}
	book, _ := GetBook(report.BookID)
	w.Write(ufmt.Sprintf("# Erratum #%d\n\n[Back to %s](%s)\n\n",
		id, sanitize.InlineText(book.Title), bookURL(book.ID)))
	w.Write(ufmt.Sprintf("- Location: %s\n- Finder: [%s](%s)\n- Status: %s\n- Paid: %s\n\n## Correction\n\n%s\n\n",
		sanitize.InlineText(report.Location), report.Finder.String(), finderURL(report.Finder),
		report.Status, errata.FormatUgnot(report.Paid), sanitize.InlineText(report.Text)))
	w.Write(ufmt.Sprintf("## Status history\n\n- Height %d — Pending (submitted)\n", report.SubmittedAt))
	if report.Status != Pending {
		w.Write(ufmt.Sprintf("- Height %d — %s\n", report.ReviewedAt, report.Status))
	}
	if report.Note != "" {
		w.Write("- Review note: " + sanitize.InlineText(report.Note) + "\n")
	}
	if report.DuplicateOf != 0 {
		w.Write(ufmt.Sprintf("- Earlier report: [#%d](%s)\n", report.DuplicateOf, erratumURL(report.DuplicateOf)))
	}
}

func renderFinder(w *mux.ResponseWriter, req *mux.Request) {
	raw := req.GetVar("addr")
	cleaned := sanitize.BechString(raw, "g")
	if cleaned == "" || cleaned != raw || !address(cleaned).IsValid() {
		notFound(w, "Finder")
		return
	}
	finder, _ := finders.Get(cleaned).(*finderRecord)
	count, paid := FinderStats(address(cleaned))
	offset, ok := pageOffset(req, count)
	if !ok {
		notFound(w, "Page")
		return
	}
	w.Write(ufmt.Sprintf("# Finder account\n\n%s\n\n- Accepted finds: %d\n- Total earned: %s\n\n",
		sanitize.InlineCode(cleaned), count, errata.FormatUgnot(paid)))
	if finder == nil {
		w.Write("No accepted finds yet.\n")
		return
	}
	w.Write("| Book | Find | Height found | Paid |\n| --- | --- | ---: | ---: |\n")
	makeFinderRows(w, listReports(&finder.ids, offset, pageSize))
	pagination(w, "finder/"+cleaned, offset, count)
}

func makeFinderRows(w *mux.ResponseWriter, reports []Erratum) {
	for _, report := range reports {
		book, _ := GetBook(report.BookID)
		w.Write(ufmt.Sprintf("| [%s](%s) | [%s](%s) | %d | %s |\n",
			sanitize.TableCell(book.Title), bookURL(book.ID),
			sanitize.TableCell(report.Location), erratumURL(report.ID), report.SubmittedAt,
			errata.FormatUgnot(report.Paid)))
	}
}