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

addresses.gno

package bolo

import (
	"chain"

	"gno.land/p/nt/seqid/v0"
)

// The paths Bolo's addresses derive from. pkgPath is this realm's own; a test
// checks it against the realm.
const (
	pkgPath      = "gno.land/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo/v0"
	registryPath = "gno.land/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo"
	slashedPath  = "slashed" // where slashed bonds go; nothing ever spends it (INV-8)
)

// escrowPath and bondPath are a campaign's sub-paths (API §1): one escrow and one
// bond address per campaign, so a bug in one campaign can't spend another's.
func escrowPath(id seqid.ID) string { return "c/" + idString(id) }

func bondPath(id seqid.ID) string { return "b/" + idString(id) }

// escrowSub and bondSub are the only places Bolo derives a sub-realm, and so the
// only way to a banker for a campaign's addresses (API C9, INV-8, INV-18). They
// take the stored campaign itself, never an ID: an ID parsed from an argument has
// to find its campaign first.
func escrowSub(cur realm, c *campaign) realm { return cur.Sub(escrowPath(c.id)) }

func bondSub(cur realm, c *campaign) realm { return cur.Sub(bondPath(c.id)) }

// The same addresses for queries and Render, which have no cur, and the other
// addresses Bolo never pays a campaign to (API §1).
func escrowAddr(id seqid.ID) address { return chain.DerivePkgSubAddr(pkgPath, escrowPath(id)) }

func bondAddr(id seqid.ID) address { return chain.DerivePkgSubAddr(pkgPath, bondPath(id)) }

func slashedAddr() address { return chain.DerivePkgSubAddr(pkgPath, slashedPath) }

func realmAddr() address { return chain.PackageAddress(pkgPath) }

func depositAddr() address { return chain.DeriveStorageDepositAddr(pkgPath) }

func registryAddr() address { return chain.PackageAddress(registryPath) }

func registryDepositAddr() address { return chain.DeriveStorageDepositAddr(registryPath) }

addresses_test.gno

package bolo

import (
	"chain"
	"strings"
	"testing"

	"gno.land/p/nt/seqid/v0"
)

// TestAddresses: the addresses queries derive are the ones the realm's bankers
// spend from, and each one is distinct (API §1, INV-18).
func TestAddresses(cur realm, t *testing.T) {
	if cur.PkgPath() != pkgPath {
		t.Fatalf("pkgPath is %s, but the realm is %s", pkgPath, cur.PkgPath())
	}
	if realmAddr() != cur.Address() {
		t.Errorf("realmAddr() = %s, the realm is %s", realmAddr(), cur.Address())
	}
	// Each fixed address is the one its role names: the keeper's deposit address
	// for this realm, this realm's "slashed" sub-address, and the package one path
	// up, where the registry lives.
	if depositAddr() != chain.DeriveStorageDepositAddr(cur.PkgPath()) {
		t.Errorf("depositAddr() isn't the realm's storage-deposit address")
	}
	if slashedAddr() != cur.Sub("slashed").Address() {
		t.Errorf("slashedAddr() isn't the realm's slashed sub-address")
	}
	if registryAddr() != chain.PackageAddress(strings.TrimSuffix(cur.PkgPath(), "/v0")) {
		t.Errorf("registryAddr() isn't the registry's, one path up")
	}
	if registryDepositAddr() != chain.DeriveStorageDepositAddr(strings.TrimSuffix(cur.PkgPath(), "/v0")) {
		t.Errorf("registryDepositAddr() isn't the registry's storage-deposit address")
	}
	seen := map[address]string{
		realmAddr():           "the realm",
		slashedAddr():         "slashed",
		depositAddr():         "the storage deposit",
		registryAddr():        "the registry",
		registryDepositAddr(): "the registry's storage deposit",
	}
	if len(seen) != 5 {
		t.Fatalf("realm, slashed, deposit and registry addresses collide")
	}
	for _, id := range []seqid.ID{1, 2, 42, 1 << 63} {
		c := &campaign{id: id}
		if escrowSub(cur, c).Address() != escrowAddr(id) {
			t.Errorf("campaign %d: escrowSub and escrowAddr differ", uint64(id))
		}
		if bondSub(cur, c).Address() != bondAddr(id) {
			t.Errorf("campaign %d: bondSub and bondAddr differ", uint64(id))
		}
		for _, a := range []address{escrowAddr(id), bondAddr(id)} {
			if other, dup := seen[a]; dup {
				t.Errorf("campaign %d: %s is also %s", uint64(id), a, other)
			}
			seen[a] = "campaign " + idString(id)
		}
	}
	// The address for "42" is campaign 42's; "042" names nothing (INV-18).
	id, _ := parseID("42")
	if escrowAddr(id) != escrowAddr(42) {
		t.Errorf("parsed and stored IDs give different escrows")
	}
}

admin.gno

package bolo

// adminAddr is Bolo's admin (API §3.6): a constant in source, never the deployer.
//
// Until the real admin key exists, it is an address nobody holds a key for, so a
// deployment made by mistake has no admin at all. Tests and local runs stage the
// realm with a test admin instead (internal/stage).
const adminAddr address = "g1at2h7kdhz2m9lv6azn54mwu4wl95k94wu90uwj"

administration.gno

package bolo

import (
	"chain"
	"chain/runtime"
)

// Administration (API §3.6). Every write here starts with C11's realm branch, then
// assertSigner: the master key, never a session key, in either branch, and then the
// admin's address — for AcceptAdmin, the proposed admin's. The rules on the values
// live in plain helpers, which unit tests drive directly: a crossing call's panic
// can't be recovered by a test, so the writes' refusals are tested in txtar (plan
// §3.3).

// assertCodeCaller refuses any caller but a deployed realm (API C11). A maketx run
// script is ephemeral and code at once: it is refused here, as is a user.
func assertCodeCaller(cur realm) {
	if p := cur.Previous(); !p.IsCode() || p.IsEphemeral() {
		panic(ErrNotUserCall)
	}
}

// assertSigner runs right after C11's branch: no session key, in either branch
// (C11), then the caller must be who (API §3.6).
func assertSigner(cur realm, who address) {
	if _, _, _, isSession := runtime.GetSessionInfo(); isSession {
		panic(ErrSessionKey)
	}
	if cur.Previous().Address() != who {
		panic(ErrNotAdmin)
	}
}

// ProposeAdmin proposes next as the admin, who takes over by accepting. None of
// Bolo's own addresses can ever accept, so none can be proposed. A second proposal
// replaces the first.
func ProposeAdmin(cur realm, next address) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	checkOutsideBolo(next)
	pendingAdmin = next
	chain.Emit(evAdminProposed, "next", next.String())
}

// AcceptAdmin makes the proposed admin the admin, and ends the proposal.
func AcceptAdmin(cur realm) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, pendingAdmin)
	previous := admin
	admin, pendingAdmin = pendingAdmin, ""
	chain.Emit(evAdminChanged, "admin", admin.String(), "previous", previous.String())
}

// SetParams sets the Params new campaigns get; every live campaign keeps its own
// (INV-5).
func SetParams(cur realm, deposit int64, dormancyDays, exitDelayDays, bondHoldDays int) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	params = checkParams(deposit, dormancyDays, exitDelayDays, bondHoldDays)
	chain.Emit(evParamsChanged,
		"deposit", itoa(params.CreationDeposit),
		"dormancy", itoa(params.DormancyPeriod),
		"exitDelay", itoa(params.ExitDelay),
		"bondHold", itoa(params.BondHold),
	)
}

// SetTipRecipient sets where tips and swept strays go: never one of Bolo's own
// addresses.
func SetTipRecipient(cur realm, addr address) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	checkOutsideBolo(addr)
	tipRecipient = addr
	chain.Emit(evTipRecipientChanged, "to", addr.String())
}

// SetMinDonation sets the smallest gift Donate accepts, in ugnot, for new gifts.
func SetMinDonation(cur realm, amount int64) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	if amount <= 0 {
		panic(ErrSetting)
	}
	minDonation = amount
	chain.Emit(evMinDonationChanged, "amount", itoa(amount))
}

// SetPresets sets the four one-click amounts, in ugnot. Display only.
func SetPresets(cur realm, a, b, c, d int64) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	presets = checkPresets(a, b, c, d)
	chain.Emit(evPresetsChanged, "a", itoa(a), "b", itoa(b), "c", itoa(c), "d", itoa(d))
}

// SetEscrowCap sets the most one campaign's tracked escrow balance may reach; 0
// removes the cap. It gates gifts only, never money going out (INV-4).
func SetEscrowCap(cur realm, max int64) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	if max < 0 {
		panic(ErrSetting)
	}
	escrowCap = max
	chain.Emit(evEscrowCapChanged, "max", itoa(max))
}

// AddCategory adds a category. There is no remove and no rename: every campaign
// keeps a valid category.
func AddCategory(cur realm, code string) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	checkNewCategory(code)
	categories.Set(code, true)
	categoryOrder = append(categoryOrder, code)
	chain.Emit(evCategoryAdded, "code", code)
}

// Sunset stops CreateCampaign for good. It names no successor: where new campaigns
// start is the registry's Current() (API §3.7). A second call changes nothing.
func Sunset(cur realm) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	if sunset {
		return
	}
	sunset = true
	chain.Emit(evSunset)
}

// Pause stops CreateCampaign, Donate and PostBond — money coming in, never money
// going out. Pausing while paused changes nothing.
func Pause(cur realm) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	if paused {
		return
	}
	paused = true
	chain.Emit(evPaused)
}

// Unpause lifts a pause. Unpausing while running changes nothing.
func Unpause(cur realm) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	if !paused {
		return
	}
	paused = false
	chain.Emit(evUnpaused)
}

// checkParams returns the Params for SetParams' arguments, or panics with
// ErrSetting when one is out of bounds (API §3.6). The upper bounds keep the
// conversion to seconds far from overflowing.
func checkParams(deposit int64, dormancyDays, exitDelayDays, bondHoldDays int) Params {
	if deposit <= 0 || !between(dormancyDays, 1, 3650) || !between(exitDelayDays, 7, 3650) || !between(bondHoldDays, 0, 3650) {
		panic(ErrSetting)
	}
	return Params{
		CreationDeposit: deposit,
		DormancyPeriod:  daysToSeconds(dormancyDays, ErrSetting),
		ExitDelay:       daysToSeconds(exitDelayDays, ErrSetting),
		BondHold:        daysToSeconds(bondHoldDays, ErrSetting),
	}
}

func between(n, min, max int) bool { return n >= min && n <= max }

// checkPresets returns the four amounts, or panics with ErrSetting unless they
// are positive and strictly ascending (API §3.6).
func checkPresets(a, b, c, d int64) [4]int64 {
	if a <= 0 || a >= b || b >= c || c >= d {
		panic(ErrSetting)
	}
	return [4]int64{a, b, c, d}
}

// checkOutsideBolo refuses, with ErrSetting, a malformed address (C12) and every
// address of Bolo's own (API §3.6): the realm's, where tips would stay (INV-3); the
// escrow and bond addresses derived so far, where an escrow would count tips as
// untracked money; slashed, where they would be burned; the storage-deposit
// address, the keeper's (Q8); and the registry, with its storage-deposit address.
// Tips must not go there, and none of them can ever accept the admin role.
func checkOutsideBolo(a address) {
	checkAddress(a, ErrSetting)
	if a == realmAddr() || a == slashedAddr() || a == depositAddr() || a == registryAddr() || a == registryDepositAddr() || derived.Has(a.String()) {
		panic(ErrSetting)
	}
}

// checkNewCategory refuses a code that isn't 3 to 20 lowercase letters, one already
// listed, or one past the cap (API §3.6).
func checkNewCategory(code string) {
	if len(code) < 3 || len(code) > 20 || categories.Has(code) || len(categoryOrder) >= maxCategories {
		panic(ErrSetting)
	}
	for i := 0; i < len(code); i++ {
		if code[i] < 'a' || code[i] > 'z' {
			panic(ErrSetting)
		}
	}
}

administration_test.gno

package bolo

import (
	"chain"
	"testing"

	"gno.land/p/nt/testutils/v0"
)

// TestAdministration walks the admin's writes on a fresh deployment, each called
// straight from the test's body, as AssertOriginCall requires (plan §3.3): the
// launch values, then each write's effect, then the handover to a realm, which
// then administers through C11's realm branch. The writes' refusals are tested in
// txtar (admin.txtar): a crossing call's panic can't be recovered here.
func TestAdministration(cur realm, t *testing.T) {
	// The walk changes every setting and the admin: put them back, so later
	// tests start from the launch values.
	defer restoreSettings(admin, pendingAdmin, params, presets, minDonation, escrowCap, tipRecipient, paused, sunset, categoryOrder)

	// The launch values as API §2.2 states them: literals, not the constants under
	// test.
	if p := GetParams(); p != (Params{1_000_000, 90 * 86400, 60 * 86400, 30 * 86400}) {
		t.Errorf("launch params = %v", p)
	}
	s := GetSettings()
	if s.Version != "v0" || s.Presets != [4]int64{5_000_000, 10_000_000, 20_000_000, 50_000_000} ||
		s.MinDonation != 1_000_000 || s.MaxEscrowBalance != 1_000_000_000 ||
		s.TipRecipient != adminAddr || s.Paused || s.Sunset {
		t.Errorf("launch settings = %v", s)
	}
	launchSet := []string{
		"medical", "emergency", "disaster", "humanitarian", "water", "food",
		"education", "orphans", "animals", "funeral", "worship", "community",
		"sport", "celebration", "personal", "other",
	}
	if len(s.Categories) != len(launchSet) {
		t.Errorf("launch categories = %v", s.Categories)
	}
	for i, code := range launchSet {
		if i >= len(s.Categories) || s.Categories[i] != code || !categories.Has(code) {
			t.Errorf("launch category %d: want %s, listed and found", i, code)
		}
	}
	if a, p := GetAdmin(); a != adminAddr || p != "" {
		t.Errorf("GetAdmin() = %s, %q", a, p)
	}
	// GetSettings hands out a copy (C6).
	s.Categories[0] = "changed"
	if GetSettings().Categories[0] != "medical" {
		t.Errorf("GetSettings shares its categories with the realm")
	}

	testing.SetRealm(testing.NewUserRealm(adminAddr))
	SetParams(cross(cur), 2_000_000, 30, 14, 0)
	SetMinDonation(cross(cur), 500_000)
	SetPresets(cross(cur), 1_000_000, 2_000_000, 3_000_000, 4_000_000)
	SetEscrowCap(cross(cur), 0)
	AddCategory(cross(cur), "garden")
	treasurer := testutils.TestAddress("treasurer")
	SetTipRecipient(cross(cur), treasurer)
	Pause(cross(cur))
	Sunset(cross(cur))
	if p := GetParams(); p != (Params{2_000_000, 30 * secondsPerDay, 14 * secondsPerDay, 0}) {
		t.Errorf("params = %v", p)
	}
	s = GetSettings()
	if s.MinDonation != 500_000 || s.Presets != [4]int64{1_000_000, 2_000_000, 3_000_000, 4_000_000} ||
		s.MaxEscrowBalance != 0 || s.TipRecipient != treasurer || !s.Paused || !s.Sunset ||
		len(s.Categories) != 17 || s.Categories[16] != "garden" || !categories.Has("garden") {
		t.Errorf("settings = %v", s)
	}
	Unpause(cross(cur))
	if GetSettings().Paused {
		t.Errorf("still paused")
	}

	// The handover (ADR D11): a second proposal replaces the first; accepting ends
	// the proposal, and the new admin is a realm.
	dao := chain.PackageAddress("gno.land/r/test/dao")
	ProposeAdmin(cross(cur), testutils.TestAddress("someone"))
	ProposeAdmin(cross(cur), dao)
	if a, p := GetAdmin(); a != adminAddr || p != dao {
		t.Errorf("after two proposals: GetAdmin() = %s, %s", a, p)
	}
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/test/dao"))
	AcceptAdmin(cross(cur))
	if a, p := GetAdmin(); a != dao || p != "" {
		t.Errorf("after accepting: GetAdmin() = %s, %q", a, p)
	}
	SetEscrowCap(cross(cur), 7)
	if GetSettings().MaxEscrowBalance != 7 {
		t.Errorf("the realm admin's write didn't apply")
	}
}

func TestCheckParams(t *testing.T) {
	if got := checkParams(1, 1, 7, 0); got != (Params{1, secondsPerDay, 7 * secondsPerDay, 0}) {
		t.Errorf("lower bounds: %v", got)
	}
	if got := checkParams(1, 3650, 3650, 3650); got != (Params{1, 3650 * secondsPerDay, 3650 * secondsPerDay, 3650 * secondsPerDay}) {
		t.Errorf("upper bounds: %v", got)
	}
	for name, c := range map[string]struct {
		deposit                   int64
		dormancy, exitDelay, hold int
	}{
		"no deposit":           {0, 90, 60, 30},
		"negative deposit":     {-1, 90, 60, 30},
		"no dormancy":          {1, 0, 60, 30},
		"dormancy too long":    {1, 3651, 60, 30},
		"exit delay too short": {1, 90, 6, 30},
		"exit delay too long":  {1, 90, 3651, 30},
		"negative bond hold":   {1, 90, 60, -1},
		"bond hold too long":   {1, 90, 60, 3651},
	} {
		if !panicsWith(func() { checkParams(c.deposit, c.dormancy, c.exitDelay, c.hold) }, ErrSetting) {
			t.Errorf("%s: not refused", name)
		}
	}
}

func TestCheckPresets(t *testing.T) {
	if got := checkPresets(1, 2, 3, 4); got != [4]int64{1, 2, 3, 4} {
		t.Errorf("checkPresets = %v", got)
	}
	for name, p := range map[string][4]int64{
		"zero":        {0, 2, 3, 4},
		"negative":    {-1, 2, 3, 4},
		"equal pair":  {1, 2, 2, 4},
		"last equal":  {1, 2, 3, 3},
		"first equal": {1, 1, 3, 4},
		"descending":  {4, 3, 2, 1},
	} {
		if !panicsWith(func() { checkPresets(p[0], p[1], p[2], p[3]) }, ErrSetting) {
			t.Errorf("%s: not refused", name)
		}
	}
}

func TestCheckOutsideBolo(t *testing.T) {
	checkOutsideBolo(testutils.TestAddress("treasurer"))
	campaign := escrowAddr(9)
	derived.Set(campaign.String(), true)
	defer derived.Remove(campaign.String())
	for name, a := range map[string]address{
		"the realm":              realmAddr(),
		"slashed":                slashedAddr(),
		"the storage deposit":    depositAddr(),
		"the registry":           registryAddr(),
		"the registry's deposit": registryDepositAddr(),
		"a campaign's escrow":    campaign,
		"malformed":              "g1notanaddress",
	} {
		if !panicsWith(func() { checkOutsideBolo(a) }, ErrSetting) {
			t.Errorf("%s: not refused", name)
		}
	}
}

func TestCheckNewCategory(t *testing.T) {
	checkNewCategory("orchard")
	checkNewCategory("abc")
	checkNewCategory("abcdefghijklmnopqrst")
	for name, code := range map[string]string{
		"too short":      "ab",
		"too long":       "abcdefghijklmnopqrstu",
		"capitals":       "Orchard",
		"a digit":        "orchard2",
		"a space":        "or chard",
		"already listed": "water",
	} {
		if !panicsWith(func() { checkNewCategory(code) }, ErrSetting) {
			t.Errorf("%s: not refused", name)
		}
	}
	// The 50th fits, the 51st doesn't (API §3.6, INV-9).
	saved := categoryOrder
	defer func() { categoryOrder = saved }()
	for len(categoryOrder) < 49 {
		categoryOrder = append(categoryOrder, "filler")
	}
	checkNewCategory("orchard")
	categoryOrder = append(categoryOrder, "orchard")
	if !panicsWith(func() { checkNewCategory("grove") }, ErrSetting) {
		t.Errorf("a 51st category: not refused")
	}
}

// restoreSettings puts back what TestAdministration changes.
func restoreSettings(a, pending address, p Params, pr [4]int64, minimum, ceiling int64, tips address, pause, sun bool, order []string) {
	admin, pendingAdmin, params, presets = a, pending, p, pr
	minDonation, escrowCap, tipRecipient, paused, sunset = minimum, ceiling, tips, pause, sun
	for _, code := range categoryOrder[len(order):] {
		categories.Remove(code)
	}
	categoryOrder = order
}

close.gno

package bolo

import (
	"chain"
	"chain/runtime"
)

// Close closes campaign id to new donations. Its organizer can, at any time; anyone
// can, once it is past its deadline or inactive for long enough — the campaign's page
// says when. Closing stops gifts only: what the campaign holds still goes to the
// beneficiary, or back to its donors.
//
// Its branch follows state, never the caller (API §3.1, Q7). Past its deadline, Close
// records the close if nothing has yet, and never fails. A dormant campaign closes as
// dormant, whoever calls. Only an open campaign nobody else may close yet takes the
// organizer's branch, which checks how the call arrived (C11) before it reads who
// sent it.
func Close(cur realm, id string) {
	assertCurrent(cur)
	c := campaignOf(id)
	recordDeadline(cur, c)
	if c.deadline != 0 && now() >= c.deadline {
		return // recorded above, now or before: housekeeping, never an error
	}
	assertOpen(c)
	if now() >= dormantAt(c) {
		closeNow(c, reasonDormant, cur.Previous().Address())
		return
	}
	if !cur.Previous().IsUserCall() {
		panic(ErrNotUserCall)
	}
	runtime.AssertOriginCall()
	if cur.Previous().Address() != c.organizer {
		panic(ErrNotClosable)
	}
	closeNow(c, reasonOrganizer, c.organizer)
}

// closeNow closes the open campaign c now, for reason, and takes it out of the
// active indexes; Closed names by, who sent the call (API §3.1, §6).
func closeNow(c *campaign, reason string, by address) {
	s := c.state
	s.status, s.closedAt, s.closeReason = statusClosed, now(), reason
	stats.open--
	dropActive(c)
	chain.Emit(evClosed, "id", idString(c.id), "reason", reason, "by", by.String())
}

// closeNotYet is CanClose's reason while only the organizer may close.
const closeNotYet = "not_yet"

// CanClose says what Close(id), sent by caller from a wallet, would do now (API
// §4): true, with the reason it would record — "deadline" or "dormant" for anyone,
// "organizer" for the organizer alone — or false, with "closed" once closed or
// settled, and "not_yet" while only the organizer may close.
func CanClose(id string, caller address) (bool, string) {
	c := campaignOf(id)
	status, _, _ := effective(c)
	switch {
	case status != statusOpen && c.state.status == statusOpen:
		return true, reasonDeadline // passed, not yet recorded
	case status != statusOpen:
		return false, statusClosed
	case now() >= dormantAt(c):
		return true, reasonDormant
	case caller == c.organizer:
		return true, reasonOrganizer
	}
	return false, closeNotYet
}

close_test.gno

package bolo

import (
	"testing"

	"gno.land/p/nt/testutils/v0"
)

// TestClose walks each of Close's branches. Before each call, CanClose names the
// reason Close then records (API §4); the refusals are in txtar (organizer.txtar).
func TestClose(cur realm, t *testing.T) {
	closed := func(c *campaign, reason string, at int64) bool {
		s := c.state
		return s.status == statusClosed && s.closeReason == reason && s.closedAt == at && !active.Has(c.id.Binary()) &&
			!activeByCategory.Has(c.category+"/"+c.id.Binary())
	}

	// The organizer closes an open campaign, now.
	c := testCampaign(9201, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	if ok, why := CanClose(id, c.organizer); !ok || why != reasonOrganizer {
		t.Errorf("CanClose(organizer) = %t, %q", ok, why)
	}
	testing.SetRealm(testing.NewUserRealm(c.organizer))
	Close(cross(cur), id)
	if !closed(c, reasonOrganizer, now()) {
		t.Errorf("organizer: %v", *c.state)
	}
	if ok, why := CanClose(id, c.organizer); ok || why != statusClosed {
		t.Errorf("CanClose once closed = %t, %q", ok, why)
	}

	// Past dormancy, anyone closes it for dormancy, its organizer too (Q7).
	d := testCampaign(9202, modeEscrow, 0)
	idD, unstoreD := storeCampaign(d)
	defer unstoreD()
	e := testCampaign(9203, modeEscrow, 0)
	idE, unstoreE := storeCampaign(e)
	defer unstoreE()
	testing.SkipHeights(90 * heightsPerDay)
	if ok, why := CanClose(idD, passerby); !ok || why != reasonDormant {
		t.Errorf("CanClose(passerby), dormant = %t, %q", ok, why)
	}
	testing.SetRealm(testing.NewUserRealm(passerby))
	Close(cross(cur), idD)
	if !closed(d, reasonDormant, now()) {
		t.Errorf("passerby, dormant: %v", *d.state)
	}
	if ok, why := CanClose(idE, e.organizer); !ok || why != reasonDormant {
		t.Errorf("CanClose(organizer), dormant = %t, %q", ok, why)
	}
	testing.SetRealm(testing.NewUserRealm(e.organizer))
	Close(cross(cur), idE)
	if !closed(e, reasonDormant, now()) {
		t.Errorf("organizer, dormant: %v", *e.state)
	}

	// Past its deadline: closed at the deadline by whoever calls first; a second
	// call changes nothing, and fails nothing.
	f := testCampaign(9204, modeEscrow, now()+2*secondsPerDay)
	idF, unstoreF := storeCampaign(f)
	defer unstoreF()
	g := testCampaign(9205, modeEscrow, now()+2*secondsPerDay)
	idG, unstoreG := storeCampaign(g)
	defer unstoreG()
	testing.SetRealm(testing.NewUserRealm(g.organizer))
	Close(cross(cur), idG)
	closedG := now()
	testing.SkipHeights(3 * heightsPerDay)
	if ok, why := CanClose(idF, passerby); !ok || why != reasonDeadline {
		t.Errorf("CanClose(passerby), deadline = %t, %q", ok, why)
	}
	testing.SetRealm(testing.NewUserRealm(passerby))
	Close(cross(cur), idF)
	if !closed(f, reasonDeadline, f.deadline) {
		t.Errorf("passerby, deadline: %v", *f.state)
	}
	Close(cross(cur), idF)
	if !closed(f, reasonDeadline, f.deadline) {
		t.Errorf("a second close changed it: %v", *f.state)
	}
	// One the organizer closed before its deadline keeps its close after it.
	Close(cross(cur), idG)
	if !closed(g, reasonOrganizer, closedG) {
		t.Errorf("closed before its deadline, then housekept: %v", *g.state)
	}
}

// TestDormancy: dormancy counts from the latest of creation, the last gift and the
// last update, so an update resets it (API §3.1).
func TestDormancy(cur realm, t *testing.T) {
	c := testCampaign(9206, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	testing.SkipHeights(80 * heightsPerDay)
	testing.SetRealm(testing.NewUserRealm(c.organizer))
	PostUpdate(cross(cur), id, "Still here.")
	testing.SkipHeights(90*heightsPerDay - 1)
	if ok, why := CanClose(id, passerby); ok || why != closeNotYet {
		t.Errorf("a height before 90 days from the update: %t, %q", ok, why)
	}
	testing.SkipHeights(1)
	if ok, why := CanClose(id, passerby); !ok || why != reasonDormant {
		t.Errorf("90 days from the update: %t, %q", ok, why)
	}
	c.state.lastDonationAt = now()
	if ok, why := CanClose(id, passerby); ok || why != closeNotYet {
		t.Errorf("right after a gift: %t, %q", ok, why)
	}
}

func TestCanClose(t *testing.T) {
	organizer := testutils.TestAddress("organizer")
	open := testCampaign(9211, modeEscrow, 0)
	dormant := testCampaign(9212, modeEscrow, 0)
	dormant.createdAt = now() - 90*secondsPerDay
	passed := testCampaign(9213, modeEscrow, now()-1)
	both := testCampaign(9214, modeEscrow, now()-1)
	both.createdAt = now() - 91*secondsPerDay
	recorded := testCampaign(9215, modeEscrow, now()-1)
	recorded.state.status = statusClosed
	shut := testCampaign(9216, modeEscrow, 0)
	shut.state.status = statusClosed
	settled := testCampaign(9217, modeEscrow, 0)
	settled.state.status = statusSettled
	for _, k := range []struct {
		name   string
		c      *campaign
		caller address
		ok     bool
		why    string
	}{
		{"open, organizer", open, organizer, true, reasonOrganizer},
		{"open, passerby", open, passerby, false, closeNotYet},
		{"dormant, passerby", dormant, passerby, true, reasonDormant},
		{"dormant, organizer", dormant, organizer, true, reasonDormant},
		{"deadline passed, unrecorded", passed, passerby, true, reasonDeadline},
		{"deadline passed and dormant", both, organizer, true, reasonDeadline},
		{"deadline recorded", recorded, passerby, false, statusClosed},
		{"closed", shut, organizer, false, statusClosed},
		{"settled", settled, organizer, false, statusClosed},
	} {
		id, unstore := storeCampaign(k.c)
		ok, why := CanClose(id, k.caller)
		unstore()
		if ok != k.ok || why != k.why {
			t.Errorf("%s: CanClose = %t, %q, want %t, %q", k.name, ok, why, k.ok, k.why)
		}
	}
	if !panicsWith(func() { CanClose("042", organizer) }, ErrNotFound) {
		t.Errorf("CanClose(\"042\"): not ErrNotFound")
	}
}

create.gno

package bolo

import (
	"chain"
	"chain/banker"
	"chain/runtime"

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

// maxDeadlineDays bounds how far ahead a deadline may be, so no timer computed from
// it can overflow (API §3.1).
const maxDeadlineDays = 3650

// CreateCampaign opens a campaign, which you organize, and returns its ID. Send the
// creation deposit with it — Bolo's "Start a campaign" link attaches it — and it comes
// back when the campaign completes. title and description are public, and the
// description may hold links, never an image. category is one of Bolo's categories.
// imageCID and imageAlt are a photo on IPFS and what it shows, or both empty.
// beneficiary is the address the money goes to, which can never change. goal is in
// ugnot, 0 for none. mode is "escrow" or "direct". deadline is a Unix time, 0 for
// none.
//
// It opens a campaign for its caller, the organizer (API §3.1). The envelope is
// exactly the creation deposit, which goes to the campaign's bond address: the realm
// keeps nothing (INV-3).
func CreateCampaign(cur realm, title, description, category, imageCID, imageAlt string, beneficiary address, goal int64, mode string, deadline int64) string {
	assertCurrent(cur)
	if !cur.Previous().IsUserCall() {
		panic(ErrNotUserCall)
	}
	runtime.AssertOriginCall()
	if envelopeUgnot() != params.CreationDeposit {
		panic(ErrDepositMismatch)
	}
	if paused {
		panic(ErrPaused)
	}
	if sunset {
		panic(ErrSunset)
	}
	text := checkCampaignText(title, description, imageCID, imageAlt)
	checkCampaignTerms(category, mode, goal, deadline)
	checkBeneficiary(beneficiary, nextID+1)

	id := nextID.Next()
	c := &campaign{
		id:          id,
		category:    category,
		organizer:   cur.Previous().Address(),
		beneficiary: beneficiary,
		mode:        mode,
		goal:        goal,
		deadline:    deadline,
		createdAt:   now(),
		params:      params,

		text:  text,
		state: &campaignState{status: statusOpen, listed: true},

		contributions: avl.NewTree(),
		receipts:      avl.NewTree(),
		withdrawals:   avl.NewTree(),
		refunds:       avl.NewTree(),
		updates:       avl.NewTree(),
	}
	key := id.Binary()
	campaigns.Set(key, c)
	stats.open++
	derived.Set(escrowAddr(id).String(), true)
	derived.Set(bondAddr(id).String(), true)
	addActive(c)
	byOrganizer.Set(c.organizer.String()+"/"+key, true)
	byBeneficiary.Set(beneficiary.String()+"/"+key, true)

	banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(realmAddr(), bondAddr(id), chain.NewCoins(chain.NewCoin("ugnot", c.params.CreationDeposit)))
	chain.Emit(evCampaignCreated,
		"id", idString(id),
		"organizer", c.organizer.String(),
		"beneficiary", beneficiary.String(),
		"mode", mode,
		"category", category,
		"goal", itoa(goal),
		"deadline", itoa(deadline),
	)
	return idString(id)
}

// checkCampaignText checks a campaign's text (API §2.3) and returns it normalized:
// the title, the story, and the photo with its description.
func checkCampaignText(title, description, imageCID, imageAlt string) *campaignText {
	title = checkText(title, titleMin, titleMax, false, ErrTitle)
	description = checkStory(description, 0, descriptionMax, ErrDescription)
	imageCID, imageAlt = checkImage(imageCID, imageAlt)
	return &campaignText{title: title, description: description, imageCID: imageCID, imageAlt: imageAlt}
}

// checkCampaignTerms refuses a category not listed, a mode that isn't one, a
// negative goal, and a deadline neither 0 nor in the future, at most maxDeadlineDays
// ahead (API §3.1).
func checkCampaignTerms(category, mode string, goal, deadline int64) {
	if !categories.Has(category) {
		panic(ErrCategory)
	}
	if mode != modeDirect && mode != modeEscrow {
		panic(ErrMode)
	}
	if goal < 0 {
		panic(ErrGoal)
	}
	if deadline != 0 && (deadline <= now() || deadline > now()+maxDeadlineDays*secondsPerDay) {
		panic(ErrDeadline)
	}
}

// checkBeneficiary refuses a malformed address (C12) and every address a campaign
// must never pay (API §1): the realm's, slashed, the storage-deposit address, the
// registry and its storage-deposit address, every escrow and bond address handed
// out — and those of id, the campaign about to be created, which paying itself
// would trap every gift.
func checkBeneficiary(b address, id seqid.ID) {
	checkAddress(b, ErrBeneficiary)
	if b == realmAddr() || b == slashedAddr() || b == depositAddr() || b == registryAddr() || b == registryDepositAddr() ||
		derived.Has(b.String()) || b == escrowAddr(id) || b == bondAddr(id) {
		panic(ErrBeneficiary)
	}
}

create_test.gno

package bolo

import (
	"chain"
	"chain/banker"
	"strings"
	"testing"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/testutils/v0"
)

// TestCreateCampaign creates campaigns as a user, straight from the test's body as
// AssertOriginCall requires (plan §3.3), with the envelope and the realm's coins a
// real transaction would bring. Its refusals are in txtar (create.txtar): a test
// can't recover a crossing call's panic.
func TestCreateCampaign(cur realm, t *testing.T) {
	defer restoreCampaigns(nextID)
	defer restoreSettings(admin, pendingAdmin, params, presets, minDonation, escrowCap, tipRecipient, paused, sunset, categoryOrder)

	organizer := testutils.TestAddress("organizer")
	beneficiary := testutils.TestAddress("beneficiary")
	deposit := params.CreationDeposit
	first := nextID + 1

	testing.SetRealm(testing.NewUserRealm(organizer))
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", deposit)))
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", deposit)))
	id := CreateCampaign(cross(cur), "  Clean water for Ndiaganiao ", "A pump.", "water", "", "", beneficiary, 1_500_000_000, modeEscrow, 0)
	if id != idString(first) {
		t.Fatalf("CreateCampaign returned %q, want %q", id, idString(first))
	}

	// The deposit went to the bond address; the realm keeps nothing (INV-3).
	rb := banker.NewReadonlyBanker()
	if got := rb.GetCoin(bondAddr(first), "ugnot"); got != deposit {
		t.Errorf("bond address holds %d, want the deposit %d", got, deposit)
	}
	if got := rb.GetCoin(realmAddr(), "ugnot"); got != 0 {
		t.Errorf("the realm kept %d", got)
	}

	v := GetCampaign(id)
	want := CampaignView{
		ID: id, Title: "Clean water for Ndiaganiao", Description: "A pump.", Category: "water",
		Organizer: organizer, Beneficiary: beneficiary, Mode: modeEscrow, Status: statusOpen, Listed: true,
		Goal: 1_500_000_000, Deposit: deposit, CreatedAt: now(),
		ClosableByAnyoneAt: now() + params.DormancyPeriod,
		EscrowAddress:      escrowAddr(first), BondAddress: bondAddr(first), Params: params,
	}
	if v != want {
		t.Errorf("GetCampaign =\n%v\nwant\n%v", v, want)
	}
	key := first.Binary()
	for name, tree := range map[string]*avl.Tree{
		"campaigns":        &campaigns,
		"active":           &active,
		"activeByCategory": &activeByCategory,
		"byOrganizer":      &byOrganizer,
		"byBeneficiary":    &byBeneficiary,
	} {
		k := key
		switch name {
		case "activeByCategory":
			k = "water/" + key
		case "byOrganizer":
			k = organizer.String() + "/" + key
		case "byBeneficiary":
			k = beneficiary.String() + "/" + key
		}
		if !tree.Has(k) {
			t.Errorf("campaign %s is missing from %s", id, name)
		}
	}
	if !derived.Has(escrowAddr(first).String()) || !derived.Has(bondAddr(first).String()) {
		t.Errorf("campaign %s's escrow and bond addresses aren't recorded as derived", id)
	}

	// A change of Params applies to campaigns created afterwards only (INV-5).
	testing.SetRealm(testing.NewUserRealm(adminAddr))
	SetParams(cross(cur), 3_000_000, 30, 14, 7)
	testing.SetRealm(testing.NewUserRealm(organizer))
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 3_000_000)))
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 3_000_000)))
	second := CreateCampaign(cross(cur), "A second campaign", "", "food", "", "", beneficiary, 0, modeDirect, 0)
	if v := GetCampaign(id); v.Params != want.Params || v.Deposit != deposit {
		t.Errorf("SetParams changed campaign %s: %v", id, v.Params)
	}
	if v := GetCampaign(second); v.Params != GetParams() || v.Deposit != 3_000_000 {
		t.Errorf("campaign %s didn't get the new Params: %v", second, v.Params)
	}
}

func TestCheckCampaignTerms(t *testing.T) {
	checkCampaignTerms("water", modeDirect, 0, 0)
	checkCampaignTerms("water", modeEscrow, 1, now()+1)
	checkCampaignTerms("water", modeEscrow, 1, now()+maxDeadlineDays*secondsPerDay)
	for name, c := range map[string]struct {
		category, mode string
		goal, deadline int64
		err            Error
	}{
		"unknown category":  {"rockets", modeDirect, 0, 0, ErrCategory},
		"no mode":           {"water", "", 0, 0, ErrMode},
		"unknown mode":      {"water", "both", 0, 0, ErrMode},
		"negative goal":     {"water", modeDirect, -1, 0, ErrGoal},
		"deadline now":      {"water", modeDirect, 0, now(), ErrDeadline},
		"deadline past":     {"water", modeDirect, 0, now() - 1, ErrDeadline},
		"deadline too far":  {"water", modeDirect, 0, now() + maxDeadlineDays*secondsPerDay + 1, ErrDeadline},
		"deadline negative": {"water", modeDirect, 0, -1, ErrDeadline},
	} {
		if !panicsWith(func() { checkCampaignTerms(c.category, c.mode, c.goal, c.deadline) }, c.err) {
			t.Errorf("%s: not refused with %s", name, c.err)
		}
	}
}

func TestCheckCampaignText(t *testing.T) {
	text := checkCampaignText(" Clean water ", " A pump. ", "", "")
	if text.title != "Clean water" || text.description != "A pump." {
		t.Errorf("checkCampaignText = %v", text)
	}
	for name, c := range map[string]struct {
		title, description, cid, alt string
		err                          Error
	}{
		"short title":       {"abc", "", "", "", ErrTitle},
		"image in story":    {"Clean water", "![x](u)", "", "", ErrMarkup},
		"photo without alt": {"Clean water", "", "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG", "", ErrImage},
	} {
		if !panicsWith(func() { checkCampaignText(c.title, c.description, c.cid, c.alt) }, c.err) {
			t.Errorf("%s: not refused with %s", name, c.err)
		}
	}
}

func TestCheckBeneficiary(t *testing.T) {
	next := seqid.ID(7)
	checkBeneficiary(testutils.TestAddress("beneficiary"), next)
	handedOut := escrowAddr(3)
	derived.Set(handedOut.String(), true)
	defer derived.Remove(handedOut.String())
	for name, a := range map[string]address{
		"malformed":                 "g1notanaddress",
		"in capitals":               address(strings.ToUpper(string(testutils.TestAddress("beneficiary")))),
		"the realm":                 realmAddr(),
		"slashed":                   slashedAddr(),
		"the storage deposit":       depositAddr(),
		"the registry":              registryAddr(),
		"the registry's deposit":    registryDepositAddr(),
		"an escrow handed out":      handedOut,
		"the new campaign's escrow": escrowAddr(next),
		"the new campaign's bond":   bondAddr(next),
	} {
		if !panicsWith(func() { checkBeneficiary(a, next) }, ErrBeneficiary) {
			t.Errorf("%s: not refused", name)
		}
	}
}

func TestGetCampaignNotFound(t *testing.T) {
	for _, id := range []string{"", "0", "042", "+1", " 1", "999999"} {
		if !panicsWith(func() { GetCampaign(id) }, ErrNotFound) {
			t.Errorf("GetCampaign(%q): not ErrNotFound", id)
		}
	}
}

// restoreCampaigns removes every campaign created after last from every tree. IDs
// keep counting: the bank keeps the coins those campaigns' addresses got, so a later
// test's campaigns get fresh addresses.
func restoreCampaigns(last seqid.ID) {
	for id := last + 1; id <= nextID; id++ {
		v := campaigns.Get(id.Binary())
		if v == nil {
			continue
		}
		c := v.(*campaign)
		key := id.Binary()
		campaigns.Remove(key)
		active.Remove(key)
		activeByCategory.Remove(c.category + "/" + key)
		byOrganizer.Remove(c.organizer.String() + "/" + key)
		byBeneficiary.Remove(c.beneficiary.String() + "/" + key)
		derived.Remove(escrowAddr(id).String())
		derived.Remove(bondAddr(id).String())
	}
}

deadline.gno

package bolo

import "chain"

// recordDeadline records a passed deadline (API §3.1): an open campaign whose
// deadline has passed becomes closed, at its deadline, for reason deadline, and
// leaves the active indexes; Closed is emitted, naming the caller there and only
// there. Every crossing function that takes a campaign ID calls it before any other
// precondition; queries and Render compute the same with effective, writing nothing.
func recordDeadline(cur realm, c *campaign) {
	s := c.state
	if s.status != statusOpen || c.deadline == 0 || now() < c.deadline {
		return
	}
	s.status, s.closedAt, s.closeReason = statusClosed, c.deadline, reasonDeadline
	stats.open--
	dropActive(c)
	chain.Emit(evClosed, "id", idString(c.id), "reason", reasonDeadline, "by", cur.Previous().Address().String())
}

// addActive puts c in the two active indexes, which list the open, listed campaigns
// (API §2.5).
func addActive(c *campaign) {
	key := c.id.Binary()
	active.Set(key, true)
	activeByCategory.Set(c.category+"/"+key, true)
}

// dropActive takes c out of the two active indexes (API §2.5).
func dropActive(c *campaign) {
	key := c.id.Binary()
	active.Remove(key)
	activeByCategory.Remove(c.category + "/" + key)
}

doc.gno

// Package bolo, at v0, is Bolo: give together, and see where it goes. Each campaign's
// money sits at its own address, where anyone can check it. Bolo takes no fee, and
// nothing in Bolo can freeze a gift. Its pages start at /r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo/v0.
//
// For developers: its interface is docs/API.md, its design
// docs/adr/0001-bolo-realm-design.md, and docs/TRACEABILITY.md maps each of their
// rules to the tests that hold it.
package bolo

donate.gno

package bolo

import (
	"chain"
	"chain/banker"
	"chain/runtime"
	"math"
	"strconv"

	"gno.land/p/nt/seqid/v0"
)

// Donate gives to campaign id, and returns your receipt's ID. Send the gift and any
// tip together: tip is the part of what you send that goes to Bolo, in ugnot — 0 for
// none. message is optional, and public. anonymous, if true, keeps your address off
// Bolo's pages; the chain still shows it. In a direct campaign the gift goes straight
// to the beneficiary; in escrow, to the campaign's escrow, until the beneficiary
// withdraws it.
//
// Any user, by a direct transaction, the donor being the caller (API §3.2). The
// envelope is the gift plus the tip. The gift goes to the beneficiary, or to the
// campaign's escrow, and the tip to the tip recipient: the realm keeps nothing
// (INV-3), and coins found there are never credited (C4).
func Donate(cur realm, id string, tip int64, message string, anonymous bool) string {
	assertCurrent(cur)
	if !cur.Previous().IsUserCall() {
		panic(ErrNotUserCall)
	}
	runtime.AssertOriginCall()
	c := campaignOf(id)
	recordDeadline(cur, c)
	amount := checkGift(c, envelopeUgnot(), tip)
	message = checkText(message, 0, messageMax, false, ErrMessage)
	checkRoom(c, amount)

	donor := cur.Previous().Address()
	s := c.state
	s.raised += amount
	s.donationCount++
	s.lastDonationAt = now()
	key := donor.String()
	var k *contribution
	if v := c.contributions.Get(key); v != nil {
		k = v.(*contribution)
	} else {
		k = &contribution{}
		c.contributions.Set(key, k)
		s.donorCount++
	}
	k.amount += amount
	if !anonymous && !k.public {
		k.public = true
		byDonor.Set(key+"/"+c.id.Binary(), true)
	}
	seq := s.receiptSeq.Next()
	c.receipts.Set(seq.Binary(), &receipt{
		seq: uint64(seq), donor: donor, anonymous: anonymous, amount: amount, tip: tip,
		message: message, at: now(), raisedAfter: s.raised, refundedBefore: k.refunded,
	})
	s.recent[s.recentNext] = uint64(seq)
	s.recentNext = (s.recentNext + 1) % recentSize

	if c.mode == modeDirect {
		banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(realmAddr(), c.beneficiary, chain.NewCoins(chain.NewCoin("ugnot", amount)))
	} else {
		banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(realmAddr(), escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", amount)))
	}
	if tip > 0 {
		banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(realmAddr(), tipRecipient, chain.NewCoins(chain.NewCoin("ugnot", tip)))
	}
	chain.Emit(evDonated,
		"id", idString(c.id),
		"seq", idString(seq),
		"donor", key,
		"amount", itoa(amount),
		"tip", itoa(tip),
		"anonymous", strconv.FormatBool(anonymous),
	)
	return receiptID(c.id, seq)
}

// checkGift returns the gift in an envelope of total ugnot carrying tip, or panics
// (API §3.2), in this order: a negative tip, or nothing left for the gift; a
// campaign that isn't open; a paused Bolo; a gift under the minimum.
func checkGift(c *campaign, total, tip int64) int64 {
	if tip < 0 || total-tip <= 0 {
		panic(ErrBadAmount)
	}
	amount := total - tip
	assertOpen(c)
	if paused {
		panic(ErrPaused)
	}
	if amount < minDonation {
		panic(ErrBadAmount)
	}
	return amount
}

// checkRoom refuses a gift of amount that c can't take (API §3.2): one that would
// push Raised past int64, or, in escrow mode with a cap set, the tracked balance —
// never the bank's — past MaxEscrowBalance.
func checkRoom(c *campaign, amount int64) {
	if amount > math.MaxInt64-c.state.raised {
		panic(ErrBadAmount)
	}
	if c.mode == modeEscrow && escrowCap > 0 && trackedBalance(c)+amount > escrowCap {
		panic(ErrCapReached)
	}
}

// receiptID is a receipt's ID: its campaign's, a slash, and its sequence number
// (API C9).
func receiptID(campaign, seq seqid.ID) string { return idString(campaign) + "/" + idString(seq) }

// SweepStrays sends the coins someone sent to Bolo's own address by mistake to the
// tip recipient, and returns how much: anyone can.
//
// It sends the ugnot at the realm's address to the tip recipient (API §3.4). The
// realm holds nothing between transactions (INV-3), so all of it is strays; anyone
// may call, and with nothing there it sends nothing and emits nothing (Q3).
func SweepStrays(cur realm) int64 {
	assertCurrent(cur)
	amount := banker.NewReadonlyBanker().GetCoin(realmAddr(), "ugnot")
	if amount == 0 {
		return 0
	}
	banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(realmAddr(), tipRecipient, chain.NewCoins(chain.NewCoin("ugnot", amount)))
	chain.Emit(evStraysSwept, "amount", itoa(amount), "to", tipRecipient.String())
	return amount
}

donate_test.gno

package bolo

import (
	"chain"
	"chain/banker"
	"math"
	"testing"

	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/testutils/v0"
)

// The helpers' tests come first: a write's test that panics through a crossing
// call stops the package's run, so a test after it would never report.

func TestCheckGift(t *testing.T) {
	defer func(p bool, m int64) { paused, minDonation = p, m }(paused, minDonation)
	minDonation = 1000
	c := testCampaign(9303, modeEscrow, 0)
	if got := checkGift(c, 1500, 500); got != 1000 {
		t.Errorf("checkGift(1500, 500) = %d, want 1000", got)
	}
	for name, k := range map[string]struct {
		status     string
		paused     bool
		total, tip int64
		err        Error
	}{
		"a negative tip":           {statusOpen, false, 1500, -1, ErrBadAmount},
		"all tip":                  {statusOpen, false, 1500, 1500, ErrBadAmount},
		"a tip above the envelope": {statusOpen, false, 1500, 1501, ErrBadAmount},
		"nothing sent":             {statusOpen, false, 0, 0, ErrBadAmount},
		"under the minimum":        {statusOpen, false, 1499, 500, ErrBadAmount},
		"closed":                   {statusClosed, false, 1500, 0, ErrCampaignClosed},
		"settled":                  {statusSettled, false, 1500, 0, ErrCampaignSettled},
		"paused":                   {statusOpen, true, 1500, 0, ErrPaused},
		"closed, and paused":       {statusClosed, true, 1500, 0, ErrCampaignClosed},
		"nothing left, and closed": {statusClosed, false, 500, 500, ErrBadAmount},
		"paused, and under":        {statusOpen, true, 10, 0, ErrPaused},
	} {
		c.state.status, paused = k.status, k.paused
		if !panicsWith(func() { checkGift(c, k.total, k.tip) }, k.err) {
			t.Errorf("%s: not %s", name, k.err)
		}
	}
}

func TestCheckRoom(t *testing.T) {
	defer func(cap int64) { escrowCap = cap }(escrowCap)
	escrowCap = 1000
	c := testCampaign(9304, modeEscrow, 0)
	c.state.raised, c.state.withdrawn = 900, 300 // tracked: 600
	checkRoom(c, 400)
	if !panicsWith(func() { checkRoom(c, 401) }, ErrCapReached) {
		t.Errorf("a gift past the cap: not ErrCapReached")
	}
	// The cap reads the tracked balance, never the bank's: coins sent straight to
	// the escrow don't block a gift.
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 5000)))
	checkRoom(c, 400)
	// No cap, and direct mode, take any gift the books can hold.
	escrowCap = 0
	checkRoom(c, 1_000_000)
	escrowCap = 1000
	d := testCampaign(9305, modeDirect, 0)
	checkRoom(d, 1_000_000)
	d.state.raised = math.MaxInt64 - 5
	checkRoom(d, 5)
	if !panicsWith(func() { checkRoom(d, 6) }, ErrBadAmount) {
		t.Errorf("Raised past int64: not ErrBadAmount")
	}
}

// TestDonate gives as a user, straight from the test's body as AssertOriginCall
// requires (plan §3.3), with the envelope and the realm's coins a real transaction
// would bring. Its refusals are in txtar (give.txtar) and filetests.
func TestDonate(cur realm, t *testing.T) {
	donor := testutils.TestAddress("donor")
	rb := banker.NewReadonlyBanker()
	c := testCampaign(9301, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	// A tip recipient other than the admin, which it starts as: a tip must go to
	// whoever SetTipRecipient named, never to the launch admin.
	launch := tipRecipient
	tipRecipient = testutils.TestAddress("tips")
	defer func() { tipRecipient = launch }()
	escrowBefore, tipsBefore, realmBefore := rb.GetCoin(escrowAddr(c.id), "ugnot"), rb.GetCoin(tipRecipient, "ugnot"), rb.GetCoin(realmAddr(), "ugnot")

	// A public gift with a tip: the gift to the escrow, the tip to the tip
	// recipient, nothing kept by the realm (INV-3).
	testing.SetRealm(testing.NewUserRealm(donor))
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 2_500_000)))
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 2_500_000)))
	if rid := Donate(cross(cur), id, 500_000, "  Courage! ", false); rid != "9301/1" {
		t.Fatalf("Donate returned %q, want 9301/1", rid)
	}
	checkBooks(t, c)
	if got := rb.GetCoin(escrowAddr(c.id), "ugnot") - escrowBefore; got != 2_000_000 {
		t.Errorf("the escrow got %d, want 2000000", got)
	}
	if got := rb.GetCoin(tipRecipient, "ugnot") - tipsBefore; got != 500_000 {
		t.Errorf("the tip recipient got %d, want 500000", got)
	}
	if got := rb.GetCoin(realmAddr(), "ugnot"); got != realmBefore {
		t.Errorf("the realm holds %d, it held %d", got, realmBefore)
	}
	s := c.state
	if s.raised != 2_000_000 || s.donationCount != 1 || s.donorCount != 1 || s.lastDonationAt != now() {
		t.Errorf("after one gift: raised %d, %d gifts, %d donors, last %d", s.raised, s.donationCount, s.donorCount, s.lastDonationAt)
	}
	k := c.contributions.Get(donor.String()).(*contribution)
	if k.amount != 2_000_000 || !k.public || !byDonor.Has(donor.String()+"/"+c.id.Binary()) {
		t.Errorf("contribution %v; by-donor entry %t", *k, byDonor.Has(donor.String()+"/"+c.id.Binary()))
	}
	defer byDonor.Remove(donor.String() + "/" + c.id.Binary())
	r := c.receipts.Get(seqid.ID(1).Binary()).(*receipt)
	want := receipt{seq: 1, donor: donor, amount: 2_000_000, tip: 500_000, message: "Courage!", at: now(), raisedAfter: 2_000_000}
	if *r != want {
		t.Errorf("receipt = %v, want %v", *r, want)
	}

	// The same donor again, anonymously and with no tip: one donor still, the
	// contribution summed, nothing sent to the tip recipient (Q2).
	tipsBefore = rb.GetCoin(tipRecipient, "ugnot")
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 1_000_000)))
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 1_000_000)))
	Donate(cross(cur), id, 0, "", true)
	checkBooks(t, c)
	if s.donorCount != 1 || s.donationCount != 2 || k.amount != 3_000_000 || !k.public {
		t.Errorf("a second gift: %d donors, %d gifts, contribution %v", s.donorCount, s.donationCount, *k)
	}
	if got := rb.GetCoin(tipRecipient, "ugnot"); got != tipsBefore {
		t.Errorf("a gift with no tip sent %d to the tip recipient", got-tipsBefore)
	}
	if v := campaignView(c); v.Balance != 3_000_000 || v.Raised != 3_000_000 {
		t.Errorf("balance %d, raised %d, want 3000000 each (INV-2)", v.Balance, v.Raised)
	}

	// An anonymous first gift adds no by-donor entry.
	shy := testutils.TestAddress("shy")
	testing.SetRealm(testing.NewUserRealm(shy))
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 1_000_000)))
	Donate(cross(cur), id, 0, "", true)
	checkBooks(t, c)
	if s.donorCount != 2 || byDonor.Has(shy.String()+"/"+c.id.Binary()) || c.contributions.Get(shy.String()).(*contribution).public {
		t.Errorf("an anonymous donor: %d donors, by-donor entry %t", s.donorCount, byDonor.Has(shy.String()+"/"+c.id.Binary()))
	}

	// The same donor, publicly this time: in the by-donor index now, and still
	// counted once.
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 1_000_000)))
	Donate(cross(cur), id, 0, "", false)
	checkBooks(t, c)
	defer byDonor.Remove(shy.String() + "/" + c.id.Binary())
	if s.donorCount != 2 || !byDonor.Has(shy.String()+"/"+c.id.Binary()) || !c.contributions.Get(shy.String()).(*contribution).public {
		t.Errorf("anonymous, then public: %d donors, by-donor entry %t", s.donorCount, byDonor.Has(shy.String()+"/"+c.id.Binary()))
	}
}

// TestDonateDirect: a direct gift goes to the beneficiary, and the campaign's
// balance stays 0 (INV-2). A delisted campaign takes gifts, and so does one in a
// sunset version.
func TestDonateDirect(cur realm, t *testing.T) {
	defer func(s bool) { sunset = s }(sunset)
	rb := banker.NewReadonlyBanker()
	c := testCampaign(9302, modeDirect, 0)
	c.state.listed = false
	id, unstore := storeCampaign(c)
	defer unstore()
	sunset = true
	before := rb.GetCoin(c.beneficiary, "ugnot")
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("donor")))
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 1_500_000)))
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 1_500_000)))
	Donate(cross(cur), id, 0, "", true)
	checkBooks(t, c)
	if got := rb.GetCoin(c.beneficiary, "ugnot") - before; got != 1_500_000 {
		t.Errorf("the beneficiary got %d, want 1500000", got)
	}
	if v := campaignView(c); v.Balance != 0 || v.Raised != 1_500_000 || v.NetRaised != 1_500_000 {
		t.Errorf("direct: balance %d, raised %d", v.Balance, v.Raised)
	}
}

func TestReceipts(cur realm, t *testing.T) {
	c := testCampaign(9306, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	donors := []address{testutils.TestAddress("ada"), testutils.TestAddress("bo")}
	for i := 0; i < 25; i++ {
		testing.SetRealm(testing.NewUserRealm(donors[i%2]))
		testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", int64(1_000_000+i))))
		testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", int64(1_000_000+i))))
		Donate(cross(cur), id, 0, "gift", i%2 == 1)
	}
	defer byDonor.Remove(donors[0].String() + "/" + c.id.Binary())

	// The ring holds the last 20, newest first.
	recent := ListRecent(id)
	if len(recent) != recentSize || recent[0].Seq != 25 || recent[recentSize-1].Seq != 6 {
		t.Fatalf("ListRecent: %d receipts, %d first, %d last", len(recent), recent[0].Seq, recent[len(recent)-1].Seq)
	}
	for i, r := range recent {
		if want := GetReceipt(id, r.Seq); r != want || r.Seq != int64(25-i) {
			t.Errorf("recent[%d] = %v, GetReceipt says %v", i, r, want)
		}
	}

	// Anonymous gifts hide their donor; a hidden message is blanked; a refund shows.
	public, anon := GetReceipt(id, 1), GetReceipt(id, 2)
	if public.Donor != donors[0] || anon.Donor != "" || !anon.Anonymous || public.ID != id+"/1" || public.CampaignID != id {
		t.Errorf("public %v, anonymous %v", public, anon)
	}
	c.receipts.Get(seqid.ID(1).Binary()).(*receipt).messageHidden = true
	c.contributions.Get(donors[0].String()).(*contribution).refunded = 7
	if r := GetReceipt(id, 1); r.Message != "" || !r.MessageHidden || r.DonorRefunded != 7 || r.Amount != 1_000_000 {
		t.Errorf("hidden and refunded: %v", r)
	}
	for _, seq := range []int64{0, -1, 26, math.MaxInt64} {
		if !panicsWith(func() { GetReceipt(id, seq) }, ErrNotFound) {
			t.Errorf("GetReceipt(%d): not ErrNotFound", seq)
		}
	}
	if !panicsWith(func() { ListRecent("042") }, ErrNotFound) {
		t.Errorf("ListRecent(\"042\"): not ErrNotFound")
	}
	empty, unstoreEmpty := storeCampaign(testCampaign(9307, modeEscrow, 0))
	defer unstoreEmpty()
	if got := ListRecent(empty); len(got) != 0 {
		t.Errorf("a campaign without gifts lists %d", len(got))
	}
}

// TestSweepStrays: what sits at the realm goes to the tip recipient; then there is
// nothing to sweep, and nothing is sent (Q3).
func TestSweepStrays(cur realm, t *testing.T) {
	rb := banker.NewReadonlyBanker()
	SweepStrays(cross(cur)) // whatever earlier tests left
	launch := tipRecipient
	tipRecipient = testutils.TestAddress("tips")
	defer func() { tipRecipient = launch }()
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 123)))
	before := rb.GetCoin(tipRecipient, "ugnot")
	if got := SweepStrays(cross(cur)); got != 123 {
		t.Errorf("SweepStrays = %d, want 123", got)
	}
	if got := rb.GetCoin(tipRecipient, "ugnot") - before; got != 123 || rb.GetCoin(realmAddr(), "ugnot") != 0 {
		t.Errorf("the tip recipient got %d; the realm holds %d", got, rb.GetCoin(realmAddr(), "ugnot"))
	}
	if got := SweepStrays(cross(cur)); got != 0 {
		t.Errorf("SweepStrays with nothing there = %d", got)
	}
}

envelope.gno

package bolo

import "chain/runtime/unsafe"

// envelopeUgnot returns the ugnot attached to this call (API C3, C4): an envelope is
// one ugnot coin, or nothing; anything else is ErrWrongDenom. It is the one place
// Bolo reads OriginSend, and only user-only writes reach it: C11's keyed refusal, then
// AssertOriginCall, in their own body (make check). Never a write behind C11's realm
// branch, which a deployed realm passes with an envelope paid to itself.
func envelopeUgnot() int64 {
	sent := unsafe.OriginSend()
	if len(sent) == 0 {
		return 0
	}
	if len(sent) > 1 || sent[0].Denom != "ugnot" {
		panic(ErrWrongDenom)
	}
	return sent[0].Amount
}

errors.gno

package bolo

// Error is the type of every failure Bolo reports (API C10, §7). Each one is a
// constant, never a variable another realm could reassign (C6), and its text
// starts with its copy key, which a client turns into a message (UI spec §8).
type Error string

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

const (
	ErrNotFound           Error = "err.not_found: no such campaign or receipt"
	ErrNotUserCall        Error = "err.use_wallet: not a direct transaction from a wallet"
	ErrSessionKey         Error = "err.master_key: a session key can't do this"
	ErrWrongDenom         Error = "err.amount: only ugnot is accepted"
	ErrBadAmount          Error = "err.amount: the amount is wrong"
	ErrDepositMismatch    Error = "err.amount: send exactly the creation deposit"
	ErrPaused             Error = "err.paused: Bolo is paused"
	ErrNotOrganizer       Error = "err.not_allowed: only the organizer can do this"
	ErrNotBeneficiary     Error = "err.not_allowed: only the beneficiary can do this"
	ErrNotAdmin           Error = "err.not_allowed: only the admin can do this"
	ErrCampaignClosed     Error = "err.state: the campaign is closed"
	ErrCampaignSettled    Error = "err.state: the campaign is settled"
	ErrBondSlashed        Error = "err.state: the bond was slashed"
	ErrNoBond             Error = "err.state: there is no bond to slash"
	ErrHoldEnded          Error = "err.state: the bond's hold has ended"
	ErrWrongMode          Error = "err.mode: not for this custody mode"
	ErrNothingToRefund    Error = "err.refund: nothing to refund"
	ErrRefundWindowClosed Error = "err.refund: no refund window is open"
	ErrExitOpen           Error = "err.exit_open: the exit window is open"
	ErrNotClosable        Error = "err.not_yet: the campaign can't be closed yet"
	ErrNotFinalizable     Error = "err.not_yet: the campaign can't be finalized yet"
	ErrNothingToWithdraw  Error = "err.withdraw: nothing to withdraw"
	ErrTitle              Error = "err.text: the title's length is out of bounds"
	ErrDescription        Error = "err.text: the story's length is out of bounds"
	ErrMessage            Error = "err.text: the message's length is out of bounds"
	ErrUpdate             Error = "err.text: the update's length is out of bounds"
	ErrNotice             Error = "err.text: the notice's length is out of bounds"
	ErrImage              Error = "err.text: the photo or its description is invalid"
	ErrMarkup             Error = "err.markup: a story or update holds no image and no raw HTML"
	ErrBeneficiary        Error = "err.input: invalid beneficiary"
	ErrCategory           Error = "err.input: unknown category"
	ErrMode               Error = "err.input: invalid custody mode"
	ErrDeadline           Error = "err.input: invalid deadline"
	ErrGoal               Error = "err.input: invalid goal"
	ErrSetting            Error = "err.input: invalid setting"
	ErrSunset             Error = "err.sunset: this version takes no new campaigns"
	ErrCapReached         Error = "err.cap: the campaign's escrow cap is reached"
	ErrBooksMismatch      Error = "err.internal: the books exceed the bank (INV-1)"
)

errors_test.gno

package bolo

import (
	"strings"
	"testing"
)

// Each error and its copy key, as API §7 pairs them; every key resolves to a
// message in UI spec §8.
var errorKeys = map[Error]string{
	ErrNotFound:           "err.not_found",
	ErrNotUserCall:        "err.use_wallet",
	ErrSessionKey:         "err.master_key",
	ErrWrongDenom:         "err.amount",
	ErrBadAmount:          "err.amount",
	ErrDepositMismatch:    "err.amount",
	ErrPaused:             "err.paused",
	ErrNotOrganizer:       "err.not_allowed",
	ErrNotBeneficiary:     "err.not_allowed",
	ErrNotAdmin:           "err.not_allowed",
	ErrCampaignClosed:     "err.state",
	ErrCampaignSettled:    "err.state",
	ErrBondSlashed:        "err.state",
	ErrNoBond:             "err.state",
	ErrHoldEnded:          "err.state",
	ErrWrongMode:          "err.mode",
	ErrNothingToRefund:    "err.refund",
	ErrRefundWindowClosed: "err.refund",
	ErrExitOpen:           "err.exit_open",
	ErrNotClosable:        "err.not_yet",
	ErrNotFinalizable:     "err.not_yet",
	ErrNothingToWithdraw:  "err.withdraw",
	ErrTitle:              "err.text",
	ErrDescription:        "err.text",
	ErrMessage:            "err.text",
	ErrUpdate:             "err.text",
	ErrNotice:             "err.text",
	ErrImage:              "err.text",
	ErrMarkup:             "err.markup",
	ErrBeneficiary:        "err.input",
	ErrCategory:           "err.input",
	ErrMode:               "err.input",
	ErrDeadline:           "err.input",
	ErrGoal:               "err.input",
	ErrSetting:            "err.input",
	ErrSunset:             "err.sunset",
	ErrCapReached:         "err.cap",
	ErrBooksMismatch:      "err.internal",
}

// TestErrorsLeadWithCopyKeys: every error of API §7 starts with its own copy key,
// then ": " and a message (API C10). The static check refuses an Error without a
// key; this pins which key each one has.
func TestErrorsLeadWithCopyKeys(t *testing.T) {
	if len(errorKeys) != 38 {
		t.Errorf("%d errors, API §7 has 38", len(errorKeys))
	}
	for e, want := range errorKeys {
		key, msg, ok := strings.Cut(string(e), ": ")
		if !ok || key != want || msg == "" {
			t.Errorf("%q doesn't start with %s", string(e), want)
		}
	}
}

events.gno

package bolo

import "strconv"

// The events Bolo emits (API §6), for the web app's indexer. Their attributes are
// strings.
const (
	evCampaignCreated     = "CampaignCreated"
	evBondPosted          = "BondPosted"
	evBondReleased        = "BondReleased"
	evDonated             = "Donated"
	evWithdrawn           = "Withdrawn"
	evRefunded            = "Refunded"
	evUpdatePosted        = "UpdatePosted"
	evClosed              = "Closed"
	evSettled             = "Settled"
	evDelisted            = "Delisted"
	evRelisted            = "Relisted"
	evNoticeSet           = "NoticeSet"
	evStraysSwept         = "StraysSwept"
	evImageHidden         = "ImageHidden"
	evMessageHidden       = "MessageHidden"
	evParamsChanged       = "ParamsChanged"
	evAdminProposed       = "AdminProposed"
	evAdminChanged        = "AdminChanged"
	evPaused              = "Paused"
	evUnpaused            = "Unpaused"
	evTipRecipientChanged = "TipRecipientChanged"
	evMinDonationChanged  = "MinDonationChanged"
	evPresetsChanged      = "PresetsChanged"
	evEscrowCapChanged    = "EscrowCapChanged"
	evCategoryAdded       = "CategoryAdded"
	evSunset              = "Sunset"
)

// itoa formats an amount, a timestamp or a sequence number as an attribute.
func itoa(n int64) string { return strconv.FormatInt(n, 10) }

finalize.gno

package bolo

import (
	"chain"
	"chain/banker"
)

// Finalize completes closed campaign id: anyone can, once the campaign's page offers
// it. It returns the organizer's deposit, and sends the beneficiary the coins someone
// sent to the escrow outside Bolo. What donors can still reclaim stays theirs.
//
// It settles a closed campaign, and forwards what no donor is owed (API §3.4): anyone
// may call, with no identity. At its first call it settles the campaign;
// every call forwards the coins sent to the escrow outside Bolo to the beneficiary,
// and everything at the bond address but a bond still on hold to the organizer — the
// deposit, and the bond once its hold has ended. It never moves the tracked balance:
// that stays the donors' (INV-16).
func Finalize(cur realm, id string) {
	assertCurrent(cur)
	c := campaignOf(id)
	recordDeadline(cur, c)
	f := bookFinalize(c)
	if f.toBeneficiary > 0 {
		banker.NewBanker(banker.BankerTypeRealmSend, escrowSub(cur, c)).SendCoins(escrowAddr(c.id), c.beneficiary, chain.NewCoins(chain.NewCoin("ugnot", f.toBeneficiary)))
	}
	if f.toOrganizer > 0 {
		banker.NewBanker(banker.BankerTypeRealmSend, bondSub(cur, c)).SendCoins(bondAddr(c.id), c.organizer, chain.NewCoins(chain.NewCoin("ugnot", f.toOrganizer)))
	}
	if f.settled {
		chain.Emit(evSettled, "id", idString(c.id), "toOrganizer", itoa(f.toOrganizer), "toBeneficiary", itoa(f.toBeneficiary))
	}
	if f.released > 0 {
		chain.Emit(evBondReleased, "id", idString(c.id), "amount", itoa(f.released), "to", c.organizer.String())
	}
}

// settlement is what one Finalize call moves, and announces.
type settlement struct {
	toBeneficiary int64 // the untracked coins at the escrow
	toOrganizer   int64 // everything at the bond address but a bond still on hold
	released      int64 // the bond this call releases, or 0
	settled       bool  // this call settles the campaign
}

// bookFinalize checks a Finalize call on c and enters it in the books, before any coin
// moves (API §3.4): the first settles c, if checkFinalizable allows; every one works
// out what to forward, and releases a bond whose hold has ended.
func bookFinalize(c *campaign) settlement {
	s := c.state
	settled := false
	if s.status != statusSettled {
		checkFinalizable(c)
		s.status = statusSettled
		stats.settled++
		settled = true
	}
	f := pending(c)
	f.settled = settled
	if f.released > 0 {
		s.bondReleased = true
	}
	return f
}

// checkFinalizable refuses c's first settlement (API §3.4), with ErrNotFinalizable,
// unless it is closed and its FinalizableAt has come: at once in direct mode or with
// no tracked balance, else once its exit window opens. The view, CanFinalize and this
// share one rule, finalizableAt.
func checkFinalizable(c *campaign) {
	s := c.state
	if s.status != statusClosed {
		panic(ErrNotFinalizable)
	}
	if now() < finalizableAt(c, s.closedAt, trackedBalance(c)) {
		panic(ErrNotFinalizable)
	}
}

// pending works out what a Finalize call would move from c now, without writing: the
// escrow's coins above its books, to the beneficiary; the bond address's coins but a
// bond still on hold — not slashed, not released, its hold not ended — to the
// organizer, the bond itself included once its hold has ended. Books above the bank,
// at either address, are ErrBooksMismatch (INV-1, INV-7).
func pending(c *campaign) settlement {
	s := c.state
	var f settlement
	f.toBeneficiary = banker.NewReadonlyBanker().GetCoin(escrowAddr(c.id), "ugnot") - trackedBalance(c)
	held := int64(0)
	if s.bond > 0 && !s.bondSlashed && !s.bondReleased {
		if now() >= s.closedAt+c.params.BondHold {
			f.released = s.bond
		} else {
			held = s.bond
		}
	}
	f.toOrganizer = banker.NewReadonlyBanker().GetCoin(bondAddr(c.id), "ugnot") - held
	if f.toBeneficiary < 0 || f.toOrganizer < 0 {
		panic(ErrBooksMismatch)
	}
	return f
}

// CanFinalize says what Finalize(id) would do now (API §4), a passed deadline counted
// as recorded: true with "settle" for the first settlement, or "forward" on a settled
// campaign with something to move; false with "open", "not_yet" while a tracked balance
// waits for its exit window, or "settled" with nothing to move.
func CanFinalize(id string) (bool, string) {
	c := campaignOf(id)
	status, _, closedAt := effective(c)
	switch status {
	case statusOpen:
		return false, statusOpen
	case statusClosed:
		if now() < finalizableAt(c, closedAt, trackedBalance(c)) {
			return false, "not_yet"
		}
		return true, "settle"
	}
	if f := pending(c); f.toBeneficiary > 0 || f.toOrganizer > 0 {
		return true, "forward"
	}
	return false, statusSettled
}

gnomod.toml

module = "gno.land/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo/v0"
gno = "0.9"

[addpkg]
  creator = "g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv"
  height = 359079
  max_deposit = "30000000ugnot"

guards.gno

package bolo

import (
	"math"
	"time"
)

// assertCurrent is the first statement of every crossing function (API C2).
func assertCurrent(cur realm) {
	if !cur.IsCurrent() {
		panic("bolo: not the current realm")
	}
}

// checkAddress refuses an address argument that isn't a well-formed address (API
// C12): exactly 40 characters, a lowercase "g" first, then IsValid(). MsgCall
// passes an address argument through unchecked, and a malformed one stored once
// would make every later send to it fail. IsValid alone also accepts an address in
// capitals, which the bank pays as the same account but which never equals the
// lowercase spelling; it refuses mixed case, so a lowercase "g" means a lowercase
// address. The length comes first, so IsValid only ever parses address-sized
// input.
func checkAddress(a address, err Error) {
	if len(a) != 40 || a[0] != 'g' || !a.IsValid() {
		panic(err)
	}
}

const secondsPerDay = 24 * 60 * 60

// daysToSeconds converts a duration in whole days to seconds, refusing a negative
// one and one whose seconds would overflow (API §2.3).
func daysToSeconds(days int, err Error) int64 {
	if days < 0 || int64(days) > math.MaxInt64/secondsPerDay {
		panic(err)
	}
	return int64(days) * secondsPerDay
}

// now is block time in Unix seconds (API C8).
func now() int64 { return time.Now().Unix() }

guards_test.gno

package bolo

import (
	"math"
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
)

func TestCheckAddress(t *testing.T) {
	good := testutils.TestAddress("beneficiary")
	checkAddress(good, ErrBeneficiary)

	bad := string(good)
	last := "q"
	if bad[39] == 'q' {
		last = "p"
	}
	for name, a := range map[string]address{
		"empty":        "",
		"39 chars":     address(bad[:39]),
		"41 chars":     address(bad + "q"),
		"bad checksum": address(bad[:39] + last),
		"not bech32":   address("0x00000000000000000000000000000000000000"),
		// IsValid takes an address in capitals, as the same account; it must not
		// pass as a second address (API C12). Mixed case is refused by IsValid.
		"capitals":   address(strings.ToUpper(bad)),
		"mixed case": address(bad[:20] + strings.ToUpper(bad[20:])),
	} {
		if !panicsWith(func() { checkAddress(a, ErrBeneficiary) }, ErrBeneficiary) {
			t.Errorf("%s: not refused", name)
		}
	}
}

func TestDaysToSeconds(t *testing.T) {
	if got := daysToSeconds(0, ErrSetting); got != 0 {
		t.Errorf("0 days = %d", got)
	}
	if got := daysToSeconds(3650, ErrSetting); got != 315360000 {
		t.Errorf("3650 days = %d", got)
	}
	for _, days := range []int{-1, math.MaxInt64/secondsPerDay + 1, math.MaxInt64} {
		if !panicsWith(func() { daysToSeconds(days, ErrSetting) }, ErrSetting) {
			t.Errorf("%d days: not refused", days)
		}
	}
}

func TestNow(t *testing.T) {
	start := now()
	testing.SkipHeights(12)
	if got := now() - start; got != 60 {
		t.Errorf("12 heights moved now() by %d seconds, want 60", got)
	}
}

helpers_test.gno

package bolo

// panicsWith reports whether f panics with err.
func panicsWith(f func(), err Error) (ok bool) {
	defer func() {
		r := recover()
		e, isErr := r.(Error)
		ok = isErr && e == err
	}()
	f()
	return false
}

ids.gno

package bolo

import (
	"strconv"

	"gno.land/p/nt/seqid/v0"
)

// parseID returns the campaign ID s names, if s is canonical (API C9): the
// decimal form of a positive ID — digits only, no sign, no leading zero, no
// space. "042" names nothing, never campaign 42: one ID has one spelling, and so
// one set of addresses (INV-18).
func parseID(s string) (seqid.ID, bool) {
	if len(s) == 0 || len(s) > 20 || s[0] == '0' {
		return 0, false
	}
	for i := 0; i < len(s); i++ {
		if s[i] < '0' || s[i] > '9' {
			return 0, false
		}
	}
	n, err := strconv.ParseUint(s, 10, 64)
	if err != nil {
		return 0, false
	}
	return seqid.ID(n), true
}

// idString is the canonical decimal form of id.
func idString(id seqid.ID) string {
	return strconv.FormatUint(uint64(id), 10)
}

ids_test.gno

package bolo

import "testing"

func TestParseID(t *testing.T) {
	for _, s := range []string{"1", "7", "42", "18446744073709551615"} {
		id, ok := parseID(s)
		if !ok || idString(id) != s {
			t.Errorf("parseID(%q) = %d, %t; want %s", s, uint64(id), ok, s)
		}
	}
	// One ID, one spelling (API C9, INV-18): anything else names no campaign.
	for _, s := range []string{
		"", "0", "00", "042", "+42", "-1", " 42", "42 ", "4 2", "4.2", "0x2a", "1e3",
		"18446744073709551616", "99999999999999999999", "123456789012345678901",
		"42", "٤٢",
	} {
		if id, ok := parseID(s); ok {
			t.Errorf("parseID(%q) = %d; want no campaign", s, uint64(id))
		}
	}
}

init.gno

package bolo

// init refuses to deploy Bolo from its admin's own key (API §3.6, ADR D11). The
// key that deploys under the namespace must not also be the admin: one stolen key
// could otherwise deploy a malicious version and point the registry at it. Then it
// lists the launch categories for lookups (API §2.1).
func init(cur realm) {
	if cur.Previous().Address() == adminAddr {
		panic("bolo: the admin key may not deploy Bolo; deploy from the namespace key, which must not be the admin")
	}
	for _, code := range categoryOrder {
		categories.Set(code, true)
	}
}

lists.gno

package bolo

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

// Lists (API §4). A size is clamped to 1–50 (INV-9). The campaign lists page by
// cursor: each reaches its place in its index by key, in O(log n), never by counting
// entries. The per-campaign lists page by number, by offset in the campaign's own tree.

const maxPageSize = 50

// idKeyLen is the length of a campaign's key, seqid.ID.Binary().
const idKeyLen = 8

// pageSize clamps a requested size to 1–50.
func pageSize(size int) int {
	if size < 1 {
		return 1
	}
	if size > maxPageSize {
		return maxPageSize
	}
	return size
}

// ListCampaigns returns the open, listed campaigns, newest first, from below after (""
// for the newest), and the cursor to pass next, "" at the end; category may be "".
// A campaign past a deadline nobody recorded is left out (Q6). One call reads at most
// four times size entries, so a page can be short while the cursor isn't "".
func ListCampaigns(after string, size int, category string) ([]CampaignView, string) {
	size = pageSize(size)
	index, prefix := &active, ""
	if category != "" {
		index, prefix = &activeByCategory, category+"/"
	}
	return campaignPage(index, prefix, after, size, 4*size, func(c *campaign) bool {
		status, _, _ := effective(c)
		return status == statusOpen
	})
}

// ListByOrganizer returns the campaigns addr organizes, delisted included, newest
// first, from below after, and the cursor to pass next. An address is compared as
// given (C12).
func ListByOrganizer(addr address, after string, size int) ([]CampaignView, string) {
	size = pageSize(size)
	return campaignPage(&byOrganizer, addr.String()+"/", after, size, size, everyCampaign)
}

// ListByBeneficiary returns the campaigns naming addr as beneficiary, delisted included
// — the beneficiary must keep seeing them (INV-4) — newest first, from below after,
// and the cursor to pass next.
func ListByBeneficiary(addr address, after string, size int) ([]CampaignView, string) {
	size = pageSize(size)
	return campaignPage(&byBeneficiary, addr.String()+"/", after, size, size, everyCampaign)
}

// ListByDonor returns the campaigns addr gave to at least once without anonymity,
// newest first, from below after, and the cursor to pass next: a campaign where all of
// addr's gifts were anonymous is in no index under addr.
func ListByDonor(addr address, after string, size int) ([]CampaignView, string) {
	size = pageSize(size)
	return campaignPage(&byDonor, addr.String()+"/", after, size, size, everyCampaign)
}

func everyCampaign(*campaign) bool { return true }

// campaignPage reads index newest first: the keys under prefix — a category's or an
// address's range, which ends at the "/" after it, or the whole index for "" — below
// after's key. It reads at most budget entries, keeps size views of those keep
// accepts, and returns them with the ID of the last entry read when more remain, ""
// when the range is done. A non-canonical after is ErrNotFound (C9).
func campaignPage(index *avl.Tree, prefix, after string, size, budget int, keep func(*campaign) bool) ([]CampaignView, string) {
	start, end := prefix, ""
	if prefix != "" {
		end = prefix[:len(prefix)-1] + "0" // "0" sorts right after "/"
	}
	cursor := ""
	if after != "" {
		id, ok := parseID(after)
		if !ok {
			panic(ErrNotFound)
		}
		cursor = prefix + id.Binary()
		end = cursor
	}
	views := []CampaignView{}
	last, read, more := "", 0, false
	// A reverse traversal includes its end: the cursor's own entry, read last time, is
	// skipped. A key whose ID part isn't a campaign key's eight bytes stops the reading:
	// only a prefix holding "/" — an address or a category crafted to end in a key's
	// first bytes — meets one, and every key in its range is such a key, so walking on
	// would read them all, past the budget, to find nothing.
	index.ReverseIterate(start, end, func(key string, _ any) bool {
		if key == cursor {
			return false
		}
		if len(key) != len(prefix)+idKeyLen {
			return true
		}
		if len(views) == size || read == budget {
			more = true
			return true
		}
		read++
		c := campaigns.Get(key[len(prefix):]).(*campaign)
		last = idString(c.id)
		if keep(c) {
			views = append(views, campaignView(c))
		}
		return false
	})
	if !more {
		return views, ""
	}
	return views, last
}

// pageOffset returns where page starts, newest first, in a tree of n entries paged by
// size, and false past the end. A page counts from 1; below 1 reads as 1.
func pageOffset(page, size, n int) (int, bool) {
	if page < 1 {
		page = 1
	}
	if page-1 > n/size {
		return 0, false
	}
	return (page - 1) * size, true
}

// ListReceipts returns a page of the campaign's gifts, newest first.
func ListReceipts(id string, page, size int) []ReceiptView {
	c := campaignOf(id)
	size = pageSize(size)
	views := []ReceiptView{}
	if offset, ok := pageOffset(page, size, c.receipts.Size()); ok {
		c.receipts.ReverseIterateByOffset(offset, size, func(_ string, v any) bool {
			views = append(views, receiptView(c, v.(*receipt)))
			return false
		})
	}
	return views
}

// WithdrawalView is one payout to the beneficiary (API §2.4): its tracked amount and
// the coins sent outside Bolo it carried, apart.
type WithdrawalView struct {
	Seq, Amount, Untracked, At int64
	To                         address
}

// ListWithdrawals returns a page of the campaign's withdrawals, newest first.
func ListWithdrawals(id string, page, size int) []WithdrawalView {
	c := campaignOf(id)
	size = pageSize(size)
	views := []WithdrawalView{}
	if offset, ok := pageOffset(page, size, c.withdrawals.Size()); ok {
		c.withdrawals.ReverseIterateByOffset(offset, size, func(_ string, v any) bool {
			w := v.(*withdrawal)
			views = append(views, WithdrawalView{Seq: int64(w.seq), Amount: w.amount, Untracked: w.untracked, At: w.at, To: w.to})
			return false
		})
	}
	return views
}

// RefundView is one payout to a donor (API §2.4). Donor is empty when all of that
// donor's gifts to the campaign were anonymous; Kind is "open" or "exit".
type RefundView struct {
	Seq, Amount, At int64
	Donor           address
	Kind            string
}

// ListRefunds returns a page of the campaign's refunds, newest first.
func ListRefunds(id string, page, size int) []RefundView {
	c := campaignOf(id)
	size = pageSize(size)
	views := []RefundView{}
	if offset, ok := pageOffset(page, size, c.refunds.Size()); ok {
		c.refunds.ReverseIterateByOffset(offset, size, func(_ string, v any) bool {
			r := v.(*refund)
			view := RefundView{Seq: int64(r.seq), Amount: r.amount, At: r.at, Kind: r.kind}
			if k := contributionOf(c, r.donor); k != nil && k.public {
				view.Donor = r.donor
			}
			views = append(views, view)
			return false
		})
	}
	return views
}

// UpdateView is one organizer update (API §2.4).
type UpdateView struct {
	Seq, At int64
	Body    string
}

// ListUpdates returns a page of the campaign's updates, newest first.
func ListUpdates(id string, page, size int) []UpdateView {
	c := campaignOf(id)
	size = pageSize(size)
	views := []UpdateView{}
	if offset, ok := pageOffset(page, size, c.updates.Size()); ok {
		c.updates.ReverseIterateByOffset(offset, size, func(_ string, v any) bool {
			u := v.(*update)
			views = append(views, UpdateView{Seq: int64(u.seq), At: u.at, Body: u.body})
			return false
		})
	}
	return views
}

lists_test.gno

package bolo

import (
	"math"
	"strings"
	"testing"

	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/testutils/v0"
)

func TestPageSize(t *testing.T) {
	for size, want := range map[int]int{math.MinInt: 1, -5: 1, 0: 1, 1: 1, 20: 20, 50: 50, 51: 50, math.MaxInt: 50} {
		if got := pageSize(size); got != want {
			t.Errorf("pageSize(%d) = %d, want %d", size, got, want)
		}
	}
}

func TestPageOffset(t *testing.T) {
	for _, k := range []struct {
		page, size, n, want int
		ok                  bool
	}{
		{1, 10, 25, 0, true},
		{3, 10, 25, 20, true},
		{0, 10, 25, 0, true}, // below 1 reads as 1
		{-7, 10, 25, 0, true},
		{4, 10, 25, 0, false}, // past the end
		{math.MaxInt, 50, 25, 0, false},
		{1, 10, 0, 0, true}, // an empty tree has an empty first page
	} {
		got, ok := pageOffset(k.page, k.size, k.n)
		if got != k.want || ok != k.ok {
			t.Errorf("pageOffset(%d, %d, %d) = %d, %t; want %d, %t", k.page, k.size, k.n, got, ok, k.want, k.ok)
		}
	}
}

// indexCampaigns stores n campaigns, IDs first to first+n-1, as CreateCampaign leaves
// them — in campaigns and every campaign index — organized by org for ben, in the
// category "animals", and returns them with what removes them again.
func indexCampaigns(first seqid.ID, n int, org, ben address) ([]*campaign, func()) {
	var cs []*campaign
	for i := 0; i < n; i++ {
		c := testCampaign(first+seqid.ID(i), modeEscrow, 0)
		c.category, c.organizer, c.beneficiary = "animals", org, ben
		key := c.id.Binary()
		campaigns.Set(key, c)
		addActive(c)
		byOrganizer.Set(org.String()+"/"+key, true)
		byBeneficiary.Set(ben.String()+"/"+key, true)
		cs = append(cs, c)
	}
	return cs, func() {
		for _, c := range cs {
			key := c.id.Binary()
			campaigns.Remove(key)
			dropActive(c)
			byOrganizer.Remove(c.organizer.String() + "/" + key)
			byBeneficiary.Remove(c.beneficiary.String() + "/" + key)
		}
	}
}

// pageAll follows a list's cursor to its end, at most 100 calls, and returns every
// ID seen, in order, with the number of calls.
func pageAll(list func(after string) ([]CampaignView, string)) ([]string, int) {
	var ids []string
	after, calls := "", 0
	for calls < 100 {
		views, next := list(after)
		calls++
		for _, v := range views {
			ids = append(ids, v.ID)
		}
		if next == "" {
			break
		}
		after = next
	}
	return ids, calls
}

// TestListCursor: a list paged to its end by cursor returns every campaign once,
// newest first; next is "" exactly at the end (API §4).
func TestListCursor(t *testing.T) {
	org, ben := testutils.TestAddress("listorg"), testutils.TestAddress("listben")
	_, unindex := indexCampaigns(9901, 7, org, ben)
	defer unindex()
	want := "9907 9906 9905 9904 9903 9902 9901"
	for name, list := range map[string]func(string) ([]CampaignView, string){
		"ListCampaigns":     func(a string) ([]CampaignView, string) { return ListCampaigns(a, 3, "animals") },
		"ListByOrganizer":   func(a string) ([]CampaignView, string) { return ListByOrganizer(org, a, 3) },
		"ListByBeneficiary": func(a string) ([]CampaignView, string) { return ListByBeneficiary(ben, a, 3) },
	} {
		ids, calls := pageAll(list)
		if got := strings.Join(ids, " "); got != want || calls != 3 {
			t.Errorf("%s: %q in %d calls, want %q in 3", name, got, calls, want)
		}
	}
	// A full last page knows it is last: the list peeks one entry further.
	if views, next := ListByOrganizer(org, "9904", 3); len(views) != 3 || next != "" {
		t.Errorf("the last full page: %d views, next %q", len(views), next)
	}
	if views, next := ListByOrganizer(org, "", 3); len(views) != 3 || next != "9905" {
		t.Errorf("the first page: %d views, next %q", len(views), next)
	}
	for _, after := range []string{"042", "+42", " 42", "x", "9901/1"} {
		if !panicsWith(func() { ListByOrganizer(org, after, 3) }, ErrNotFound) {
			t.Errorf("after %q: not ErrNotFound", after)
		}
	}
}

// TestListCampaignsPassed (Q6): a campaign past a deadline nobody recorded is left
// out; one call reads at most four times size entries, so a page can come back short
// or empty while next isn't "", and no campaign repeats or goes missing.
func TestListCampaignsPassed(t *testing.T) {
	org, ben := testutils.TestAddress("listorg"), testutils.TestAddress("listben")
	cs, unindex := indexCampaigns(9911, 9, org, ben)
	defer unindex()
	for _, c := range cs[2:7] { // 9913–9917 are past their deadline, unrecorded
		c.deadline = now() - 1
	}
	if views, next := ListCampaigns("9918", 1, "animals"); len(views) != 0 || next != "9914" {
		t.Errorf("after 9918, size 1: %d views, next %q; want none, read up to 9914", len(views), next)
	}
	ids, _ := pageAll(func(a string) ([]CampaignView, string) { return ListCampaigns(a, 1, "animals") })
	if got := strings.Join(ids, " "); got != "9919 9918 9912 9911" {
		t.Errorf("paged to the end: %q", got)
	}
	// The other lists keep every campaign, closed and past a deadline included.
	ids, _ = pageAll(func(a string) ([]CampaignView, string) { return ListByOrganizer(org, a, 50) })
	if len(ids) != 9 {
		t.Errorf("ListByOrganizer: %d campaigns, want 9", len(ids))
	}
}

// TestListRanges: an address's range stops at the "/" after it, so an address that is
// the start of a real one finds nothing (C12); a delisted campaign stays on its
// organizer's and beneficiary's lists, off ListCampaigns; ListByDonor holds only the
// campaigns an address gave to without anonymity.
func TestListRanges(t *testing.T) {
	org, ben := testutils.TestAddress("listorg"), testutils.TestAddress("listben")
	cs, unindex := indexCampaigns(9921, 3, org, ben)
	defer unindex()
	if views, next := ListByOrganizer(address(org.String()[:20]), "", 50); len(views) != 0 || next != "" {
		t.Errorf("a prefix of the organizer's address: %d views", len(views))
	}
	if views, _ := ListByOrganizer(ben, "", 50); len(views) != 0 {
		t.Errorf("the beneficiary as organizer: %d views", len(views))
	}

	delisted := cs[1]
	delisted.state.listed = false
	dropActive(delisted)
	defer addActive(delisted) // unindex drops it again
	if views, _ := ListCampaigns("", 50, "animals"); len(views) != 2 {
		t.Errorf("ListCampaigns with one delisted: %d views", len(views))
	}
	for name, views := range map[string][]CampaignView{
		"ListByOrganizer":   first(ListByOrganizer(org, "", 50)),
		"ListByBeneficiary": first(ListByBeneficiary(ben, "", 50)),
	} {
		if len(views) != 3 || views[1].Listed || views[1].ID != "9922" {
			t.Errorf("%s: %d views, the delisted one %v", name, len(views), views[1].Listed)
		}
	}

	public, anonymous := testutils.TestAddress("listpublic"), testutils.TestAddress("listanon")
	key := public.String() + "/" + cs[0].id.Binary()
	byDonor.Set(key, true)
	defer byDonor.Remove(key)
	if views, _ := ListByDonor(public, "", 50); len(views) != 1 || views[0].ID != "9921" {
		t.Errorf("ListByDonor, a public donor: %d views", len(views))
	}
	if views, _ := ListByDonor(anonymous, "", 50); len(views) != 0 {
		t.Errorf("ListByDonor, a donor whose gifts were all anonymous: %d views", len(views))
	}
}

func first(views []CampaignView, _ string) []CampaignView { return views }

// TestCampaignLists: a campaign's receipts, withdrawals, refunds and updates, newest
// first, by page number; a refund's donor blanked when all their gifts were anonymous.
func TestCampaignLists(t *testing.T) {
	c := testCampaign(9931, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	public, anonymous := testutils.TestAddress("listpublic"), testutils.TestAddress("listanon")
	c.contributions.Set(public.String(), &contribution{amount: 30, public: true})
	c.contributions.Set(anonymous.String(), &contribution{amount: 20})
	for i := 1; i <= 5; i++ {
		seq := seqid.ID(i)
		c.receipts.Set(seq.Binary(), &receipt{seq: uint64(i), donor: public, amount: int64(i)})
		c.withdrawals.Set(seq.Binary(), &withdrawal{seq: uint64(i), amount: int64(10 * i)})
		c.updates.Set(seq.Binary(), &update{seq: uint64(i), body: "update " + itoa(int64(i))})
	}
	c.refunds.Set(seqid.ID(1).Binary(), &refund{seq: 1, amount: 3, donor: public, kind: windowOpen})
	c.refunds.Set(seqid.ID(2).Binary(), &refund{seq: 2, amount: 2, donor: anonymous, kind: windowOpen})

	seqs := func(n []int64) string {
		var out []string
		for _, s := range n {
			out = append(out, itoa(s))
		}
		return strings.Join(out, " ")
	}
	receipts := func(page, size int) string {
		var n []int64
		for _, v := range ListReceipts(id, page, size) {
			n = append(n, v.Seq)
		}
		return seqs(n)
	}
	for _, k := range []struct {
		page, size int
		want       string
	}{
		{1, 2, "5 4"}, {2, 2, "3 2"}, {3, 2, "1"}, {4, 2, ""}, {0, 2, "5 4"}, {-1, 2, "5 4"},
		{1, 0, "5"}, {1, 1000, "5 4 3 2 1"}, {math.MaxInt, 2, ""},
	} {
		if got := receipts(k.page, k.size); got != k.want {
			t.Errorf("ListReceipts(page %d, size %d) = %q, want %q", k.page, k.size, got, k.want)
		}
	}
	if w := ListWithdrawals(id, 1, 2); len(w) != 2 || w[0].Seq != 5 || w[0].Amount != 50 {
		t.Errorf("ListWithdrawals: %v", w)
	}
	if u := ListUpdates(id, 2, 3); len(u) != 2 || u[0].Seq != 2 || u[0].Body != "update 2" {
		t.Errorf("ListUpdates, page 2: %v", u)
	}
	r := ListRefunds(id, 1, 50)
	if len(r) != 2 || r[0].Seq != 2 || r[0].Donor != "" || r[1].Donor != public || r[1].Kind != windowOpen {
		t.Errorf("ListRefunds: %v", r)
	}
}

// TestGetStats reads the counters the writes keep (API §2.4); the writes are counted
// in z_stats_filetest.gno.
func TestGetStats(t *testing.T) {
	saved := stats
	defer func() { stats = saved }()
	stats = statsState{open: 3, settled: 2}
	s := GetStats()
	if s.Campaigns != campaigns.Size() || s.Open != 3 || s.Settled != 2 {
		t.Errorf("GetStats: %v", s)
	}
}

// TestListCrafted: an address or a category holding "/" can't make a list read a key
// that isn't one of its own entries — it finds nothing, and never panics unkeyed.
func TestListCrafted(t *testing.T) {
	org, ben := testutils.TestAddress("listorg"), testutils.TestAddress("listben")
	cs, unindex := indexCampaigns(0x2f00, 1, org, ben) // its key's seventh byte is "/"
	defer unindex()
	bin := cs[0].id.Binary()
	crafted := address(org.String() + "/" + bin[:6])
	if views, next := ListByOrganizer(crafted, "", 50); len(views) != 0 || next != "" {
		t.Errorf("an address ending in a key's first bytes: %d views", len(views))
	}
	if views, _ := ListCampaigns("", 50, "animals/"+bin[:6]); len(views) != 0 {
		t.Errorf("a category ending in a key's first bytes: %d views", len(views))
	}
}

// TestListCraftedAddress: an address or a category ending in "/" and a key's bytes
// names nothing, so its list comes back empty (C12). Campaigns 47 and 48 end their keys
// in "/" and "0", which a reverse traversal's inclusive end would reach.
func TestListCraftedAddress(t *testing.T) {
	org, ben := testutils.TestAddress("listorg"), testutils.TestAddress("listben")
	_, unindex := indexCampaigns(47, 2, org, ben)
	defer unindex()
	tail := "/\x00\x00\x00\x00\x00\x00\x00"
	for name, list := range map[string]func() ([]CampaignView, string){
		"organizer":   func() ([]CampaignView, string) { return ListByOrganizer(address(org.String()+tail), "", 50) },
		"beneficiary": func() ([]CampaignView, string) { return ListByBeneficiary(address(ben.String()+tail), "", 50) },
		"category":    func() ([]CampaignView, string) { return ListCampaigns("", 50, "animals"+tail) },
	} {
		if views, next := list(); len(views) != 0 || next != "" {
			t.Errorf("%s: %d views, next %q", name, len(views), next)
		}
	}
}

// TestListRangeStops: an organizer's list holds its own campaigns only, though another
// organizer's entries sort right after them.
func TestListRangeStops(t *testing.T) {
	org, later := testutils.TestAddress("listorg"), testutils.TestAddress("listpub")
	if org.String() >= later.String() {
		t.Fatalf("fixture: %s must sort before %s", org, later)
	}
	_, unindex := indexCampaigns(9951, 2, org, org)
	defer unindex()
	_, unindex2 := indexCampaigns(9953, 2, later, later)
	defer unindex2()
	if views, next := ListByOrganizer(org, "", 50); len(views) != 2 || next != "" {
		t.Errorf("ListByOrganizer: %d views, next %q; want 2, \"\"", len(views), next)
	}
}

moderation.gno

package bolo

import (
	"chain"
	"chain/banker"
	"chain/runtime"
	"strconv"
)

// Moderation (API §3.5): visibility, and the organizer's own bond — nothing else.
// Every write here starts with C11's realm branch, then assertSigner: the master key,
// then the admin's address, before anything is read. Then the campaign and its passed
// deadline, since a slash's window runs from closedAt. The rules live in plain
// helpers, which unit tests drive directly; the writes keep the caller checks, the
// send and the events. Withdraw, Refund and Finalize never read what is written here
// (INV-4).

// Delist takes the campaign off the active lists, with a public notice, and with slash
// moves its bond to the slashed address, where nothing ever spends it (INV-8).
// Delisting again replaces the notice, and may slash a bond not yet slashed.
func Delist(cur realm, id, notice string, slash bool) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	c := campaignOf(id)
	recordDeadline(cur, c)
	notice = checkText(notice, noticeMin, noticeMax, false, ErrNotice)
	if slash {
		bond := bookSlash(c)
		banker.NewBanker(banker.BankerTypeRealmSend, bondSub(cur, c)).SendCoins(bondAddr(c.id), slashedAddr(), chain.NewCoins(chain.NewCoin("ugnot", bond)))
	}
	s := c.state
	s.listed, s.notice = false, notice
	dropActive(c)
	chain.Emit(evDelisted, "id", idString(c.id), "notice", notice, "slashed", strconv.FormatBool(slash))
}

// bookSlash checks a slash of c's bond and enters it in the books, before the coins
// move (API §3.5), and returns what moves: the bond, never the deposit. It refuses, in
// order, no bond posted, a bond already slashed, a hold that has ended — once closed,
// BondHold after closedAt, settled or not — and a bond address holding less than the
// bond (INV-7).
func bookSlash(c *campaign) int64 {
	s := c.state
	if s.bond == 0 {
		panic(ErrNoBond)
	}
	if s.bondSlashed {
		panic(ErrBondSlashed)
	}
	if s.status != statusOpen && now() >= s.closedAt+c.params.BondHold {
		panic(ErrHoldEnded)
	}
	if banker.NewReadonlyBanker().GetCoin(bondAddr(c.id), "ugnot") < s.bond {
		panic(ErrBooksMismatch)
	}
	s.bondSlashed = true
	return s.bond
}

// Relist puts a delisted campaign back on the lists, and into the active indexes if
// it is still open (API §3.5). Its notice stays, as does a slash. Relisting a listed
// campaign changes nothing.
func Relist(cur realm, id string) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	c := campaignOf(id)
	recordDeadline(cur, c)
	s := c.state
	if s.listed {
		return
	}
	s.listed = true
	if s.status == statusOpen {
		addActive(c)
	}
	chain.Emit(evRelisted, "id", idString(c.id))
}

// SetNotice attaches a public warning to the campaign without delisting it, or clears
// it with "" (API §3.5). An unchanged notice changes nothing.
func SetNotice(cur realm, id, notice string) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	c := campaignOf(id)
	recordDeadline(cur, c)
	notice = checkNotice(c, notice)
	if notice == c.state.notice {
		return
	}
	c.state.notice = notice
	chain.Emit(evNoticeSet, "id", idString(c.id), "notice", notice)
}

// checkNotice returns notice as SetNotice stores it (API §3.5): "" clears, except on a
// delisted campaign, which keeps a public reason; any other text is normalized, 1–280
// characters. It panics with ErrNotice otherwise.
func checkNotice(c *campaign, notice string) string {
	if notice != "" {
		return checkText(notice, noticeMin, noticeMax, false, ErrNotice)
	}
	if !c.state.listed {
		panic(ErrNotice)
	}
	return ""
}

// HideMessage hides one gift's message (API §3.5): visibility only. The receipt, its
// amount and its donor stay, and so does the stored text. Hiding a hidden message, or
// a receipt without one, changes nothing.
func HideMessage(cur realm, id string, seq int64) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	assertSigner(cur, admin)
	c := campaignOf(id)
	recordDeadline(cur, c)
	r := receiptOf(c, seq)
	if r.message == "" || r.messageHidden {
		return
	}
	r.messageHidden = true
	chain.Emit(evMessageHidden, "id", idString(c.id), "seq", itoa(seq))
}

moderation_test.gno

package bolo

import (
	"chain"
	"chain/banker"
	"strings"
	"testing"

	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/testutils/v0"
)

// The helpers' tests come first: a write's test that panics through a crossing call
// ends the package's unit tests.

// TestBookSlash: a slash takes the bond and only the bond, once, while the campaign
// is open or within BondHold of its close, settled or not (API §3.5, INV-7).
func TestBookSlash(t *testing.T) {
	c := testCampaign(9801, modeDirect, 0)
	if !panicsWith(func() { bookSlash(c) }, ErrNoBond) {
		t.Errorf("no bond: not ErrNoBond")
	}
	testing.IssueCoins(bondAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 1000+300))) // the deposit, the bond
	c.state.bond = 300
	if got := bookSlash(c); got != 300 || !c.state.bondSlashed {
		t.Errorf("open: slashed %d, flagged %t; want the bond, 300", got, c.state.bondSlashed)
	}
	if !panicsWith(func() { bookSlash(c) }, ErrBondSlashed) {
		t.Errorf("a second slash: not ErrBondSlashed")
	}

	for i, status := range []string{statusClosed, statusSettled} {
		d := testCampaign(seqid.ID(9802+i), modeDirect, 0)
		testing.IssueCoins(bondAddr(d.id), chain.NewCoins(chain.NewCoin("ugnot", 300)))
		d.state.bond, d.state.status, d.state.closedAt = 300, status, now()-d.params.BondHold
		if !panicsWith(func() { bookSlash(d) }, ErrHoldEnded) {
			t.Errorf("%s, the hold just ended: not ErrHoldEnded", status)
		}
		d.state.closedAt++
		if got := bookSlash(d); got != 300 {
			t.Errorf("%s, a second before the hold ends: slashed %d", status, got)
		}
	}

	e := testCampaign(9804, modeDirect, 0)
	testing.IssueCoins(bondAddr(e.id), chain.NewCoins(chain.NewCoin("ugnot", 200)))
	e.state.bond = 300
	if !panicsWith(func() { bookSlash(e) }, ErrBooksMismatch) {
		t.Errorf("a bond address holding less than the bond: not ErrBooksMismatch")
	}
	if e.state.bondSlashed {
		t.Errorf("a refused slash marked the bond slashed")
	}
}

// TestCheckNotice: "" clears, except on a delisted campaign; any other notice is
// normalized and holds 1–280 characters (API §2.3, §3.5).
func TestCheckNotice(t *testing.T) {
	c := testCampaign(9805, modeEscrow, 0)
	if got := checkNotice(c, ""); got != "" {
		t.Errorf(`"" on a listed campaign: %q`, got)
	}
	if got := checkNotice(c, "  Unverified\tclaims "); got != "Unverified claims" {
		t.Errorf("normalized: %q", got)
	}
	for name, notice := range map[string]string{
		"blank":    " \t ",
		"too long": strings.Repeat("a", noticeMax+1),
	} {
		if !panicsWith(func() { checkNotice(c, notice) }, ErrNotice) {
			t.Errorf("%s: not ErrNotice", name)
		}
	}
	c.state.listed = false
	if !panicsWith(func() { checkNotice(c, "") }, ErrNotice) {
		t.Errorf(`"" on a delisted campaign: not ErrNotice`)
	}
	if got := checkNotice(c, "Fraud reported"); got != "Fraud reported" {
		t.Errorf("a delisted campaign's new notice: %q", got)
	}
}

// TestDelist delists as the admin, straight from the test's body: off the active
// indexes, with the notice; then again, which replaces the notice and slashes, moving
// the bond and only the bond to the slashed address (API §3.5, INV-7).
func TestDelist(cur realm, t *testing.T) {
	rb := banker.NewReadonlyBanker()
	c := testCampaign(9806, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	testing.IssueCoins(bondAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 1000+300)))
	c.state.bond = 300
	slashed, key := rb.GetCoin(slashedAddr(), "ugnot"), c.id.Binary()

	testing.SetRealm(testing.NewUserRealm(admin))
	Delist(cross(cur), id, " Under review ", false)
	if s := c.state; s.listed || s.notice != "Under review" || s.bondSlashed || active.Has(key) || activeByCategory.Has(c.category+"/"+key) {
		t.Errorf("delisted: listed %t, notice %q, slashed %t, active %t", s.listed, s.notice, s.bondSlashed, active.Has(key))
	}
	Delist(cross(cur), id, "Fraud reported", true)
	if s := c.state; s.notice != "Fraud reported" || !s.bondSlashed {
		t.Errorf("delisted again: notice %q, slashed %t", s.notice, s.bondSlashed)
	}
	if got := rb.GetCoin(slashedAddr(), "ugnot") - slashed; got != 300 {
		t.Errorf("the slashed address got %d, want the bond, 300", got)
	}
	if got := rb.GetCoin(bondAddr(c.id), "ugnot"); got != 1000 {
		t.Errorf("the bond address holds %d, want the deposit, 1000", got)
	}
}

// TestRelist: back on the lists, and in the active indexes only while still open; the
// notice stays (API §3.5).
func TestRelist(cur realm, t *testing.T) {
	open := testCampaign(9807, modeEscrow, 0)
	closed := testCampaign(9808, modeEscrow, 0)
	closed.state.status, closed.state.closedAt = statusClosed, now()
	testing.SetRealm(testing.NewUserRealm(admin))
	for _, c := range []*campaign{open, closed} {
		id, unstore := storeCampaign(c)
		Delist(cross(cur), id, "Under review", false)
		Relist(cross(cur), id)
		key := c.id.Binary()
		if !c.state.listed || c.state.notice != "Under review" || active.Has(key) != (c == open) || activeByCategory.Has(c.category+"/"+key) != (c == open) {
			t.Errorf("%s, relisted: listed %t, notice %q, active %t", c.state.status, c.state.listed, c.state.notice, active.Has(key))
		}
		unstore()
	}
}

// TestSetNotice: a notice without delisting, normalized, then cleared (API §3.5).
func TestSetNotice(cur realm, t *testing.T) {
	c := testCampaign(9809, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	testing.SetRealm(testing.NewUserRealm(admin))
	SetNotice(cross(cur), id, " Unverified\tclaims ")
	if c.state.notice != "Unverified claims" || !c.state.listed || !active.Has(c.id.Binary()) {
		t.Errorf("noticed: %q, listed %t", c.state.notice, c.state.listed)
	}
	SetNotice(cross(cur), id, "")
	if c.state.notice != "" {
		t.Errorf("cleared: %q", c.state.notice)
	}
}

// TestHideMessage: the view blanks the message and keeps the receipt — its donor, its
// amount; the stored text stays (API §3.5).
func TestHideMessage(cur realm, t *testing.T) {
	c := testCampaign(9810, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	donor := testutils.TestAddress("donor")
	c.receipts.Set(seqid.ID(1).Binary(), &receipt{seq: 1, donor: donor, amount: 500, message: "Courage"})
	testing.SetRealm(testing.NewUserRealm(admin))
	HideMessage(cross(cur), id, 1)
	if v := GetReceipt(id, 1); v.Message != "" || !v.MessageHidden || v.Amount != 500 || v.Donor != donor {
		t.Errorf("hidden: %v", v)
	}
	if r := receiptOf(c, 1); r.message != "Courage" {
		t.Errorf("the stored text: %q", r.message)
	}
}

organizer.gno

package bolo

import (
	"chain"
	"chain/banker"
	"chain/runtime"
	"math"
)

// Who hid a campaign's photo: ImageHidden's by (API §6).
const (
	hiderOrganizer = "organizer"
	hiderModerator = "moderator"
)

// PostBond adds what you send to campaign id's bond: a stake its organizer may post,
// lost if Bolo's moderator delists the campaign for fraud. It is not a guarantee. The
// organizer only, while the campaign is open.
//
// It adds the envelope to the campaign's bond (API §3.1): its organizer only, by a
// direct transaction, while the campaign is open, its bond unslashed and Bolo not
// paused. The bond only grows, and the coins go on to the bond address: the
// realm keeps nothing (INV-3).
func PostBond(cur realm, id string) {
	assertCurrent(cur)
	if !cur.Previous().IsUserCall() {
		panic(ErrNotUserCall)
	}
	runtime.AssertOriginCall()
	c := campaignOf(id)
	recordDeadline(cur, c)
	if cur.Previous().Address() != c.organizer {
		panic(ErrNotOrganizer)
	}
	amount := envelopeUgnot()
	checkBond(c, amount)
	c.state.bond += amount
	banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(realmAddr(), bondAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", amount)))
	chain.Emit(evBondPosted, "id", idString(c.id), "amount", itoa(amount), "bond", itoa(c.state.bond))
}

// checkBond refuses amount as more bond for c (API §3.1), in this order: nothing
// sent, a campaign that isn't open, a slashed bond, a paused Bolo, and a bond that
// would pass int64.
func checkBond(c *campaign, amount int64) {
	if amount <= 0 {
		panic(ErrBadAmount)
	}
	assertOpen(c)
	if c.state.bondSlashed {
		panic(ErrBondSlashed)
	}
	if paused {
		panic(ErrPaused)
	}
	if amount > math.MaxInt64-c.state.bond {
		panic(ErrBadAmount)
	}
}

// assertOpen refuses a campaign that isn't open, by its stored status:
// ErrCampaignSettled once settled, ErrCampaignClosed otherwise. A passed deadline
// is recorded before (API §3.1).
func assertOpen(c *campaign) {
	switch c.state.status {
	case statusOpen:
	case statusSettled:
		panic(ErrCampaignSettled)
	default:
		panic(ErrCampaignClosed)
	}
}

// PostUpdate posts an update on campaign id, shown under its story, and returns the
// update's number: its organizer only. body may hold links, never an image.
//
// It appends an update to the campaign (API §3.1): its organizer only, by a direct
// transaction, in every status and while paused. Updates are append-only, and each
// resets the dormancy clock.
func PostUpdate(cur realm, id, body string) string {
	assertCurrent(cur)
	if !cur.Previous().IsUserCall() {
		panic(ErrNotUserCall)
	}
	runtime.AssertOriginCall()
	c := campaignOf(id)
	recordDeadline(cur, c)
	if cur.Previous().Address() != c.organizer {
		panic(ErrNotOrganizer)
	}
	body = checkStory(body, updateMin, updateMax, ErrUpdate)
	s := c.state
	seq := s.updateSeq.Next()
	c.updates.Set(seq.Binary(), &update{seq: uint64(seq), at: now(), body: body})
	s.updateCount++
	s.lastUpdateAt = now()
	chain.Emit(evUpdatePosted, "id", idString(c.id), "seq", idString(seq))
	return idString(seq)
}

// HideImage hides campaign id's photo, for good: its organizer can, and so can Bolo's
// moderator.
//
// Its organizer may, by a direct transaction, and so may the moderator, with the
// master key — a DAO realm, once one holds the role, through C11's realm branch (API
// §3.1, §3.5). The CID stays: it is a fingerprint, and never replaced. Hiding a
// hidden photo, or a campaign with none, changes nothing.
func HideImage(cur realm, id string) {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	c := campaignOf(id)
	recordDeadline(cur, c)
	by := hiderOrganizer
	if cur.Previous().Address() != c.organizer { // an organizer is a user: CreateCampaign admits no other
		assertSigner(cur, admin)
		by = hiderModerator
	}
	if c.text.imageCID == "" || c.state.imageHidden {
		return
	}
	c.state.imageHidden = true
	chain.Emit(evImageHidden, "id", idString(c.id), "by", by)
}

organizer_test.gno

package bolo

import (
	"chain"
	"chain/banker"
	"math"
	"strings"
	"testing"

	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/testutils/v0"
)

const testCID = "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG"

// storeCampaign stores c as CreateCampaign leaves a campaign, in campaigns and the
// active indexes, and returns its ID and what removes it again. The organizer's
// writes are called straight from each test's body, as AssertOriginCall requires
// (plan §3.3); their refusals are in txtar (organizer.txtar).
func storeCampaign(c *campaign) (string, func()) {
	key := c.id.Binary()
	campaigns.Set(key, c)
	active.Set(key, true)
	activeByCategory.Set(c.category+"/"+key, true)
	return idString(c.id), func() {
		campaigns.Remove(key)
		dropActive(c)
	}
}

func TestPostBond(cur realm, t *testing.T) {
	c := testCampaign(9101, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	rb := banker.NewReadonlyBanker()
	bondBefore, realmBefore := rb.GetCoin(bondAddr(c.id), "ugnot"), rb.GetCoin(realmAddr(), "ugnot")

	testing.SetRealm(testing.NewUserRealm(c.organizer))
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 500)))
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 500)))
	PostBond(cross(cur), id)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 300)))
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 300)))
	PostBond(cross(cur), id)

	// The bond grew by both envelopes, at the bond address; the realm keeps nothing
	// (INV-3).
	if c.state.bond != 800 || GetCampaign(id).Bond != 800 {
		t.Errorf("bond = %d, want 800", c.state.bond)
	}
	if got := rb.GetCoin(bondAddr(c.id), "ugnot") - bondBefore; got != 800 {
		t.Errorf("the bond address got %d, want 800", got)
	}
	if got := rb.GetCoin(realmAddr(), "ugnot"); got != realmBefore {
		t.Errorf("the realm holds %d, it held %d", got, realmBefore)
	}
}

func TestCheckBond(t *testing.T) {
	defer func(p bool) { paused = p }(paused)
	c := testCampaign(9102, modeEscrow, 0)
	checkBond(c, 1)
	c.state.bond = math.MaxInt64 - 5
	checkBond(c, 5)
	for name, k := range map[string]struct {
		status  string
		slashed bool
		paused  bool
		bond    int64
		amount  int64
		err     Error
	}{
		"nothing sent":             {statusOpen, false, false, 0, 0, ErrBadAmount},
		"a negative amount":        {statusOpen, false, false, 0, -1, ErrBadAmount},
		"closed":                   {statusClosed, false, false, 0, 1, ErrCampaignClosed},
		"settled":                  {statusSettled, false, false, 0, 1, ErrCampaignSettled},
		"slashed":                  {statusOpen, true, false, 0, 1, ErrBondSlashed},
		"paused":                   {statusOpen, false, true, 0, 1, ErrPaused},
		"past int64":               {statusOpen, false, false, math.MaxInt64 - 5, 6, ErrBadAmount},
		"nothing sent, and closed": {statusClosed, false, false, 0, 0, ErrBadAmount},
		"closed, and slashed":      {statusClosed, true, false, 0, 1, ErrCampaignClosed},
		"slashed, and paused":      {statusOpen, true, true, 0, 1, ErrBondSlashed},
	} {
		c.state.status, c.state.bondSlashed, c.state.bond = k.status, k.slashed, k.bond
		paused = k.paused
		if !panicsWith(func() { checkBond(c, k.amount) }, k.err) {
			t.Errorf("%s: not %s", name, k.err)
		}
	}
}

func TestAssertOpen(t *testing.T) {
	c := testCampaign(9103, modeEscrow, 0)
	assertOpen(c)
	for status, err := range map[string]Error{statusClosed: ErrCampaignClosed, statusSettled: ErrCampaignSettled} {
		c.state.status = status
		if !panicsWith(func() { assertOpen(c) }, err) {
			t.Errorf("%s: not %s", status, err)
		}
	}
}

func TestPostUpdate(cur realm, t *testing.T) {
	defer func(p bool) { paused = p }(paused)
	c := testCampaign(9104, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	testing.SkipHeights(10 * heightsPerDay)

	testing.SetRealm(testing.NewUserRealm(c.organizer))
	if seq := PostUpdate(cross(cur), id, "  Day one:\r\nthe pump is ordered.  "); seq != "1" {
		t.Fatalf("first update: seq %q, want \"1\"", seq)
	}
	u := c.updates.Get(seqid.ID(1).Binary()).(*update)
	if u.seq != 1 || u.at != now() || u.body != "Day one:\nthe pump is ordered." {
		t.Errorf("stored update = %v", *u)
	}
	// An update resets the dormancy clock.
	if s := c.state; s.updateCount != 1 || s.lastUpdateAt != now() || dormantAt(c) != now()+c.params.DormancyPeriod {
		t.Errorf("after an update: count %d, last %d, dormant at %d", s.updateCount, s.lastUpdateAt, dormantAt(c))
	}

	// In every status, and while paused.
	c.state.status = statusSettled
	paused = true
	if seq := PostUpdate(cross(cur), id, "The surgery went well."); seq != "2" {
		t.Errorf("update on a settled campaign, paused: seq %q, want \"2\"", seq)
	}
	if c.state.updateCount != 2 || c.updates.Size() != 2 {
		t.Errorf("%d updates counted, %d stored, want 2", c.state.updateCount, c.updates.Size())
	}
}

func TestCheckUpdate(t *testing.T) {
	if got := checkStory(" News ", updateMin, updateMax, ErrUpdate); got != "News" {
		t.Errorf("checkStory = %q", got)
	}
	for name, body := range map[string]string{
		"empty":            "",
		"spaces":           "   \n  ",
		"an accent alone":  "́",
		"one too many":     strings.Repeat("a", updateMax+1),
		"invisible filler": "ㅤ⠀",
	} {
		if !panicsWith(func() { checkStory(body, updateMin, updateMax, ErrUpdate) }, ErrUpdate) {
			t.Errorf("%s: not ErrUpdate", name)
		}
	}
	if !panicsWith(func() { checkStory("![x](https://example.com/x.png)", updateMin, updateMax, ErrUpdate) }, ErrMarkup) {
		t.Errorf("an image in an update: not ErrMarkup")
	}
}

func TestHideImage(cur realm, t *testing.T) {
	// The organizer hides the photo; the CID stays, and hiding again changes nothing.
	c := testCampaign(9105, modeEscrow, 0)
	c.text = &campaignText{title: "Clean water", imageCID: testCID, imageAlt: "The well"}
	id, unstore := storeCampaign(c)
	defer unstore()
	testing.SetRealm(testing.NewUserRealm(c.organizer))
	HideImage(cross(cur), id)
	if !c.state.imageHidden || c.text.imageCID != testCID || !GetCampaign(id).ImageHidden {
		t.Errorf("organizer: hidden %t, CID %q", c.state.imageHidden, c.text.imageCID)
	}
	HideImage(cross(cur), id)
	if !c.state.imageHidden {
		t.Errorf("hiding again showed the photo")
	}

	// The moderator hides another campaign's photo.
	d := testCampaign(9106, modeEscrow, 0)
	d.text = &campaignText{title: "Clean water", imageCID: testCID, imageAlt: "The well"}
	idD, unstoreD := storeCampaign(d)
	defer unstoreD()
	testing.SetRealm(testing.NewUserRealm(admin))
	HideImage(cross(cur), idD)
	if !d.state.imageHidden {
		t.Errorf("moderator: the photo isn't hidden")
	}

	// A campaign without a photo has nothing to hide.
	e := testCampaign(9107, modeEscrow, 0)
	idE, unstoreE := storeCampaign(e)
	defer unstoreE()
	testing.SetRealm(testing.NewUserRealm(e.organizer))
	HideImage(cross(cur), idE)
	if e.state.imageHidden {
		t.Errorf("a campaign without a photo got one hidden")
	}
}

var passerby = testutils.TestAddress("passerby")

payout.gno

package bolo

import (
	"chain"
	"chain/banker"
	"chain/runtime"
	"math/bits"

	"gno.land/p/nt/seqid/v0"
)

// The refund windows' names: Refund's kind, GetContribution's window (API §3.2).
const (
	windowOpen = "open"
	windowExit = "exit"
)

// Withdraw sends everything campaign id's escrow holds to its beneficiary, and returns
// how much: the beneficiary only, until the exit window opens — the campaign's page
// says when.
//
// The beneficiary only — a user by a direct transaction, or a deployed realm, through
// C11's realm branch (API §3.3). The tracked part counts as Withdrawn,
// and only it ends the open refund window; coins sent to the escrow outside Bolo go
// along, recorded apart.
func Withdraw(cur realm, id string) int64 {
	assertCurrent(cur)
	if cur.Previous().IsUserCall() {
		runtime.AssertOriginCall()
	} else {
		assertCodeCaller(cur)
	}
	c := campaignOf(id)
	recordDeadline(cur, c)
	if cur.Previous().Address() != c.beneficiary {
		panic(ErrNotBeneficiary)
	}
	w := bookWithdrawal(c)
	total := w.amount + w.untracked
	banker.NewBanker(banker.BankerTypeRealmSend, escrowSub(cur, c)).SendCoins(escrowAddr(c.id), c.beneficiary, chain.NewCoins(chain.NewCoin("ugnot", total)))
	chain.Emit(evWithdrawn,
		"id", idString(c.id),
		"seq", idString(seqid.ID(w.seq)),
		"to", w.to.String(),
		"amount", itoa(w.amount),
		"untracked", itoa(w.untracked),
	)
	return total
}

// bookWithdrawal checks a withdrawal from c and enters it in the books, before any
// coin moves (API §3.3): the refusals of checkWithdrawable; nothing at the escrow;
// INV-1. Everything at the escrow goes, the tracked part as Withdrawn — ending the
// open refund window only when above 0 — and the rest recorded apart. It returns the
// stored record.
func bookWithdrawal(c *campaign) *withdrawal {
	checkWithdrawable(c)
	total := banker.NewReadonlyBanker().GetCoin(escrowAddr(c.id), "ugnot")
	if total == 0 {
		panic(ErrNothingToWithdraw)
	}
	assertBooks(c)
	s := c.state
	tracked := trackedBalance(c)
	s.withdrawn += tracked
	if tracked > 0 {
		s.everWithdrawn = true
	}
	seq := s.withdrawalSeq.Next()
	w := &withdrawal{seq: uint64(seq), amount: tracked, untracked: total - tracked, at: now(), to: c.beneficiary}
	c.withdrawals.Set(seq.Binary(), w)
	return w
}

// checkWithdrawable refuses a withdrawal from c (API §3.3), in this order: a direct
// campaign, a settled one, and a closed one whose exit window has opened — what is
// left belongs to the exit process then.
func checkWithdrawable(c *campaign) {
	if c.mode != modeEscrow {
		panic(ErrWrongMode)
	}
	s := c.state
	if s.status == statusSettled {
		panic(ErrCampaignSettled)
	}
	if s.status == statusClosed && now() >= s.closedAt+c.params.ExitDelay {
		panic(ErrExitOpen)
	}
}

// Refund gives you back, from campaign id's escrow, what you can take back now, and
// returns how much: your whole gift until the beneficiary first withdraws, or, once
// the beneficiary's window after the campaign closes has passed, your share of what
// they left uncollected. The campaign's page offers it when a donor can.
//
// It pays the caller back from their own contribution to the campaign (API §3.2,
// INV-13): a donor, by a direct transaction, while a refund window is open to them.
// The open window — no tracked withdrawal ever — pays everything not yet refunded.
func Refund(cur realm, id string) int64 {
	assertCurrent(cur)
	if !cur.Previous().IsUserCall() {
		panic(ErrNotUserCall)
	}
	runtime.AssertOriginCall()
	c := campaignOf(id)
	recordDeadline(cur, c)
	donor := cur.Previous().Address()
	r := bookRefund(c, donor)
	banker.NewBanker(banker.BankerTypeRealmSend, escrowSub(cur, c)).SendCoins(escrowAddr(c.id), donor, chain.NewCoins(chain.NewCoin("ugnot", r.amount)))
	chain.Emit(evRefunded,
		"id", idString(c.id),
		"seq", idString(seqid.ID(r.seq)),
		"donor", donor.String(),
		"amount", itoa(r.amount),
		"kind", r.kind,
	)
	return r.amount
}

// bookRefund checks a refund of donor's contribution to c and enters it in the
// books, before any coin moves (API §3.2): the refusals of checkRefund, then INV-1,
// on the books as they stand. An exit claim freezes the pool and its base if it is
// the first, uses the donor's one claim, and may not exceed the tracked balance
// (INV-17). It returns the stored record.
func bookRefund(c *campaign, donor address) *refund {
	k, window, amount := checkRefund(c, donor)
	assertBooks(c)
	s := c.state
	if window == windowExit {
		if !s.exitFrozen {
			s.exitFrozen, s.exitPool, s.exitBase = true, trackedBalance(c), s.raised-s.refunded
		}
		if amount > trackedBalance(c) {
			panic(ErrBooksMismatch)
		}
		k.exitClaimed = true
	}
	k.refunded += amount
	s.refunded += amount
	s.refundCount++
	seq := s.refundSeq.Next()
	r := &refund{seq: uint64(seq), amount: amount, at: now(), donor: donor, kind: window}
	c.refunds.Set(seq.Binary(), r)
	return r
}

// checkRefund returns donor's contribution to c, the window Refund would use and what
// it would pay, or panics (API §3.2), in this order: a direct campaign; nothing to
// refund; no window open, a used exit claim included; an exit claim that rounds down
// to 0.
func checkRefund(c *campaign, donor address) (*contribution, string, int64) {
	if c.mode != modeEscrow {
		panic(ErrWrongMode)
	}
	k := contributionOf(c, donor)
	if k == nil || k.amount-k.refunded <= 0 {
		panic(ErrNothingToRefund)
	}
	window, amount := refundable(c, k)
	if window == "" {
		panic(ErrRefundWindowClosed)
	}
	if amount == 0 {
		panic(ErrNothingToRefund)
	}
	return k, window, amount
}

// refundable returns the window Refund would use for k now, and what it would pay
// (API §3.2). The open window, while no tracked withdrawal ever happened, pays all not
// yet refunded. After one, the exit window opens once the campaign is closed and
// ExitDelay has passed, while a tracked balance is left: one claim per donor, pro-rata
// against the pool and base the first claim froze — or would freeze now. It reads the
// effective status, as GetContribution can't record a passed deadline.
func refundable(c *campaign, k *contribution) (string, int64) {
	left := k.amount - k.refunded
	if c.mode != modeEscrow || left <= 0 {
		return "", 0
	}
	s := c.state
	if !s.everWithdrawn {
		return windowOpen, left
	}
	status, _, closedAt := effective(c)
	if status == statusOpen || now() < closedAt+c.params.ExitDelay || k.exitClaimed || trackedBalance(c) <= 0 {
		return "", 0
	}
	pool, base := s.exitPool, s.exitBase
	if !s.exitFrozen {
		pool, base = trackedBalance(c), s.raised-s.refunded
	}
	return windowExit, exitClaim(left, pool, base)
}

// exitClaim is left × pool / base, rounded down (API §3.2): computed in 128 bits, as
// both factors fit in 63 bits but their product doesn't. A claimant's left is part of
// the base, so the base is above 0 and the quotient at most the pool, and Div64's own
// panics, keyless, can't be reached; both conditions are asserted first.
func exitClaim(left, pool, base int64) int64 {
	if base <= 0 || left > base || pool < 0 {
		panic(ErrBooksMismatch)
	}
	hi, lo := bits.Mul64(uint64(left), uint64(pool))
	quo, _ := bits.Div64(hi, lo, uint64(base))
	return int64(quo)
}

// assertBooks panics with ErrBooksMismatch when c's books hold more than its escrow
// does (INV-1). It runs before every payout from an escrow, on the books as they
// stand, so a bug in the books stops a payment instead of paying out coins they
// can't account for.
func assertBooks(c *campaign) {
	if banker.NewReadonlyBanker().GetCoin(escrowAddr(c.id), "ugnot") < trackedBalance(c) {
		panic(ErrBooksMismatch)
	}
}

// contributionOf returns donor's record in c, or nil.
func contributionOf(c *campaign, donor address) *contribution {
	if v := c.contributions.Get(donor.String()); v != nil {
		return v.(*contribution)
	}
	return nil
}

// ContributionView is one donor's record in one campaign (API §2.4), with what Refund
// would pay them now: a copy.
type ContributionView struct {
	Amount, Refunded, RefundableNow int64
	Window                          string // "open", "exit", or "" for none: the window Refund would use now
	ExitClaimed                     bool
}

// GetContribution returns donor's record in campaign id (API §4): zeros and no
// window for an address that never gave, and no window for an exit claim that rounds
// to 0, which Refund refuses. An address is compared as given (C12).
func GetContribution(id string, donor address) ContributionView {
	c := campaignOf(id)
	k := contributionOf(c, donor)
	if k == nil {
		return ContributionView{}
	}
	window, pay := refundable(c, k)
	if pay == 0 {
		window = ""
	}
	return ContributionView{Amount: k.amount, Refunded: k.refunded, RefundableNow: pay, Window: window, ExitClaimed: k.exitClaimed}
}

payout_test.gno

package bolo

import (
	"chain"
	"chain/banker"
	"testing"

	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/testutils/v0"
)

// checkBooks holds c's books against the bank (INV-1) and against its own records:
// the contributions add up to Raised and Refunded. Money tests run it after every
// step.
func checkBooks(t *testing.T, c *campaign) {
	s := c.state
	if trackedBalance(c) < 0 {
		t.Errorf("campaign %d: balance %d, below 0 (INV-2)", uint64(c.id), trackedBalance(c))
	}
	if bank := banker.NewReadonlyBanker().GetCoin(escrowAddr(c.id), "ugnot"); bank < trackedBalance(c) {
		t.Errorf("campaign %d: books %d, bank %d (INV-1)", uint64(c.id), trackedBalance(c), bank)
	}
	if c.mode == modeDirect && trackedBalance(c) != 0 {
		t.Errorf("campaign %d, direct: balance %d (INV-2)", uint64(c.id), trackedBalance(c))
	}
	var amount, refunded int64
	c.contributions.Iterate("", "", func(_ string, v any) bool {
		amount += v.(*contribution).amount
		refunded += v.(*contribution).refunded
		return false
	})
	if amount != s.raised || refunded != s.refunded {
		t.Errorf("campaign %d: contributions %d given, %d refunded; books %d, %d", uint64(c.id), amount, refunded, s.raised, s.refunded)
	}
}

// fund records a gift of amount by donor in c's books and issues the coins to its
// escrow, as Donate leaves them, without a crossing call.
func fund(c *campaign, donor address, amount int64) {
	k := contributionOf(c, donor)
	if k == nil {
		k = &contribution{}
		c.contributions.Set(donor.String(), k)
		c.state.donorCount++
	}
	k.amount += amount
	c.state.raised += amount
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", amount)))
}

// The helpers' tests come first: a write's test that panics through a crossing call
// ends the package's unit tests.

func TestCheckWithdrawable(t *testing.T) {
	c := testCampaign(9401, modeEscrow, 0)
	checkWithdrawable(c)
	c.state.status, c.state.closedAt = statusClosed, now()-c.params.ExitDelay+1
	checkWithdrawable(c) // closed, a second before the exit window
	for name, k := range map[string]struct {
		mode, status string
		closedAt     int64
		err          Error
	}{
		"direct":               {modeDirect, statusOpen, 0, ErrWrongMode},
		"direct, and settled":  {modeDirect, statusSettled, 0, ErrWrongMode},
		"settled":              {modeEscrow, statusSettled, 0, ErrCampaignSettled},
		"exit window open":     {modeEscrow, statusClosed, now() - c.params.ExitDelay, ErrExitOpen},
		"long past the window": {modeEscrow, statusClosed, 1, ErrExitOpen},
	} {
		c.mode, c.state.status, c.state.closedAt = k.mode, k.status, k.closedAt
		if !panicsWith(func() { checkWithdrawable(c) }, k.err) {
			t.Errorf("%s: not %s", name, k.err)
		}
	}
}

func TestCheckRefund(t *testing.T) {
	donor, stranger := testutils.TestAddress("donor"), testutils.TestAddress("stranger")
	c := testCampaign(9402, modeEscrow, 0)
	c.contributions.Set(donor.String(), &contribution{amount: 700, refunded: 200})
	k, window, amount := checkRefund(c, donor)
	if k.amount != 700 || window != windowOpen || amount != 500 {
		t.Errorf("checkRefund = %v, %q, %d", *k, window, amount)
	}
	if !panicsWith(func() { checkRefund(c, stranger) }, ErrNothingToRefund) {
		t.Errorf("a stranger: not ErrNothingToRefund")
	}
	c.state.everWithdrawn = true
	if !panicsWith(func() { checkRefund(c, donor) }, ErrRefundWindowClosed) {
		t.Errorf("after a withdrawal: not ErrRefundWindowClosed")
	}
	k.refunded = k.amount
	if !panicsWith(func() { checkRefund(c, donor) }, ErrNothingToRefund) {
		t.Errorf("all refunded, window closed: not ErrNothingToRefund")
	}
	c.mode = modeDirect
	if !panicsWith(func() { checkRefund(c, donor) }, ErrWrongMode) {
		t.Errorf("direct, nothing left: not ErrWrongMode")
	}
}

// TestAssertBooks corrupts the books on purpose (INV-1): books above the bank stop
// every payout, before anything is written.
func TestAssertBooks(t *testing.T) {
	donor := testutils.TestAddress("donor")
	c := testCampaign(9403, modeEscrow, 0)
	fund(c, donor, 1000)
	assertBooks(c)
	c.state.raised += 1 // the books now claim a coin the escrow doesn't hold
	if !panicsWith(func() { assertBooks(c) }, ErrBooksMismatch) {
		t.Fatalf("books above the bank: not ErrBooksMismatch")
	}
	for name, f := range map[string]func(){
		"a withdrawal": func() { bookWithdrawal(c) },
		"a refund":     func() { bookRefund(c, donor) },
	} {
		if !panicsWith(f, ErrBooksMismatch) {
			t.Errorf("%s on books above the bank: not ErrBooksMismatch", name)
		}
	}
	if c.state.withdrawn != 0 || c.state.refunded != 0 || c.withdrawals.Size() != 0 || c.refunds.Size() != 0 {
		t.Errorf("a refused payout wrote the books")
	}
}

func TestBookWithdrawal(t *testing.T) {
	donor := testutils.TestAddress("donor")
	c := testCampaign(9404, modeEscrow, 0)
	if !panicsWith(func() { bookWithdrawal(c) }, ErrNothingToWithdraw) {
		t.Errorf("an empty escrow: not ErrNothingToWithdraw")
	}

	// Untracked coins alone: withdrawn as untracked, and the open window stays open.
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 300)))
	w := bookWithdrawal(c)
	checkBooks(t, c)
	if w.amount != 0 || w.untracked != 300 || w.seq != 1 || c.state.everWithdrawn || c.state.withdrawn != 0 {
		t.Errorf("untracked only: %v; everWithdrawn %t", *w, c.state.everWithdrawn)
	}
	// Tracked and untracked: Withdrawn grows by the tracked part only (INV-2). The
	// books moved no coin, so the 300 are still there.
	fund(c, donor, 1000)
	w = bookWithdrawal(c)
	checkBooks(t, c)
	if w.amount != 1000 || w.untracked != 300 || !c.state.everWithdrawn || c.state.withdrawn != 1000 || trackedBalance(c) != 0 {
		t.Errorf("tracked and untracked: %v; withdrawn %d", *w, c.state.withdrawn)
	}
	if got := c.withdrawals.Get(seqid.ID(2).Binary()).(*withdrawal); got != w || w.to != c.beneficiary || w.at != now() {
		t.Errorf("stored record %v", *got)
	}
}

func TestBookRefund(t *testing.T) {
	ada, bo := testutils.TestAddress("ada"), testutils.TestAddress("bo")
	c := testCampaign(9405, modeEscrow, 0)
	fund(c, ada, 2000)
	fund(c, bo, 1000)
	fund(c, c.organizer, 500) // a record a misdirected refund could pay from
	r := bookRefund(c, ada)
	checkBooks(t, c)
	if r.amount != 2000 || r.donor != ada || r.kind != windowOpen || r.seq != 1 {
		t.Errorf("refund %v", *r)
	}
	if k := contributionOf(c, ada); k.refunded != 2000 || c.state.refunded != 2000 || c.state.refundCount != 1 {
		t.Errorf("after a refund: contribution %v, refunded %d", *k, c.state.refunded)
	}
	// It pays only from the caller's own record: bo's is untouched (INV-13).
	if k := contributionOf(c, bo); k.refunded != 0 {
		t.Errorf("bo's record changed: %v", *k)
	}
	if !panicsWith(func() { bookRefund(c, ada) }, ErrNothingToRefund) {
		t.Errorf("a second refund: not ErrNothingToRefund")
	}
}

func TestGetContribution(t *testing.T) {
	donor := testutils.TestAddress("donor")
	c := testCampaign(9406, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	if v := GetContribution(id, testutils.TestAddress("stranger")); v != (ContributionView{}) {
		t.Errorf("a stranger: %v", v)
	}
	c.contributions.Set(donor.String(), &contribution{amount: 700, refunded: 200, public: true})
	if v := GetContribution(id, donor); v != (ContributionView{Amount: 700, Refunded: 200, RefundableNow: 500, Window: windowOpen}) {
		t.Errorf("open window: %v", v)
	}
	c.state.everWithdrawn = true
	if v := GetContribution(id, donor); v.Window != "" || v.RefundableNow != 0 || v.Amount != 700 {
		t.Errorf("after a withdrawal: %v", v)
	}
	if !panicsWith(func() { GetContribution("042", donor) }, ErrNotFound) {
		t.Errorf("GetContribution(\"042\"): not ErrNotFound")
	}
}

// TestWithdraw withdraws as the beneficiary, straight from the test's body as
// AssertOriginCall requires (plan §3.3), the books held against the bank after every
// step. Its refusals are unit-tested above and in txtar (money_out.txtar).
func TestWithdraw(cur realm, t *testing.T) {
	defer func(cap int64) { escrowCap = cap }(escrowCap)
	rb := banker.NewReadonlyBanker()
	donor := testutils.TestAddress("donor")
	c := testCampaign(9407, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	other := testCampaign(9408, modeEscrow, 0)
	idOther, unstoreOther := storeCampaign(other)
	defer unstoreOther()
	fund(c, donor, 3000)
	fund(other, donor, 500)
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 40))) // outside Bolo
	checkBooks(t, c)

	// Everything goes to the beneficiary: the tracked 3000 counted as Withdrawn,
	// the 40 recorded apart. The other campaign's escrow isn't touched.
	before, otherBefore := rb.GetCoin(c.beneficiary, "ugnot"), rb.GetCoin(escrowAddr(other.id), "ugnot")
	testing.SetRealm(testing.NewUserRealm(c.beneficiary))
	if got := Withdraw(cross(cur), id); got != 3040 {
		t.Errorf("Withdraw = %d, want 3040", got)
	}
	checkBooks(t, c)
	if got := rb.GetCoin(c.beneficiary, "ugnot") - before; got != 3040 || rb.GetCoin(escrowAddr(c.id), "ugnot") != 0 {
		t.Errorf("the beneficiary got %d; the escrow holds %d", got, rb.GetCoin(escrowAddr(c.id), "ugnot"))
	}
	if v := GetCampaign(id); v.Withdrawn != 3000 || v.Balance != 0 || !v.EverWithdrawn {
		t.Errorf("after the withdrawal: withdrawn %d, balance %d", v.Withdrawn, v.Balance)
	}
	if rb.GetCoin(escrowAddr(other.id), "ugnot") != otherBefore || GetCampaign(idOther).Balance != 500 {
		t.Errorf("a withdrawal touched another campaign")
	}

	// A withdrawal makes room under the cap.
	escrowCap = 3000
	checkRoom(c, 3000)

	// Closing traps nothing: closed, before the exit window, the beneficiary
	// still withdraws.
	fund(c, donor, 700)
	c.state.status, c.state.closedAt = statusClosed, now()
	if got := Withdraw(cross(cur), id); got != 700 {
		t.Errorf("Withdraw from a closed campaign = %d, want 700", got)
	}
	checkBooks(t, c)
}

// TestRefund refunds as a donor in the open window, the books held against the bank
// after every step: the caller is paid from their own record, and their receipts show
// it (INV-12, INV-13).
func TestRefund(cur realm, t *testing.T) {
	rb := banker.NewReadonlyBanker()
	ada, bo := testutils.TestAddress("ada"), testutils.TestAddress("bo")
	c := testCampaign(9409, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	testing.SetRealm(testing.NewUserRealm(ada))
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 2_000_000)))
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 2_000_000)))
	Donate(cross(cur), id, 0, "", false)
	defer byDonor.Remove(ada.String() + "/" + c.id.Binary())
	fund(c, bo, 1_000_000)
	checkBooks(t, c)

	before := rb.GetCoin(ada, "ugnot")
	if got := Refund(cross(cur), id); got != 2_000_000 {
		t.Errorf("Refund = %d, want 2000000", got)
	}
	checkBooks(t, c)
	if got := rb.GetCoin(ada, "ugnot") - before; got != 2_000_000 {
		t.Errorf("ada got %d back", got)
	}
	if r := GetReceipt(id, 1); r.DonorRefunded != 2_000_000 {
		t.Errorf("ada's receipt: DonorRefunded %d", r.DonorRefunded)
	}
	if v := GetCampaign(id); v.Refunded != 2_000_000 || v.RefundCount != 1 || v.Balance != 1_000_000 || v.NetRaised != 1_000_000 {
		t.Errorf("after the refund: %v", v)
	}
	if v := GetContribution(id, bo); v.RefundableNow != 1_000_000 || v.Window != windowOpen {
		t.Errorf("bo's record: %v", v)
	}

	// Given again after a refund, ada is paid what is left of her record, never all
	// of it: the escrow holds enough that paying more would go through (INV-13).
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 1_000_000)))
	testing.IssueCoins(realmAddr(), chain.NewCoins(chain.NewCoin("ugnot", 1_000_000)))
	Donate(cross(cur), id, 0, "", false)
	fund(c, bo, 2_000_000)
	checkBooks(t, c)
	before = rb.GetCoin(ada, "ugnot")
	if got := Refund(cross(cur), id); got != 1_000_000 {
		t.Errorf("a second Refund = %d, want 1000000", got)
	}
	checkBooks(t, c)
	if got := rb.GetCoin(ada, "ugnot") - before; got != 1_000_000 {
		t.Errorf("ada got %d back the second time, want 1000000", got)
	}
}

receipts.gno

package bolo

import "gno.land/p/nt/seqid/v0"

// ReceiptView is one gift, as the receipt page and the campaign page show it (API
// §2.4): a copy, holding nothing of the realm's state.
type ReceiptView struct {
	ID, CampaignID string
	Seq            int64
	Donor          address // empty when Anonymous
	Anonymous      bool
	Amount, Tip    int64
	Message        string // empty when MessageHidden
	MessageHidden  bool   // hidden by moderation; the receipt and amount stay
	At             int64
	RaisedAfter    int64 // the campaign's gross total right after this gift
	DonorRefunded  int64 // what this donor was refunded on this campaign after this gift (INV-12)
}

// GetReceipt returns gift seq of campaign id (API §4): an unknown campaign or
// sequence number is ErrNotFound.
func GetReceipt(id string, seq int64) ReceiptView {
	c := campaignOf(id)
	return receiptView(c, receiptOf(c, seq))
}

// receiptOf returns gift seq of c, or panics with ErrNotFound.
func receiptOf(c *campaign, seq int64) *receipt {
	if seq <= 0 {
		panic(ErrNotFound)
	}
	v := c.receipts.Get(seqid.ID(seq).Binary())
	if v == nil {
		panic(ErrNotFound)
	}
	return v.(*receipt)
}

// ListRecent returns the campaign's last gifts, newest first, at most recentSize
// (API §4): read through the ring of sequence numbers in its hot state.
func ListRecent(id string) []ReceiptView {
	c := campaignOf(id)
	s := c.state
	n := s.donationCount
	if n > recentSize {
		n = recentSize
	}
	views := make([]ReceiptView, 0, n)
	for i := 1; i <= n; i++ {
		seq := s.recent[(s.recentNext-i+recentSize)%recentSize]
		views = append(views, receiptView(c, c.receipts.Get(seqid.ID(seq).Binary()).(*receipt)))
	}
	return views
}

// receiptView builds r's view (API §2.4): the donor blanked when the gift was
// anonymous, the message when moderation hid it, and what this donor was refunded
// since, so a receipt can't vouch for money taken back (INV-12).
func receiptView(c *campaign, r *receipt) ReceiptView {
	v := ReceiptView{
		ID:            receiptID(c.id, seqid.ID(r.seq)),
		CampaignID:    idString(c.id),
		Seq:           int64(r.seq),
		Anonymous:     r.anonymous,
		Amount:        r.amount,
		Tip:           r.tip,
		MessageHidden: r.messageHidden,
		At:            r.at,
		RaisedAfter:   r.raisedAfter,
	}
	if !r.anonymous {
		v.Donor = r.donor
	}
	if !r.messageHidden {
		v.Message = r.message
	}
	if k := contributionOf(c, r.donor); k != nil {
		v.DonorRefunded = k.refunded - r.refundedBefore
	}
	return v
}

render.gno

package bolo

import (
	"math"
	"strconv"
	"strings"
	"time"

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

// Render (API §5): gnoweb's pages, each laid out for who reads it (UI spec §4.13). The
// path is attacker-controlled: it is parsed into typed values, and anything that fails
// gets one fixed page that echoes nothing from the request. User text is escaped by
// who wrote it: strangers and moderators through inline, the organizer through
// Blockquote; addresses go into code spans, where gnoweb makes no link of them. Render
// writes nothing and reads balances only through views.

const (
	webPath        = "/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo/v0" // this realm on gnoweb
	maxPathLen     = 256                 // longer than any valid path
	listPage       = 20                  // entries a list page shows
	updatesPage    = 5                   // updates a page shows: each can cost 0.18 billion gas to render
	addressSection = 10                  // entries each address-page section shows
	barWide        = 1000                // a progress bar's width across a page, scaled down to fit
	barCard        = 400                 // and in a card, half a row
	notFound       = "# Not found\n\nThere is nothing here. [Bolo](" + webPath + ")\n"
)

// Render returns the markdown page for path (API §5).
func Render(path string) string {
	if len(path) > maxPathLen {
		return notFound
	}
	route, rawQuery, _ := strings.Cut(path, "?")
	q, ok := parseQuery(rawQuery)
	if !ok {
		return notFound
	}
	if out, ok := route2page(route, q); ok {
		return out
	}
	return notFound
}

// route2page renders route, or reports false when route names nothing or a value in
// q doesn't parse. Every prefix of a route renders a page, as gnoweb's header links
// each one: "c" the home page, "c/{id}/r" the gifts, "u" the form to find an address.
func route2page(route string, q map[string]string) (string, bool) {
	switch route {
	case "", "c":
		return renderHome(q)
	case "u":
		return renderLookup(q), true
	case "about":
		return renderAbout(), true
	case "params":
		return renderParams(), true
	}
	segs := strings.Split(route, "/")
	switch {
	case segs[0] == "c" && len(segs) >= 2 && len(segs) <= 4:
		c, ok := lookup(segs[1])
		if !ok {
			return "", false
		}
		switch {
		case len(segs) == 2:
			return renderCampaign(c), true
		case len(segs) == 3 && (segs[2] == "donations" || segs[2] == "r"):
			return pageOf(q, func(page int) string { return renderDonations(c, page) })
		case len(segs) == 3 && segs[2] == "give":
			return renderGive(c, q), true
		case len(segs) == 3 && segs[2] == "ledger":
			return pageOf(q, func(page int) string { return renderLedger(c, page) })
		case len(segs) == 3 && segs[2] == "updates":
			return pageOf(q, func(page int) string { return renderUpdates(c, page) })
		case len(segs) == 4 && segs[2] == "r":
			seq, ok := parseID(segs[3])
			if !ok || c.receipts.Get(seq.Binary()) == nil {
				return "", false
			}
			return renderReceipt(c, int64(seq)), true
		}
	case segs[0] == "u" && (len(segs) == 2 || len(segs) == 3):
		addr, ok := parseAddress(segs[1])
		if !ok {
			return "", false
		}
		if len(segs) == 2 {
			return renderAddress(addr), true
		}
		list, heading := addressList(segs[2])
		if list == nil {
			return "", false
		}
		after, ok := q["after"]
		if ok {
			if _, canonical := parseID(after); !canonical {
				return "", false
			}
		}
		return renderAddressList(addr, segs[2], heading, list, after), true
	}
	return "", false
}

// parseQuery splits a query into its key=value pairs: an empty pair is skipped, a key
// given twice fails. Values are taken as they are: the routes parse them.
func parseQuery(raw string) (map[string]string, bool) {
	q := map[string]string{}
	if raw == "" {
		return q, true
	}
	for _, pair := range strings.Split(raw, "&") {
		if pair == "" {
			continue
		}
		k, v, _ := strings.Cut(pair, "=")
		if _, seen := q[k]; seen {
			return nil, false
		}
		q[k] = v
	}
	return q, true
}

// pageOf calls render with the page q asks for, 1 when it asks none, or fails when
// its page isn't a canonical number of at least 1.
func pageOf(q map[string]string, render func(page int) string) (string, bool) {
	page := 1
	if v, ok := q["page"]; ok {
		n, ok := parsePage(v)
		if !ok {
			return "", false
		}
		page = n
	}
	return render(page), true
}

// parsePage parses a page number: canonical decimal — no sign, no leading zero — from
// 1, at most nine digits.
func parsePage(s string) (int, bool) {
	if s == "" || len(s) > 9 || s[0] == '0' {
		return 0, false
	}
	n := 0
	for i := 0; i < len(s); i++ {
		if s[i] < '0' || s[i] > '9' {
			return 0, false
		}
		n = n*10 + int(s[i]-'0')
	}
	return n, true
}

// parseAddress checks an address from a path as C12 checks an argument: exactly 40
// characters, a lowercase "g" first, then IsValid.
func parseAddress(s string) (address, bool) {
	if len(s) != 40 || s[0] != 'g' || !address(s).IsValid() {
		return "", false
	}
	return address(s), true
}

// renderHome is the home page: the guarantees in one line, how it works, the links to
// start a campaign and to find an address, the newest active campaigns in a category
// or all, 20 at a time by cursor, and the categories.
func renderHome(q map[string]string) (string, bool) {
	after, ok := q["after"]
	if ok {
		if _, canonical := parseID(after); !canonical {
			return "", false
		}
	}
	cat, set := q["cat"]
	if set && !categories.Has(cat) {
		return "", false
	}
	var b strings.Builder
	b.WriteString("# Bolo\n\nGive together. See where it goes.\n\n")
	b.WriteString("**0% platform fee · every gift checkable · nothing in Bolo can freeze your gift** — [what Bolo guarantees, and what it doesn't](" + webPath + ":about)\n\n")
	b.WriteString("How it works: give from your wallet → get a receipt → check where the money went.\n\n")
	writeStart(&b)
	if cat == "" {
		b.WriteString("## Newest campaigns\n\n")
	} else {
		b.WriteString("## Newest campaigns in " + cat + "\n\n")
	}
	views, next := ListCampaigns(after, listPage, cat)
	writeCards(&b, views)
	switch {
	case len(views) > 0:
	case after == "" && next == "":
		b.WriteString("No campaigns here yet.\n\n")
	default:
		b.WriteString("None on this page.\n\n")
	}
	if next != "" {
		more := webPath + ":?after=" + next
		if cat != "" {
			more += "&cat=" + cat
		}
		b.WriteString("[More](" + more + ")\n\n")
	}
	b.WriteString("## Categories\n\n")
	for i, code := range categoryOrder {
		if i > 0 {
			b.WriteString(" · ")
		}
		b.WriteString("[" + code + "](" + webPath + ":?cat=" + code + ")")
	}
	b.WriteString("\n")
	return b.String(), true
}

// writeStart writes the link to start a campaign — CreateCampaign's form, the creation
// deposit attached — while this version takes new campaigns, or why it doesn't; then
// the link to find an address.
func writeStart(b *strings.Builder) {
	switch {
	case sunset:
		b.WriteString("This version of Bolo takes no new campaigns: [see where they start](/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo)")
	case paused:
		b.WriteString("Bolo is paused: new campaigns and gifts wait until it resumes")
	default:
		link := txlink.Realm(pkgPath).NewLink("CreateCampaign").SetSend(strconv.FormatInt(params.CreationDeposit, 10) + "ugnot").URL()
		b.WriteString("[Start a campaign](" + link + ") — a " + gnot(params.CreationDeposit) + " deposit, returned when it completes")
	}
	b.WriteString(" · [Find an address](" + webPath + ":u)\n\n")
}

// writeCards writes campaigns as cards, two to a row in gnoweb's columns (UI spec
// §4.13): the title as a link, the progress bar, raised of the goal and donors, then
// the mode, the category, the time left or how it ended, and a bond or a moderator's
// notice when there is one. The one user text, the title, goes through inline, whose
// InlineText escapes "<": nothing in it can open, separate or close a block. A
// separator is written self-closing, the spelling every gnoweb reads as one.
func writeCards(b *strings.Builder, views []CampaignView) {
	for i, v := range views {
		if i%2 == 0 {
			b.WriteString("<gno-columns>\n")
		} else {
			b.WriteString("<gno-columns-sep />\n")
		}
		b.WriteString("### [" + inline(v.Title) + "](" + webPath + ":c/" + v.ID + ")\n\n")
		if bar := progressBar(v.NetRaised, v.Goal, barCard); bar != "" {
			b.WriteString(bar + "\n\n")
		}
		b.WriteString("**" + gnot(v.NetRaised) + "**")
		if v.Goal > 0 {
			b.WriteString(" of " + gnot(v.Goal))
		} else {
			b.WriteString(" raised")
		}
		b.WriteString(" · " + count(v.DonorCount, "donor", "donors") + "  \n")
		b.WriteString(modeWord(v.Mode) + " · " + v.Category + " · " + timeWord(v))
		if v.Bond > 0 {
			if v.BondSlashed {
				b.WriteString(" · bond slashed")
			} else {
				b.WriteString(" · bond " + gnot(v.Bond))
			}
		}
		if v.Notice != "" {
			b.WriteString(" · **moderator's notice**")
		}
		b.WriteString("\n")
		if i%2 == 1 || i == len(views)-1 {
			if i%2 == 0 { // a row's last card alone: an empty column keeps it half wide
				b.WriteString("<gno-columns-sep />\n")
			}
			b.WriteString("</gno-columns>\n\n")
		}
	}
}

// timeWord says where a campaign stands in time, on a card: the time left, no
// deadline, or how it ended.
func timeWord(v CampaignView) string {
	switch {
	case v.Status == statusSettled:
		return "completed"
	case v.Status != statusOpen:
		return "closed to new donations"
	case v.Deadline != 0:
		return left(v.Deadline)
	}
	return "no deadline"
}

// renderCampaign is a campaign's page (API §5, UI spec §4.13), Bolo's own blocks
// before the organizer's words: the notice, the photo, the title and byline, the
// figures, the mode, the state banner, the donate links, where the money is, the
// verification block; then the story as a quote; then the recent gifts, the latest
// update, and last the actions of the organizer, the beneficiary and anyone.
func renderCampaign(c *campaign) string {
	v := campaignView(c)
	space := room(v)
	anyone, reason := CanClose(v.ID, "")
	var b strings.Builder
	if v.Notice != "" {
		b.WriteString("> [!WARNING] Notice from Bolo's moderator\n> " + lineStart(v.Notice) + "\n\n")
	}
	if v.ImageCID != "" && !v.ImageHidden {
		b.WriteString("![" + inline(v.ImageAlt) + "](ipfs://" + v.ImageCID + ")\n\n")
	}
	b.WriteString("# " + lineStart(v.Title) + "\n\n")
	b.WriteString(v.Category + " · by " + addrLink(v.Organizer) + " · for " + addrLink(v.Beneficiary))
	if !v.Listed {
		b.WriteString(" · **hidden from listings**")
	}
	b.WriteString("\n\n")
	writeFigures(&b, v)
	writeMode(&b, v)
	writeBanner(&b, v, space, anyone && reason == reasonDormant)
	writeGive(&b, v, space)
	writeMoney(&b, v)
	writeVerify(&b, v)
	if v.Description != "" {
		b.WriteString("---\n\n## In the organizer's words\n")
		b.WriteString(sanitize.Blockquote(v.Description))
		b.WriteString("---\n\n")
	}
	b.WriteString("## Recent gifts\n\n")
	recent := ListRecent(v.ID)
	for _, r := range recent {
		writeGift(&b, r)
	}
	if len(recent) == 0 {
		b.WriteString("No gifts yet.\n")
	}
	b.WriteString("\n[All gifts](" + webPath + ":c/" + v.ID + "/donations)")
	if v.Mode == modeEscrow {
		b.WriteString(" · [Money out](" + webPath + ":c/" + v.ID + "/ledger)")
	}
	b.WriteString("\n\n")
	if v.UpdateCount > 0 {
		b.WriteString("## Latest update\n\n")
		u := ListUpdates(v.ID, 1, 1)[0]
		b.WriteString("**" + when(u.At) + "**\n")
		b.WriteString(sanitize.Blockquote(u.Body))
		b.WriteString("[All updates](" + webPath + ":c/" + v.ID + "/updates)\n\n")
	}
	writeManage(&b, v, anyone)
	return b.String()
}

// writeFigures writes the progress bar, then three figures, a short line each, which
// stay short on a phone: raised, of the goal; donors and gifts; the time left, or how
// it ended.
func writeFigures(b *strings.Builder, v CampaignView) {
	if bar := progressBar(v.NetRaised, v.Goal, barWide); bar != "" {
		b.WriteString(bar + "\n\n")
	}
	b.WriteString("**" + gnot(v.NetRaised) + "** raised")
	if v.Goal > 0 {
		b.WriteString(" · " + percent(v.NetRaised, v.Goal) + " of a " + gnot(v.Goal) + " goal")
	}
	b.WriteString("  \n**" + count(v.DonorCount, "donor", "donors") + "** · " + count(v.DonationCount, "gift", "gifts"))
	if v.RefundCount > 0 {
		b.WriteString(", " + count(v.RefundCount, "refund", "refunds"))
	}
	b.WriteString("  \n")
	switch {
	case v.Status == statusSettled:
		b.WriteString("**Completed** · closed on " + day(v.ClosedAt))
	case v.Status != statusOpen:
		b.WriteString("**Closed to new donations** · on " + day(v.ClosedAt))
	case v.Deadline != 0:
		b.WriteString("**" + left(v.Deadline) + "** · until " + day(v.Deadline))
	default:
		b.WriteString("**No deadline** · open until it is closed")
	}
	b.WriteString("\n\n")
}

// writeMode writes the custody mode in words and what it means now (UI spec §4.3,
// ModeChip), with the refund link while a refund window is open to some donor — as
// far as the books can tell: after every donor's exit claim, rounding can leave a few
// ugnot that keep the window open in the books (API §2.4, §5).
func writeMode(b *strings.Builder, v CampaignView) {
	if v.Mode != modeEscrow {
		b.WriteString("**Direct**: each gift goes straight to the beneficiary, in the same transaction. Gifts can't be refunded.\n\n")
		return
	}
	b.WriteString("**Escrow**: ")
	switch {
	case v.Status != statusOpen && v.Balance == 0:
		b.WriteString("no gift is held any more.")
	case v.Status != statusOpen && now() >= v.ExitOpensAt: // the beneficiary's window has passed
		b.WriteString("the beneficiary didn't collect in time, so a donor who hasn't reclaimed their share yet can, at any time.")
	case v.EverWithdrawn:
		b.WriteString("the beneficiary has withdrawn funds, so gifts can't be refunded now.")
	default:
		b.WriteString("the gifts stay in escrow until the beneficiary withdraws them. Until then, a donor can take their gift back.")
	}
	if v.ExitOpen || !v.EverWithdrawn && v.Balance > 0 {
		b.WriteString(" [Refund](" + txlink.Realm(pkgPath).NewLink("Refund").AddArgs("id", v.ID).URL() + ")")
	}
	b.WriteString("\n\n")
}

// writeBanner writes the one state banner the UI spec's state matrix gives the
// campaign now (§6), as gnoweb's alert box, which no user text can open (API §5): how
// it was closed and what remains to happen, that it completed, that Bolo is paused,
// that the escrow cap leaves no room for a gift, or that anyone may close it as it is
// dormant. space is the room the cap leaves.
func writeBanner(b *strings.Builder, v CampaignView, space int64, dormant bool) {
	kind, title, text := "NOTE", "", ""
	switch {
	case v.Status == statusSettled:
		kind, title = "SUCCESS", "Completed"
		text = "Closed to new donations on " + when(v.ClosedAt) + ", then settled: the organizer's deposit went back to them."
	case v.Status != statusOpen:
		title, text = "Closed to new donations", closedText(v)
	case paused:
		kind, title, text = "CAUTION", "Bolo is paused", "New gifts wait until it resumes. Withdrawals and refunds still work."
	case space < minDonation:
		title, text = "Full for now", "This campaign can't take more until the beneficiary withdraws."
		if escrowCap < minDonation { // no withdrawal makes room
			text = "Bolo's escrow cap is set below its smallest gift, so no campaign in escrow can take a gift for now."
		}
	case dormant:
		title, text = "Inactive", "No gift and no update for "+days(v.Params.DormancyPeriod)+": anyone can close it now."
	default:
		return
	}
	b.WriteString("> [!" + kind + "] " + title + "\n> " + text + "\n\n")
}

// closedText says how a campaign was closed and, in escrow, what remains: the
// beneficiary's countdown to the exit window, or the window open to donors.
func closedText(v CampaignView) string {
	var out string
	switch v.CloseReason {
	case reasonDeadline:
		out = "It ended at its deadline, on " + when(v.ClosedAt) + "."
	case reasonDormant:
		out = "Closed on " + when(v.ClosedAt) + ", after " + days(v.Params.DormancyPeriod) + " with no gift and no update."
	default:
		out = "Closed by its organizer on " + when(v.ClosedAt) + "."
	}
	if v.Mode != modeEscrow || v.Balance == 0 {
		return out
	}
	if now() < v.ExitOpensAt {
		return out + " The beneficiary can withdraw the " + gnot(v.Balance) + " held until " + when(v.ExitOpensAt) + ", " + left(v.ExitOpensAt) + "; after that, donors can reclaim their share."
	}
	return out + " The beneficiary didn't collect in time: a donor who hasn't reclaimed their share yet can, at any time."
}

// room is how much more campaign v can take: what the escrow cap leaves, in escrow
// with a cap (checkRoom); otherwise as much as an amount can be.
func room(v CampaignView) int64 {
	if v.Mode != modeEscrow || escrowCap == 0 {
		return math.MaxInt64
	}
	return escrowCap - v.Balance
}

// writeGive writes the one-click donate links (API §5): while the campaign is open,
// listed and Bolo isn't paused, one per preset Donate would take — at least the
// smallest gift, and no more than the room the escrow cap leaves, space — then the
// page for another amount, with the room said when it left a preset out.
func writeGive(b *strings.Builder, v CampaignView, space int64) {
	if v.Status != statusOpen || !v.Listed || paused || space < minDonation {
		return
	}
	var links []string
	capped := false
	for _, preset := range presets {
		if preset > space {
			capped = true
			continue
		}
		if preset < minDonation {
			continue
		}
		links = append(links, giveLink(v.ID, preset))
	}
	links = append(links, "[Another amount]("+webPath+":c/"+v.ID+"/give)")
	b.WriteString("## Give\n\n" + strings.Join(links, " · ") + "\n\n")
	if capped {
		b.WriteString("It can take " + gnot(space) + " more for now: the beneficiary's next withdrawal makes room.\n\n")
	}
}

// giveLink is a one-click link that gives ugnot to campaign id, with no tip and no
// message: gnoweb's form attaches the coins once the donor confirms them.
func giveLink(id string, ugnot int64) string {
	link := txlink.Realm(pkgPath).NewLink("Donate").
		AddArgs("id", id, "tip", "0", "message", "", "anonymous", "false").
		SetSend(strconv.FormatInt(ugnot, 10) + "ugnot").URL()
	return "[Give " + gnot(ugnot) + "](" + link + ")"
}

// renderGive is the page for another amount (API §5). gnoweb's function form attaches
// only the coins a link carries, so this page asks the amount in gnoweb's own form,
// which submits back as ?amount=, and answers an amount Donate would take with its
// one-click link. Any other amount gets the form again with what the campaign can
// take, echoing nothing; a campaign Bolo offers no gift link for says so.
func renderGive(c *campaign, q map[string]string) string {
	v := campaignView(c)
	space := room(v)
	back := "[Back to the campaign](" + webPath + ":c/" + v.ID + ")\n"
	var b strings.Builder
	b.WriteString("# Give to [" + inline(v.Title) + "](" + webPath + ":c/" + v.ID + ")\n\n")
	if v.Status != statusOpen || !v.Listed || paused || space < minDonation {
		b.WriteString("Bolo offers no gift link for this campaign now: its page says why.\n\n" + back)
		return b.String()
	}
	raw, asked := q["amount"]
	if asked {
		if ugnot, ok := parseGNOT(raw); ok && ugnot >= minDonation && ugnot <= space {
			b.WriteString("**" + giveLink(v.ID, ugnot) + "**\n\n")
			b.WriteString("gnoweb's form asks you to confirm the coins before it adds them.\n\n" + back)
			return b.String()
		}
		b.WriteString("That isn't an amount this campaign can take.\n\n")
	}
	b.WriteString("Any amount from " + gnot(minDonation))
	if space < math.MaxInt64 {
		b.WriteString(" to " + gnot(space))
	}
	b.WriteString(", in GNOT.\n\n")
	b.WriteString("<gno-form path=\"c/" + v.ID + "/give\">\n  <gno-input name=\"amount\" placeholder=\"7.5\" />\n</gno-form>\n\n" + back)
	return b.String()
}

// parseGNOT parses an amount in GNOT into ugnot (API §5): digits without a sign or a
// leading zero, at most 12 of them, then optionally a decimal point — "." or, as a
// form sends a comma, "%2C" — and one to six digits; but not a comma and exactly
// three, which may be a thousands separator. The spaces a form sends around a value,
// as "+", are dropped first.
func parseGNOT(s string) (int64, bool) {
	s = strings.Trim(s, "+")
	whole, frac, point := strings.Cut(s, ".")
	if !point {
		whole, frac, point = strings.Cut(s, "%2C")
		if point && len(frac) == 3 { // "1,000": a thousand, or one?
			return 0, false
		}
	}
	if whole == "" || len(whole) > 12 || len(whole) > 1 && whole[0] == '0' || point && (frac == "" || len(frac) > 6) {
		return 0, false
	}
	var n int64
	for i := 0; i < len(whole); i++ {
		if whole[i] < '0' || whole[i] > '9' {
			return 0, false
		}
		n = n*10 + int64(whole[i]-'0')
	}
	n *= 1_000_000
	unit := int64(100_000)
	for i := 0; i < len(frac); i++ {
		if frac[i] < '0' || frac[i] > '9' {
			return 0, false
		}
		n += int64(frac[i]-'0') * unit
		unit /= 10
	}
	return n, true
}

// writeMoney writes where the money is, a table of amounts: given, then, in escrow,
// refunded, raised net of refunds, withdrawn and held; in direct mode, sent straight
// to the beneficiary.
func writeMoney(b *strings.Builder, v CampaignView) {
	b.WriteString("## Where the money is\n\n| | GNOT |\n|---|--:|\n")
	b.WriteString("| Given: " + count(v.DonationCount, "gift", "gifts") + " from " + count(v.DonorCount, "donor", "donors") + " | " + amount(v.Raised) + " |\n")
	if v.Mode != modeEscrow {
		b.WriteString("| Sent straight to the beneficiary | " + amount(v.Raised) + " |\n\n")
		return
	}
	b.WriteString("| Refunded to donors | " + amount(v.Refunded) + " |\n")
	b.WriteString("| **Raised**, net of refunds | **" + amount(v.NetRaised) + "** |\n")
	b.WriteString("| Withdrawn by the beneficiary | " + amount(v.Withdrawn) + " |\n")
	b.WriteString("| Held in escrow | " + amount(v.Balance) + " |\n\n")
}

// writeVerify writes the verification block: where to check every figure on the chain
// itself (UI spec §2, level 3), each address in full.
func writeVerify(b *strings.Builder, v CampaignView) {
	b.WriteString("## Check it yourself\n\n")
	if v.Mode == modeEscrow {
		b.WriteString("- **Escrow** `" + v.EscrowAddress.String() + "`: its bank balance is the " + gnot(v.Balance) + " held, plus " + gnot(v.Untracked) + " sent there outside Bolo\n")
	}
	b.WriteString("- **Bond address** `" + v.BondAddress.String() + "`: the organizer's " + gnot(v.Deposit) + " deposit")
	if v.Status == statusSettled {
		b.WriteString(", returned when the campaign completed")
	} else {
		b.WriteString(", returned when the campaign completes")
	}
	switch {
	case v.Bond == 0:
	case v.BondSlashed:
		b.WriteString("; a " + gnot(v.Bond) + " bond, slashed")
	case v.Status != statusOpen && now() >= v.BondReleasableAt:
		b.WriteString("; a " + gnot(v.Bond) + " bond the organizer staked, whose hold ended " + when(v.BondReleasableAt) + ": no longer at stake, it goes back to the organizer")
	default:
		b.WriteString("; a " + gnot(v.Bond) + " bond the organizer staked, lost if the campaign is delisted for fraud — not a guarantee")
	}
	b.WriteString("\n- **Organizer** `" + v.Organizer.String() + "`\n- **Beneficiary** `" + v.Beneficiary.String() + "`\n\n")
	b.WriteString("Created " + when(v.CreatedAt))
	if v.Deadline != 0 {
		b.WriteString(" · deadline " + when(v.Deadline))
	}
	if v.ClosedAt != 0 {
		b.WriteString(" · closed " + when(v.ClosedAt))
	}
	b.WriteString("\n\n")
}

// writeManage writes the actions of the organizer, the beneficiary and anyone, each
// with who may take it, when that call could succeed for someone (API §5): last, as
// the web app puts maintenance last (UI spec §4.3). anyone is whether CanClose lets
// anyone close it.
func writeManage(b *strings.Builder, v CampaignView, anyone bool) {
	id := v.ID
	var links []string
	if v.Mode == modeEscrow && v.Balance+v.Untracked > 0 && (v.Status == statusOpen || v.Status == statusClosed && now() < v.ExitOpensAt) {
		links = append(links, "[Withdraw]("+txlink.Realm(pkgPath).NewLink("Withdraw").AddArgs("id", id).URL()+"): the beneficiary")
	}
	if anyone || v.Status == statusOpen {
		who := "the organizer"
		if anyone {
			who = "anyone"
		}
		links = append(links, "[Close]("+txlink.Realm(pkgPath).NewLink("Close").AddArgs("id", id).URL()+"): "+who)
	}
	if ok, _ := CanFinalize(id); ok {
		links = append(links, "[Finalize]("+txlink.Realm(pkgPath).NewLink("Finalize").AddArgs("id", id).URL()+"): anyone")
	}
	links = append(links, "[Post an update]("+txlink.Realm(pkgPath).NewLink("PostUpdate").AddArgs("id", id).URL()+"): the organizer")
	b.WriteString("## Manage this campaign\n\n- " + strings.Join(links, "\n- ") + "\n")
}

// writeGift writes one gift in two lines: its amount, and its message unless
// moderation hid it; then who gave it — a short address linking to its page, or
// anonymous — when, how much its donor was refunded since (INV-12), and its receipt.
func writeGift(b *strings.Builder, r ReceiptView) {
	b.WriteString("- **" + gnot(r.Amount) + "**")
	if r.MessageHidden {
		b.WriteString(" · message hidden by moderation")
	} else if r.Message != "" {
		b.WriteString(" · “" + inline(r.Message) + "”")
	}
	b.WriteString("  \n  ")
	if r.Anonymous {
		b.WriteString("Anonymous")
	} else {
		b.WriteString("from " + addrLink(r.Donor))
	}
	b.WriteString(" · " + when(r.At))
	if r.DonorRefunded > 0 {
		b.WriteString(" · **" + gnot(r.DonorRefunded) + " refunded since**")
	}
	b.WriteString(" · [receipt](" + webPath + ":c/" + r.CampaignID + "/r/" + strconv.FormatInt(r.Seq, 10) + ")\n")
}

// renderReceipt is a gift's receipt: the shareable object (PRD §5). When its donor was
// refunded since, the refund banner comes first, so a refunded receipt never looks like
// a live gift (UI spec §4.5, INV-12).
func renderReceipt(c *campaign, seq int64) string {
	r := GetReceipt(idString(c.id), seq)
	v := campaignView(c)
	var b strings.Builder
	if r.DonorRefunded > 0 {
		b.WriteString("> [!CAUTION] Refunded since\n> " + gnot(r.DonorRefunded) + " went back to this donor after this gift.\n\n")
	}
	b.WriteString("# Gift receipt\n\n")
	b.WriteString("**" + gnot(r.Amount) + "** to [" + inline(v.Title) + "](" + webPath + ":c/" + v.ID + "), on " + when(r.At) + ".\n\n")
	b.WriteString("| Receipt | " + r.ID + " |\n|---|---|\n")
	if r.Anonymous {
		b.WriteString("| From | Anonymous |\n")
	} else {
		b.WriteString("| From | `" + r.Donor.String() + "` |\n")
	}
	if r.Tip > 0 {
		b.WriteString("| Tip to Bolo | " + gnot(r.Tip) + " |\n")
	}
	b.WriteString("| The campaign's total right after it | " + gnot(r.RaisedAfter) + " |\n\n")
	if r.MessageHidden {
		b.WriteString("Message: hidden by moderation.\n\n")
	} else if r.Message != "" {
		b.WriteString("Message: “" + inline(r.Message) + "”\n\n")
	}
	b.WriteString("## Where it went\n\n")
	if bar := progressBar(v.NetRaised, v.Goal, barWide); bar != "" {
		b.WriteString(bar + "\n\n")
	}
	b.WriteString("The campaign is " + strings.ToLower(statusWord(v.Status)) + ": " + gnot(v.NetRaised) + " raised net of refunds")
	if v.Goal > 0 {
		b.WriteString(", " + percent(v.NetRaised, v.Goal) + " of its " + gnot(v.Goal) + " goal")
	}
	b.WriteString(".\n\n")
	if v.Mode == modeEscrow {
		b.WriteString("- " + gnot(v.Withdrawn) + " withdrawn by the beneficiary, `" + v.Beneficiary.String() + "`\n")
		b.WriteString("- " + gnot(v.Balance) + " held in escrow, at `" + v.EscrowAddress.String() + "`\n\n")
	} else {
		b.WriteString("Every gift went straight to the beneficiary, `" + v.Beneficiary.String() + "`, in the same transaction.\n\n")
	}
	b.WriteString("[The campaign](" + webPath + ":c/" + v.ID + ") · [All gifts](" + webPath + ":c/" + v.ID + "/donations)")
	if v.Mode == modeEscrow {
		b.WriteString(" · [Money out](" + webPath + ":c/" + v.ID + "/ledger)")
	}
	b.WriteString("\n")
	return b.String()
}

// renderDonations is a page of a campaign's gifts, newest first, under one line of
// totals.
func renderDonations(c *campaign, page int) string {
	id := idString(c.id)
	s := c.state
	var b strings.Builder
	b.WriteString("# Gifts to [" + inline(c.text.title) + "](" + webPath + ":c/" + id + ")\n\n")
	b.WriteString(count(s.donationCount, "gift", "gifts") + " from " + count(s.donorCount, "donor", "donors") + " · " + gnot(s.raised) + " given")
	if s.refunded > 0 {
		b.WriteString(" · " + gnot(s.refunded) + " refunded")
	}
	b.WriteString("\n\n")
	gifts := ListReceipts(id, page, listPage)
	for _, r := range gifts {
		writeGift(&b, r)
	}
	if len(gifts) == 0 {
		b.WriteString(empty(page, "No gifts yet.\n", "No gifts on this page.\n"))
	}
	writePager(&b, webPath+":c/"+id+"/donations", page, listPage, c.receipts.Size())
	return b.String()
}

// renderLedger is a page of a campaign's money out of its escrow: withdrawals, then
// refunds, each newest first. In direct mode, it says that nothing goes out: Withdraw
// and Refund refuse a direct campaign, so neither list ever holds one.
func renderLedger(c *campaign, page int) string {
	id := idString(c.id)
	var b strings.Builder
	b.WriteString("# Money out of [" + inline(c.text.title) + "](" + webPath + ":c/" + id + ")\n\n")
	if c.mode != modeEscrow {
		b.WriteString("**Direct**: each gift went straight to the beneficiary, `" + c.beneficiary.String() + "`, when it was given. Nothing is held, so nothing goes out.\n\n")
		b.WriteString("[All gifts](" + webPath + ":c/" + id + "/donations)\n")
		return b.String()
	}
	b.WriteString("Every coin that left the escrow, `" + escrowAddr(c.id).String() + "`: to the beneficiary, or back to donors.\n\n")
	b.WriteString("## Withdrawals\n\n")
	if ws := ListWithdrawals(id, page, listPage); len(ws) > 0 {
		b.WriteString("| When (UTC) | GNOT | Outside Bolo | To |\n|---|--:|--:|---|\n")
		for _, w := range ws {
			b.WriteString("| " + stamp(w.At) + " | " + amount(w.Amount) + " | " + amount(w.Untracked) + " | `" + w.To.String() + "` |\n")
		}
		b.WriteString("\nOutside Bolo: coins sent to the escrow directly, which the withdrawal carried too.\n")
	} else {
		b.WriteString(empty(page, "None.\n", "None on this page.\n"))
	}
	b.WriteString("\n## Refunds\n\n")
	if rs := ListRefunds(id, page, listPage); len(rs) > 0 {
		b.WriteString("| When (UTC) | GNOT | How | To |\n|---|--:|---|---|\n")
		for _, r := range rs {
			to := "Anonymous"
			if r.Donor != "" {
				to = "`" + r.Donor.String() + "`"
			}
			how := "refund"
			if r.Kind == windowExit {
				how = "exit claim"
			}
			b.WriteString("| " + stamp(r.At) + " | " + amount(r.Amount) + " | " + how + " | " + to + " |\n")
		}
	} else {
		b.WriteString(empty(page, "None.\n", "None on this page.\n"))
	}
	n := c.withdrawals.Size()
	if m := c.refunds.Size(); m > n {
		n = m
	}
	writePager(&b, webPath+":c/"+id+"/ledger", page, listPage, n)
	return b.String()
}

// renderUpdates is a page of a campaign's updates, newest first, each as a quote.
func renderUpdates(c *campaign, page int) string {
	id := idString(c.id)
	var b strings.Builder
	b.WriteString("# Updates on [" + inline(c.text.title) + "](" + webPath + ":c/" + id + ")\n\n")
	updates := ListUpdates(id, page, updatesPage)
	for _, u := range updates {
		b.WriteString("## " + when(u.At) + "\n")
		b.WriteString(sanitize.Blockquote(u.Body))
	}
	if len(updates) == 0 {
		b.WriteString(empty(page, "No updates yet.\n", "No updates on this page.\n"))
	}
	writePager(&b, webPath+":c/"+id+"/updates", page, updatesPage, c.updates.Size())
	return b.String()
}

// empty says a page of a campaign's list has nothing on it: first on the list's first
// page, where it means the list is empty, later past it (API §5).
func empty(page int, first, later string) string {
	if page == 1 {
		return first
	}
	return later
}

// writePager writes links to the pages before and after page, of n entries, size a
// page.
func writePager(b *strings.Builder, base string, page, size, n int) {
	var links []string
	if page > 1 {
		links = append(links, "[Newer]("+base+"?page="+strconv.Itoa(page-1)+")")
	}
	if page*size < n {
		links = append(links, "[Older]("+base+"?page="+strconv.Itoa(page+1)+")")
	}
	if len(links) > 0 {
		b.WriteString("\n" + strings.Join(links, " · ") + "\n")
	}
}

// addressList returns the address page's list a path segment names, and its heading;
// nil for any other segment. They show listed campaigns only, as they promote (API §5).
func addressList(name string) (func(address, string, int) ([]CampaignView, string), string) {
	switch name {
	case "organized":
		return ListByOrganizer, "Organized"
	case "named":
		return ListByBeneficiary, "Named as beneficiary by an organizer"
	case "gave":
		return ListByDonor, "Gave to, without anonymity"
	}
	return nil, ""
}

// renderAddress is the public address page: the short address as its title and the
// full one under it, then the 10 newest campaigns of each list, as cards, with "More"
// while a list goes on.
func renderAddress(addr address) string {
	var b strings.Builder
	b.WriteString("# `" + short(addr) + "` on Bolo\n\n")
	b.WriteString("`" + addr.String() + "`: the campaigns this address organized, is named beneficiary of, or gave to without anonymity. Campaigns hidden from listings and anonymous gifts aren't shown.\n\n")
	for _, name := range []string{"organized", "named", "gave"} {
		list, heading := addressList(name)
		b.WriteString("## " + heading + "\n\n")
		views, next := list(addr, "", addressSection)
		writeListed(&b, views, next != "")
		if next != "" {
			b.WriteString("[More](" + webPath + ":u/" + addr.String() + "/" + name + "?after=" + next + ")\n\n")
		}
	}
	return b.String()
}

// renderAddressList is one of the address page's lists, 20 at a time by cursor.
func renderAddressList(addr address, name, heading string, list func(address, string, int) ([]CampaignView, string), after string) string {
	var b strings.Builder
	b.WriteString("# `" + short(addr) + "`: " + strings.ToLower(heading[:1]) + heading[1:] + "\n\n")
	b.WriteString("[All of `" + addr.String() + "` on Bolo](" + webPath + ":u/" + addr.String() + ")\n\n")
	views, next := list(addr, after, listPage)
	writeListed(&b, views, after != "" || next != "")
	if next != "" {
		b.WriteString("[More](" + webPath + ":u/" + addr.String() + "/" + name + "?after=" + next + ")\n")
	}
	return b.String()
}

// writeListed writes the cards of the listed campaigns among views: a delisted one is
// left out of a list that promotes. With none to show, it says so, and whether this is
// only one page of the list: a later one, or one a "More" follows (paged).
func writeListed(b *strings.Builder, views []CampaignView, paged bool) {
	var listed []CampaignView
	for _, v := range views {
		if v.Listed {
			listed = append(listed, v)
		}
	}
	switch {
	case len(listed) > 0:
		writeCards(b, listed)
	case paged:
		b.WriteString("None on this page.\n\n")
	default:
		b.WriteString("None.\n\n")
	}
}

// renderLookup is the page that finds an address: gnoweb's form, which submits back
// here as ?address=. A valid address gets its page; anything else, the form again with
// one fixed line, echoing nothing from the request (API §5).
func renderLookup(q map[string]string) string {
	raw, asked := q["address"]
	if asked {
		if addr, ok := parseAddress(raw); ok {
			return renderAddress(addr)
		}
	}
	var b strings.Builder
	b.WriteString("# Find an address\n\n")
	if asked {
		b.WriteString("That isn't a gno.land address.\n\n")
	}
	b.WriteString("See what an address has done on Bolo: the campaigns it organized, is named beneficiary of, or gave to without anonymity.\n\n")
	b.WriteString("<gno-form path=\"u\">\n  <gno-input name=\"address\" placeholder=\"g1…\" />\n</gno-form>\n")
	return b.String()
}

// renderAbout is the guarantees table, what Bolo costs, where tips go, how to check it,
// and what not to do (PRD §3, UI spec §4.11).
func renderAbout() string {
	return "# What Bolo guarantees, and what it doesn't\n\n" +
		"| A donor can verify themselves | A donor must still take on faith |\n|---|---|\n" +
		"| The exact amount the campaign has received | That the campaign's story is true |\n" +
		"| Every payout: amount, destination, timestamp | That the beneficiary spends it as promised |\n" +
		"| That no fee was taken | That the person in the photo consented to it |\n" +
		"| That the organizer cannot quietly change the beneficiary | That the organizer is who they claim to be |\n" +
		"| That their own donation arrived and is counted | |\n" +
		"| That nothing in Bolo, and nobody running it, can freeze or seize it | |\n\n" +
		"The last row is scoped to Bolo: the gno.land chain's own governance sits above every application on it.\n\n" +
		"**A chain fixes custody fraud. It does not fix claim fraud.** \"Verified on-chain\" never means \"verified true\".\n\n" +
		"## Fees\n\n0% platform fee. Your wallet pays a small network fee. Tips to Bolo are optional.\n\n" +
		"## Where tips go\n\nTo `" + tipRecipient.String() + "`, in the same transaction as your gift: Bolo keeps no treasury.\n\n" +
		"## How to check\n\nEvery campaign page lists its escrow and bond addresses: read their balances on any explorer, and every transaction behind each figure. The code doing all of this is public, at `" + pkgPath + "`, and nobody can change it.\n\n" +
		"## Don't send coins to Bolo's addresses directly\n\nGive through a campaign's page. Coins sent straight to this version's own address can be swept to the tip recipient; coins sent to the version registry can't be recovered.\n\n" +
		"[Bolo](" + webPath + ")\n"
}

// renderParams shows the parameters new campaigns get, the live settings in words,
// and the admin.
func renderParams() string {
	s := GetSettings()
	p := params
	a, pending := GetAdmin()
	var b strings.Builder
	b.WriteString("# Parameters\n\n## For new campaigns\n\n")
	b.WriteString("- Creation deposit: " + gnot(p.CreationDeposit) + "\n")
	b.WriteString("- Dormancy: " + days(p.DormancyPeriod) + "; exit delay: " + days(p.ExitDelay) + "; bond hold: " + days(p.BondHold) + "\n\n")
	b.WriteString("## Settings\n\n")
	if s.Paused {
		b.WriteString("- Gifts: paused — withdrawals and refunds still work\n")
	} else {
		b.WriteString("- Gifts: accepted\n")
	}
	switch {
	case s.Sunset:
		b.WriteString("- New campaigns: not on this version\n")
	case s.Paused:
		b.WriteString("- New campaigns: paused\n")
	default:
		b.WriteString("- New campaigns: accepted\n")
	}
	b.WriteString("- Smallest gift: " + gnot(s.MinDonation) + "\n")
	b.WriteString("- One-click amounts: ")
	for i, preset := range s.Presets {
		if i > 0 {
			b.WriteString(" · ")
		}
		b.WriteString(gnot(preset))
	}
	b.WriteString("\n- Escrow cap: ")
	if s.MaxEscrowBalance == 0 {
		b.WriteString("none")
	} else {
		b.WriteString(gnot(s.MaxEscrowBalance))
	}
	b.WriteString("\n- Tips go to: `" + s.TipRecipient.String() + "`\n")
	b.WriteString("- Categories: " + strings.Join(s.Categories, ", ") + "\n\n")
	b.WriteString("## Admin\n\n`" + a.String() + "`")
	if pending != "" {
		b.WriteString(", handing over to `" + pending.String() + "`")
	}
	b.WriteString("\n")
	return b.String()
}

// progressBar draws how much of its goal a campaign raised (UI spec §5, ProgressBar):
// an SVG image of two numbers, which gnoweb accepts inline as a data URI, width wide.
// It fills min(net, goal) of goal; its text, the percentage, is uncapped. With no goal,
// there is no bar.
func progressBar(net, goal int64, width int) string {
	if goal <= 0 {
		return ""
	}
	filled := net
	if filled > goal {
		filled = goal
	}
	w := strconv.Itoa(width)
	return "![" + percent(net, goal) + " of the goal](data:image/svg+xml;utf8," +
		"%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='" + w + "'%20height='10'%20viewBox='0%200%20" + w + "%2010'%3E" +
		"%3Crect%20width='" + w + "'%20height='10'%20rx='5'%20fill='%23888'%20fill-opacity='.25'/%3E" +
		"%3Crect%20width='" + strconv.FormatInt(share(filled, goal, int64(width)), 10) + "'%20height='10'%20rx='5'%20fill='%23E4A11B'/%3E" +
		"%3C/svg%3E)"
}

// percent writes net as a share of goal, rounded down and uncapped: "124%".
func percent(net, goal int64) string {
	return strconv.FormatInt(share(net, goal, 100), 10) + "%"
}

// share is part×scale/whole rounded down, for whole > 0, and 0 for part ≤ 0: exact for
// any part up to math.MaxInt64/scale, past every amount of ugnot there is, and held
// there beyond, so the product never overflows.
func share(part, whole, scale int64) int64 {
	if part <= 0 {
		return 0
	}
	if part > math.MaxInt64/scale {
		part = math.MaxInt64 / scale
	}
	return part * scale / whole
}

// short shortens an address where a reader recognizes it rather than checks it: its
// first eight and last six characters (UI spec §4.13).
func short(a address) string {
	s := a.String()
	if len(s) <= 14 {
		return s
	}
	return s[:8] + "…" + s[len(s)-6:]
}

// addrLink links an address's short form, in a code span, to its address page: Bolo's
// own link, where gnoweb makes no mention (API §5).
func addrLink(a address) string {
	return "[`" + short(a) + "`](" + webPath + ":u/" + a.String() + ")"
}

// gnot writes an amount of ugnot in GNOT: up to six decimals, trailing zeros dropped.
func gnot(ugnot int64) string {
	return amount(ugnot) + " GNOT"
}

// amount writes an amount of ugnot as a number of GNOT, for a column headed GNOT.
func amount(ugnot int64) string {
	sign := ""
	if ugnot < 0 {
		sign, ugnot = "-", -ugnot
	}
	whole, frac := ugnot/1_000_000, ugnot%1_000_000
	out := sign + strconv.FormatInt(whole, 10)
	if frac != 0 {
		f := strconv.FormatInt(frac+1_000_000, 10)[1:]
		out += "." + strings.TrimRight(f, "0")
	}
	return out
}

// when writes a Unix time in UTC.
func when(unix int64) string {
	return stamp(unix) + " UTC"
}

// stamp writes a Unix time in UTC without saying so, for a column that does.
func stamp(unix int64) string {
	return time.Unix(unix, 0).UTC().Format("2006-01-02 15:04")
}

// day writes a Unix time's day in UTC, where the minute is written nearby: a figure's
// caption, under the full time in the dates line.
func day(unix int64) string {
	return time.Unix(unix, 0).UTC().Format("2006-01-02")
}

// left writes a real timer's countdown (UI spec §5, Countdown): whole days left, then
// "less than a day left".
func left(until int64) string {
	d := (until - now()) / secondsPerDay
	if d < 1 {
		return "less than a day left"
	}
	return count(int(d), "day left", "days left")
}

// count writes n of something: one, or many.
func count(n int, one, many string) string {
	if n == 1 {
		return "1 " + one
	}
	return strconv.Itoa(n) + " " + many
}

// days writes a duration in seconds as whole days.
func days(seconds int64) string {
	return strconv.FormatInt(seconds/secondsPerDay, 10) + " days"
}

// statusWord names a status in the UI spec's words (§8.1).
func statusWord(status string) string {
	switch status {
	case statusOpen:
		return "Open"
	case statusClosed:
		return "Closed to new donations"
	}
	return "Completed"
}

// modeWord names a custody mode in the UI spec's words (§8.1).
func modeWord(mode string) string {
	if mode == modeEscrow {
		return "Escrow"
	}
	return "Direct"
}

// inline escapes text for an inline slot: sanitize.InlineText, which leaves no link and
// no image, then the mentions gnoweb would still make links of — "@name", and an
// address after a space — each to a page whose owner writes it (API §5). A backslash
// keeps "@" as it reads; a no-break space looks like the space it replaces.
func inline(s string) string {
	s = strings.ReplaceAll(sanitize.InlineText(s), "@", `\@`)
	return strings.ReplaceAll(s, " g1", "\u00a0g1")
}

// lineStart escapes text for an inline slot that opens a line — the title's heading,
// the notice's line — where gnoweb also links an address with nothing before it:
// "&#103;" reads as the "g" it replaces. Only there: gnoweb's table of contents shows a
// card's heading as written, and a card's title sits in a link's text, where gnoweb
// makes no mention (API §5).
func lineStart(s string) string {
	s = inline(s)
	if strings.HasPrefix(s, "g1") {
		s = "&#103;" + s[1:]
	}
	return s
}

render_test.gno

package bolo

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

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

func TestGnot(t *testing.T) {
	for ugnot, want := range map[int64]string{
		0: "0 GNOT", 1: "0.000001 GNOT", 1_500_000: "1.5 GNOT", 5_000_000: "5 GNOT",
		1_234_567: "1.234567 GNOT", 10_000_010: "10.00001 GNOT", -2_500_000: "-2.5 GNOT",
	} {
		if got := gnot(ugnot); got != want {
			t.Errorf("gnot(%d) = %q, want %q", ugnot, got, want)
		}
	}
	if got := when(0); got != "1970-01-01 00:00 UTC" {
		t.Errorf("when(0) = %q", got)
	}
	for n, want := range map[int]string{0: "0 donors", 1: "1 donor", 2: "2 donors"} {
		if got := count(n, "donor", "donors"); got != want {
			t.Errorf("count(%d) = %q, want %q", n, got, want)
		}
	}
}

func TestParsers(t *testing.T) {
	for s, want := range map[string]int{"1": 1, "20": 20, "999999999": 999999999} {
		if n, ok := parsePage(s); !ok || n != want {
			t.Errorf("parsePage(%q) = %d, %t", s, n, ok)
		}
	}
	for _, s := range []string{"", "0", "01", "-1", "+1", "1x", " 1", "1000000000"} {
		if _, ok := parsePage(s); ok {
			t.Errorf("parsePage(%q) accepted", s)
		}
	}
	good := testutils.TestAddress("renderer").String()
	if _, ok := parseAddress(good); !ok {
		t.Errorf("parseAddress refused %s", good)
	}
	last := "q"
	if good[39:] == "q" {
		last = "p"
	}
	badSum := good[:39] + last // 40 characters, a lowercase "g", a wrong checksum
	for _, s := range []string{"", "notanaddress", strings.ToUpper(good), good[:39], good + "x", badSum} {
		if _, ok := parseAddress(s); ok {
			t.Errorf("parseAddress(%q) accepted", s)
		}
	}
	if q, ok := parseQuery("page=2&&size=1000000&x"); !ok || q["page"] != "2" || q["size"] != "1000000" {
		t.Errorf("parseQuery: %v, %t", q, ok)
	}
	if _, ok := parseQuery("page=1&page=2"); ok {
		t.Errorf("parseQuery accepted a key twice")
	}
}

// TestRenderNotFound: every path that fails gets the one not-found page, which echoes
// nothing from the request (API §5).
func TestRenderNotFound(t *testing.T) {
	c := testCampaign(9961, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	c.receipts.Set(seqid.ID(1).Binary(), &receipt{seq: 1, donor: testutils.TestAddress("donor"), amount: 5})
	bad := []string{
		"c/0" + id, "c/x", "c/" + id + "/", "c/" + id + "/r/x", "c/" + id + "/r/0", "c/" + id + "/r/2",
		"c/" + id + "/donations?page=-1", "c/" + id + "/donations?page=0", "c/" + id + "/ledger?page=x",
		"c/" + id + "/updates?page=1&page=2", "c/" + id + "/nope", "c/99999", "c/", "c/" + id + "/r/1/x",
		"u/notanaddress", "u/" + strings.ToUpper(testutils.TestAddress("renderer").String()),
		"u/" + testutils.TestAddress("renderer").String() + "/nope",
		"u/" + testutils.TestAddress("renderer").String() + "/gave?after=0x",
		"?after=x", "?after=", "?cat=nope", "?cat=", "c?cat=nope", "c/" + id + "/r?page=0", "u/", "u?address=a&address=b",
		"about/x", "x", "/", "//", strings.Repeat("c/", 200),
	}
	for _, path := range bad {
		if got := Render(path); got != notFound {
			t.Errorf("Render(%q) isn't the not-found page:\n%s", path, got)
		}
	}
	// A key the route doesn't take is ignored.
	if Render("c/"+id+"/donations?size=1000000") == notFound || Render("?page=-1") == notFound {
		t.Errorf("an ignored key made the page fail")
	}
}

// injection is what a stranger, a moderator or an organizer might write to pass for
// Bolo, plant a link, an image, raw HTML or a mention, open an alert or one of
// gnoweb's blocks, hide characters, or break out of their slot — shapes the writes'
// own checks let through, the hidden characters stripped (API §2.3).
const injection = "[!WARNING] [Verify](https://evil.example) **BOLO** # x | y ] ) ! <b>raw</b> ![i](https://evil.example/i.png) \u200b\u202e @bolo_help </gno-columns> <gno-columns-sep> <gno-form path=\"u\">"

// mention reports whether s holds what gnoweb makes a link of on its own: an "@" no
// backslash escapes, or an address after a space or opening a line's text.
func mention(s string) bool {
	for i := 0; i < len(s); i++ {
		if s[i] == '@' && (i == 0 || s[i-1] != '\\') {
			return true
		}
	}
	for _, line := range strings.Split(s, "\n") {
		if strings.HasPrefix(strings.TrimLeft(line, "#>- "), "g1") {
			return true
		}
	}
	return strings.Contains(s, " g1")
}

// ownTags reports whether every tag of gnoweb's blocks in s that isn't escaped stands
// on a line of its own, as Bolo writes them — the only place gnoweb reads one — and the
// columns open as often as they close.
func ownTags(s string) bool {
	lines := map[string]bool{"<gno-columns>": true, "<gno-columns-sep />": true, "</gno-columns>": true,
		"<gno-form path=\"u\">": true, "  <gno-input name=\"address\" placeholder=\"g1…\" />": true, "</gno-form>": true}
	for _, line := range strings.Split(s, "\n") {
		own := lines[line] || line == "  <gno-input name=\"amount\" placeholder=\"7.5\" />" ||
			strings.HasPrefix(line, "<gno-form path=\"c/") && strings.HasSuffix(line, "/give\">") && isDigits(line[len("<gno-form path=\"c/"):len(line)-len("/give\">")])
		for i := 0; i+5 <= len(line); i++ {
			if (line[i:i+5] == "<gno-" || line[i:i+5] == "</gno") && (i == 0 || line[i-1] != '\\') && !own {
				return false
			}
		}
	}
	return strings.Count(s, "\n<gno-columns>\n") == strings.Count(s, "\n</gno-columns>\n")
}

// isDigits reports whether s is one or more decimal digits.
func isDigits(s string) bool {
	for i := 0; i < len(s); i++ {
		if s[i] < '0' || s[i] > '9' {
			return false
		}
	}
	return s != ""
}

// TestRenderEscapes: every text slot is escaped by who wrote it. Strangers' and
// moderators' text can carry no link, no image, no mention and none of gnoweb's
// blocks; the organizer's story and updates stay inside their quote, below Bolo's own
// blocks; the alerts are Bolo's — the notice on the campaign's page, the refund banner
// on a refunded gift's receipt — which no user text can open; addresses sit in code
// spans (API §5).
func TestRenderEscapes(t *testing.T) {
	phisher := testutils.TestAddress("phisher").String()
	inj := phisher + " " + injection + " " + phisher
	story := "[!WARNING] Notice from Bolo's moderator\nHelp us.\n## Check it yourself\n- Escrow: `g1fake`\n| a | b |\n[ok](https://ok.example) @bolo_help"
	body := "## Act\n[Give 5 GNOT](https://evil.example)"
	donor := testutils.TestAddress("donor")
	c := testCampaign(9962, modeEscrow, 0)
	c.text.title, c.text.description = inj, story
	c.text.imageCID, c.text.imageAlt = "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG", inj
	c.state.notice = inj
	id, unstore := storeCampaign(c)
	defer unstore()
	c.receipts.Set(seqid.ID(1).Binary(), &receipt{seq: 1, donor: donor, amount: 5, message: inj})
	c.state.donationCount, c.state.recent[0], c.state.recentNext = 1, 1, 1
	c.updates.Set(seqid.ID(1).Binary(), &update{seq: 1, body: body})
	c.state.updateCount = 1
	c.contributions.Set(donor.String(), &contribution{amount: 5, refunded: 1, public: true})
	c.refunds.Set(seqid.ID(1).Binary(), &refund{seq: 1, amount: 1, donor: donor, kind: "open"})
	c.withdrawals.Set(seqid.ID(1).Binary(), &withdrawal{seq: 1, amount: 1, to: c.beneficiary})
	byOrganizer.Set(c.organizer.String()+"/"+c.id.Binary(), true)
	defer byOrganizer.Remove(c.organizer.String() + "/" + c.id.Binary())

	org := "u/" + c.organizer.String()
	for _, path := range []string{"c/" + id, "c/" + id + "/r/1", "c/" + id + "/donations", "c/" + id + "/updates", "c/" + id + "/ledger", "c/" + id + "/give", "c/" + id + "/give?amount=5", "?cat=water", org, org + "/organized"} {
		out := Render(path)
		// The organizer's own text, quoted, keeps its links and mentions: without it,
		// nothing on the page may carry one.
		rest := strings.ReplaceAll(strings.ReplaceAll(out, sanitize.Blockquote(story), ""), sanitize.Blockquote(body), "")
		if strings.Contains(rest, "](https://") || mention(rest) {
			t.Errorf("%s: a link, an image or a mention outside the organizer's quote:\n%s", path, rest)
		}
		if strings.Contains(strings.ReplaceAll(rest, `\<`, ""), "<b>") || strings.ContainsAny(rest, "\u200b\u202e") {
			t.Errorf("%s: raw HTML or a hidden character outside the organizer's quote:\n%s", path, rest)
		}
		if !ownTags(rest) {
			t.Errorf("%s: a block's tag Bolo didn't write:\n%s", path, rest)
		}
		alerts, entities := 0, 0
		switch path {
		case "c/" + id:
			alerts, entities = 1, 2
			if !strings.HasPrefix(out, "> [!WARNING] Notice from Bolo's moderator\n> ") {
				t.Errorf("the notice isn't the alert at the top of the page:\n%s", out)
			}
		case "c/" + id + "/r/1":
			alerts = 1
			if !strings.HasPrefix(out, "> [!CAUTION] Refunded since\n> 0.000001 GNOT went back to this donor after this gift.\n\n# Gift receipt") {
				t.Errorf("the refund banner isn't the alert at the top of the receipt:\n%s", out)
			}
		}
		if n := strings.Count("\n"+out, "\n> [!"); n != alerts {
			t.Errorf("%s: %d alerts, want %d", path, n, alerts)
		}
		// The title's heading and the notice's line open with an address; nothing
		// else may write its "g" as an entity, which a table of contents shows as is.
		if n := strings.Count(out, "&#103;"); n != entities {
			t.Errorf("%s: %d entities, want %d", path, n, entities)
		}
	}
	page := Render("c/" + id)
	verifyAt, storyAt := strings.Index(page, "## Check it yourself\n\n- **Escrow** `g1"), strings.Index(page, "## In the organizer's words")
	if verifyAt < 0 || storyAt < 0 || verifyAt > storyAt {
		t.Errorf("the verification block isn't before the story: %d, %d", verifyAt, storyAt)
	}
	if !strings.Contains(page, "## In the organizer's words\n"+sanitize.Blockquote(story)) {
		t.Errorf("the story isn't quoted under its heading:\n%s", page)
	}
	if !strings.Contains(page, "](ipfs://QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG)") {
		t.Errorf("the photo is missing:\n%s", page)
	}
}

// TestRenderHiddenPhoto: a hidden photo is gone from the campaign's page, its
// description with it (API §3.1, §3.5, §5).
func TestRenderHiddenPhoto(t *testing.T) {
	c := testCampaign(9968, modeEscrow, 0)
	c.text.imageCID, c.text.imageAlt = "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG", "The village well"
	id, unstore := storeCampaign(c)
	defer unstore()
	if page := Render("c/" + id); !strings.Contains(page, "![The village well](ipfs://") {
		t.Errorf("the photo is missing:\n%s", page)
	}
	c.state.imageHidden = true
	if page := Render("c/" + id); strings.Contains(page, "ipfs://") || strings.Contains(page, "The village well") {
		t.Errorf("a hidden photo is still on the page:\n%s", page)
	}
}

// TestRenderDelisted: a delisted campaign shows its notice and no donate links, and is
// on no list that promotes (API §5).
func TestRenderDelisted(t *testing.T) {
	org := testutils.TestAddress("renderorg")
	cs, unindex := indexCampaigns(9963, 2, org, org)
	defer unindex()
	off := cs[0]
	off.state.listed, off.state.notice = false, "Under review"
	dropActive(off)
	defer addActive(off)
	if page := Render("c/9963"); !strings.Contains(page, "Under review") || strings.Contains(page, "## Give") || strings.Contains(page, "func=Donate&id=9963&tip") {
		t.Errorf("a delisted campaign's page:\n%s", page)
	}
	if !strings.Contains(Render("c/9964"), "## Give") {
		t.Errorf("a listed campaign has no donate links")
	}
	for _, path := range []string{"u/" + org.String(), "u/" + org.String() + "/organized"} {
		if addr := Render(path); strings.Contains(addr, ":c/9963)") || !strings.Contains(addr, ":c/9964)") {
			t.Errorf("%s lists the delisted campaign, or misses the listed one:\n%s", path, addr)
		}
	}
	if home := Render("?cat=animals"); strings.Contains(home, ":c/9963)") || !strings.Contains(home, ":c/9964)") {
		t.Errorf("the home page:\n%s", home)
	}
}

// TestRenderBounds: a path longer than any valid one gets the not-found page before it
// is parsed, and a page's size never comes from the query: ?size= is ignored (API §5).
func TestRenderBounds(t *testing.T) {
	if got := Render("?pad=" + strings.Repeat("a", 300)); got != notFound {
		t.Errorf("a 305-byte path rendered")
	}
	c := testCampaign(9965, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	for i := 1; i <= 25; i++ {
		c.receipts.Set(seqid.ID(i).Binary(), &receipt{seq: uint64(i), donor: testutils.TestAddress("donor"), amount: 5})
	}
	if n := strings.Count(Render("c/"+id+"/donations?size=50"), "[receipt]("); n != 20 {
		t.Errorf("?size=50: %d gifts on the page, want 20", n)
	}
	if n := strings.Count(Render("c/"+id+"/donations?page=2"), "[receipt]("); n != 5 {
		t.Errorf("page 2: %d gifts, want 5", n)
	}
}

// TestRenderGiveLinks: the one-click donate links appear only while the campaign is
// open, listed, and Bolo isn't paused (API §5).
func TestRenderGiveLinks(t *testing.T) {
	c := testCampaign(9966, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	defer func() { paused = false }()
	give := func() bool { return strings.Contains(Render("c/"+id), "## Give") }
	if !give() {
		t.Errorf("an open, listed campaign has no donate links")
	}
	paused = true
	if give() {
		t.Errorf("donate links while Bolo is paused")
	}
	paused = false
	c.deadline = now() - 1
	if give() {
		t.Errorf("donate links past the deadline")
	}
	c.deadline = 0
	c.state.status = statusClosed
	if give() {
		t.Errorf("donate links on a closed campaign")
	}
}

// TestRenderActLinks: Withdraw is offered only while the escrow holds coins, and Close
// whenever someone could close: the organizer while the campaign is open, anyone once
// CanClose says so (API §5).
func TestRenderActLinks(t *testing.T) {
	c := testCampaign(9967, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	page := func() string { return Render("c/" + id) }
	closeBy := func(who string) string { return "func=Close&id=" + id + "): " + who }
	if p := page(); strings.Contains(p, "[Withdraw](") || !strings.Contains(p, closeBy("the organizer")) {
		t.Errorf("an empty escrow offers Withdraw, or the organizer can't close:\n%s", p)
	}
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 5)))
	if p := page(); !strings.Contains(p, "[Withdraw](") {
		t.Errorf("an escrow holding coins offers no Withdraw:\n%s", p)
	}
	c.deadline = now() - 1 // passed, not recorded: anyone may close
	if p := page(); !strings.Contains(p, closeBy("anyone")) {
		t.Errorf("a passed deadline nobody recorded offers no Close to anyone:\n%s", p)
	}
	c.deadline, c.state.status = 0, statusClosed
	if p := page(); strings.Contains(p, "[Close](") {
		t.Errorf("a closed campaign offers Close:\n%s", p)
	}
	// Withdraw stops when the beneficiary's window ends; Finalize appears when it can.
	c.state.raised, c.state.withdrawn, c.state.everWithdrawn, c.state.closedAt = 7_000_000, 2_000_000, true, now()
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 5_000_000))) // the 5 GNOT the books hold
	if p := page(); !strings.Contains(p, "[Withdraw](") || strings.Contains(p, "[Finalize](") {
		t.Errorf("closed, the beneficiary's window running: no Withdraw, or a Finalize:\n%s", p)
	}
	c.state.closedAt = now() - c.params.ExitDelay
	if p := page(); strings.Contains(p, "[Withdraw](") || !strings.Contains(p, "func=Finalize&id="+id+"): anyone") {
		t.Errorf("closed, the beneficiary's window over: a Withdraw, or no Finalize:\n%s", p)
	}
}

// TestRenderEmptyPages: a page with nothing to show says so, and says "None on this
// page." on a later page or when a "More" follows — the home page once its read budget
// went on passed deadlines, an address list whose newest are all delisted, a campaign's
// own lists past their first page (API §5).
func TestRenderEmptyPages(t *testing.T) {
	org := testutils.TestAddress("emptyorg")
	if home := Render("?cat=animals"); !strings.Contains(home, "No campaigns here yet.") {
		t.Errorf("an empty category:\n%s", home)
	}
	if later := Render("?cat=animals&after=1"); !strings.Contains(later, "None on this page.") || strings.Contains(later, "[More](") {
		t.Errorf("a later page with nothing on it:\n%s", later)
	}
	cs, unindex := indexCampaigns(9600, 4*listPage+1, org, org)
	defer unindex()
	for _, c := range cs {
		c.deadline = now() - 1
	}
	if home := Render("?cat=animals"); !strings.Contains(home, "None on this page.") || !strings.Contains(home, "[More](") {
		t.Errorf("a page of passed deadlines, with more to read:\n%s", home)
	}
	for _, c := range cs {
		c.state.listed = false
	}
	for _, p := range []string{"u/" + org.String(), "u/" + org.String() + "/organized"} {
		if page := Render(p); !strings.Contains(page, "None on this page.") || !strings.Contains(page, "[More](") {
			t.Errorf("%s: a page of delisted campaigns, with more to come:\n%s", p, page)
		}
	}
	other := "u/" + testutils.TestAddress("nobody").String() + "/organized"
	if first, later := Render(other), Render(other+"?after=1"); !strings.Contains(first, "None.") || !strings.Contains(later, "None on this page.") {
		t.Errorf("an empty address list, first and later pages:\n%s\n%s", first, later)
	}
	c := testCampaign(9969, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	for route, first := range map[string]string{"donations": "No gifts yet.", "ledger": "None.\n\n## Refunds\n\nNone.", "updates": "No updates yet."} {
		later := strings.ReplaceAll(strings.ReplaceAll(first, "yet.", "on this page."), "None.", "None on this page.")
		if p1, p2 := Render("c/"+id+"/"+route), Render("c/"+id+"/"+route+"?page=2"); !strings.Contains(p1, first) || !strings.Contains(p2, later) {
			t.Errorf("an empty %s list, pages 1 and 2:\n%s\n%s", route, p1, p2)
		}
	}
	var b strings.Builder
	writeListed(&b, []CampaignView{{Listed: false}}, true)
	if b.String() != "None on this page.\n\n" {
		t.Errorf("a list of delisted campaigns with more to come: %q", b.String())
	}
	b.Reset()
	writeListed(&b, nil, false)
	if b.String() != "None.\n\n" {
		t.Errorf("an empty list: %q", b.String())
	}
}

// giveTo records a public gift of amount ugnot from donor to c, as Donate would for
// the pages to show: its receipt, the recent gifts, the counts, the donor's
// contribution, and the donor's list.
func giveTo(c *campaign, seq uint64, donor address, amount int64) {
	s := c.state
	c.receipts.Set(seqid.ID(seq).Binary(), &receipt{seq: seq, donor: donor, amount: amount, at: now(), message: "Courage"})
	s.recent[s.recentNext%recentSize] = seq
	s.recentNext++
	s.donationCount++
	s.donorCount++
	s.raised += amount
	c.contributions.Set(donor.String(), &contribution{amount: amount, public: true})
	byDonor.Set(donor.String()+"/"+c.id.Binary(), true)
}

// pageLinks returns the paths of a page's links to Bolo's own pages, and the
// functions its transaction links call.
func pageLinks(page string) (paths, funcs []string) {
	at := "](" + webPath
	for i := strings.Index(page, at); i >= 0; i = strings.Index(page, at) {
		page = page[i+len(at):]
		end := strings.Index(page, ")")
		target := page[:end]
		switch {
		case target == "":
			paths = append(paths, "")
		case target[0] == ':':
			paths = append(paths, target[1:])
		case strings.HasPrefix(target, "$help&func="):
			name, _, _ := strings.Cut(strings.TrimPrefix(target, "$help&func="), "&")
			funcs = append(funcs, name)
		}
	}
	return paths, funcs
}

// TestRenderLinks: every link a page writes leads to a page, every transaction link
// calls one of Bolo's writes, and every prefix of every path renders a page too, as
// gnoweb's header links each one (UI spec §4.13) — on campaigns of each kind.
func TestRenderLinks(t *testing.T) {
	org, ben, donor := testutils.TestAddress("linkorg"), testutils.TestAddress("linkben"), testutils.TestAddress("linkdonor")
	cs, unindex := indexCampaigns(9700, 4, org, ben)
	defer unindex()
	open, direct, closed, settled := cs[0], cs[1], cs[2], cs[3]
	direct.mode = modeDirect
	closed.state.status, closed.state.closedAt, closed.state.closeReason = statusClosed, now(), reasonOrganizer
	settled.state.status, settled.state.closedAt, settled.state.closeReason = statusSettled, now(), reasonOrganizer
	dropActive(closed)
	dropActive(settled)
	for _, c := range cs {
		giveTo(c, 1, donor, 5_000_000)
		defer byDonor.Remove(donor.String() + "/" + c.id.Binary())
	}
	open.updates.Set(seqid.ID(1).Binary(), &update{seq: 1, at: now(), body: "Started."})
	open.state.updateCount = 1
	open.withdrawals.Set(seqid.ID(1).Binary(), &withdrawal{seq: 1, amount: 1_000_000, at: now(), to: ben})
	open.state.withdrawn, open.state.everWithdrawn = 1_000_000, true
	closed.refunds.Set(seqid.ID(1).Binary(), &refund{seq: 1, amount: 1_000_000, at: now(), donor: donor, kind: windowOpen})
	closed.state.refunded = 1_000_000
	for _, c := range cs { // the bank holds what the books say
		if held := trackedBalance(c); held > 0 {
			testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", held)))
		}
	}

	writes := map[string]bool{"Donate": true, "Refund": true, "Withdraw": true, "Close": true, "Finalize": true, "PostUpdate": true, "CreateCampaign": true}
	seen := map[string]bool{}
	queue := []string{"", "about", "params", "u", "u?address=" + donor.String(), "u?address=nope", "c/9700/give?amount=7.5", "c/9700/give?amount=nope"}
	for _, c := range cs {
		queue = append(queue, "c/"+idString(c.id)+"/r/1")
	}
	for len(queue) > 0 {
		path := queue[0]
		queue = queue[1:]
		if seen[path] {
			continue
		}
		seen[path] = true
		page := Render(path)
		if page == notFound {
			t.Errorf("%q: not found", path)
			continue
		}
		paths, funcs := pageLinks(page)
		for _, f := range funcs {
			if !writes[f] {
				t.Errorf("%q links to a transaction calling %q", path, f)
			}
		}
		route, _, _ := strings.Cut(path, "?")
		segs := strings.Split(route, "/")
		for i := 1; i < len(segs); i++ {
			paths = append(paths, strings.Join(segs[:i], "/"))
		}
		queue = append(queue, paths...)
	}
	for _, want := range []string{"c", "c/9700", "c/9700/r", "c/9700/give", "c/9700/donations", "c/9700/ledger", "c/9700/updates", "u", "u/" + org.String(), "u/" + ben.String(), "u/" + donor.String()} {
		if !seen[want] {
			t.Errorf("no link or prefix reaches %q", want)
		}
	}
}

// TestRenderPrefixes: the prefixes gnoweb's header links render the pages they stand
// for: "c" the home page, "c/{id}/r" the campaign's gifts (UI spec §4.13).
func TestRenderPrefixes(t *testing.T) {
	c := testCampaign(9971, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	if Render("c") != Render("") || Render("c?cat=water") != Render("?cat=water") {
		t.Errorf("c isn't the home page")
	}
	if Render("c/"+id+"/r") != Render("c/"+id+"/donations") || Render("c/"+id+"/r?page=2") != Render("c/"+id+"/donations?page=2") {
		t.Errorf("c/%s/r isn't the gifts page", id)
	}
}

// TestRenderLookup: "u" is a form to find an address, which submits back as
// ?address=: a valid address gets its page, anything else the form again with one
// fixed line, echoing nothing (API §5).
func TestRenderLookup(t *testing.T) {
	form := Render("u")
	if !strings.Contains(form, "# Find an address") || !strings.Contains(form, "\n<gno-form path=\"u\">\n  <gno-input name=\"address\" placeholder=\"g1…\" />\n</gno-form>\n") || strings.Contains(form, "isn't") {
		t.Errorf("the lookup page:\n%s", form)
	}
	good := testutils.TestAddress("lookedup").String()
	if got := Render("u?address=" + good); got != Render("u/"+good) {
		t.Errorf("a valid address doesn't get its page:\n%s", got)
	}
	for _, bad := range []string{"", "notanaddress", strings.ToUpper(good), good + "x", "%3Cb%3Eecho%3C/b%3E", "<b>echo</b>"} {
		got := Render("u?address=" + bad)
		if !strings.Contains(got, "That isn't a gno.land address.") || !strings.Contains(got, "<gno-form") {
			t.Errorf("u?address=%s: no form, or no line saying why:\n%s", bad, got)
		}
		if bad != "" && strings.Contains(got, bad) {
			t.Errorf("u?address=%s: the page echoes it:\n%s", bad, got)
		}
	}
}

// TestRenderGiveRoom: the donate links offer only what Donate would take — the presets
// within the room the escrow cap leaves, and the room said — and none, with a banner,
// when not even the smallest gift fits (API §5).
func TestRenderGiveRoom(t *testing.T) {
	c := testCampaign(9972, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	saved := escrowCap
	defer func() { escrowCap = saved }()
	presetLink := func(page string, ugnot int64) bool {
		return strings.Contains(page, "&.send="+strconv.FormatInt(ugnot, 10)+"ugnot&")
	}
	escrowCap = 30_000_000
	c.state.raised = 12_000_000 // 18 GNOT of room
	page := Render("c/" + id)
	if !presetLink(page, 5_000_000) || !presetLink(page, 10_000_000) || presetLink(page, 20_000_000) || presetLink(page, 50_000_000) {
		t.Errorf("presets past the room, or none within it:\n%s", page)
	}
	if !strings.Contains(page, "[Another amount](/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo/v0:c/"+id+"/give)") || !strings.Contains(page, "It can take 18 GNOT more for now") {
		t.Errorf("no other amount, or the room isn't said:\n%s", page)
	}
	c.state.raised = 29_500_000 // half a GNOT: less than the smallest gift
	page = Render("c/" + id)
	if strings.Contains(page, "## Give") || !strings.Contains(page, "> [!NOTE] Full for now\n") {
		t.Errorf("donate links with no room, or no banner:\n%s", page)
	}
	escrowCap = 0
	if page = Render("c/" + id); !presetLink(page, 50_000_000) || strings.Contains(page, "It can take") {
		t.Errorf("no cap, yet a preset left out or a room said:\n%s", page)
	}
	escrowCap = 30_000_000
	c.mode = modeDirect // the cap is escrow's
	if page = Render("c/" + id); !presetLink(page, 50_000_000) || strings.Contains(page, "Full for now") {
		t.Errorf("a direct campaign held to the escrow cap:\n%s", page)
	}
	// The room is the cap less the tracked balance, never the bank's, and a preset
	// under the smallest gift is left out too.
	c.mode = modeEscrow
	c.state.raised, c.state.withdrawn, c.state.refunded, c.state.everWithdrawn = 40_000_000, 20_000_000, 2_000_000, true // 18 GNOT tracked
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 27_000_000)))                             // and 9 sent outside Bolo
	page = Render("c/" + id)
	if !presetLink(page, 5_000_000) || !presetLink(page, 10_000_000) || presetLink(page, 20_000_000) || !strings.Contains(page, "It can take 12 GNOT more for now") {
		t.Errorf("the room isn't the cap less the tracked balance:\n%s", page)
	}
	savedMin := minDonation
	minDonation = 7_000_000
	if page = Render("c/" + id); presetLink(page, 5_000_000) || !presetLink(page, 10_000_000) {
		t.Errorf("a preset under the smallest gift:\n%s", page)
	}
	minDonation = savedMin
	escrowCap = 23_000_000 // exactly 5 GNOT of room
	if page = Render("c/" + id); !presetLink(page, 5_000_000) || presetLink(page, 10_000_000) {
		t.Errorf("a preset equal to the room left out:\n%s", page)
	}
	escrowCap = 19_000_000 // room for exactly the smallest gift
	if page = Render("c/" + id); !strings.Contains(page, "## Give") || presetLink(page, 5_000_000) || !strings.Contains(page, "It can take 1 GNOT more for now") {
		t.Errorf("room for exactly the smallest gift:\n%s", page)
	}
}

// TestRenderBanner: the campaign's page shows the one state banner the UI spec's state
// matrix gives its state (§6), and none while nothing is out of the ordinary.
func TestRenderBanner(t *testing.T) {
	c := testCampaign(9973, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	defer func() { paused = false }()
	banner := func() string {
		page := Render("c/" + id)
		if n := strings.Count("\n"+page, "\n> [!"); n > 1 {
			t.Errorf("%d banners:\n%s", n, page)
		}
		i := strings.Index(page, "> [!")
		if i < 0 {
			return ""
		}
		return page[i : i+strings.Index(page[i:], "\n\n")]
	}
	if b := banner(); b != "" {
		t.Errorf("an open campaign shows a banner: %q", b)
	}
	paused = true
	if b := banner(); !strings.HasPrefix(b, "> [!CAUTION] Bolo is paused\n") {
		t.Errorf("paused: %q", b)
	}
	paused = false
	saved, savedMin := escrowCap, minDonation
	escrowCap = 500_000 // below the smallest gift: no withdrawal makes room
	if b := banner(); b != "> [!NOTE] Full for now\n> Bolo's escrow cap is set below its smallest gift, so no campaign in escrow can take a gift for now." {
		t.Errorf("a cap below the smallest gift: %q", b)
	}
	escrowCap, c.state.raised = 2_000_000, 1_500_000 // half a GNOT of room, under the smallest gift
	if b := banner(); b != "> [!NOTE] Full for now\n> This campaign can't take more until the beneficiary withdraws." {
		t.Errorf("a full escrow: %q", b)
	}
	escrowCap = minDonation // a cap of exactly the smallest gift: a withdrawal makes room
	if b := banner(); b != "> [!NOTE] Full for now\n> This campaign can't take more until the beneficiary withdraws." {
		t.Errorf("a full escrow, its cap the smallest gift: %q", b)
	}
	escrowCap, minDonation, c.state.raised = saved, savedMin, 0
	c.params.DormancyPeriod = 30 * secondsPerDay // the campaign's own, not the live setting's 90
	c.createdAt = now() - c.params.DormancyPeriod
	if b := banner(); b != "> [!NOTE] Inactive\n> No gift and no update for 30 days: anyone can close it now." {
		t.Errorf("dormant: %q", b)
	}
	c.createdAt = now()
	s := c.state
	s.status, s.closedAt, s.closeReason, s.raised = statusClosed, now(), reasonOrganizer, 7_000_000
	if b := banner(); !strings.HasPrefix(b, "> [!NOTE] Closed to new donations\n> Closed by its organizer on ") || !strings.Contains(b, "The beneficiary can withdraw the 7 GNOT held until ") || !strings.Contains(b, ", 60 days left; after that, donors can reclaim their share.") {
		t.Errorf("closed, before the exit window: %q", b)
	}
	s.closedAt, s.everWithdrawn = now()-c.params.ExitDelay, true
	if b := banner(); !strings.Contains(b, "The beneficiary didn't collect in time: a donor who hasn't reclaimed their share yet can, at any time.") {
		t.Errorf("closed, the exit window open: %q", b)
	}
	s.closeReason = reasonDormant
	if b := banner(); !strings.Contains(b, "after 30 days with no gift and no update.") {
		t.Errorf("closed as dormant: %q", b)
	}
	s.closeReason, s.raised = reasonDeadline, 0
	if b := banner(); !strings.HasSuffix(b, "It ended at its deadline, on "+when(s.closedAt)+".") {
		t.Errorf("ended at its deadline, nothing held: %q", b)
	}
	s.status = statusSettled
	if b := banner(); b != "> [!SUCCESS] Completed\n> Closed to new donations on "+when(s.closedAt)+", then settled: the organizer's deposit went back to them." {
		t.Errorf("settled: %q", b)
	}
}

// TestRenderMode: the mode in words says what it means now, with the refund link
// while a refund window is open to some donor (UI spec §4.3).
func TestRenderMode(t *testing.T) {
	c := testCampaign(9974, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	mode := func() string {
		page := Render("c/" + id)
		i := strings.Index(page, "\n**Escrow**: ")
		if i < 0 {
			i = strings.Index(page, "\n**Direct**: ")
		}
		if i < 0 {
			t.Fatalf("no mode line:\n%s", page)
		}
		return page[i+1 : i+1+strings.Index(page[i+1:], "\n")]
	}
	refund := " [Refund](/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo/v0$help&func=Refund&id=" + id + ")"
	if m := mode(); m != "**Escrow**: the gifts stay in escrow until the beneficiary withdraws them. Until then, a donor can take their gift back." {
		t.Errorf("escrow, nothing given: %q", m)
	}
	c.state.raised = 5_000_000
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 5_000_000))) // the bank holds what the books say
	if m := mode(); !strings.HasSuffix(m, "a donor can take their gift back."+refund) {
		t.Errorf("escrow, gifts held, nothing withdrawn: %q", m)
	}
	c.state.status, c.state.closedAt = statusClosed, now() // closed, the beneficiary's window running
	if m := mode(); !strings.HasSuffix(m, "a donor can take their gift back."+refund) {
		t.Errorf("escrow, closed, nothing withdrawn, the window running: %q", m)
	}
	c.state.closedAt = now() - c.params.ExitDelay // never withdrawn, the window passed
	if m := mode(); m != "**Escrow**: "+"the beneficiary didn't collect in time, so a donor who hasn't reclaimed their share yet can, at any time."+refund {
		t.Errorf("escrow, the beneficiary's window passed with nothing withdrawn: %q", m)
	}
	c.state.status = statusSettled
	if m := mode(); m != "**Escrow**: "+"the beneficiary didn't collect in time, so a donor who hasn't reclaimed their share yet can, at any time."+refund {
		t.Errorf("escrow, settled with nothing withdrawn and coins held: %q", m)
	}
	c.state.refunded = 5_000_000 // every gift back: nothing held
	if m := mode(); m != "**Escrow**: no gift is held any more." {
		t.Errorf("escrow, settled, nothing held: %q", m)
	}
	c.state.status, c.state.closedAt = statusClosed, now()
	if m := mode(); m != "**Escrow**: no gift is held any more." {
		t.Errorf("escrow, closed, nothing held: %q", m)
	}
	c.state.status, c.state.closedAt, c.state.refunded = statusOpen, 0, 0
	c.state.withdrawn, c.state.everWithdrawn = 2_000_000, true
	if m := mode(); m != "**Escrow**: the beneficiary has withdrawn funds, so gifts can't be refunded now." {
		t.Errorf("escrow, after a withdrawal: %q", m)
	}
	c.state.status, c.state.closedAt = statusClosed, now()
	if m := mode(); m != "**Escrow**: the beneficiary has withdrawn funds, so gifts can't be refunded now." {
		t.Errorf("escrow, closed after a withdrawal, the window running: %q", m)
	}
	c.state.closedAt = now() - c.params.ExitDelay
	if m := mode(); m != "**Escrow**: "+"the beneficiary didn't collect in time, so a donor who hasn't reclaimed their share yet can, at any time."+refund {
		t.Errorf("escrow, the exit window open: %q", m)
	}
	c.mode = modeDirect
	if m := mode(); m != "**Direct**: each gift goes straight to the beneficiary, in the same transaction. Gifts can't be refunded." {
		t.Errorf("direct: %q", m)
	}
}

// TestProgressBar: the bar fills min(net, goal) of its width, its text the uncapped
// percentage; with no goal there is none; a share never overflows (UI spec §5).
func TestProgressBar(t *testing.T) {
	fill := func(bar string) string {
		i := strings.LastIndex(bar, "%3Crect%20width='")
		rest := bar[i+len("%3Crect%20width='"):]
		return rest[:strings.Index(rest, "'")]
	}
	for _, tc := range []struct {
		net, goal   int64
		width       int
		alt, filled string
	}{
		{0, 400, barWide, "0%", "0"},
		{90_000_000, 400_000_000, barWide, "22%", "225"},
		{90_000_000, 400_000_000, barCard, "22%", "90"},
		{496_000_000, 400_000_000, barWide, "124%", "1000"},
		{1, 3, barWide, "33%", "333"},
	} {
		bar := progressBar(tc.net, tc.goal, tc.width)
		if !strings.HasPrefix(bar, "!["+tc.alt+" of the goal](data:image/svg+xml;utf8,%3Csvg%20") || fill(bar) != tc.filled || !strings.Contains(bar, "width='"+strconv.Itoa(tc.width)+"'%20height='10'") {
			t.Errorf("progressBar(%d, %d, %d) = %s", tc.net, tc.goal, tc.width, bar)
		}
	}
	if bar := progressBar(5, 0, barWide); bar != "" {
		t.Errorf("a bar with no goal: %s", bar)
	}
	if got := share(math.MaxInt64, 1, 1000); got <= 0 {
		t.Errorf("share overflowed: %d", got)
	}
	if got := share(-5, 10, 100); got != 0 {
		t.Errorf("share of a negative part: %d", got)
	}
}

// TestRenderCards: campaigns are cards two to a row, a lone last one in a row of its
// own with an empty column; a card says what a donor weighs (UI spec §4.13).
func TestRenderCards(t *testing.T) {
	var b strings.Builder
	v := CampaignView{ID: "1", Title: "Well", Category: "water", Mode: modeEscrow, Status: statusOpen, NetRaised: 3_000_000, Goal: 10_000_000, DonorCount: 1, Bond: 5_000_000, Notice: "Under review"}
	writeCards(&b, []CampaignView{v, v, v})
	out := b.String()
	if strings.Count(out, "<gno-columns>\n") != 2 || strings.Count(out, "</gno-columns>\n\n") != 2 || strings.Count(out, "\n<gno-columns-sep />\n") != 2 ||
		strings.Contains(out, "<gno-columns-sep>") || !strings.HasSuffix(out, "<gno-columns-sep />\n</gno-columns>\n\n") {
		t.Errorf("not two to a row:\n%s", out)
	}
	if !strings.Contains(out, "**3 GNOT** of 10 GNOT · 1 donor  \nEscrow · water · no deadline · bond 5 GNOT · **moderator's notice**\n") {
		t.Errorf("a card's lines:\n%s", out)
	}
	b.Reset()
	v.Goal, v.Deadline, v.Bond, v.Notice, v.Status = 0, now()+3*secondsPerDay+60, 0, "", statusOpen
	writeCards(&b, []CampaignView{v, v})
	if out = b.String(); strings.Contains(out, "data:image") || !strings.Contains(out, "**3 GNOT** raised · 1 donor  \nEscrow · water · 3 days left\n") || strings.HasSuffix(out, "<gno-columns-sep />\n</gno-columns>\n\n") {
		t.Errorf("two cards with no goal:\n%s", out)
	}
	for status, word := range map[string]string{statusClosed: "closed to new donations", statusSettled: "completed"} {
		v.Status = status
		if got := timeWord(v); got != word {
			t.Errorf("timeWord(%s) = %q", status, got)
		}
	}
	if got := left(now() + secondsPerDay - 1); got != "less than a day left" {
		t.Errorf("left, under a day: %q", got)
	}
}

// TestRenderLedgerDirect: a direct campaign's money out says nothing goes out, and
// its page doesn't link there (API §5).
func TestRenderLedgerDirect(t *testing.T) {
	c := testCampaign(9975, modeDirect, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	if page := Render("c/" + id + "/ledger"); strings.Contains(page, "## Withdrawals") || !strings.Contains(page, "**Direct**: each gift went straight to the beneficiary, `"+c.beneficiary.String()+"`") {
		t.Errorf("a direct campaign's money out:\n%s", page)
	}
	if page := Render("c/" + id); strings.Contains(page, "/ledger)") || strings.Contains(page, "| Held in escrow |") {
		t.Errorf("a direct campaign's page links to money out, or shows an escrow:\n%s", page)
	}
}

// TestRenderStart: the home page links to CreateCampaign's form, the deposit attached,
// only while this version takes new campaigns; paused or sunset, it says why, and a
// sunset version points to the registry, where new campaigns start (UI spec §4.13).
func TestRenderStart(t *testing.T) {
	defer func() { paused, sunset = false, false }()
	start := "[Start a campaign](/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo/v0$help&func=CreateCampaign&.send=" + strconv.FormatInt(params.CreationDeposit, 10) + "ugnot) — a " + gnot(params.CreationDeposit) + " deposit, returned when it completes · [Find an address](/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo/v0:u)\n"
	if home := Render(""); !strings.Contains(home, start) {
		t.Errorf("no link to start a campaign:\n%s", home)
	}
	paused = true
	if home := Render(""); strings.Contains(home, "func=CreateCampaign") || !strings.Contains(home, "Bolo is paused: new campaigns and gifts wait until it resumes · [Find an address]") {
		t.Errorf("paused:\n%s", home)
	}
	paused, sunset = false, true
	if home := Render(""); strings.Contains(home, "func=CreateCampaign") || !strings.Contains(home, "This version of Bolo takes no new campaigns: [see where they start](/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo) · [Find an address]") {
		t.Errorf("sunset:\n%s", home)
	}
	paused = true // and sunset, which is for good
	if home, params := Render(""), Render("params"); !strings.Contains(home, "This version of Bolo takes no new campaigns") || !strings.Contains(params, "- New campaigns: not on this version\n") {
		t.Errorf("paused and sunset:\n%s\n%s", home, params)
	}
}

// TestParseGNOT: an amount in GNOT parses only in its one grammar (API §5).
func TestParseGNOT(t *testing.T) {
	for s, want := range map[string]int64{"1": 1_000_000, "7.5": 7_500_000, "7%2C5": 7_500_000, "0.000001": 1, "0.5": 500_000, "999999999999": 999_999_999_999_000_000, "10.25": 10_250_000,
		"+7.5+": 7_500_000, "++7.5": 7_500_000, "1%2C00": 1_000_000, "1%2C0000": 1_000_000, "1.000": 1_000_000} {
		if got, ok := parseGNOT(s); !ok || got != want {
			t.Errorf("parseGNOT(%q) = %d, %t; want %d", s, got, ok, want)
		}
	}
	for _, s := range []string{"", ".5", "1.", "01", "00.5", "-1", "1e3", "1.1234567", "1,5", "7%2c5", "1 ", " 1", "1..5", "7.5.1", "1234567890123", "%2C5", "1%2C",
		"1%2C000", "12%2C500", "+", "+-1", "7+5"} {
		if got, ok := parseGNOT(s); ok {
			t.Errorf("parseGNOT(%q) accepted: %d", s, got)
		}
	}
}

// TestRenderGive: another amount's page asks the amount in gnoweb's form and answers
// one Donate would take with its one-click link; any other gets the form again with
// what the campaign can take, echoing nothing; a campaign that takes no gift says so
// (API §5).
func TestRenderGive(t *testing.T) {
	c := testCampaign(9976, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	saved := escrowCap
	defer func() { escrowCap, paused = saved, false }()
	escrowCap = 30_000_000
	c.state.raised = 12_000_000 // 18 GNOT of room
	page := func(q string) string { return Render("c/" + id + "/give" + q) }
	form := "\n<gno-form path=\"c/" + id + "/give\">\n  <gno-input name=\"amount\" placeholder=\"7.5\" />\n</gno-form>\n"
	if p := page(""); !strings.Contains(p, form) || !strings.Contains(p, "Any amount from 1 GNOT to 18 GNOT, in GNOT.") || strings.Contains(p, "isn't") {
		t.Errorf("the page for another amount:\n%s", p)
	}
	link := "**[Give 7.5 GNOT](/r/g12yg9nh4ncma44emgm8msxe8aavzywt0p95tanv/bolo/v0$help&func=Donate&.send=7500000ugnot&anonymous=false&id=" + id + "&message=&tip=0)**"
	for _, q := range []string{"?amount=7.5", "?amount=7%2C5"} {
		if p := page(q); !strings.Contains(p, link) || strings.Contains(p, "<gno-form") {
			t.Errorf("%s: no link for 7.5 GNOT, or the form again:\n%s", q, p)
		}
	}
	if p := page("?amount=18"); !strings.Contains(p, "&.send=18000000ugnot&") {
		t.Errorf("the whole room refused:\n%s", p)
	}
	for _, bad := range []string{"0.5", "18.000001", "50", "zz9", "7.5.1", "%3Cb%3Eecho", "1234567890123"} {
		p := page("?amount=" + bad)
		if !strings.Contains(p, "That isn't an amount this campaign can take.") || !strings.Contains(p, form) || strings.Contains(p, "func=Donate") {
			t.Errorf("?amount=%s: a link, or no form and line saying why:\n%s", bad, p)
		}
		if strings.Contains(p, bad) {
			t.Errorf("?amount=%s: the page echoes it:\n%s", bad, p)
		}
	}
	if p := page("?amount=1"); !strings.Contains(p, "&.send=1000000ugnot&") {
		t.Errorf("exactly the smallest gift refused:\n%s", p)
	}
	escrowCap = 0
	if p := page(""); !strings.Contains(p, "Any amount from 1 GNOT, in GNOT.") {
		t.Errorf("no cap, yet a most said:\n%s", p)
	}
	// No link while Bolo is paused, the campaign is hidden or closed, or the cap leaves
	// less room than the smallest gift: the page says so, and links back.
	none := func(why string) {
		if p := page("?amount=1"); strings.Contains(p, "func=Donate") || strings.Contains(p, "<gno-form") || !strings.Contains(p, "Bolo offers no gift link for this campaign now: its page says why.") {
			t.Errorf("%s: a link, or the form:\n%s", why, p)
		}
	}
	paused = true
	none("paused")
	paused = false
	c.state.listed = false
	none("hidden from listings")
	c.state.listed = true
	escrowCap = 12_500_000 // half a GNOT of room
	none("no room")
	escrowCap = 0
	c.state.status = statusClosed
	none("closed")
}

// TestRenderMoney: where the money is comes from the books — the escrow's coins sent
// outside Bolo said apart — and in direct mode all went straight through, with no money
// out on its receipt; the bond reads as at stake, its hold over, or slashed.
func TestRenderMoney(t *testing.T) {
	c := testCampaign(9977, modeEscrow, 0)
	id, unstore := storeCampaign(c)
	defer unstore()
	donor := testutils.TestAddress("moneydonor")
	giveTo(c, 1, donor, 40_000_000)
	defer byDonor.Remove(donor.String() + "/" + c.id.Binary())
	c.state.withdrawn, c.state.refunded, c.state.everWithdrawn = 20_000_000, 2_000_000, true
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 27_000_000))) // 18 held, and 9 sent outside Bolo
	page := Render("c/" + id)
	for _, want := range []string{"| Given: 1 gift from 1 donor | 40 |\n", "| Refunded to donors | 2 |\n", "| **Raised**, net of refunds | **38** |\n",
		"| Withdrawn by the beneficiary | 20 |\n", "| Held in escrow | 18 |\n", "its bank balance is the 18 GNOT held, plus 9 GNOT sent there outside Bolo"} {
		if !strings.Contains(page, want) {
			t.Errorf("missing %q:\n%s", want, page)
		}
	}
	c.state.bond = 5_000_000
	if p := Render("c/" + id); !strings.Contains(p, "; a 5 GNOT bond the organizer staked, lost if the campaign is delisted for fraud — not a guarantee\n") {
		t.Errorf("a bond at stake:\n%s", p)
	}
	c.state.status, c.state.closedAt, c.state.closeReason = statusClosed, now()-c.params.BondHold, reasonOrganizer
	if p := Render("c/" + id); !strings.Contains(p, "; a 5 GNOT bond the organizer staked, whose hold ended "+when(now())+": no longer at stake, it goes back to the organizer\n") {
		t.Errorf("a bond whose hold ended:\n%s", p)
	}
	c.state.bondSlashed = true
	if p := Render("c/" + id); !strings.Contains(p, "; a 5 GNOT bond, slashed\n") {
		t.Errorf("a slashed bond:\n%s", p)
	}

	d := testCampaign(9978, modeDirect, 0)
	did, undirect := storeCampaign(d)
	defer undirect()
	giveTo(d, 1, donor, 15_000_000)
	defer byDonor.Remove(donor.String() + "/" + d.id.Binary())
	if p := Render("c/" + did); !strings.Contains(p, "| Given: 1 gift from 1 donor | 15 |\n| Sent straight to the beneficiary | 15 |\n\n") || strings.Contains(p, "Held in escrow") {
		t.Errorf("a direct campaign's money:\n%s", p)
	}
	if r := Render("c/" + did + "/r/1"); strings.Contains(r, "/ledger)") || !strings.Contains(r, "Every gift went straight to the beneficiary, `"+d.beneficiary.String()+"`, in the same transaction.") {
		t.Errorf("a direct receipt:\n%s", r)
	}
}

settings.gno

package bolo

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

// Phase 0's values (API §2.2): placeholders for the deposit, the minimum donation and
// the escrow cap, whose launch values API §2.2 proposes, and the three durations it
// proposes. All are settled before Phase 1 (README), and only the admin changes them
// afterwards.
const (
	launchDeposit     int64 = 1_000_000 // ugnot
	launchDormancy    int64 = 90 * secondsPerDay
	launchExitDelay   int64 = 60 * secondsPerDay
	launchBondHold    int64 = 30 * secondsPerDay
	launchMinDonation int64 = 1_000_000     // ugnot, a placeholder
	launchEscrowCap   int64 = 1_000_000_000 // ugnot (1,000 GNOT), a placeholder

	// maxCategories keeps the list GetSettings returns to one bounded read (INV-9).
	maxCategories = 50
)

// The admin and the settings only it changes (API §2.2, §3.6). Package state, all
// unexported (C6).
var (
	admin        address = adminAddr // a realm once a DAO accepts the role (ADR D11)
	pendingAdmin address             // the proposed admin until it accepts; "" for none

	params = Params{ // for campaigns created from now on (INV-5)
		CreationDeposit: launchDeposit,
		DormancyPeriod:  launchDormancy,
		ExitDelay:       launchExitDelay,
		BondHold:        launchBondHold,
	}

	presets              = [4]int64{5_000_000, 10_000_000, 20_000_000, 50_000_000}
	minDonation          = launchMinDonation
	escrowCap            = launchEscrowCap // 0: no cap
	tipRecipient address = adminAddr
	paused       bool
	sunset       bool

	// The categories: a tree to look one up, and the codes in the order they were
	// added, for GetSettings. init fills the tree from the launch set (API §2.1).
	categories    avl.Tree // code → true
	categoryOrder = []string{
		"medical", "emergency", "disaster", "humanitarian", "water", "food",
		"education", "orphans", "animals", "funeral", "worship", "community",
		"sport", "celebration", "personal", "other",
	}
)

// SettingsView is the live settings (API §2.4): a copy, holding nothing of the
// realm's state.
type SettingsView struct {
	Version          string // "v0"
	Presets          [4]int64
	MaxEscrowBalance int64 // 0 = no cap
	Categories       []string
	TipRecipient     address
	MinDonation      int64
	Paused, Sunset   bool
}

// GetParams returns the Params a campaign created now would get (API §4).
func GetParams() Params { return params }

// GetSettings returns the live settings (API §4).
func GetSettings() SettingsView {
	return SettingsView{
		Version:          "v0",
		Presets:          presets,
		MaxEscrowBalance: escrowCap,
		Categories:       append([]string(nil), categoryOrder...),
		TipRecipient:     tipRecipient,
		MinDonation:      minDonation,
		Paused:           paused,
		Sunset:           sunset,
	}
}

// GetAdmin returns the admin and the proposed admin, "" when there is none (API §4).
func GetAdmin() (address, address) { return admin, pendingAdmin }

settle_test.gno

package bolo

import (
	"chain"
	"chain/banker"
	"math"
	"strconv"
	"testing"

	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/testutils/v0"
)

// The helpers' tests come first: a write's test that panics through a crossing call
// ends the package's unit tests.

func TestExitClaim(t *testing.T) {
	for _, k := range []struct{ left, pool, base, want int64 }{
		{100, 150, 300, 50},
		{1, 1, 3, 0}, // rounding down: dust stays in the escrow
		{2, 1, 3, 0},
		{3, math.MaxInt64, 7, 3952873730080618203},
		{math.MaxInt64, math.MaxInt64, math.MaxInt64, math.MaxInt64},
		{math.MaxInt64 / 2, math.MaxInt64 - 1, math.MaxInt64, 4611686018427387902},
		{1_000_000_000_000_000, 1_000_000_000_000_000, 3_000_000_000_000_007, 333333333333332},
		{123456789, 987654321987, 999999999999, 121932631},
		{5, 0, 9, 0},
	} {
		if got := exitClaim(k.left, k.pool, k.base); got != k.want {
			t.Errorf("exitClaim(%d, %d, %d) = %d, want %d", k.left, k.pool, k.base, got, k.want)
		}
	}
	// Neither of Div64's own panics, keyless, is ever reached.
	for name, k := range map[string]struct{ left, pool, base int64 }{
		"a base of 0":            {0, 10, 0},
		"a left above the base":  {11, 10, 10},
		"a negative pool":        {1, -1, 10},
		"a negative base":        {1, 10, -1},
		"past 64 bits otherwise": {math.MaxInt64, math.MaxInt64, math.MaxInt64 - 1},
	} {
		if !panicsWith(func() { exitClaim(k.left, k.pool, k.base) }, ErrBooksMismatch) {
			t.Errorf("%s: not ErrBooksMismatch", name)
		}
	}
}

// exitCampaign is an escrow campaign whose exit window is open: ada, bo and cy gave
// amounts, then withdrawn was taken, and it closed ExitDelay ago. Its escrow holds the
// tracked rest.
func exitCampaign(id seqid.ID, withdrawn int64, amounts ...int64) (*campaign, []address) {
	c := testCampaign(id, modeEscrow, 0)
	donors := []address{testutils.TestAddress("ada"), testutils.TestAddress("bo"), testutils.TestAddress("cy")}
	for i, amount := range amounts {
		c.contributions.Set(donors[i].String(), &contribution{amount: amount})
		c.state.raised += amount
		c.state.donorCount++
	}
	s := c.state
	s.withdrawn, s.everWithdrawn = withdrawn, true
	s.status, s.closedAt = statusClosed, now()-c.params.ExitDelay
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", s.raised-withdrawn)))
	return c, donors
}

// TestExitRefunds: the first claim freezes the pool and the base, each donor claims
// once, pro-rata, and the claims never add up to more than the pool (INV-17). The pool
// is the tracked balance: coins sent outside Bolo aren't the donors'. The first model
// is the reviewer's: three gifts of 100, 150 withdrawn, 50 each — where a claim
// repeated against a recomputed pool once drained about 100.
func TestExitRefunds(t *testing.T) {
	for i, k := range []struct {
		withdrawn       int64
		amounts, claims []int64
	}{
		{150, []int64{100, 100, 100}, []int64{50, 50, 50}},
		{300, []int64{100, 200, 300}, []int64{50, 100, 150}},
		{100, []int64{100, 100, 101}, []int64{66, 66, 67}}, // rounded down: 2 stay in the escrow
	} {
		c, donors := exitCampaign(seqid.ID(9501+100*i), k.withdrawn, k.amounts...)
		testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 7))) // sent outside Bolo
		id, unstore := storeCampaign(c)
		pool, base := c.state.raised-k.withdrawn, c.state.raised
		checkBooks(t, c)
		if v := GetContribution(id, donors[1]); v.Window != windowExit || v.RefundableNow != k.claims[1] {
			t.Errorf("model %d, bo before any claim: %v", i, v)
		}
		var paid int64
		for j, want := range k.claims {
			r := bookRefund(c, donors[j])
			checkBooks(t, c)
			if r.amount != want || r.kind != windowExit {
				t.Errorf("model %d, claim %d = %v, want %d", i, j, *r, want)
			}
			paid += r.amount
			// The snapshot is the first claim's, never recomputed (INV-17).
			if s := c.state; !s.exitFrozen || s.exitPool != pool || s.exitBase != base {
				t.Errorf("model %d, after claim %d: frozen %t, pool %d, base %d", i, j, s.exitFrozen, s.exitPool, s.exitBase)
			}
			if !panicsWith(func() { bookRefund(c, donors[j]) }, ErrRefundWindowClosed) {
				t.Errorf("model %d, a second claim by donor %d: not ErrRefundWindowClosed", i, j)
			}
			if v := GetContribution(id, donors[j]); v.Window != "" || v.RefundableNow != 0 || !v.ExitClaimed {
				t.Errorf("model %d, donor %d after their claim: %v", i, j, v)
			}
		}
		if paid > pool {
			t.Errorf("model %d: the claims add up to %d, past the pool %d", i, paid, pool)
		}
		unstore()
	}
}

// TestExitClaimCap: a claim above the tracked balance is ErrBooksMismatch, whatever
// the snapshot says (INV-17).
func TestExitClaimCap(t *testing.T) {
	c, donors := exitCampaign(9520, 150, 100, 100, 100)
	s := c.state
	s.exitFrozen, s.exitPool, s.exitBase = true, 300, 100 // ada's claim: 300, the tracked balance 150
	if !panicsWith(func() { bookRefund(c, donors[0]) }, ErrBooksMismatch) {
		t.Errorf("a claim above the tracked balance: not ErrBooksMismatch")
	}
}

// TestExitBase: the base is what is left of every record when the first claim comes,
// Raised − Refunded: an open-window refund before the withdrawal is taken out of it.
func TestExitBase(t *testing.T) {
	c := testCampaign(9502, modeEscrow, 0)
	ada, bo, cy := testutils.TestAddress("ada"), testutils.TestAddress("bo"), testutils.TestAddress("cy")
	c.contributions.Set(ada.String(), &contribution{amount: 400})
	c.contributions.Set(bo.String(), &contribution{amount: 200})
	c.contributions.Set(cy.String(), &contribution{amount: 300, refunded: 300}) // all back, in the open window
	s := c.state
	s.raised, s.refunded, s.withdrawn, s.everWithdrawn = 900, 300, 300, true
	s.status, s.closedAt = statusClosed, now()-c.params.ExitDelay
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 300)))
	checkBooks(t, c)
	// Tracked 300, base 600 — ada's 400 and bo's 200: ada claims 400 × 300 / 600.
	if r := bookRefund(c, ada); r.amount != 200 || s.exitBase != 600 || s.exitPool != 300 {
		t.Errorf("ada's claim %d; base %d, pool %d", r.amount, s.exitBase, s.exitPool)
	}
	checkBooks(t, c)
}

// TestExitUneven: forty donors with uneven gifts, some refunded in the open window,
// then a withdrawal, more gifts from half of them and others, and every donor's claim
// in a scrambled order. Each claim is paid from the tracked balance, the claims never
// pass the pool, and what is left is rounding dust, under one ugnot a claim (INV-17).
func TestExitUneven(t *testing.T) {
	c := testCampaign(9519, modeEscrow, 0)
	x := int64(12345)
	next := func() int64 { // a fixed sequence of amounts from 1 to about a million
		x = (x*1103515245 + 12345) % 2147483648
		return x%1_000_003 + 1
	}
	donors := make([]address, 40)
	for i := range donors {
		donors[i] = testutils.TestAddress("donor" + strconv.Itoa(i))
	}
	s := c.state
	for i := 0; i < 20; i++ {
		if i%7 == 3 { // refunded in full in the open window: the coins went back
			a := next()
			c.contributions.Set(donors[i].String(), &contribution{amount: a, refunded: a})
			s.raised, s.refunded, s.donorCount = s.raised+a, s.refunded+a, s.donorCount+1
			continue
		}
		fund(c, donors[i], next())
	}
	bookWithdrawal(c)
	for i := 10; i < 40; i++ {
		fund(c, donors[i], next())
	}
	s.status, s.closedAt = statusClosed, now()-c.params.ExitDelay
	checkBooks(t, c)
	pool := trackedBalance(c)
	var paid, claims int64
	for i := 0; i < 40; i++ {
		d := donors[i*17%40] // every donor once: 17 and 40 share no factor
		if k := contributionOf(c, d); k.amount == k.refunded {
			continue
		}
		left := trackedBalance(c)
		r := bookRefund(c, d)
		checkBooks(t, c)
		if r.amount > left || r.amount <= 0 {
			t.Errorf("a claim of %d against a tracked %d", r.amount, left)
		}
		paid += r.amount
		claims++
	}
	if paid > pool || pool-paid >= claims || claims != 39 { // all but donor 3: refunded in full, never gave again
		t.Errorf("%d claims paid %d of a pool %d", claims, paid, pool)
	}
}

// TestExitWindow: the exit window needs a withdrawal, a close, ExitDelay passed and a
// tracked balance; a claim that rounds to 0 uses nothing.
func TestExitWindow(t *testing.T) {
	c, donors := exitCampaign(9503, 300, 100, 200, 300)
	c.state.closedAt = now() - c.params.ExitDelay + 1
	if !panicsWith(func() { checkRefund(c, donors[0]) }, ErrRefundWindowClosed) {
		t.Errorf("a second before the exit window: not ErrRefundWindowClosed")
	}
	c.state.closedAt = now() - c.params.ExitDelay
	checkRefund(c, donors[0])
	c.state.status = statusSettled
	checkRefund(c, donors[0]) // settlement closes no window (INV-16)
	c.state.status = statusOpen
	if !panicsWith(func() { checkRefund(c, donors[0]) }, ErrRefundWindowClosed) {
		t.Errorf("open: not ErrRefundWindowClosed")
	}
	c.state.status = statusClosed
	c.state.withdrawn = 600 // nothing tracked left
	if !panicsWith(func() { checkRefund(c, donors[0]) }, ErrRefundWindowClosed) {
		t.Errorf("no tracked balance: not ErrRefundWindowClosed")
	}

	// Dust: a gift of 1 against a pool far smaller than the base claims 0.
	d := testCampaign(9504, modeEscrow, 0)
	tiny, big := testutils.TestAddress("tiny"), testutils.TestAddress("big")
	d.contributions.Set(tiny.String(), &contribution{amount: 1})
	d.contributions.Set(big.String(), &contribution{amount: 1000})
	d.state.raised, d.state.withdrawn, d.state.everWithdrawn = 1001, 1000, true
	d.state.status, d.state.closedAt = statusClosed, now()-d.params.ExitDelay
	if !panicsWith(func() { checkRefund(d, tiny) }, ErrNothingToRefund) {
		t.Errorf("a claim of 0: not ErrNothingToRefund")
	}
	if contributionOf(d, tiny).exitClaimed {
		t.Errorf("a claim of 0 used the claim")
	}
	dustID, unstoreDust := storeCampaign(d)
	if v := GetContribution(dustID, tiny); v.Window != "" || v.RefundableNow != 0 {
		t.Errorf("a claim of 0 shows a window Refund refuses: %v", v)
	}
	unstoreDust()

	// GetContribution counts a passed deadline as recorded: the stored status is open.
	e := testCampaign(9505, modeEscrow, now()-61*secondsPerDay)
	e.contributions.Set(tiny.String(), &contribution{amount: 100})
	e.contributions.Set(big.String(), &contribution{amount: 100})
	e.state.raised, e.state.withdrawn, e.state.everWithdrawn = 200, 100, true
	id, unstore := storeCampaign(e)
	defer unstore()
	if v := GetContribution(id, tiny); v.Window != windowExit || v.RefundableNow != 50 {
		t.Errorf("past an unrecorded deadline and its exit delay: %v", v)
	}
}

func TestCheckFinalizable(t *testing.T) {
	c := testCampaign(9506, modeEscrow, 0)
	if !panicsWith(func() { checkFinalizable(c) }, ErrNotFinalizable) {
		t.Errorf("open: not ErrNotFinalizable")
	}
	c.state.status, c.state.closedAt = statusClosed, now()
	checkFinalizable(c) // nothing tracked
	c.state.raised = 10
	if !panicsWith(func() { checkFinalizable(c) }, ErrNotFinalizable) {
		t.Errorf("a tracked balance before the exit window: not ErrNotFinalizable")
	}
	c.state.closedAt = now() - c.params.ExitDelay
	checkFinalizable(c) // the exit window is open
	d := testCampaign(9507, modeDirect, 0)
	d.state.status, d.state.closedAt = statusClosed, now()
	checkFinalizable(d) // direct: at once
}

// TestFinalizeBooks: the first call settles; untracked coins go to the beneficiary,
// the tracked balance never; the bond address's coins to the organizer, but a bond on
// hold; the bond once its hold ends, unless slashed; later calls forward what arrives.
func TestFinalizeBooks(t *testing.T) {
	c := testCampaign(9508, modeEscrow, 0)
	fund(c, testutils.TestAddress("donor"), 500) // tracked, the donors'
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 70)))
	testing.IssueCoins(bondAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 1000+300)))
	c.state.bond = 300
	c.state.status, c.state.closedAt = statusClosed, now()-c.params.ExitDelay
	f := bookFinalize(c)
	if !f.settled || c.state.status != statusSettled || f.toBeneficiary != 70 || f.toOrganizer != 1300 || f.released != 300 || !c.state.bondReleased {
		// ExitDelay (60 days) is past BondHold (30): the bond goes too.
		t.Errorf("first call: %v", f)
	}

	// On hold: a campaign closed now keeps its bond at the bond address.
	d := testCampaign(9509, modeDirect, 0)
	testing.IssueCoins(bondAddr(d.id), chain.NewCoins(chain.NewCoin("ugnot", 1000+300)))
	d.state.bond = 300
	d.state.status, d.state.closedAt = statusClosed, now()
	f = bookFinalize(d)
	if !f.settled || f.toOrganizer != 1000 || f.released != 0 || d.state.bondReleased {
		t.Errorf("bond on hold: %v", f)
	}
	// The coins don't move here; a later call, before the hold ends, has the same
	// 1000 to forward and still holds the bond, without settling again.
	if f = bookFinalize(d); f.settled || f.toOrganizer != 1000 || f.released != 0 {
		t.Errorf("a second call on hold: %v", f)
	}
	// A slashed bond is never released: the slash took it, and the deposit is left.
	e := testCampaign(9518, modeDirect, 0)
	testing.IssueCoins(bondAddr(e.id), chain.NewCoins(chain.NewCoin("ugnot", 1000)))
	e.state.bond, e.state.bondSlashed = 300, true
	e.state.status, e.state.closedAt = statusClosed, now()-e.params.BondHold
	if f = bookFinalize(e); f.released != 0 || e.state.bondReleased || f.toOrganizer != 1000 {
		t.Errorf("slashed: %v", f)
	}
	// Within the hold too: the slash took the bond, so the deposit goes at once.
	s := testCampaign(9530, modeDirect, 0)
	testing.IssueCoins(bondAddr(s.id), chain.NewCoins(chain.NewCoin("ugnot", 1000)))
	s.state.bond, s.state.bondSlashed = 300, true
	s.state.status, s.state.closedAt = statusClosed, now()
	if f = bookFinalize(s); !f.settled || f.released != 0 || f.toOrganizer != 1000 {
		t.Errorf("slashed, within the hold: %v", f)
	}

	// A bond address holding less than the bond on hold stops it (INV-7).
	h := testCampaign(9521, modeDirect, 0)
	testing.IssueCoins(bondAddr(h.id), chain.NewCoins(chain.NewCoin("ugnot", 200)))
	h.state.bond = 300
	h.state.status, h.state.closedAt = statusClosed, now()
	if !panicsWith(func() { bookFinalize(h) }, ErrBooksMismatch) {
		t.Errorf("a bond above the bond address's coins: not ErrBooksMismatch")
	}

	// Books above the bank stop it (INV-1).
	g := testCampaign(9510, modeEscrow, 0)
	g.state.raised = 5
	g.state.status, g.state.closedAt = statusClosed, now()-g.params.ExitDelay
	if !panicsWith(func() { bookFinalize(g) }, ErrBooksMismatch) {
		t.Errorf("books above the bank: not ErrBooksMismatch")
	}
}

func TestCanFinalize(t *testing.T) {
	open := testCampaign(9511, modeEscrow, 0)
	waiting := testCampaign(9512, modeEscrow, 0)
	fund(waiting, testutils.TestAddress("donor"), 10)
	waiting.state.status, waiting.state.closedAt = statusClosed, now()
	ready := testCampaign(9513, modeDirect, 0)
	ready.state.status, ready.state.closedAt = statusClosed, now()
	passed := testCampaign(9514, modeDirect, now()-1) // past its deadline, unrecorded
	exit := testCampaign(9522, modeEscrow, 0)
	fund(exit, testutils.TestAddress("donor"), 10)
	exit.state.status, exit.state.closedAt = statusClosed, now()-exit.params.ExitDelay // its exit window opens now
	settled := testCampaign(9515, modeDirect, 0)
	settled.state.status, settled.state.closedAt = statusSettled, now()
	stray := testCampaign(9516, modeDirect, 0)
	stray.state.status, stray.state.closedAt = statusSettled, now()
	testing.IssueCoins(escrowAddr(stray.id), chain.NewCoins(chain.NewCoin("ugnot", 3)))
	for _, k := range []struct {
		name string
		c    *campaign
		ok   bool
		why  string
	}{
		{"open", open, false, statusOpen},
		{"waiting for the exit window", waiting, false, "not_yet"},
		{"closed, direct", ready, true, "settle"},
		{"past an unrecorded deadline", passed, true, "settle"},
		{"at the exit window", exit, true, "settle"},
		{"settled, nothing to move", settled, false, statusSettled},
		{"settled, coins arrived", stray, true, "forward"},
	} {
		id, unstore := storeCampaign(k.c)
		ok, why := CanFinalize(id)
		unstore()
		if ok != k.ok || why != k.why {
			t.Errorf("%s: CanFinalize = %t, %q, want %t, %q", k.name, ok, why, k.ok, k.why)
		}
	}
}

// TestFinalize settles as anyone, straight from the test's body, and moves the coins
// bookFinalize names: the untracked to the beneficiary, the deposit to the organizer,
// the tracked balance nowhere (INV-16), which a donor still claims after (API §3.4).
func TestFinalize(cur realm, t *testing.T) {
	rb := banker.NewReadonlyBanker()
	c, donors := exitCampaign(9517, 300, 100, 200, 300)
	id, unstore := storeCampaign(c)
	defer unstore()
	testing.IssueCoins(escrowAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 40))) // sent outside Bolo
	testing.IssueCoins(bondAddr(c.id), chain.NewCoins(chain.NewCoin("ugnot", 1000))) // the deposit
	checkBooks(t, c)
	beneficiary, organizer := rb.GetCoin(c.beneficiary, "ugnot"), rb.GetCoin(c.organizer, "ugnot")
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("passerby")))
	Finalize(cross(cur), id)
	checkBooks(t, c)
	if got := rb.GetCoin(c.beneficiary, "ugnot") - beneficiary; got != 40 {
		t.Errorf("the beneficiary got %d, want the untracked 40", got)
	}
	if got := rb.GetCoin(c.organizer, "ugnot") - organizer; got != 1000 {
		t.Errorf("the organizer got %d, want the deposit 1000", got)
	}
	if got := rb.GetCoin(escrowAddr(c.id), "ugnot"); got != 300 || c.state.status != statusSettled {
		t.Errorf("the escrow holds %d; status %s", got, c.state.status)
	}
	// Claims still paid after settlement (INV-16).
	testing.SetRealm(testing.NewUserRealm(donors[2]))
	if got := Refund(cross(cur), id); got != 150 {
		t.Errorf("cy's exit claim after settlement = %d, want 150", got)
	}
	checkBooks(t, c)
}

state.gno

package bolo

import (
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/seqid/v0"
)

// Params are the settings snapshotted into each campaign when it is created
// (API §2.2): its deposit and its timers never change afterwards (INV-5).
// Durations are in seconds.
type Params struct {
	CreationDeposit int64
	DormancyPeriod  int64
	ExitDelay       int64
	BondHold        int64
}

// Custody modes, statuses and close reasons (API §2.1).
const (
	modeDirect = "direct"
	modeEscrow = "escrow"

	statusOpen    = "open"
	statusClosed  = "closed"
	statusSettled = "settled"

	reasonOrganizer = "organizer"
	reasonDeadline  = "deadline"
	reasonDormant   = "dormant"
)

// campaign holds what never changes once a campaign is created (INV-10), and
// points to what does. Gno re-saves a changed object and every object that owns
// it, up to the first with two owners, so each donation re-saves this object with
// its hot state and its trees: it holds only small fields, and the organizer's
// text lives in its own object, written once (API §2.5).
type campaign struct {
	id          seqid.ID
	category    string
	organizer   address
	beneficiary address
	mode        string // modeDirect or modeEscrow
	goal        int64  // ugnot; 0: no goal
	deadline    int64  // Unix seconds; 0: none
	createdAt   int64
	params      Params

	text  *campaignText  // written once; read by views and Render
	state *campaignState // counters, timers and flags

	// One object each, keyed by donor address or by seqid.Binary(): a donation
	// writes O(log n) small nodes, not the campaign's history.
	contributions *avl.Tree // address → *contribution
	receipts      *avl.Tree // seq → *receipt
	withdrawals   *avl.Tree // seq → *withdrawal
	refunds       *avl.Tree // seq → *refund
	updates       *avl.Tree // seq → *update
}

// campaignText is what the organizer wrote, which never changes (INV-10): written
// once, off the path every donation re-saves.
type campaignText struct {
	title       string
	description string
	imageCID    string
	imageAlt    string
}

const recentSize = 20

// campaignState is a campaign's hot object: small, rewritten on every donation.
type campaignState struct {
	status      string // as stored; a passed deadline counts as closed before it is recorded
	closeReason string
	closedAt    int64
	listed      bool
	notice      string
	imageHidden bool

	raised    int64 // gross: every donation ever
	refunded  int64
	withdrawn int64 // tracked coins only; untracked ones are counted apart

	donorCount    int
	donationCount int
	refundCount   int
	updateCount   int

	bond         int64
	bondSlashed  bool
	bondReleased bool

	lastDonationAt int64
	lastUpdateAt   int64
	everWithdrawn  bool // ends the open refund window for good

	// The exit window's snapshot, frozen by the first exit claim (API §3.2).
	exitFrozen bool
	exitPool   int64
	exitBase   int64

	// The last donations' sequence numbers, a ring: numbers, not receipts.
	recent     [recentSize]uint64
	recentNext int

	receiptSeq    seqid.ID
	withdrawalSeq seqid.ID
	refundSeq     seqid.ID
	updateSeq     seqid.ID
}

// contribution is one donor's record in one campaign (API §3.2).
type contribution struct {
	amount      int64 // everything given
	refunded    int64 // everything paid back
	exitClaimed bool  // the one exit claim is used (INV-17)
	public      bool  // at least one gift wasn't anonymous
}

// receipt is one donation.
type receipt struct {
	seq           uint64
	donor         address
	anonymous     bool
	amount        int64
	tip           int64
	message       string
	messageHidden bool
	at            int64
	raisedAfter   int64

	refundedBefore int64 // what this donor was refunded on this campaign before this gift
}

// withdrawal is one payout to the beneficiary.
type withdrawal struct {
	seq       uint64
	amount    int64 // tracked coins
	untracked int64 // coins sent to the escrow outside Bolo
	at        int64
	to        address
}

// refund is one payout to a donor.
type refund struct {
	seq    uint64
	amount int64
	at     int64
	donor  address
	kind   string // "open" or "exit"
}

// update is one organizer update: append-only.
type update struct {
	seq  uint64
	at   int64
	body string
}

// Package state, all unexported (API C6).
var (
	nextID    seqid.ID // the last campaign ID given out
	campaigns avl.Tree // seqid.Binary() → *campaign

	// derived holds every escrow and bond address a campaign ever got: none of
	// them may be a beneficiary (API §1).
	derived avl.Tree // address → true

	// The indexes (API §2.5): keys sort newest campaign last.
	active           avl.Tree // seqid.Binary() → true: the open, listed campaigns
	activeByCategory avl.Tree // category + "/" + seqid.Binary() → true: the same
	byOrganizer      avl.Tree // organizer + "/" + seqid.Binary() → true
	byBeneficiary    avl.Tree // beneficiary + "/" + seqid.Binary() → true
	byDonor          avl.Tree // donor + "/" + seqid.Binary() → true: a gift that wasn't anonymous
)

stats.gno

package bolo

// statsState holds Bolo-wide counters (API §2.4), kept as things happen, never by
// walking the campaigns. Gift and refund totals aren't kept: an indexer sums them.
type statsState struct {
	open    int // campaigns whose close isn't recorded yet
	settled int // campaigns settled
}

var stats statsState

// StatsView is what GetStats returns (API §2.4).
type StatsView struct {
	Campaigns, Open, Settled int
}

// GetStats returns Bolo-wide figures (API §4). Open counts a campaign past a deadline
// nobody recorded until someone does (§3.1).
func GetStats() StatsView {
	return StatsView{Campaigns: campaigns.Size(), Open: stats.open, Settled: stats.settled}
}

text.gno

package bolo

import (
	"strings"
	"unicode"
	"unicode/utf8"

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

// Text limits in characters — Unicode code points — after normalization (API
// §2.3). Every text also has a byte cap of four times its character limit, on
// the argument as sent.
const (
	titleMin, titleMax   = 4, 80
	descriptionMax       = 5000
	messageMax           = 140
	updateMin, updateMax = 1, 2000
	noticeMin, noticeMax = 1, 280
	altMin, altMax       = 1, 250
	cidMaxBytes          = 100
)

// normalize prepares user text for checking and storing (API C7, §2.3). Bidi and
// zero-width characters go first, through the very function sanitize.Block calls
// when it renders, so that no check can be dodged by what rendering removes. Line
// breaks are unified — CR-LF, CR, NEL and the Unicode line and paragraph
// separators all become "\n" — and kept in multiline text; elsewhere they become
// a space. Tabs and the other whitespace controls (a vertical tab, a form feed, the
// information separators) become a space everywhere, so words never join. Then
// every character that only pads a text goes (invisible), and surrounding
// whitespace is trimmed. Stripping more than Block does only makes the checks
// stricter, and the stripped text is what gets stored.
func normalize(s string, multiline bool) string {
	s = sanitize.StripBidiAndZeroWidth(s)
	s = sanitize.NormalizeBreaks(s)
	s = strings.Map(func(r rune) rune {
		switch {
		case r == '\n' || r == '\u0085' || r == '\u2028' || r == '\u2029':
			if multiline {
				return '\n'
			}
			return ' '
		case r == '\t' || r == '\v' || r == '\f' || (r >= '\x1c' && r <= '\x1f'):
			return ' '
		case invisible(r):
			return -1
		}
		return r
	}, s)
	return strings.TrimSpace(s)
}

// invisible reports whether r shows nothing and only pads a text: a control or a
// format character (Unicode Cc, Cf: a word joiner, a soft hyphen), one Unicode
// lists as Other_Default_Ignorable_Code_Point (a Hangul filler, the combining
// grapheme joiner), or a blank symbol (the Braille blank, the musical null
// notehead). A Latin-1 character skips the tables, which are costly and which
// English or French text seldom leaves: of them, only the controls and the soft
// hyphen are invisible (TestLatin1 holds this to the tables). Every control is
// Latin-1.
func invisible(r rune) bool {
	if r <= unicode.MaxLatin1 {
		return r < 0x20 || r >= 0x7f && r <= 0x9f || r == 0xad
	}
	return unicode.Is(unicode.Cf, r) || unicode.Is(unicode.Other_Default_Ignorable_Code_Point, r) ||
		r == '\u2800' || r == '\U0001D159'
}

// checkText checks one text argument and returns it normalized, the form Bolo
// stores (API §2.3): valid UTF-8 and at most four bytes per allowed character as
// sent; then, normalized, at most max characters, of which at least min show on
// their own. It panics with err otherwise.
func checkText(s string, min, max int, multiline bool, err Error) string {
	if !utf8.ValidString(s) || len(s) > 4*max {
		panic(err)
	}
	s = normalize(s, multiline)
	if utf8.RuneCountInString(s) > max || !visible(s, min) {
		panic(err)
	}
	return s
}

// visible reports whether at least min characters of s show on their own —
// letters, digits, punctuation, symbols and spacing marks — counting the spaces
// between two of them. A mark that takes no space (an accent, a variation
// selector) only changes the character before it, a private-use character or a
// code point Unicode hasn't assigned shows nothing a reader can count on, and a
// space shows only between characters that do. They all stay in the text, but
// don't count toward a minimum. Latin-1 skips the tables, as in invisible: there,
// every character shows on its own but the controls, the soft hyphen and the two
// spaces, ' ' and U+00A0. Counting stops once min characters have shown, so a long
// text pays the tables only until then, and a story, whose minimum is 0, never.
func visible(s string, min int) bool {
	n, spaces, shown := 0, 0, false
	for _, r := range s {
		if n >= min {
			break
		}
		switch {
		case r > ' ' && r < 0x7f, r > 0xa0 && r <= unicode.MaxLatin1 && r != 0xad,
			r > unicode.MaxLatin1 && unicode.In(r, unicode.L, unicode.Mc, unicode.N, unicode.P, unicode.S):
			n += 1 + spaces
			spaces, shown = 0, true
		case shown && (r == ' ' || r == 0xa0 || r > unicode.MaxLatin1 && unicode.Is(unicode.Zs, r)):
			spaces++
		}
	}
	return n >= min
}

// checkStory checks a story or an update, the organizer's own text, and returns it
// normalized (API §2.3): the limits of checkText, then no image and no raw HTML,
// judged on the normalized text that sanitize.Block will render.
func checkStory(s string, min, max int, err Error) string {
	s = checkText(s, min, max, true, err)
	checkMarkup(s)
	return s
}

// checkMarkup refuses an image or raw HTML (API §2.3): `![`, or `<` followed by a
// letter, `/`, `!` or `?` — every way CommonMark opens raw HTML. The campaign
// photo is the only image a campaign shows, and `<3` still passes.
func checkMarkup(s string) {
	if strings.Contains(s, "![") {
		panic(ErrMarkup)
	}
	for i := 0; i+1 < len(s); i++ {
		if s[i] != '<' {
			continue
		}
		c := s[i+1]
		if c == '/' || c == '!' || c == '?' || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') {
			panic(ErrMarkup)
		}
	}
}

// checkImage checks a campaign photo's CID and its description (API §2.3, ADR
// D16), and returns both, the description normalized: no photo, no description;
// a photo, a description of 1 to 250 characters.
func checkImage(cid, alt string) (string, string) {
	if cid == "" {
		if alt != "" {
			panic(ErrImage)
		}
		return "", ""
	}
	if !validCID(cid) {
		panic(ErrImage)
	}
	return cid, checkText(alt, altMin, altMax, false, ErrImage)
}

// validCID reports whether s has the shape of an IPFS CID Bolo accepts: v0, "Qm"
// and 44 more base58btc characters; or v1 in lowercase base32, "b" then that
// alphabet; at most 100 bytes. Render writes the CID into `(ipfs://…)` as it is,
// so the character set is the escaping (API §2.3).
func validCID(s string) bool {
	switch {
	case len(s) > cidMaxBytes:
		return false
	case len(s) == 46 && strings.HasPrefix(s, "Qm"):
		return allIn(s, base58btc)
	case len(s) > 1 && s[0] == 'b':
		return allIn(s[1:], base32Lower)
	}
	return false
}

const (
	base58btc   = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
	base32Lower = "abcdefghijklmnopqrstuvwxyz234567"
)

func allIn(s, set string) bool {
	for i := 0; i < len(s); i++ {
		if strings.IndexByte(set, s[i]) < 0 {
			return false
		}
	}
	return true
}

text_test.gno

package bolo

import (
	"strings"
	"testing"
	"unicode"
)

func TestNormalize(t *testing.T) {
	for _, c := range []struct {
		in        string
		multiline bool
		want      string
	}{
		{"  Clean water  ", false, "Clean water"},
		{"a\u200bb\u202ec\ufeffd\u2066e", false, "abcde"},
		{"one\r\ntwo\rthree", true, "one\ntwo\nthree"},
		// Every line break is one; outside multiline text, it and a tab become a
		// space, so words never join.
		{"one\r\ntwo\nthree", false, "one two three"},
		{"bell\a and\ttab", false, "bell and tab"},
		{"rub\x7fout", false, "rubout"},
		{"a\vb\fc\x1cd\x1fe", false, "a b c d e"},
		{"a\tb\vc", true, "a b c"},
		{"a\u0085b\u2028c\u2029d", true, "a\nb\nc\nd"},
		{"a\u0085b\u2028c\u2029d", false, "a b c d"},
		{"word\u2060joiner, soft\u00adhyphen", false, "wordjoiner, softhyphen"},
		// Fillers that show nothing go: Hangul fillers, the combining grapheme
		// joiner, the Braille blank. A variation selector stays, for emoji.
		{"a\u3164b\uffa0c\u115fd\u034fe\u2800f\U0001D159g", false, "abcdefg"},
		{"I \u2764\ufe0f you", false, "I \u2764\ufe0f you"},
		{"\n\n story \n\n", true, "story"},
	} {
		if got := normalize(c.in, c.multiline); got != c.want {
			t.Errorf("normalize(%q, %t) = %q, want %q", c.in, c.multiline, got, c.want)
		}
	}
}

// TestLatin1 holds the Latin-1 shortcut of invisible and visible to the Unicode
// tables they read beyond it: invisible is Cc, Cf or Other_Default_Ignorable; a
// character shows on its own (counts alone) if it is L, Mc, N, P or S; a space (Zs)
// counts only between two of those.
func TestLatin1(t *testing.T) {
	for r := rune(0); r <= unicode.MaxLatin1; r++ {
		if want := unicode.In(r, unicode.Cc, unicode.Cf, unicode.Other_Default_Ignorable_Code_Point); invisible(r) != want {
			t.Errorf("invisible(%U) = %t, the tables say %t", r, !want, want)
		}
		shows := unicode.In(r, unicode.L, unicode.Mc, unicode.N, unicode.P, unicode.S)
		if got := visible(string(r), 1); got != shows {
			t.Errorf("visible(%U, 1) = %t, the tables say %t", r, got, shows)
		}
		between := shows || unicode.Is(unicode.Zs, r)
		if got := visible("x"+string(r)+"x", 3); got != between {
			t.Errorf("visible(x %U x, 3) = %t, the tables say %t", r, got, between)
		}
	}
}

// TestVisible checks visible's threshold: at least min, the spaces between two
// shown characters counted, marks and spaces elsewhere not.
func TestVisible(t *testing.T) {
	for _, c := range []struct {
		s    string
		min  int
		want bool
	}{
		{"", 0, true},
		{"", 1, false},
		{"abc", 4, false},
		{"abcd", 4, true},
		{"ab cd", 5, true},
		{"ab  ", 3, false},
		{"a\u0301\u0301\u0301", 2, false},
	} {
		if got := visible(c.s, c.min); got != c.want {
			t.Errorf("visible(%q, %d) = %t, want %t", c.s, c.min, got, c.want)
		}
	}
}

func TestCheckText(t *testing.T) {
	if got := checkText("  Clean water for Ndiaganiao ", titleMin, titleMax, false, ErrTitle); got != "Clean water for Ndiaganiao" {
		t.Errorf("checkText = %q", got)
	}
	// 80 characters of four bytes each: exactly the byte cap.
	if got := checkText(strings.Repeat("💧", 80), titleMin, titleMax, false, ErrTitle); len(got) != 320 {
		t.Errorf("80 four-byte characters: got %d bytes", len(got))
	}
	// Four letters, one with a combining accent: four characters show. So do
	// emoji with a skin tone, flags, CJK, Arabic, a Devanagari word with a spacing
	// vowel sign, and two letters with the spaces between them.
	for _, s := range []string{"Cafe\u0301", "\U0001F44D\U0001F3FD\U0001F44D\U0001F3FD", "\U0001F1F8\U0001F1F3\U0001F1F8\U0001F1F3", "水井项目", "بئر ماء", "कमला", "a  b"} {
		if got := checkText(s, titleMin, titleMax, false, ErrTitle); got != s {
			t.Errorf("checkText(%q) = %q", s, got)
		}
	}
	for name, s := range map[string]string{
		"too short":                 "abc",
		"four spaces":               "    ",
		"four invisible characters": "\u200b\u200b\u200b\u200b",
		"four word joiners":         "\u2060\u2060\u2060\u2060",
		"four soft hyphens":         "\u00ad\u00ad\u00ad\u00ad",
		"four Hangul fillers":       "\u3164\u3164\u3164\u3164",
		"four halfwidth fillers":    "\uffa0\uffa0\uffa0\uffa0",
		"four grapheme joiners":     "\u034f\u034f\u034f\u034f",
		"four Braille blanks":       "\u2800\u2800\u2800\u2800",
		"four variation selectors":  "\ufe0f\ufe0f\ufe0f\ufe0f",
		"one letter, three accents": "a\u0301\u0301\u0301",
		"four null noteheads":       "\U0001D159\U0001D159\U0001D159\U0001D159",
		"four private-use":          "\ue000\ue000\ue000\ue000",
		"four noncharacters":        "\uffff\uffff\uffff\uffff",
		// Spaces count only between shown characters: wrapped in characters
		// that don't count, they would escape the trim and pass as a title.
		"spaces in variation selectors":  "\ufe0f    \ufe0f",
		"spaces in accents":              "\u0301    \u0301",
		"spaces in private-use":          "\ue000    \ue000",
		"spaces in noncharacters":        "\uffff    \uffff",
		"no-break spaces in selectors":   "\U000E0100\u00a0\u00a0\u00a0\u00a0\U000E0100",
		"ideographic spaces":             "\ufe0f\u3000\u3000\u3000\u3000\ufe0f",
		"one letter and trailing spaces": "a\ufe0f   \ufe0f",
		"leading spaces and one letter":  "\ufe0f    a",
		"too long":                       strings.Repeat("a", 81),
		"invalid UTF-8":                  "\xff\xfeabcd",
		// Fits once normalized, but is more than four bytes per allowed character
		// as sent: the byte cap applies to the argument (API §2.3).
		"padded past the byte cap": "abcd" + strings.Repeat("\u200b", 110),
	} {
		if !panicsWith(func() { checkText(s, titleMin, titleMax, false, ErrTitle) }, ErrTitle) {
			t.Errorf("%s: not refused", name)
		}
	}
}

func TestCheckStory(t *testing.T) {
	// Accepted, and stored normalized; a refusal of any kind fails the test.
	for _, c := range []struct{ in, want string }{
		{"We need **1,500 GNOT** for the pump.\n\nSee [the quote](https://example.org/q).", "We need **1,500 GNOT** for the pump.\n\nSee [the quote](https://example.org/q)."},
		{"Thanks <3 to everyone", "Thanks <3 to everyone"},
		{"a < b, and x<5", "a < b, and x<5"},
		{"", ""},
		{" Line one\r\n\r\nline\u2028two\t ", "Line one\n\nline\ntwo"},
	} {
		if got := checkStory(c.in, 0, descriptionMax, ErrDescription); got != c.want {
			t.Errorf("checkStory(%q) = %q, want %q", c.in, got, c.want)
		}
	}
	for name, s := range map[string]string{
		"an image":                    "![the pump](https://imgur.com/p.png)",
		"an image behind zero-width":  "!\u200b[the pump](https://imgur.com/p.png)",
		"an image behind a bidi mark": "!\u202e[the pump](https://imgur.com/p.png)",
		"a tag":                       "<script>alert(1)</script>",
		"an upper-case tag":           "<IMG SRC=x>",
		"a closing tag":               "fine </p>",
		"a comment":                   "visible <!-- hidden from the page -->",
		"a declaration":               "<!DOCTYPE html>",
		"a processing instruction":    "<?php echo 1 ?>",
	} {
		if !panicsWith(func() { checkStory(s, 0, descriptionMax, ErrDescription) }, ErrMarkup) {
			t.Errorf("%s: not refused", name)
		}
	}
	if !panicsWith(func() { checkStory(strings.Repeat("a", descriptionMax+1), 0, descriptionMax, ErrDescription) }, ErrDescription) {
		t.Errorf("a story one character too long: not refused")
	}
}

func TestCheckImage(t *testing.T) {
	const v0 = "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG"
	const v1 = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi"
	if cid, alt := checkImage("", ""); cid != "" || alt != "" {
		t.Errorf("no photo: got %q, %q", cid, alt)
	}
	for _, cid := range []string{v0, v1} {
		if _, alt := checkImage(cid, "  The village well, dry since March "); alt != "The village well, dry since March" {
			t.Errorf("%s: alt = %q", cid, alt)
		}
	}
	for name, c := range map[string][2]string{
		"alt text without a photo": {"", "a well"},
		"a photo without alt text": {v0, ""},
		"blank alt text":           {v0, "   "},
		"alt text of a space":      {v0, "\ufe0f \ufe0f"},
		"alt text too long":        {v0, strings.Repeat("a", altMax+1)},
		"v0 with a 0":              {"Qm0wAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG", "a well"},
		"v0 too short":             {v0[:45], "a well"},
		"v1 in upper case":         {strings.ToUpper(v1), "a well"},
		"v1 breaking out":          {"bafy](javascript:alert(1))", "a well"},
		"v1 too long":              {"b" + strings.Repeat("a", cidMaxBytes), "a well"},
		"not a CID":                {"https://imgur.com/p.png", "a well"},
	} {
		if !panicsWith(func() { checkImage(c[0], c[1]) }, ErrImage) {
			t.Errorf("%s: not refused", name)
		}
	}
}

views.gno

package bolo

import "chain/banker"

// CampaignView is a campaign as clients see it (API §2.4): a copy, holding nothing
// of the realm's state, its derived fields computed at now without writing.
type CampaignView struct {
	ID, Title, Description, Category, ImageCID, ImageAlt string
	ImageHidden                                          bool
	Organizer, Beneficiary                               address
	Mode, Status, CloseReason                            string
	Listed                                               bool
	Notice                                               string

	Goal      int64
	Raised    int64
	Refunded  int64
	Withdrawn int64
	NetRaised int64
	Balance   int64
	Untracked int64

	DonorCount, DonationCount, RefundCount, UpdateCount int

	Deposit          int64
	Bond             int64
	BondSlashed      bool
	BondReleasableAt int64

	CreatedAt, Deadline, ClosedAt, LastDonationAt, LastUpdateAt int64

	ClosableByAnyoneAt int64
	ExitOpensAt        int64
	FinalizableAt      int64

	EverWithdrawn bool
	ExitOpen      bool

	EscrowAddress address
	BondAddress   address
	Params        Params
}

// GetCampaign returns campaign id's view (API §4). An unknown or non-canonical ID is
// ErrNotFound (C9).
func GetCampaign(id string) CampaignView {
	return campaignView(campaignOf(id))
}

// campaignOf returns the campaign id names, or panics with ErrNotFound (C9).
func campaignOf(id string) *campaign {
	c, ok := lookup(id)
	if !ok {
		panic(ErrNotFound)
	}
	return c
}

// lookup returns the campaign id names, if id is canonical and the campaign exists.
func lookup(id string) (*campaign, bool) {
	n, ok := parseID(id)
	if !ok {
		return nil, false
	}
	v := campaigns.Get(n.Binary())
	if v == nil {
		return nil, false
	}
	return v.(*campaign), true
}

// effective returns c's status, close reason and close time at now, counting a
// passed deadline as recorded (API §2.4, §3.1), without writing.
func effective(c *campaign) (status, reason string, closedAt int64) {
	s := c.state
	if s.status == statusOpen && c.deadline != 0 && now() >= c.deadline {
		return statusClosed, reasonDeadline, c.deadline
	}
	return s.status, s.closeReason, s.closedAt
}

// trackedBalance is what the books say the escrow holds (API §2.4): 0 in direct
// mode.
func trackedBalance(c *campaign) int64 {
	if c.mode != modeEscrow {
		return 0
	}
	s := c.state
	return s.raised - s.withdrawn - s.refunded
}

// campaignView builds c's view at now (API §2.4).
func campaignView(c *campaign) CampaignView {
	s, p := c.state, c.params
	status, reason, closedAt := effective(c)
	balance := trackedBalance(c)
	untracked := banker.NewReadonlyBanker().GetCoin(escrowAddr(c.id), "ugnot") - balance
	if untracked < 0 {
		untracked = 0
	}
	v := CampaignView{
		ID:          idString(c.id),
		Title:       c.text.title,
		Description: c.text.description,
		Category:    c.category,
		ImageCID:    c.text.imageCID,
		ImageAlt:    c.text.imageAlt,
		ImageHidden: s.imageHidden,
		Organizer:   c.organizer,
		Beneficiary: c.beneficiary,
		Mode:        c.mode,
		Status:      status,
		CloseReason: reason,
		Listed:      s.listed,
		Notice:      s.notice,

		Goal:      c.goal,
		Raised:    s.raised,
		Refunded:  s.refunded,
		Withdrawn: s.withdrawn,
		NetRaised: s.raised - s.refunded,
		Balance:   balance,
		Untracked: untracked,

		DonorCount:    s.donorCount,
		DonationCount: s.donationCount,
		RefundCount:   s.refundCount,
		UpdateCount:   s.updateCount,

		Deposit:     p.CreationDeposit,
		Bond:        s.bond,
		BondSlashed: s.bondSlashed,

		CreatedAt:      c.createdAt,
		Deadline:       c.deadline,
		ClosedAt:       closedAt,
		LastDonationAt: s.lastDonationAt,
		LastUpdateAt:   s.lastUpdateAt,

		EverWithdrawn: s.everWithdrawn,
		EscrowAddress: escrowAddr(c.id),
		BondAddress:   bondAddr(c.id),
		Params:        p,
	}
	switch status {
	case statusOpen:
		v.ClosableByAnyoneAt = dormantAt(c)
		if c.deadline != 0 {
			v.FinalizableAt = finalizableAt(c, c.deadline, balance)
		}
	case statusClosed:
		v.BondReleasableAt = closedAt + p.BondHold
		v.FinalizableAt = finalizableAt(c, closedAt, balance)
	case statusSettled:
		v.BondReleasableAt = closedAt + p.BondHold
	}
	if c.mode == modeEscrow && status != statusOpen {
		v.ExitOpensAt = closedAt + p.ExitDelay
		v.ExitOpen = s.everWithdrawn && balance > 0 && now() >= v.ExitOpensAt
	}
	return v
}

// dormantAt is when anyone may close c for dormancy: its last activity plus its
// snapshot's dormancy period (API §3.1).
func dormantAt(c *campaign) int64 { return lastActivity(c) + c.params.DormancyPeriod }

// lastActivity is the latest of c's creation, its last gift and its last update:
// dormancy counts from it (API §3.1).
func lastActivity(c *campaign) int64 {
	last := c.createdAt
	if c.state.lastDonationAt > last {
		last = c.state.lastDonationAt
	}
	if c.state.lastUpdateAt > last {
		last = c.state.lastUpdateAt
	}
	return last
}

// finalizableAt is when Finalize first succeeds for c closed at closedAt (API §2.4,
// §3.4): at once in direct mode or with nothing tracked, else once the exit opens.
func finalizableAt(c *campaign, closedAt, balance int64) int64 {
	if c.mode == modeDirect || balance == 0 {
		return closedAt
	}
	return closedAt + c.params.ExitDelay
}

views_test.gno

package bolo

import (
	"chain"
	"testing"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/testutils/v0"
)

// testCampaign builds a campaign in memory, stored nowhere: views and the deadline
// helper read only what they are given.
func testCampaign(id seqid.ID, mode string, deadline int64) *campaign {
	return &campaign{
		id: id, category: "water", mode: mode, deadline: deadline, createdAt: now(),
		organizer: testutils.TestAddress("organizer"), beneficiary: testutils.TestAddress("beneficiary"),
		params:        Params{1_000_000, 90 * secondsPerDay, 60 * secondsPerDay, 30 * secondsPerDay},
		text:          &campaignText{title: "Clean water"},
		state:         &campaignState{status: statusOpen, listed: true},
		contributions: avl.NewTree(), receipts: avl.NewTree(), withdrawals: avl.NewTree(),
		refunds: avl.NewTree(), updates: avl.NewTree(),
	}
}

const heightsPerDay = 17280 // five seconds a height (spike S10)

func TestRecordDeadline(cur realm, t *testing.T) {
	c := testCampaign(9001, modeEscrow, now()+secondsPerDay)
	key := c.id.Binary()
	active.Set(key, true)
	activeByCategory.Set("water/"+key, true)
	defer dropActive(c)

	recordDeadline(cur, c)
	if c.state.status != statusOpen || !active.Has(key) {
		t.Fatalf("closed before its deadline")
	}
	testing.SkipHeights(2 * heightsPerDay)
	recordDeadline(cur, c)
	s := c.state
	if s.status != statusClosed || s.closedAt != c.deadline || s.closeReason != reasonDeadline {
		t.Errorf("after the deadline: %s at %d (%s), want closed at the deadline %d", s.status, s.closedAt, s.closeReason, c.deadline)
	}
	if active.Has(key) || activeByCategory.Has("water/"+key) {
		t.Errorf("a closed campaign is still in the active indexes")
	}
	// A second call changes nothing.
	s.closeReason = reasonOrganizer
	recordDeadline(cur, c)
	if s.closeReason != reasonOrganizer {
		t.Errorf("recordDeadline rewrote a closed campaign")
	}
}

func TestCampaignView(t *testing.T) {
	// Live Params unlike every test campaign's snapshot: a view reading them would
	// show it (INV-5).
	defer func(p Params) { params = p }(params)
	params = Params{CreationDeposit: 7, DormancyPeriod: 1, ExitDelay: 2, BondHold: 3}

	// Open, no deadline: only dormancy has a time.
	c := testCampaign(9002, modeEscrow, 0)
	c.state.lastDonationAt = now() + 5
	v := campaignView(c)
	if v.Status != statusOpen || v.ClosableByAnyoneAt != now()+5+c.params.DormancyPeriod ||
		v.FinalizableAt != 0 || v.ExitOpensAt != 0 || v.BondReleasableAt != 0 || v.ExitOpen {
		t.Errorf("open, no deadline: %v", v)
	}

	// Open with a deadline: finalizable at the deadline while nothing is tracked,
	// once the exit opens when something is.
	d := testCampaign(9003, modeEscrow, now()+10*secondsPerDay)
	if v := campaignView(d); v.FinalizableAt != d.deadline {
		t.Errorf("open, nothing tracked: FinalizableAt = %d, want %d", v.FinalizableAt, d.deadline)
	}
	d.state.raised = 500
	if v := campaignView(d); v.Balance != 500 || v.NetRaised != 500 || v.FinalizableAt != d.deadline+d.params.ExitDelay {
		t.Errorf("open, 500 tracked: %v", v)
	}

	// Past the deadline: closed at it, without a write.
	testing.SkipHeights(11 * heightsPerDay)
	v = campaignView(d)
	if v.Status != statusClosed || v.CloseReason != reasonDeadline || v.ClosedAt != d.deadline {
		t.Errorf("past the deadline: %s, %s, %d", v.Status, v.CloseReason, v.ClosedAt)
	}
	if d.state.status != statusOpen {
		t.Errorf("a view wrote the close")
	}
	if v.ClosableByAnyoneAt != 0 || v.BondReleasableAt != d.deadline+d.params.BondHold ||
		v.ExitOpensAt != d.deadline+d.params.ExitDelay || v.FinalizableAt != v.ExitOpensAt || v.ExitOpen {
		t.Errorf("closed, never withdrawn: %v", v)
	}

	// The exit window opens only after a withdrawal, once its delay has passed.
	d.state.everWithdrawn = true
	if campaignView(d).ExitOpen {
		t.Errorf("exit open before its delay")
	}
	testing.SkipHeights(61 * heightsPerDay)
	if !campaignView(d).ExitOpen {
		t.Errorf("exit not open after its delay")
	}
	d.state.everWithdrawn = false
	if campaignView(d).ExitOpen {
		t.Errorf("exit open after its delay without any withdrawal")
	}
	// Nor once everything tracked was withdrawn: there is nothing to reclaim.
	d.state.everWithdrawn, d.state.withdrawn = true, d.state.raised
	if campaignView(d).ExitOpen {
		t.Errorf("exit open on an emptied escrow")
	}

	// Direct mode: nothing tracked, no exit, finalizable at the close.
	e := testCampaign(9004, modeDirect, now()+secondsPerDay)
	e.state.raised = 700
	testing.SkipHeights(2 * heightsPerDay)
	if v := campaignView(e); v.Balance != 0 || v.NetRaised != 700 || v.ExitOpensAt != 0 || v.FinalizableAt != e.deadline {
		t.Errorf("direct, closed: %v", v)
	}

	// Settled: nothing left to finalize; the bond's release time stays.
	e.state.status, e.state.closedAt, e.state.closeReason = statusSettled, e.deadline, reasonDeadline
	if v := campaignView(e); v.FinalizableAt != 0 || v.BondReleasableAt != e.deadline+e.params.BondHold {
		t.Errorf("settled: %v", v)
	}

	// Untracked: what the escrow holds beyond the books, never below 0.
	f := testCampaign(9005, modeEscrow, 0)
	f.state.raised = 300
	testing.IssueCoins(escrowAddr(f.id), chain.NewCoins(chain.NewCoin("ugnot", 1000)))
	if v := campaignView(f); v.Untracked != 700 {
		t.Errorf("Untracked = %d, want 700", v.Untracked)
	}
	f.state.raised = 5000
	if v := campaignView(f); v.Untracked != 0 {
		t.Errorf("Untracked = %d, want 0 when the books exceed the bank", v.Untracked)
	}
}