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
	maxListLimit = 50
)

type Book struct {
	ID               int
	Owner            address
	Title            string
	Edition          string
	Link             string
	RewardPerErratum int64
	OwnerFunds       int64
	SponsorFunds     int64
	Owed             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
	Owed        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
	byLocation  avl.Tree
	sponsors    avl.Tree
	owedReports avl.Tree
	nextOwedID  int
}

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
	owed    int64
	credits avl.Tree
	unpaid  avl.Tree
}

type FinderSummary struct {
	Credits       int
	UnpaidCredits int
	Paid          int64
	Owed          int64
}

var (
	books        = avl.NewTree()
	errataByID   = avl.NewTree()
	finders      = avl.NewTree()
	nextBookID   int
	nextReportID 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 advanceID(counter *int) int {
	if *counter == maxAmount {
		panic(errIDLimit)
	}
	*counter += 1
	return *counter
}

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()
}

// Gno v1.8.0 exposes the inbound coin envelope through unsafe.OriginSend.
// The Gno Security Guide requires IsUserCall before reading it.
// https://docs.gno.land/resources/gno-security-guide/#55-isuser-for-payment-guards
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)
	ownerFunds := 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 := advanceID(&nextBookID)
	books.Set(idKey(id), &bookRecord{book: Book{
		ID: id, Owner: owner, Title: title, Edition: edition, Link: link,
		RewardPerErratum: rewardPerErratum, OwnerFunds: ownerFunds, Open: true, CreatedAt: runtime.ChainHeight(),
	}})
	chain.Emit("BookCreated", "book", strconv.Itoa(id), "owner", owner.String(),
		"reward", strconv.FormatInt(rewardPerErratum, 10), "owner_funds", strconv.FormatInt(ownerFunds, 10))
	return id
}

// Submit records a report. Reports are public and permanent on-chain.
func Submit(cur realm, bookID int, location, text string) int {
	finder := callerAddress(cur)
	rejectCoins(cur)
	record := requireBook(bookID)
	if !record.book.Open {
		panic(errClosed)
	}
	location = requiredText("location", location, 120)
	text = requiredText("text", text, 1000)
	id := advanceID(&nextReportID)
	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)
	atLocation, _ := record.byLocation.Get(location).(*avl.Tree)
	if atLocation == nil {
		atLocation = avl.NewTree()
		record.byLocation.Set(location, atLocation)
	}
	atLocation.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)
	atLocation := record.byLocation.Get(report.Location).(*avl.Tree)
	atLocation.Remove(key)
	if atLocation.Size() == 0 {
		record.byLocation.Remove(report.Location)
	}
	record.reports(status).Set(key, report.ID)
	report.Status = status
	report.ReviewedAt = runtime.ChainHeight()
	report.Note = note
}

// Accept credits the finder and queues the reward for settlement from the book funds.
func Accept(cur realm, erratumID int, note string) {
	owner := callerAddress(cur)
	rejectCoins(cur)
	record, report := requireReview(erratumID, owner)
	if !record.book.Open {
		panic(errClosedAccept)
	}
	atLocation := record.byLocation.Get(report.Location).(*avl.Tree)
	_, first := atLocation.GetByIndex(0)
	if first.(int) != report.ID {
		panic(errEarlierPending)
	}
	review(record, report, Accepted, reviewNote(note))

	addr := report.Finder.String()
	finder, ok := finders.Get(addr).(*finderRecord)
	if !ok {
		finder = &finderRecord{}
		finders.Set(addr, finder)
	}
	key := idKey(erratumID)
	if reward := record.book.RewardPerErratum; reward > 0 && report.Finder != owner {
		finder.credits.Set(key, erratumID)
		record.queueReward(report, finder, reward)
		settleRewards(cur, record)
	} else {
		finder.unpaid.Set(key, erratumID)
	}
	chain.Emit("ErratumAccepted", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(erratumID),
		"finder", addr, "paid", strconv.FormatInt(report.Paid, 10), "owed", strconv.FormatInt(report.Owed, 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 pending or 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 != Pending && 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 submissions and acceptance. Closing opens sponsor refunds after debts settle.
func SetBookOpen(cur realm, bookID int, open bool) {
	caller := callerAddress(cur)
	rejectCoins(cur)
	record := requireBook(bookID)
	requireOwner(record, caller)
	if open && !record.book.Open && record.book.SponsorFunds > 0 {
		panic(errSponsorRefundsPending)
	}
	record.book.Open = open
	if !open {
		settleRewards(cur, record)
	}
	chain.Emit("BookOpenChanged", "book", strconv.Itoa(bookID), "open", strconv.FormatBool(open))
}

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

func pageLimit(size, offset, limit int) int {
	if offset < 0 || limit <= 0 || offset >= size {
		return 0
	}
	if limit > maxListLimit {
		limit = maxListLimit
	}
	if remaining := size - offset; limit > remaining {
		limit = remaining
	}
	return limit
}

func ListBooks(offset, limit int) []Book {
	var result []Book
	if limit = pageLimit(books.Size(), offset, limit); limit == 0 {
		return result
	}
	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 {
		return result
	}
	if limit = pageLimit(tree.Size(), offset, limit); limit == 0 {
		return result
	}
	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
}

// AcceptedEntries returns the first 50 accepted reports in submission order.
func AcceptedEntries(bookID int) []errata.Entry {
	return AcceptedEntriesPage(bookID, 0, maxListLimit)
}

// AcceptedEntriesPage is the integration API for rendering accepted reports.
// Limits are capped at 50 entries per page.
func AcceptedEntriesPage(bookID, offset, limit int) []errata.Entry {
	return acceptedEntries(ListErrata(bookID, Accepted, offset, limit))
}

func FinderStats(addr address) FinderSummary {
	if finder, ok := finders.Get(addr.String()).(*finderRecord); ok {
		return FinderSummary{
			Credits: finder.credits.Size(), UnpaidCredits: finder.unpaid.Size(),
			Paid: finder.paid, Owed: finder.owed,
		}
	}
	return FinderSummary{}
}

erratabank_test.gno

package erratabank

import (
	"chain"
	"strconv"
	"strings"
	"testing"

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

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

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

func TestReviewOrderAndPermissions(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testOwner))
	book := CreateBook(cross(cur), "Review order", "First edition", testLink, 0)
	otherBook := CreateBook(cross(cur), "Other book", "First edition", testLink, 0)
	testing.SetRealm(testing.NewUserRealm(testReader))
	first := Submit(cross(cur), book, " Section 1 ", "The first correction.")
	other := Submit(cross(cur), otherBook, "Section 1", "This location is in another book.")
	testing.SetRealm(testing.NewUserRealm(testSponsor))
	later := Submit(cross(cur), book, "Section 1", "The second 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), later, first) }), errOwnerOnly)
	assertPanic(t, revive(func() { Withdraw(cross(cur), book, 1) }), errOwnerOnly)

	testing.SetRealm(testing.NewUserRealm(testOwner))
	assertPanic(t, revive(func() { Accept(cross(cur), later, "") }), errEarlierPending)
	assertPanic(t, revive(func() { MarkDuplicate(cross(cur), first, later) }), errDuplicate)
	assertPanic(t, revive(func() { MarkDuplicate(cross(cur), later, other) }), errDuplicate)
	Accept(cross(cur), other, "")
	Accept(cross(cur), first, "")
	MarkDuplicate(cross(cur), later, first)
	duplicate, _ := GetErratum(later)
	if duplicate.Status != Duplicate || duplicate.DuplicateOf != first {
		t.Fatalf("wrong duplicate record: %+v", duplicate)
	}

	testing.SetRealm(testing.NewUserRealm(testReader))
	original := Submit(cross(cur), book, "Alternate section", "Report before Section 2.")
	firstAtLocation := Submit(cross(cur), book, "Section 2", "First at this location.")
	secondAtLocation := Submit(cross(cur), book, "Section 2", "Second at this location.")
	rejected := Submit(cross(cur), book, "Section 3", "Unconfirmed report.")
	confirmed := Submit(cross(cur), book, "Section 3", "Confirmed report.")
	testing.SetRealm(testing.NewUserRealm(testOwner))
	MarkDuplicate(cross(cur), firstAtLocation, original)
	Accept(cross(cur), secondAtLocation, "")
	Reject(cross(cur), rejected, "")
	assertPanic(t, revive(func() { MarkDuplicate(cross(cur), confirmed, rejected) }), errDuplicate)
	Accept(cross(cur), confirmed, "")
	pending, _ := GetErratum(original)
	if pending.Status != Pending {
		t.Fatalf("marking a duplicate changed the original status: %s", pending.Status)
	}
	assertPanic(t, revive(func() { Accept(cross(cur), first, "") }), errPendingOnly)
}

func TestFinderReputationAndOwed(cur realm, t *testing.T) {
	author := chain.PackageAddress("gno.land/r/test/reputationauthor")
	finder := chain.PackageAddress("gno.land/r/test/reputationfinder")
	testing.SetRealm(testing.NewUserRealm(author))
	rewarded := CreateBook(cross(cur), "Rewarded book", "First edition", testLink, 1000)
	creditOnly := CreateBook(cross(cur), "Credit-only book", "First edition", testLink, 0)
	self := Submit(cross(cur), rewarded, "Owner note", "A maintainer's own correction.")
	testing.SetRealm(testing.NewUserRealm(finder))
	eligible := Submit(cross(cur), rewarded, "Rewarded location", "A reader's correction.")
	unpaid := Submit(cross(cur), creditOnly, "Volunteer note", "A voluntary correction.")
	testing.SetRealm(testing.NewUserRealm(author))
	Accept(cross(cur), self, "")
	Accept(cross(cur), eligible, "")
	Accept(cross(cur), unpaid, "")

	owner := FinderStats(author)
	if owner.Credits != 0 || owner.UnpaidCredits != 1 || owner.Paid != 0 || owner.Owed != 0 {
		t.Fatalf("self-owned correction counted as a reward: %+v", owner)
	}
	reader := FinderStats(finder)
	if reader.Credits != 1 || reader.UnpaidCredits != 1 || reader.Paid != 0 || reader.Owed != 1000 {
		t.Fatalf("wrong reader reputation or reward ledger: %+v", reader)
	}
	path := "finder/" + finder.String()
	main := Render(path)
	if !strings.Contains(main, "Reward-eligible credits: 1") ||
		!strings.Contains(main, "Owed: 0.001 GNOT") ||
		!strings.Contains(main, "Paid: 0 GNOT") ||
		!strings.Contains(main, "Rewarded location") || strings.Contains(main, "Volunteer note") {
		t.Fatalf("wrong finder view: %s", main)
	}
	unpaidPage := Render(path + "/unpaid")
	if !strings.Contains(unpaidPage, "## Unpaid credits") ||
		!strings.Contains(unpaidPage, "Volunteer note") || strings.Contains(unpaidPage, "Rewarded location") {
		t.Fatalf("wrong unpaid page: %s", unpaidPage)
	}
}

func TestFundingAndClosureGuards(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testOwner))
	book := CreateBook(cross(cur), "Funding guards", "First edition", testLink, 1000)
	assertPanic(t, revive(func() { FundBook(cross(cur), book) }), errPayment)
	testing.SetOriginSend(chain.Coins{{Denom: "utest", Amount: 100}})
	assertPanic(t, revive(func() { FundBook(cross(cur), book) }), errPaymentDenom)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 500)))
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/test/fundingcaller"))
	assertPanic(t, revive(func() { FundBook(cross(cur), book) }), errDirectCall)

	testing.SetRealm(testing.NewUserRealm(testSponsor))
	FundBook(cross(cur), book)
	assertPanic(t, revive(func() { RefundSponsor(cross(cur), book) }), errRejectCoins)
	testing.SetOriginSend(nil)
	assertPanic(t, revive(func() { RefundSponsor(cross(cur), book) }), errRefundUnavailable)
	report := Submit(cross(cur), book, "Section 1", "A sponsored report.")
	testing.SetRealm(testing.NewUserRealm(testOwner))
	assertPanic(t, revive(func() { Withdraw(cross(cur), book, 1) }), errWithdraw)
	SetBookOpen(cross(cur), book, false)
	assertPanic(t, revive(func() { Accept(cross(cur), report, "") }), errClosedAccept)
	assertPanic(t, revive(func() { SetBookOpen(cross(cur), book, true) }), errSponsorRefundsPending)
	assertPanic(t, revive(func() { RefundSponsor(cross(cur), book) }), errNoSponsorFunds)

	testing.SetRealm(testing.NewUserRealm(testReader))
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 1)))
	assertPanic(t, revive(func() { FundBook(cross(cur), book) }), errClosedSponsor)
	assertPanic(t, revive(func() { SettleOwed(cross(cur), book) }), errRejectCoins)
	testing.SetOriginSend(nil)
	if SponsorBalance(book, testSponsor) != 500 {
		t.Fatal("a blocked action changed the sponsor balance")
	}
}

func TestCountersSurviveRemovals(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testOwner))
	first := CreateBook(cross(cur), "First book", "First edition", testLink, 0)
	second := CreateBook(cross(cur), "Second book", "First edition", testLink, 0)
	books.Remove(idKey(first))
	third := CreateBook(cross(cur), "Third book", "First edition", testLink, 0)
	if third != second+1 {
		t.Fatalf("book ID %d did not advance from %d", third, second)
	}
	a := Submit(cross(cur), third, "Section A", "A correction.")
	b := Submit(cross(cur), third, "Section B", "Another correction.")
	errataByID.Remove(idKey(a))
	c := Submit(cross(cur), third, "Section C", "A third correction.")
	if c != b+1 {
		t.Fatalf("report ID %d did not advance from %d", c, b)
	}
}

func TestBoundedLists(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testOwner))
	book := CreateBook(cross(cur), "Pagination", "First edition", testLink, 0)
	for i := 0; i < maxListLimit+1; i++ {
		CreateBook(cross(cur), "Book "+strconv.Itoa(i), "First edition", testLink, 0)
		id := Submit(cross(cur), book, "Location "+strconv.Itoa(i), "A correction.")
		Accept(cross(cur), id, "")
	}
	if got := len(ListBooks(0, int(maxAmount))); got != 50 {
		t.Fatalf("book limit = %d, want 50", got)
	}
	if len(ListBooks(books.Size(), 1)) != 0 || len(ListBooks(0, 0)) != 0 || len(ListBooks(-1, 1)) != 0 {
		t.Fatal("book list accepted an out-of-range offset or empty limit")
	}
	if got := len(ListErrata(book, Accepted, 0, int(maxAmount))); got != 50 {
		t.Fatalf("report limit = %d, want 50", got)
	}
	if len(ListErrata(book, Accepted, 52, 5)) != 0 || len(ListErrata(book, Accepted, 0, 0)) != 0 ||
		len(ListErrata(book, Accepted, -1, 1)) != 0 || len(ListErrata(book, "unknown", 0, 1)) != 0 {
		t.Fatal("report list accepted invalid pagination or a status")
	}
	if got := len(AcceptedEntries(book)); got != 50 {
		t.Fatalf("default entries = %d, want 50", got)
	}
	last := AcceptedEntriesPage(book, 50, 200)
	if len(last) != 1 || last[0].Location != "Location 50" {
		t.Fatalf("unexpected last page: %+v", last)
	}
}

func TestModeratedRendering(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testOwner))
	book := CreateBook(cross(cur), "Moderation", "First edition", testLink, 0)
	acceptedText := "Accepted marker | <b>safe</b>"
	rejectedText := "Rejected marker | <script>unsafe</script>"
	accepted := Submit(cross(cur), book, "Section A", acceptedText)
	rejected := Submit(cross(cur), book, "Section B", rejectedText)
	Accept(cross(cur), accepted, "")
	Reject(cross(cur), rejected, "Rejected note marker")
	bookPath := "book/" + strconv.Itoa(book)
	bookPage := Render(bookPath)
	for _, want := range []string{"Owner funds:", "Sponsor funds:", "(locked)", "Owed:", "The owner decides", sanitize.TableCell(acceptedText)} {
		if !strings.Contains(bookPage, want) {
			t.Errorf("book page missing %q", want)
		}
	}
	for _, route := range []string{
		"", bookPath, bookPath + "/pending",
		"erratum/" + strconv.Itoa(rejected), "finder/" + testOwner.String() + "/unpaid",
	} {
		got := Render(route)
		if strings.Contains(got, "Rejected marker") || strings.Contains(got, "Rejected note marker") {
			t.Errorf("rejected correction or note leaked into %q", route)
		}
	}
	all := Render(bookPath + "/all")
	if !strings.Contains(all, sanitize.TableCell(rejectedText)) ||
		!strings.Contains(all, "Rejected note marker") || strings.Contains(all, "<script>") {
		t.Fatalf("all reports should escape and show the rejected correction: %s", all)
	}
}

func TestPublicReportNoticeOnHomeAndBook(cur realm, t *testing.T) {
	const notice = "Reports are public and permanent on-chain."
	testing.SetRealm(testing.NewUserRealm(testOwner))
	book := CreateBook(cross(cur), "Public report notice", "First edition", testLink, 0)

	if !strings.Contains(Render(""), notice+"\n\nUse the Actions tab") {
		t.Error("home page must show the notice directly before the report instructions")
	}
	if !strings.Contains(Render("book/"+strconv.Itoa(book)), notice+"\n\n[Pending (") {
		t.Error("book page must show the notice directly before the pending report link")
	}
}

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"
	errEarlierPending        = "resolve the earlier pending report at this location first"
	errDuplicate             = "original must be an earlier pending or accepted erratum in the same book"
	errWithdraw              = "withdrawal must be positive and within unreserved owner funds"
	errClosedAccept          = "closed books cannot accept reports"
	errClosedSponsor         = "closed books cannot receive sponsor deposits"
	errSponsorRefundsPending = "refund remaining sponsor funds before reopening"
	errRefundUnavailable     = "sponsor refunds require a closed book with no unpaid rewards"
	errNoSponsorFunds        = "no sponsor funds to refund"
	errOverflow              = "amount exceeds accounting limit"
	errIDLimit               = "identifier limit reached"
)

escrow.gno

package erratabank

import (
	"chain"
	"strconv"
)

// Bound the work of a single call even when many small sponsor balances fund a reward.
const settlementSteps = 8

// FundBook records an owner deposit or a locked sponsor deposit and services the
// oldest fully funded reward first. The owner can fund existing debts after closing.
func FundBook(cur realm, bookID int) {
	caller := callerAddress(cur)
	amount := inboundUgnot(cur)
	if amount == 0 {
		panic(errPayment)
	}
	record := requireBook(bookID)
	book := &record.book
	addAmount(record.totalFunds(), amount)
	if caller == book.Owner {
		book.OwnerFunds += amount
	} else {
		if !book.Open {
			panic(errClosedSponsor)
		}
		addr := caller.String()
		balance, _ := record.sponsors.Get(addr).(int64)
		record.sponsors.Set(addr, balance+amount)
		book.SponsorFunds += amount
	}
	chain.Emit("BookFunded", "book", strconv.Itoa(bookID), "funder", caller.String(),
		"amount", strconv.FormatInt(amount, 10))
	settleRewards(cur, record)
}

func (record *bookRecord) totalFunds() int64 {
	return record.book.OwnerFunds + record.book.SponsorFunds
}

func (record *bookRecord) queueReward(report *Erratum, finder *finderRecord, reward int64) {
	record.book.Owed = addAmount(record.book.Owed, reward)
	finder.owed = addAmount(finder.owed, reward)
	report.Owed = reward
	sequence := advanceID(&record.nextOwedID)
	record.owedReports.Set(idKey(sequence), report.ID)
}

// Consume sponsor balances in address order before touching owner deposits.
func (record *bookRecord) debitFunds(amount int64) int64 {
	if record.book.SponsorFunds == 0 {
		record.book.OwnerFunds -= amount
		return amount
	}
	addr, value := record.sponsors.GetByIndex(0)
	balance := value.(int64)
	if amount >= balance {
		amount = balance
		record.sponsors.Remove(addr)
	} else {
		record.sponsors.Set(addr, balance-amount)
	}
	record.book.SponsorFunds -= amount
	return amount
}

func settleRewards(cur realm, record *bookRecord) {
	steps := settlementSteps
	for steps > 0 && record.owedReports.Size() > 0 {
		key, id := record.owedReports.GetByIndex(0)
		report := reportByID(id.(int))
		if record.totalFunds() < report.Owed {
			return
		}
		remaining := report.Owed
		for remaining > 0 && steps > 0 {
			remaining -= record.debitFunds(remaining)
			steps--
		}
		amount := report.Owed - remaining
		record.book.Owed -= amount
		report.Owed = remaining
		report.Paid += amount
		finder := finders.Get(report.Finder.String()).(*finderRecord)
		finder.owed -= amount
		finder.paid = addAmount(finder.paid, amount)
		if remaining == 0 {
			record.owedReports.Remove(key)
		}
		sendUgnot(cur, report.Finder, amount)
		chain.Emit("ErratumPaid", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(report.ID),
			"finder", report.Finder.String(), "amount", strconv.FormatInt(amount, 10),
			"owed", strconv.FormatInt(remaining, 10))
	}
}

// SettleOwed continues payouts when a previous call reached its work limit.
func SettleOwed(cur realm, bookID int) {
	callerAddress(cur)
	rejectCoins(cur)
	settleRewards(cur, requireBook(bookID))
}

func (record *bookRecord) ownerWithdrawable() int64 {
	// Complete queued payouts before making owner deposits withdrawable.
	if record.book.Owed != 0 {
		return 0
	}
	return record.book.OwnerFunds
}

// Withdraw returns only the owner's deposits in excess of outstanding rewards.
func Withdraw(cur realm, bookID int, amount int64) {
	caller := callerAddress(cur)
	rejectCoins(cur)
	record := requireBook(bookID)
	requireOwner(record, caller)
	if amount <= 0 || amount > record.ownerWithdrawable() {
		panic(errWithdraw)
	}
	record.book.OwnerFunds -= amount
	sendUgnot(cur, caller, amount)
	chain.Emit("BookWithdrawn", "book", strconv.Itoa(bookID), "owner", caller.String(),
		"amount", strconv.FormatInt(amount, 10))
}

// SponsorBalance returns the sponsor's remaining deposit for a book.
func SponsorBalance(bookID int, sponsor address) int64 {
	record := bookByID(bookID)
	if record == nil {
		return 0
	}
	balance, _ := record.sponsors.Get(sponsor.String()).(int64)
	return balance
}

// RefundSponsor returns the caller's remaining sponsor deposit on a closed book
// after all accepted rewards have settled.
func RefundSponsor(cur realm, bookID int) {
	caller := callerAddress(cur)
	rejectCoins(cur)
	record := requireBook(bookID)
	if record.book.Open || record.book.Owed != 0 {
		panic(errRefundUnavailable)
	}
	amount := SponsorBalance(bookID, caller)
	if amount == 0 {
		panic(errNoSponsorFunds)
	}
	record.sponsors.Remove(caller.String())
	record.book.SponsorFunds -= amount
	sendUgnot(cur, caller, amount)
	chain.Emit("SponsorRefunded", "book", strconv.Itoa(bookID), "sponsor", caller.String(),
		"amount", strconv.FormatInt(amount, 10))
}

gnomod.toml

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

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

render.gno

package erratabank

import (
	"strconv"

	"gno.land/p/nt/avl/v0"

	"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
const reportNotice = "Reports are public and permanent on-chain."

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.HandleFunc("finder/{addr}/unpaid", renderUnpaidFinder)
	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("Book owners decide which reports to accept. Owner deposits and locked sponsor funds can cover rewards for eligible reports.\n\n")
	w.Write(reportNotice + "\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 | Owner funds | Sponsor funds | Owed | Accepted |\n")
		w.Write("| --- | --- | ---: | ---: | ---: | ---: | ---: |\n")
		for _, book := range ListBooks(offset, pageSize) {
			w.Write(ufmt.Sprintf("| [%s](%s) | %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.OwnerFunds),
				errata.FormatUgnot(book.SponsorFunds), errata.FormatUgnot(book.Owed),
				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- Owner funds: %s\n- Sponsor funds: %s (locked)\n- Owed: %s\n- Owner funds available to withdraw: %s\n",
		sanitize.InlineText(book.Title), sanitize.InlineText(book.Edition), sanitize.InlineCode(book.Owner.String()),
		state, errata.FormatUgnot(book.RewardPerErratum), errata.FormatUgnot(book.OwnerFunds),
		errata.FormatUgnot(book.SponsorFunds), errata.FormatUgnot(book.Owed), errata.FormatUgnot(record.ownerWithdrawable())))
	if url := sanitize.URL(book.Link); url != "" {
		w.Write("- [Read the book](" + url + ")\n")
	}
	w.Write("\nThe owner decides which reports to accept. Eligible rewards are paid from book funds when available or recorded as owed.\n\n")
	w.Write(errata.RenderSection("Accepted errata", AcceptedEntriesPage(book.ID, offset, pageSize)))
	pagination(w, bookRoute(book.ID), offset, record.accepted.Size())
	w.Write("\n" + reportNotice + "\n\n")
	w.Write(ufmt.Sprintf("[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
	}
	header := "| Report | Location | Status | Finder | Height found |"
	dividers := "| --- | --- | --- | --- | ---: |"
	if status == "" {
		header += " Correction |"
		dividers += " --- |"
	}
	w.Write(header + "\n" + dividers + "\n")
	for _, report := range listReports(tree, offset, pageSize) {
		w.Write(ufmt.Sprintf("| [#%d](%s) | %s | %s | [%s](%s) | %d |",
			report.ID, erratumURL(report.ID), sanitize.TableCell(report.Location), report.Status,
			errata.ShortAddr(report.Finder.String()), finderURL(report.Finder), report.SubmittedAt))
		if status == "" {
			w.Write(" " + sanitize.TableCell(report.Text))
			if report.Status == Rejected && report.Note != "" {
				w.Write(" — " + sanitize.TableCell(report.Note))
			}
			w.Write(" |")
		}
		w.Write("\n")
	}
	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- Owed: %s\n\n",
		sanitize.InlineText(report.Location), report.Finder.String(), finderURL(report.Finder),
		report.Status, errata.FormatUgnot(report.Paid), errata.FormatUgnot(report.Owed)))
	if report.Status == Rejected {
		w.Write("[View the rejected correction in All reports](" + bookURL(book.ID) + "/all)\n\n")
	} else {
		w.Write("## Correction\n\n" + sanitize.InlineText(report.Text) + "\n\n")
	}
	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 != "" && report.Status != Rejected {
		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) {
	renderFinderCredits(w, req, false)
}

func renderUnpaidFinder(w *mux.ResponseWriter, req *mux.Request) {
	renderFinderCredits(w, req, true)
}

func renderFinderCredits(w *mux.ResponseWriter, req *mux.Request, unpaid bool) {
	raw := req.GetVar("addr")
	cleaned := sanitize.BechString(raw, "g")
	if cleaned == "" || cleaned != raw || !address(cleaned).IsValid() {
		notFound(w, "Finder")
		return
	}
	addr := address(cleaned)
	stats := FinderStats(addr)
	finder, _ := finders.Get(cleaned).(*finderRecord)
	route := "finder/" + cleaned
	count := stats.Credits
	var tree *avl.Tree
	if finder != nil {
		tree = &finder.credits
	}
	if unpaid {
		route += "/unpaid"
		count = stats.UnpaidCredits
		if finder != nil {
			tree = &finder.unpaid
		}
	}
	offset, ok := pageOffset(req, count)
	if !ok {
		notFound(w, "Page")
		return
	}

	w.Write(ufmt.Sprintf("# Finder account\n\n%s\n\n- Reward-eligible credits: %d\n- Unpaid credits: %d\n- Paid: %s\n- Owed: %s\n\n",
		sanitize.InlineCode(cleaned), stats.Credits, stats.UnpaidCredits,
		errata.FormatUgnot(stats.Paid), errata.FormatUgnot(stats.Owed)))
	if unpaid {
		w.Write("[Reward-eligible credits](" + finderURL(addr) + ")\n\n## Unpaid credits\n\n")
	} else {
		w.Write("[Unpaid credits](" + finderURL(addr) + "/unpaid)\n\n## Reward-eligible credits\n\n")
	}
	if count == 0 {
		w.Write("No credits in this view yet.\n")
		return
	}
	w.Write("| Book | Find | Height found | Paid | Owed |\n| --- | --- | ---: | ---: | ---: |\n")
	for _, report := range listReports(tree, offset, pageSize) {
		book, _ := GetBook(report.BookID)
		w.Write(ufmt.Sprintf("| [%s](%s) | [%s](%s) | %d | %s | %s |\n",
			sanitize.TableCell(book.Title), bookURL(book.ID),
			sanitize.TableCell(report.Location), erratumURL(report.ID), report.SubmittedAt,
			errata.FormatUgnot(report.Paid), errata.FormatUgnot(report.Owed)))
	}
	pagination(w, route, offset, count)
}