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

api.gno

package campaigns

import (
	"chain"
	"net/url"
	"strconv"
	"strings"

	"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/campaign/v0"
	"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/jsonw/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/r/nt/grc20reg/v0"
)

const (
	apiMaxLimit = 50
	apiMaxScan  = 2000
)

// renderAPI serves JSON for the web app, under Render("api/..."):
//
//	api/stats                                       counts, escrow totals, council, paused
//	api/campaigns?status=&tag=&page=&limit=         newest first; status "all" or empty for every campaign
//	api/campaign/<id>                               one campaign
//	api/campaign/<id>/claims?status=&page=&limit=   its claims, newest first
//	api/campaign/<id>/claimant/<address>            {"claim": an address's latest claim, or null}
//	api/user/<address>?page=&limit=                 campaigns an address is involved in, with roles and their claim
func renderAPI(route string, q url.Values) string {
	parts := strings.Split(route, "/")
	switch {
	case route == "api/stats":
		return apiStats()
	case route == "api/campaigns":
		status := q.Get("status")
		if _, ok := campaign.ParseStatus(status); status != "" && status != "all" && !ok {
			return apiError("unknown status")
		}
		limit := limitOf(q)
		list, more := scan(status, strings.ToLower(q.Get("tag")), (pageOf(q)-1)*limit, limit)
		items := make([]string, len(list))
		for i, c := range list {
			items[i] = campaignJSON(c, false)
		}
		return jsonw.Obj("items", jsonw.Arr(items), "more", jsonw.Bool(more))
	case len(parts) >= 3 && len(parts) <= 5 && parts[1] == "campaign":
		id, err := strconv.ParseUint(parts[2], 10, 64)
		if err != nil {
			return apiError("invalid id")
		}
		c := getCampaign(id)
		if c == nil {
			return apiError("not found")
		}
		if len(parts) == 3 {
			return campaignJSON(c, true)
		}
		if len(parts) == 4 && parts[3] == "claims" {
			return apiClaims(c, q)
		}
		if len(parts) == 5 && parts[3] == "claimant" {
			addr := address(parts[4])
			if !addr.IsValid() {
				return apiError("invalid address")
			}
			mine := jsonw.Null
			if cl := c.ClaimOf(addr); cl != nil {
				mine = claimJSON(cl)
			}
			return jsonw.Obj("claim", mine)
		}
		return apiError("unknown endpoint")
	case len(parts) == 3 && parts[1] == "user":
		return apiUser(address(parts[2]), q)
	}
	return apiError("unknown endpoint")
}

func apiStats() string {
	var escrow []string
	escrowed.Iterate("", "", func(k string, v any) bool {
		if amt := v.(int64); amt > 0 {
			escrow = append(escrow, jsonw.Obj(append([]string{"amount", jsonw.Int(amt)}, denomFields(k, grc20reg.Get(k) != nil)...)...))
		}
		return false
	})
	return jsonw.Obj(
		"total", jsonw.Int(int64(campaigns.Size())),
		"open", jsonw.Int(int64(statusCount[campaign.StatusOpen])),
		"closed", jsonw.Int(int64(statusCount[campaign.StatusClosed])),
		"escrow", jsonw.Arr(escrow),
		"council", jsonw.String(council.Owner().String()),
		"paused", jsonw.Bool(paused),
		"realmAddress", jsonw.String(chain.PackageAddress(realmPath).String()),
		"claimShareBps", jsonw.Int(ClaimShareBps),
		"maxSlots", jsonw.Int(campaign.MaxSlots),
	)
}

func apiClaims(c *campaign.Campaign, q url.Values) string {
	var st *campaign.ClaimStatus
	if s := q.Get("status"); s != "" && s != "all" {
		parsed, ok := campaign.ParseClaimStatus(s)
		if !ok {
			return apiError("unknown status")
		}
		st = &parsed
	}
	limit := limitOf(q)
	list, more := c.Claims(st, (pageOf(q)-1)*limit, limit)
	items := make([]string, len(list))
	for i, cl := range list {
		items[i] = claimJSON(cl)
	}
	return jsonw.Obj("items", jsonw.Arr(items), "more", jsonw.Bool(more))
}

func apiUser(addr address, q url.Values) string {
	if !addr.IsValid() {
		return apiError("invalid address")
	}
	limit := limitOf(q)
	var items []string
	more := false
	if v := byUser.Get(addr.String()); v != nil {
		ids := v.(*avl.Tree)
		ids.ReverseIterateByOffset((pageOf(q)-1)*limit, limit, func(k string, _ any) bool {
			if cv := campaigns.Get(k); cv != nil {
				c := cv.(*campaign.Campaign)
				mine := jsonw.Null
				if cl := c.ClaimOf(addr); cl != nil {
					mine = claimJSON(cl)
				}
				items = append(items, jsonw.Obj("campaign", campaignJSON(c, false), "roles", jsonw.Strings(roles(c, addr)), "claim", mine))
			}
			return false
		})
		more = ids.Size() > pageOf(q)*limit
	}
	return jsonw.Obj("items", jsonw.Arr(items), "more", jsonw.Bool(more))
}

func campaignJSON(c *campaign.Campaign, full bool) string {
	fields := []string{
		"id", jsonw.Uint(c.ID),
		"title", jsonw.String(c.Title),
		"tags", jsonw.Strings(c.Tags),
		"status", jsonw.String(c.Status.String()),
		"poster", jsonw.String(c.Poster.String()),
		"reward", jsonw.Int(c.Reward),
		"slots", jsonw.Int(int64(c.Slots)),
		"paid", jsonw.Int(int64(c.Paid)),
		"pending", jsonw.Int(int64(c.Pending)),
		"rejected", jsonw.Int(int64(c.Rejected)),
		"refunded", jsonw.Int(int64(c.Refunded)),
		"freeSlots", jsonw.Int(int64(c.FreeSlots())),
		"claims", jsonw.Int(int64(c.ClaimCount())),
		"total", jsonw.Int(c.Total()),
		"escrowed", jsonw.Int(c.Escrowed()),
		"paidOut", jsonw.Int(c.PaidOut()),
		"deadline", jsonw.Time(c.Deadline),
		"createdAt", jsonw.Time(c.CreatedAt),
	}
	fields = append(fields, denomFields(c.Denom, c.IsGRC20)...)
	if full {
		fields = append(fields,
			"description", jsonw.String(c.Description),
			"link", jsonw.String(c.Link),
			"reviewers", jsonw.Addresses(c.Reviewers),
			"closedAt", jsonw.Time(c.ClosedAt),
			"claimShareBps", jsonw.Int(ClaimShareBps),
		)
	}
	return jsonw.Obj(fields...)
}

func claimJSON(cl *campaign.Claim) string {
	reviewer := ""
	if cl.ReviewedBy != "" {
		reviewer = cl.ReviewedBy.String()
	}
	return jsonw.Obj(
		"number", jsonw.Int(int64(cl.Number)),
		"claimant", jsonw.String(cl.Claimant.String()),
		"proof", jsonw.String(cl.Proof),
		"status", jsonw.String(cl.Status.String()),
		"at", jsonw.Time(cl.At),
		"reviewedBy", jsonw.String(reviewer),
		"reviewedAt", jsonw.Time(cl.ReviewedAt),
		"reason", jsonw.String(cl.Reason),
	)
}

// denomFields describes how to display amounts of denom.
func denomFields(denom string, isGRC20 bool) []string {
	symbol, decimals := symbolOf(denom, isGRC20)
	return []string{
		"denom", jsonw.String(denom),
		"isGRC20", jsonw.Bool(isGRC20),
		"symbol", jsonw.String(symbol),
		"decimals", jsonw.Int(int64(decimals)),
	}
}

func limitOf(q url.Values) int {
	n, err := strconv.Atoi(q.Get("limit"))
	if err != nil || n < 1 {
		return 20
	}
	if n > apiMaxLimit {
		return apiMaxLimit
	}
	return n
}

func apiError(msg string) string {
	return jsonw.Obj("error", jsonw.String(msg))
}

campaigns.gno

// Package campaigns is Guildhall's escrow for many-hands tasks: a fixed
// reward per claim, a fixed number of slots, and one reviewer approval per
// claim. "10 GNOT each to the first 100 people who write about X" is one
// campaign holding 1000 GNOT.
//
// Each approved claim pays the claimant and writes a reputation record to
// gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation
// at ClaimShareBps of a normal record's weight, vouched for by the reviewer
// who approved it. Small, repeatable tasks therefore count for something
// without outweighing reviewed bounty work.
//
// The rules live in gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/campaign.
// This realm holds the funds, authenticates callers, moves coins, and
// renders the campaigns.
package campaigns

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

	"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/campaign/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/ownable/v0"
	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation"
	"gno.land/r/nt/grc20reg/v0"
)

const (
	// ClaimShareBps is the weight of a claim's reputation record relative to
	// a fully approved bounty milestone (10000).
	ClaimShareBps = 500

	maxDeadlineDays = 365
)

var (
	campaigns   avl.Tree // padded id -> *campaign.Campaign
	lastID      uint64
	byUser      avl.Tree // address -> *avl.Tree(padded id -> struct{})
	statusCount = map[campaign.Status]int{}
	escrowed    avl.Tree // denom key -> int64 currently held

	council *ownable.Ownable
	paused  bool
)

// InitialCouncil owns this namespace and is the only key that can deploy
// here. It can pause new campaigns until TransferCouncil hands the seat on.
const InitialCouncil address = "g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm"

func init() {
	council = ownable.NewWithAddress(InitialCouncil)
}

// ---------------------------------------------------------------------------
// Posting

// PostCampaign posts a campaign funded with the native coins sent along with
// the call, which must equal reward × slots. reviewers is a comma-separated
// address list (empty means the poster reviews alone); any one of them can
// approve a claim. deadlineDays closes the campaign to new claims after that
// many days (0: no deadline).
func PostCampaign(cur realm, title, description, link, tags, reviewers string, reward int64, slots, deadlineDays int) uint64 {
	assertNotPaused()
	if !cur.Previous().IsUserCall() {
		panic("campaigns: native campaigns must be posted directly by a user (maketx call with -send)")
	}
	sent := unsafe.OriginSend()
	if len(sent) != 1 || sent[0].Amount <= 0 {
		panic("campaigns: send exactly one coin denomination to fund the campaign")
	}
	c := newCampaign(cur, sent[0].Denom, false, title, description, link, tags, reviewers, reward, slots, deadlineDays)
	if c.Total() != sent[0].Amount {
		panic(ufmt.Sprintf("campaigns: %d slots × %d is %d%s but %d%s was sent",
			c.Slots, c.Reward, c.Total(), c.Denom, sent[0].Amount, sent[0].Denom))
	}
	return store(c)
}

// PostCampaignGRC20 posts a campaign funded with a registered GRC20 token.
// The caller must first approve this realm's address for reward × slots on
// the token; this call pulls the funds into escrow.
func PostCampaignGRC20(cur realm, tokenKey, title, description, link, tags, reviewers string, reward int64, slots, deadlineDays int) uint64 {
	assertNotPaused()
	if grc20reg.Get(tokenKey) == nil {
		panic("campaigns: unknown token " + strconv.Quote(tokenKey))
	}
	if len(unsafe.OriginSend()) > 0 && cur.Previous().IsUserCall() {
		panic("campaigns: do not send native coins with a GRC20 campaign")
	}
	c := newCampaign(cur, tokenKey, true, title, description, link, tags, reviewers, reward, slots, deadlineDays)
	grc20reg.TransferFrom(0, cur, tokenKey, c.Poster, cur.Address(), c.Total())
	return store(c)
}

func newCampaign(cur realm, denom string, isGRC20 bool, title, description, link, tags, reviewers string, reward int64, slots, deadlineDays int) *campaign.Campaign {
	if deadlineDays < 0 || deadlineDays > maxDeadlineDays {
		panic(ufmt.Sprintf("campaigns: deadline must be 0..%d days", maxDeadlineDays))
	}
	now := time.Now()
	var deadline time.Time
	if deadlineDays > 0 {
		deadline = now.Add(time.Duration(deadlineDays) * 24 * time.Hour)
	}
	c, err := campaign.New(campaign.Params{
		ID:          lastID + 1,
		Poster:      cur.Previous().Address(),
		Title:       title,
		Description: description,
		Link:        link,
		Tags:        strings.Split(tags, ","),
		Denom:       denom,
		IsGRC20:     isGRC20,
		Reward:      reward,
		Slots:       slots,
		Reviewers:   campaign.ParseAddresses(reviewers),
		Deadline:    deadline,
		Now:         now,
	})
	check(err)
	return c
}

func store(c *campaign.Campaign) uint64 {
	lastID = c.ID
	campaigns.Set(idKey(c.ID), c)
	statusCount[c.Status]++
	addEscrow(c, c.Total())
	index(c.Poster, c.ID)
	for _, r := range c.Reviewers {
		index(r, c.ID)
	}
	emit("CampaignPosted", c,
		"poster", c.Poster.String(),
		"denom", c.Denom,
		"reward", strconv.FormatInt(c.Reward, 10),
		"slots", strconv.Itoa(c.Slots))
	return c.ID
}

// ---------------------------------------------------------------------------
// Claims

// Claim asks to be paid for doing the task once. proof is a link to the work
// (the post, the PR, the page). It reserves a slot until a reviewer decides.
// Returns the claim number.
func Claim(cur realm, id uint64, proof string) int {
	c := mustGet(id)
	caller := cur.Previous().Address()
	n, err := c.Claim(caller, proof, time.Now())
	check(err)
	index(caller, id)
	emit("CampaignClaimed", c, "claim", strconv.Itoa(n), "claimant", caller.String())
	return n
}

// ApproveClaim pays a pending claim. Any reviewer of the campaign.
func ApproveClaim(cur realm, id uint64, claim int) {
	c := mustGet(id)
	before := c.Status
	caller := cur.Previous().Address()
	payouts, err := c.Approve(caller, claim, time.Now())
	check(err)
	settle(0, cur, c, payouts, caller)
	moved(c, before)
}

// RejectClaim turns down a pending claim and frees its slot. Any reviewer of
// the campaign.
func RejectClaim(cur realm, id uint64, claim int, reason string) {
	c := mustGet(id)
	caller := cur.Previous().Address()
	payouts, err := c.Reject(caller, claim, reason, time.Now())
	check(err)
	emit("CampaignClaimRejected", c, "claim", strconv.Itoa(claim), "reviewer", caller.String())
	settle(0, cur, c, payouts, caller)
}

// Close stops new claims and refunds the free slots to the poster. The
// poster can close at any time; anyone can close after the deadline. Pending
// claims can still be approved or rejected afterwards.
func Close(cur realm, id uint64) {
	c := mustGet(id)
	before := c.Status
	payouts, err := c.Close(cur.Previous().Address(), time.Now())
	check(err)
	settle(0, cur, c, payouts, "")
	moved(c, before)
	emit("CampaignClosed", c)
}

// ---------------------------------------------------------------------------
// Council

// Council is the address that can pause new campaigns.
func Council() address {
	return council.Owner()
}

// TransferCouncil hands the council seat to another address. Council only.
func TransferCouncil(cur realm, newCouncil address) {
	if err := council.TransferOwnership(0, cur, newCouncil); err != nil {
		panic(err.Error())
	}
	chain.Emit("CampaignsCouncilChanged", "council", newCouncil.String())
}

// SetPaused stops or resumes new campaigns. Existing campaigns, claims and
// payouts are never paused. Council only.
func SetPaused(cur realm, p bool) {
	council.AssertOwnedBy(cur.Previous().Address())
	paused = p
	chain.Emit("CampaignsPaused", "paused", strconv.FormatBool(p))
}

// ---------------------------------------------------------------------------
// Queries

// Count is the number of campaigns ever posted.
func Count() int {
	return campaigns.Size()
}

// CountByStatus counts campaigns in a status ("open" or "closed").
func CountByStatus(status string) int {
	s, ok := campaign.ParseStatus(status)
	if !ok {
		return 0
	}
	return statusCount[s]
}

// Escrowed is the amount of denom (a native denom or a grc20reg key) held.
func Escrowed(denom string) int64 {
	if v := escrowed.Get(denom); v != nil {
		return v.(int64)
	}
	return 0
}

// IsPaused reports whether new campaigns are paused.
func IsPaused() bool {
	return paused
}

// ---------------------------------------------------------------------------
// Internals

func settle(_ int, rlm realm, c *campaign.Campaign, payouts []campaign.Payout, reviewer address) {
	for _, p := range payouts {
		transfer(0, rlm, c, p.To, p.Amount)
		addEscrow(c, -p.Amount)
		emit("CampaignPayout", c,
			"kind", string(p.Kind),
			"to", p.To.String(),
			"amount", strconv.FormatInt(p.Amount, 10),
			"claim", strconv.Itoa(p.Claim))
		if p.Kind != campaign.PayoutWork {
			continue
		}
		cl := c.GetClaim(p.Claim)
		reputation.AddRecord(cross(rlm),
			p.To,
			c.Poster,
			[]address{reviewer},
			ClaimShareBps,
			p.Amount,
			c.Denom,
			clip(c.Title, 300),
			cl.Proof,
			ufmt.Sprintf("c%d/%d", c.ID, p.Claim),
			false,
		)
	}
}

func transfer(_ int, rlm realm, c *campaign.Campaign, to address, amount int64) {
	if amount <= 0 {
		return
	}
	if c.IsGRC20 {
		grc20reg.Transfer(0, rlm, c.Denom, to, amount)
		return
	}
	bk := banker.NewBanker(banker.BankerTypeRealmSend, rlm)
	bk.SendCoins(rlm.Address(), to, chain.Coins{{Denom: c.Denom, Amount: amount}})
}

func mustGet(id uint64) *campaign.Campaign {
	c := getCampaign(id)
	if c == nil {
		panic("campaigns: campaign " + strconv.FormatUint(id, 10) + " not found")
	}
	return c
}

func getCampaign(id uint64) *campaign.Campaign {
	v := campaigns.Get(idKey(id))
	if v == nil {
		return nil
	}
	return v.(*campaign.Campaign)
}

func moved(c *campaign.Campaign, before campaign.Status) {
	if c.Status != before {
		statusCount[before]--
		statusCount[c.Status]++
	}
}

func addEscrow(c *campaign.Campaign, delta int64) {
	cur := int64(0)
	if v := escrowed.Get(c.Denom); v != nil {
		cur = v.(int64)
	}
	escrowed.Set(c.Denom, cur+delta)
}

func index(addr address, id uint64) {
	if addr == "" {
		return
	}
	var t *avl.Tree
	if v := byUser.Get(addr.String()); v != nil {
		t = v.(*avl.Tree)
	} else {
		t = avl.NewTree()
		byUser.Set(addr.String(), t)
	}
	t.Set(idKey(id), struct{}{})
}

func assertNotPaused() {
	if paused {
		panic("campaigns: posting is paused by the council")
	}
}

func check(err error) {
	if err != nil {
		panic(err.Error())
	}
}

func emit(event string, c *campaign.Campaign, kv ...string) {
	attrs := append([]string{"id", strconv.FormatUint(c.ID, 10), "status", c.Status.String()}, kv...)
	chain.Emit(event, attrs...)
}

func idKey(id uint64) string {
	s := strconv.FormatUint(id, 10)
	for len(s) < 12 {
		s = "0" + s
	}
	return s
}

func clip(s string, n int) string {
	if len(s) <= n {
		return s
	}
	for n > 0 && !utf8.RuneStart(s[n]) {
		n--
	}
	return s[:n]
}

gnomod.toml

module = "gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/campaigns"
gno = "0.9"

[addpkg]
  creator = "g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm"
  height = 246217
  max_deposit = "100000000ugnot"

render.gno

package campaigns

import (
	"chain"
	"net/url"
	"strconv"
	"strings"

	"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/campaign/v0"
	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation"
	"gno.land/r/nt/grc20reg/v0"
)

const (
	realmPath = "gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/campaigns"
	realmURL  = "/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/campaigns"
	repURL    = "/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation"
	pageSize  = 20
)

// Render serves the campaigns:
//
//	""             every campaign (?status=open|closed|all, ?tag=x, ?page=N)
//	<id>           a campaign and its claims (?claims=pending|approved|rejected|all, ?page=N)
//	u/<address>    campaigns an address posted, reviews or claimed
//	post           how to post a campaign
func Render(path string) string {
	route, query := splitQuery(path)
	parts := strings.Split(route, "/")
	switch {
	case parts[0] == "api":
		return renderAPI(route, query)
	case route == "":
		return renderBoard(query)
	case route == "post":
		return renderPost()
	case len(parts) == 2 && parts[0] == "u":
		return renderUser(address(parts[1]), pageOf(query))
	case len(parts) == 1:
		id, err := strconv.ParseUint(strings.TrimPrefix(parts[0], "c"), 10, 64)
		if err != nil {
			return notFound()
		}
		return renderCampaign(id, query)
	}
	return notFound()
}

func renderBoard(q url.Values) string {
	status := q.Get("status")
	if status == "" {
		status = "open"
	}
	tag := strings.ToLower(q.Get("tag"))
	page := pageOf(q)

	var b strings.Builder
	b.WriteString("# Guildhall Campaigns\n\n")
	b.WriteString("A fixed reward for each person who does a task, up to a set number of people. A reviewer checks each claim before it pays.\n\n")
	b.WriteString(ufmt.Sprintf("**%d** open · **%d** closed · **%s** in escrow\n\n",
		statusCount[campaign.StatusOpen], statusCount[campaign.StatusClosed], escrowSummary()))
	if paused {
		b.WriteString("> Posting new campaigns is paused by the council. Existing campaigns are unaffected.\n\n")
	} else {
		b.WriteString("[+ Post a campaign](" + realmURL + ":post)\n\n")
	}

	var tabs []string
	for _, s := range []string{"open", "closed", "all"} {
		label := s
		if s == status {
			label = "**" + s + "**"
		}
		link := realmURL + "?status=" + s
		if tag != "" {
			link += "&tag=" + url.QueryEscape(tag)
		}
		tabs = append(tabs, "["+label+"]("+link+")")
	}
	b.WriteString(strings.Join(tabs, " · "))
	if tag != "" {
		b.WriteString(" · tag: `" + sanitize.InlineText(tag) + "` ([clear](" + realmURL + "?status=" + url.QueryEscape(status) + "))")
	}
	b.WriteString("\n\n")

	list, more := scan(status, tag, (page-1)*pageSize, pageSize)
	if len(list) == 0 {
		b.WriteString("_No campaigns here yet._\n")
	} else {
		b.WriteString("| # | Campaign | Reward each | Slots paid | Free | Status | Poster |\n|---:|---|---:|---:|---:|---|---|\n")
		for _, c := range list {
			b.WriteString(ufmt.Sprintf("| %d | [%s](%s:%d)%s | %s | %d/%d | %d | %s | %s |\n",
				c.ID, sanitize.TableCell(c.Title), realmURL, c.ID, tagSuffix(c), formatAmount(c, c.Reward),
				c.Paid, c.Slots, c.FreeSlots(), c.Status.String(), person(c.Poster)))
		}
	}

	var nav []string
	if page > 1 {
		nav = append(nav, "[← newer]("+boardLink(status, tag, page-1)+")")
	}
	if more {
		nav = append(nav, "[older →]("+boardLink(status, tag, page+1)+")")
	}
	if len(nav) > 0 {
		b.WriteString("\n" + strings.Join(nav, " · ") + "\n")
	}
	return b.String()
}

// scan lists campaigns newest first, filtered by status ("", "all" or a
// status name) and tag.
func scan(status, tag string, skip, limit int) (list []*campaign.Campaign, more bool) {
	want, filtered := campaign.ParseStatus(status)
	scanned := 0
	campaigns.ReverseIterate("", "", func(_ string, v any) bool {
		scanned++
		if scanned > apiMaxScan {
			more = true
			return true
		}
		c := v.(*campaign.Campaign)
		if filtered && c.Status != want {
			return false
		}
		if tag != "" && !hasTag(c, tag) {
			return false
		}
		if skip > 0 {
			skip--
			return false
		}
		if len(list) == limit {
			more = true
			return true
		}
		list = append(list, c)
		return false
	})
	return list, more
}

func renderCampaign(id uint64, q url.Values) string {
	c := getCampaign(id)
	if c == nil {
		return notFound()
	}
	var b strings.Builder
	b.WriteString(ufmt.Sprintf("# Campaign %d: %s\n\n", c.ID, sanitize.InlineText(c.Title)))
	b.WriteString(ufmt.Sprintf("**%s** · %s each · %d of %d slots paid · posted %s",
		strings.ToUpper(c.Status.String()), formatAmount(c, c.Reward), c.Paid, c.Slots, c.CreatedAt.UTC().Format("2006-01-02")))
	if len(c.Tags) > 0 {
		var ts []string
		for _, t := range c.Tags {
			ts = append(ts, "["+t+"]("+realmURL+"?status=all&tag="+url.QueryEscape(t)+")")
		}
		b.WriteString(" · " + strings.Join(ts, " "))
	}
	b.WriteString("\n\n")

	if c.Description != "" {
		b.WriteString(sanitize.Block(c.Description) + "\n\n")
	}
	if c.Link != "" {
		b.WriteString("Reference: " + linkOrText(c.Link) + "\n\n")
	}

	b.WriteString("| | |\n|---|---|\n")
	b.WriteString("| Posted by | " + person(c.Poster) + " |\n")
	var revs []string
	for _, r := range c.Reviewers {
		revs = append(revs, person(r))
	}
	b.WriteString("| Reviewers (any one approves) | " + strings.Join(revs, ", ") + " |\n")
	b.WriteString(ufmt.Sprintf("| Slots | %d paid · %d awaiting review · %d free · %d refunded |\n", c.Paid, c.Pending, c.FreeSlots(), c.Refunded))
	if !c.Deadline.IsZero() {
		b.WriteString("| Claims close | " + c.Deadline.UTC().Format("2006-01-02 15:04 UTC") + " |\n")
	}
	b.WriteString("| Escrow | " + formatAmount(c, c.Escrowed()) + " held · " + formatAmount(c, c.PaidOut()) + " paid |\n")
	b.WriteString(ufmt.Sprintf("| Reputation | each paid claim is a record at %s weight |\n\n", bps(ClaimShareBps)))

	b.WriteString(renderActions(c))

	filter := q.Get("claims")
	if filter == "" {
		filter = "all"
	}
	page := pageOf(q)
	var tabs []string
	for _, s := range []string{"pending", "approved", "rejected", "all"} {
		label := s
		if s == filter {
			label = "**" + s + "**"
		}
		tabs = append(tabs, "["+label+"]("+realmURL+":"+idStr(c)+"?claims="+s+")")
	}
	b.WriteString(ufmt.Sprintf("## Claims (%d)\n\n", c.ClaimCount()))
	b.WriteString(strings.Join(tabs, " · ") + "\n\n")

	var st *campaign.ClaimStatus
	if s, ok := campaign.ParseClaimStatus(filter); ok {
		st = &s
	}
	list, more := c.Claims(st, (page-1)*pageSize, pageSize)
	if len(list) == 0 {
		b.WriteString("_No claims here yet._\n")
		return b.String()
	}
	b.WriteString("| # | Claimant | Proof | Status | |\n|---:|---|---|---|---|\n")
	for _, cl := range list {
		status := claimStatus(cl)
		action := ""
		if cl.Status == campaign.ClaimPending {
			n := strconv.Itoa(cl.Number)
			action = "[approve](" + txlink.NewLink("ApproveClaim").AddArgs("id", idStr(c), "claim", n).URL() + ") · " +
				"[reject](" + txlink.NewLink("RejectClaim").AddArgs("id", idStr(c), "claim", n, "reason", "").URL() + ")"
		} else if cl.Status == campaign.ClaimRejected && cl.Reason != "" {
			action = sanitize.TableCell(cl.Reason)
		}
		b.WriteString(ufmt.Sprintf("| %d | %s | %s | %s | %s |\n", cl.Number, person(cl.Claimant), linkOrText(cl.Proof), status, action))
	}
	if page > 1 || more {
		var nav []string
		if page > 1 {
			nav = append(nav, ufmt.Sprintf("[← newer](%s:%s?claims=%s&page=%d)", realmURL, idStr(c), filter, page-1))
		}
		if more {
			nav = append(nav, ufmt.Sprintf("[older →](%s:%s?claims=%s&page=%d)", realmURL, idStr(c), filter, page+1))
		}
		b.WriteString("\n" + strings.Join(nav, " · ") + "\n")
	}
	return b.String()
}

// renderActions lists the transactions anyone might want to send, as gnoweb
// transaction links. The chain enforces who may call them.
func renderActions(c *campaign.Campaign) string {
	if c.Status != campaign.StatusOpen {
		return ""
	}
	var acts []string
	if c.FreeSlots() > 0 {
		acts = append(acts, "[Claim a slot]("+txlink.NewLink("Claim").AddArgs("id", idStr(c), "proof", "").URL()+")")
	}
	acts = append(acts, "[Close and refund free slots (poster)]("+txlink.NewLink("Close").AddArgs("id", idStr(c)).URL()+")")
	return "## Actions\n\n" + strings.Join(acts, " · ") + "\n\n"
}

func renderUser(addr address, page int) string {
	if !addr.IsValid() {
		return notFound()
	}
	var b strings.Builder
	b.WriteString("# Campaigns for " + addr.String() + "\n\n")
	b.WriteString(ufmt.Sprintf("Reputation: **%d** (%s) · [profile](%s:u/%s)\n\n",
		reputation.Score(addr), reputation.Level(addr), repURL, addr.String()))
	v := byUser.Get(addr.String())
	if v == nil {
		b.WriteString("_Not involved in any campaign yet._\n")
		return b.String()
	}
	ids := v.(*avl.Tree)
	b.WriteString("| # | Campaign | Role | Reward each | Their claim | Status |\n|---:|---|---|---:|---|---|\n")
	ids.ReverseIterateByOffset((page-1)*pageSize, pageSize, func(k string, _ any) bool {
		cv := campaigns.Get(k)
		if cv == nil {
			return false
		}
		c := cv.(*campaign.Campaign)
		mine := "-"
		if cl := c.ClaimOf(addr); cl != nil {
			mine = ufmt.Sprintf("#%d %s", cl.Number, cl.Status.String())
		}
		b.WriteString(ufmt.Sprintf("| %d | [%s](%s:%d) | %s | %s | %s | %s |\n",
			c.ID, sanitize.TableCell(c.Title), realmURL, c.ID, strings.Join(roles(c, addr), ", "), formatAmount(c, c.Reward), mine, c.Status.String()))
		return false
	})
	if ids.Size() > page*pageSize {
		b.WriteString(ufmt.Sprintf("\n[older →](%s:u/%s?page=%d)\n", realmURL, addr.String(), page+1))
	}
	return b.String()
}

func renderPost() string {
	native := txlink.NewLink("PostCampaign").
		AddArgs("title", "", "description", "", "link", "", "tags", "", "reviewers", "", "reward", "10000000", "slots", "100", "deadlineDays", "30").
		SetSend("1000000000ugnot").URL()
	grc := txlink.NewLink("PostCampaignGRC20").
		AddArgs("tokenKey", "", "title", "", "reward", "", "slots", "", "deadlineDays", "30").URL()

	var b strings.Builder
	b.WriteString("# Post a campaign\n\n")
	b.WriteString("## With GNOT\n\n")
	b.WriteString("[Open the form](" + native + ") and send exactly **reward × slots**.\n\n")
	b.WriteString("- **reward**: what each approved claim pays, in the smallest unit (`ugnot`; 10 GNOT is `10000000`).\n")
	b.WriteString("- **slots**: how many claims can be paid, up to " + strconv.Itoa(campaign.MaxSlots) + ".\n")
	b.WriteString("- **reviewers**: comma-separated addresses; any one of them can approve a claim. Leave empty to review claims yourself.\n")
	b.WriteString("- **deadlineDays**: stop taking claims after this many days (0 for none). After it, anyone can close the campaign, which refunds the free slots to you.\n\n")
	b.WriteString("```sh\ngnokey maketx call -pkgpath " + realmPath + " -func PostCampaign \\\n")
	b.WriteString("  -args \"Write about Guildhall\" -args \"Post about Guildhall on X with a link to it.\" \\\n")
	b.WriteString("  -args \"https://guildhall.clockwork.gr\" -args \"social\" -args \"\" \\\n")
	b.WriteString("  -args 10000000 -args 100 -args 30 \\\n")
	b.WriteString("  -send 1000000000ugnot -gas-fee 1000000ugnot -gas-wanted 20000000 -broadcast KEY\n```\n\n")
	b.WriteString("## With a GRC20 token\n\n")
	b.WriteString("1. Approve `" + chain.PackageAddress(realmPath).String() + "` on the token for reward × slots.\n")
	b.WriteString("2. Call [PostCampaignGRC20](" + grc + ") with the token's [grc20reg](/r/nt/grc20reg/v0) key.\n")
	return b.String()
}

func claimStatus(cl *campaign.Claim) string {
	switch cl.Status {
	case campaign.ClaimApproved:
		return "✅ paid"
	case campaign.ClaimRejected:
		return "✖️ rejected"
	}
	return "🔍 in review"
}

func roles(c *campaign.Campaign, addr address) []string {
	var out []string
	if c.Poster == addr {
		out = append(out, "poster")
	}
	if c.IsReviewer(addr) {
		out = append(out, "reviewer")
	}
	if c.ClaimOf(addr) != nil {
		out = append(out, "claimant")
	}
	return out
}

func hasTag(c *campaign.Campaign, tag string) bool {
	for _, t := range c.Tags {
		if t == tag {
			return true
		}
	}
	return false
}

func tagSuffix(c *campaign.Campaign) string {
	if len(c.Tags) == 0 {
		return ""
	}
	return " `" + strings.Join(c.Tags, "` `") + "`"
}

func person(addr address) string {
	if addr == "" {
		return "-"
	}
	s := addr.String()
	short := s
	if len(s) > 14 {
		short = s[:8] + "…" + s[len(s)-4:]
	}
	return "[" + short + "](" + repURL + ":u/" + s + ")"
}

func linkOrText(s string) string {
	if u := sanitize.URL(s); u != "" && (strings.HasPrefix(s, "https://") || strings.HasPrefix(s, "/")) {
		return "[" + sanitize.LinkTitle(s) + "](" + u + ")"
	}
	return sanitize.InlineText(s)
}

func formatAmount(c *campaign.Campaign, amount int64) string {
	symbol, decimals := symbolOf(c.Denom, c.IsGRC20)
	return decimal(amount, decimals) + " " + sanitize.InlineText(symbol)
}

func symbolOf(denom string, isGRC20 bool) (string, int) {
	switch {
	case isGRC20:
		if tok := grc20reg.Get(denom); tok != nil {
			return tok.GetSymbol(), tok.GetDecimals()
		}
	case denom == "ugnot":
		return "GNOT", 6
	}
	return denom, 0
}

func escrowSummary() string {
	var parts []string
	escrowed.Iterate("", "", func(k string, v any) bool {
		if amt := v.(int64); amt > 0 {
			symbol, decimals := symbolOf(k, grc20reg.Get(k) != nil)
			parts = append(parts, decimal(amt, decimals)+" "+sanitize.InlineText(symbol))
		}
		return false
	})
	if len(parts) == 0 {
		return "nothing"
	}
	return strings.Join(parts, " + ")
}

func decimal(amount int64, decimals int) string {
	if decimals <= 0 {
		return strconv.FormatInt(amount, 10)
	}
	s := strconv.FormatInt(amount, 10)
	neg := strings.HasPrefix(s, "-")
	s = strings.TrimPrefix(s, "-")
	for len(s) <= decimals {
		s = "0" + s
	}
	whole, frac := s[:len(s)-decimals], strings.TrimRight(s[len(s)-decimals:], "0")
	if neg {
		whole = "-" + whole
	}
	if frac == "" {
		return whole
	}
	return whole + "." + frac
}

func bps(v int64) string {
	return decimal(v, 2) + "%"
}

func idStr(c *campaign.Campaign) string {
	return strconv.FormatUint(c.ID, 10)
}

func boardLink(status, tag string, page int) string {
	l := realmURL + "?status=" + url.QueryEscape(status) + "&page=" + strconv.Itoa(page)
	if tag != "" {
		l += "&tag=" + url.QueryEscape(tag)
	}
	return l
}

func splitQuery(path string) (string, url.Values) {
	route, raw := path, ""
	if i := strings.Index(path, "?"); i >= 0 {
		route, raw = path[:i], path[i+1:]
	}
	q, _ := url.ParseQuery(raw)
	return strings.Trim(route, "/"), q
}

func pageOf(q url.Values) int {
	p, err := strconv.Atoi(q.Get("page"))
	if err != nil || p < 1 {
		return 1
	}
	return p
}

func notFound() string {
	return "# Not found\n\n[Back to campaigns](" + realmURL + ")\n"
}