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

adminparams.gno

package kourtv3
import (
	"strconv"
	"strings"
)
func adminAddr() address {
	if globalDAO != nil {
		return globalDAO.admin
	}
	return directoryAdmin
}
func purgeThreshold() int {
	if globalDAO != nil {
		return globalDAO.purgeM
	}
	return daoBootstrapM
}
func daoSeats() int {
	if globalDAO != nil {
		return globalDAO.n
	}
	return daoBootstrapN
}
func AdminParams() string {
	l := ladderDefault
	r := creditRatesDefault
	hosts := MediaHosts()
	exact, suffix := hosts, ""
	if i := strings.Index(hosts, "|"); i >= 0 {
		exact, suffix = hosts[:i], hosts[i+1:]
	}
	n := func(v int64) string { return strconv.FormatInt(v, 10) }
	return "admin:" + adminAddr().String() +
		";creationBurn:" + n(courtCreationBurn) +
		";burnBps:" + n(burnBps) +
		";assocBond:" + n(assocBondDefault) +
		";purgeM:" + strconv.Itoa(purgeThreshold()) +
		";t1:" + n(l.t1Bps) +
		";t2:" + n(l.t2Bps) +
		";t3:" + n(l.t3Bps) +
		";entry:" + n(l.postsEntry) +
		";l2:" + n(l.postsT2) +
		";l3:" + n(l.postsT3()) +
		";flag:" + n(r.flag) +
		";dispute:" + n(r.dispute) +
		";authorHigh:" + n(r.authorHigh) +
		";conviction:" + n(r.conviction) +
		";unadjudicated:" + n(r.unadjudicated) +
		";domain:" + siteDomain +
		";mediaExact:" + exact +
		";mediaSuffix:" + suffix
}
const adminParamsPath = "admin-params"
func renderAdminParams() string {
	l := ladderDefault
	r := creditRatesDefault
	n := func(v int64) string { return strconv.FormatInt(v, 10) }
	var b strings.Builder
	b.WriteString("# Realm parameters\n\n")
	b.WriteString("Everything the global DAO admin can set, and what it is set " +
		"to now. A court's moderators set their own court's bond, ladder and " +
		"standing rates; those are on the court's page, not here.\n\n")
	b.WriteString("Admin: `" + adminAddr().String() + "`\n\n")
	b.WriteString("| Setting | Now | What it does | Set with |\n")
	b.WriteString("|---|---|---|---|\n")
	b.WriteString("| Court creation burn | " + ugnotAmt(courtCreationBurn) +
		" GNOT | The minimum a new court costs to open. The whole payment is " +
		"burned. 0 turns it off, and off is the shipped default. | " +
		"`SetCourtCreationBurn` |\n")
	b.WriteString("| Burn share of each offering | " + pct(burnBps, bpsDenom) +
		" | Of every payment for a court's coin, this much burns to the keyless " +
		"sink for good; the rest is held by that court for all of its coin and " +
		"paid back pro-rata to anyone who returns coin. One-way courts burn all " +
		"of it. Applies to payments after the change; " +
		strconv.FormatInt(minBurnBps, 10) + "–" + strconv.FormatInt(maxBurnBps, 10) +
		" bps. | `SetBurnBps` |\n")
	b.WriteString("| Association bond | " + ccAmt(assocBondDefault) +
		" CC | What a stranger posts to attach an edge, in courts that set no " +
		"override. | `SetAssociationBondDefault` |\n")
	b.WriteString("| Purge threshold | " + strconv.Itoa(purgeThreshold()) + " of " +
		strconv.Itoa(daoSeats()) + " | How many global moderators must agree to purge. | " +
		"`SetPurgeThreshold` |\n")
	b.WriteString("| Posting ladder | " + n(l.t1Bps) + "/" + n(l.t2Bps) + "/" +
		n(l.t3Bps) + " bps at " + n(l.postsEntry) + "/" + n(l.postsT2) + "/" +
		n(l.postsT3()) + " posts | The default rungs a court inherits: the share " +
		"earned at each tier and the post counts that reach them. | " +
		"`SetLadderDefault` |\n")
	b.WriteString("| Standing rates | flag " + n(r.flag) + " (inert), dispute " +
		n(r.dispute) + ", author " + n(r.authorHigh) + ", conviction " +
		n(r.conviction) + ", unadjudicated " + n(r.unadjudicated) +
		" bps | The default credit each act earns toward standing. Policing " +
		"ranks above authorship, which ranks above staking. The flag rate is " +
		"still settable and still bounds what authorship may be set to, but no " +
		"path credits it since the quality lane was removed. | " +
		"`SetCreditRatesDefault` |\n")
	dom := siteDomain
	if dom == "" {
		dom = "_none_"
	}
	b.WriteString("| Site domain | " + dom + " | The website this realm belongs " +
		"to. Also allow-lists that domain for images without listing it below. | " +
		"`SetSiteDomain` |\n")
	hosts := MediaHosts()
	if hosts == "|" {
		hosts = "_none_"
	}
	b.WriteString("| Media hosts | " + hosts + " | Where images may be loaded " +
		"from: exact hosts before the bar, suffixes after it. | " +
		"`SetMediaHosts` |\n")
	b.WriteString("\nBurned to date — the sink's balance, which is every burn share, " +
		"every creation burn, and anything else ever sent there: **" +
		ugnotAmt(BurnedGNOT()) + " GNOT**, held at `" + BurnSink().String() +
		"` — an address derived from a package path that the path grammar can " +
		"never assign to a deployed realm, so no key to it exists and nothing " +
		"can ever be spent from it. " +
		"Held for coin, across every court: **" + ugnotAmt(TotalReserveGNOT()) +
		" GNOT**, at this realm's own address — which no instruction but a " +
		"holder returning coin for its pro-rata share can move.\n")
	return b.String()
}

answer.gno

package kourtv3
const answerWindow = 3 * epochBlocks
func PostAnswer(cur realm, courtSlug string, claimID uint64, verdict int) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	mustSide(verdict)
	if cs.closed {
		panic("kourtv3: this claim is closed")
	}
	if cs.frozenAt != 0 {
		panic("kourtv3: this claim already has an answer")
	}
	now := heightNow()
	if passed, known := pastDeadline(cs.openedAtTime, deadClaimSecs); (known && passed) ||
		(!known && now >= cs.openedAt+deadClaimTimeout) {
		panic("kourtv3: this claim is past the dead-claim timeout; it closes, it is not answered")
	}
	xbar, mature := cs.oi.Average(now, answerWindow)
	if !mature {
		panic("kourtv3: not enough stake history to answer yet")
	}
	if xbar < effMinAnswerX(c) {
		panic("kourtv3: trailing stake is below the minimum to answer")
	}
	inPriority := false
	if passed, known := pastDeadline(cs.openedAtTime,
		blocksToSecs(c.params.stakeOpenDelayBlocks+answerWindow)+priorityWindowSecs); priorityGateActive(c) &&
		((known && !passed) ||
			(!known && now < cs.openedAt+c.params.stakeOpenDelayBlocks+answerWindow+priorityWindowBlocks)) {
		if !mayAnswerInPriority(c, who) {
			panic("kourtv3: the priority window is open — a qualified answerer may act first (wait ~24h)")
		}
		inPriority = true
	}
	touch(c)
	advancePools(c, cs)
	if life := lifeAvgStake(cs, now); life > xbar {
		xbar = life
	}
	bond := xbar * answerBondBps / 10000
	if c.params.answerBondCapCC > 0 && bond > c.params.answerBondCapCC {
		bond = c.params.answerBondCapCC
	}
	convHi, convLo := cs.sideConv(verdict)
	floor := bondFloorAt(xbar, convHi, convLo)
	oppHi, oppLo := cs.sideConv(oppositeSide(verdict))
	if opp := bondFloorAt(xbar, oppHi, oppLo); opp > floor {
		floor = opp
	}
	if floor > bond {
		bond = floor
	}
	if bond < 1 {
		bond = 1
	}
	mustSpendable(c, who, bond)
	c.coin.Transfer(who, c.escrow, bond)
	cs.frozenAt = now
	cs.rateAccAtFreeze = c.rateAccFP
	cs.xBarFrozen = xbar
	cs.tierRef = tierRefAt(c)
	observeClaimSize(c, xbar)
	cs.yesStakeAtFreeze, cs.noStakeAtFreeze = cs.yesStake, cs.noStake
	cs.answer = int8(verdict)
	cs.answerer = who
	cs.answerBond = bond
	cs.answerBond0 = bond
	cs.answerHeight = now
	cs.answeredAtTime = nowTime()
	if inPriority {
		holdPriority(c, who, claimID)
	}
	pendingExit(c, cs)
	stripEnter(c, cs)
	onClaimAnswered(c, cs)
}
func HasAnswer(courtSlug string, claimID uint64) bool {
	return mustClaim(mustCourt(courtSlug), claimID).frozenAt != 0
}
func AnswerVerdict(courtSlug string, claimID uint64) int {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.frozenAt == 0 {
		panic("kourtv3: no answer yet")
	}
	return int(cs.answer)
}
func AnswerBond(courtSlug string, claimID uint64) int64 {
	return mustClaim(mustCourt(courtSlug), claimID).answerBond
}
func Answerer(courtSlug string, claimID uint64) address {
	return mustClaim(mustCourt(courtSlug), claimID).answerer
}
func XBarFrozen(courtSlug string, claimID uint64) int64 {
	return mustClaim(mustCourt(courtSlug), claimID).xBarFrozen
}

answerbond.gno

package kourtv3
func settleAnswerBond(c *Court, cs *claimState) {
	c.coin.Transfer(c.escrow, cs.answerer, cs.answerBond)
	cs.answerBond = 0
}
func (cs *claimState) sideConv(side int) (hi, lo uint64) {
	if side == sideYES {
		return cs.yesConvHi, cs.yesConvLo
	}
	return cs.noConvHi, cs.noConvLo
}
func bondFloorAt(xbar int64, convHi, convLo uint64) int64 {
	flat := xbar * bondFloorFlatBps / 10000
	if draw := mulDiv128(convToCC(convHi, convLo), bondFloorConvBps, 10000); draw > flat {
		return draw
	}
	return flat
}
func bondFloorFor(cs *claimState) int64 {
	hi, lo := cs.sideConv(int(cs.answer))
	return bondFloorAt(cs.xBarFrozen, hi, lo)
}

association.gno

package kourtv3
import (
	"strconv"
	"strings"
	bptree "gno.land/p/nt/bptree/v0"
)
const (
	assocSupports = int8(0)
	assocContests = int8(1)
	maxAssocOut = 32
	maxAssocIn  = 64
	maxAssocInPerAuthor = 4
)
const assocBondDefaultInit = int64(1_000_000)
var assocBondDefault = assocBondDefaultInit
func assocBondFor(c *Court) int64 {
	if c.assocBond > 0 {
		return c.assocBond
	}
	return assocBondDefault
}
func SetAssociationBondDefault(cur realm, amount int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin sets the default association bond")
	}
	if amount < 0 {
		panic("kourtv3: an association bond cannot be negative")
	}
	assocBondDefault = amount
}
func SetCourtAssociationBond(cur realm, courtSlug string, amount int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	requireActiveMod(ensureMod(c), who)
	if amount < 0 {
		panic("kourtv3: an association bond cannot be negative")
	}
	c.assocBond = amount
}
func AssociationBond(courtSlug string) int64 { return assocBondFor(mustCourt(courtSlug)) }
func AssociationBondDefault() int64 { return assocBondDefault }
const assocBondWindowSecs = int64(14 * 86400)
func mustAssocEdge(c *Court, from, to uint64) *assocEdge {
	if c.assocOut == nil {
		panic("kourtv3: no such association")
	}
	v := c.assocOut.Get(assocKey(from, to))
	if v == nil {
		panic("kourtv3: no such association")
	}
	return v.(*assocEdge)
}
func dropAssocEdge(c *Court, from, to uint64) {
	c.assocOut.Remove(assocKey(from, to))
	c.assocIn.Remove(assocKey(to, from))
}
func burnAssocBond(c *Court, e *assocEdge) {
	amt := e.bond
	e.bond = 0
	c.coin.Burn(c.escrow, amt)
}
func releaseAssocBond(c *Court, e *assocEdge) {
	if e.bond <= 0 {
		return
	}
	amt := e.bond
	e.bond = 0
	c.coin.Transfer(c.escrow, e.author, amt)
}
func ApproveAssociation(cur realm, courtSlug string, from, to uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	requireActiveMod(ensureMod(c), who)
	e := mustAssocEdge(c, from, to)
	if e.bond <= 0 {
		panic("kourtv3: no bond is held on that edge")
	}
	releaseAssocBond(c, e)
}
func DisapproveAssociation(cur realm, courtSlug string, from, to uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	requireActiveMod(ensureMod(c), who)
	e := mustAssocEdge(c, from, to)
	if e.bond <= 0 {
		panic("kourtv3: no bond is held on that edge; remove it instead")
	}
	burnAssocBond(c, e)
	dropAssocEdge(c, from, to)
}
func ClaimAssociationBond(cur realm, courtSlug string, from, to uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	e := mustAssocEdge(c, from, to)
	if e.bond <= 0 {
		panic("kourtv3: no bond is held on that edge")
	}
	if e.author != who {
		panic("kourtv3: only the edge's author may take its bond back")
	}
	if nowTime() < e.bondUntil {
		panic("kourtv3: the moderation window on that bond has not closed yet")
	}
	releaseAssocBond(c, e)
}
func pendingIncident(c *Court, claimID uint64) ([]uint64, []uint64) {
	outs, ins := []uint64{}, []uint64{}
	if c.assocOut == nil {
		return outs, ins
	}
	p := beClaimKey(claimID)
	c.assocOut.Iterate(p, "", func(key string, v any) bool {
		if !strings.HasPrefix(key, p) {
			return true
		}
		if e := v.(*assocEdge); e.bond > 0 {
			outs = append(outs, claimIDFromKey(key[8:]))
		}
		return false
	})
	c.assocIn.Iterate(p, "", func(key string, v any) bool {
		if !strings.HasPrefix(key, p) {
			return true
		}
		if e := v.(*assocEdge); e.bond > 0 {
			ins = append(ins, claimIDFromKey(key[8:]))
		}
		return false
	})
	return outs, ins
}
func ApproveAllAssociations(cur realm, courtSlug string, claimID uint64) int {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	requireActiveMod(ensureMod(c), who)
	mustClaim(c, claimID)
	outs, ins := pendingIncident(c, claimID)
	n := 0
	for _, to := range outs {
		releaseAssocBond(c, mustAssocEdge(c, claimID, to))
		n++
	}
	for _, from := range ins {
		releaseAssocBond(c, mustAssocEdge(c, from, claimID))
		n++
	}
	return n
}
func DisapproveAllAssociations(cur realm, courtSlug string, claimID uint64, reason string) int {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireActiveMod(cm, who)
	checkReason(reason)
	mustClaim(c, claimID)
	key := "assocburn:" + strconv.FormatUint(claimID, 10)
	opened := pendingOpenedAt(cm.pending, key)
	fire, _ := approveAction(cm.pending, key, who, reason, cm.m)
	if !fire {
		return 0
	}
	if opened == 0 {
		opened = heightNow()
	}
	outs, ins := pendingIncident(c, claimID)
	n := 0
	for _, to := range outs {
		n += burnIfOlder(c, claimID, to, opened)
	}
	for _, from := range ins {
		n += burnIfOlder(c, from, claimID, opened)
	}
	return n
}
func burnIfOlder(c *Court, from, to uint64, opened int64) int {
	e := mustAssocEdge(c, from, to)
	if e.bond <= 0 || e.at > opened {
		return 0
	}
	burnAssocBond(c, e)
	dropAssocEdge(c, from, to)
	return 1
}
type assocEdge struct {
	bond int64
	bondUntil int64
	stance int8
	author address
	at int64
}
func ensureAssocs(c *Court) {
	if c.assocOut == nil {
		c.assocOut = bptree.NewBPTree32()
	}
	if c.assocIn == nil {
		c.assocIn = bptree.NewBPTree32()
	}
}
func assocKey(a, b uint64) string { return beClaimKey(a) + beClaimKey(b) }
func assocTextGone(c *Court, id uint64) bool {
	if c.mod == nil {
		return false
	}
	clm := lookupClaimMod(c.mod, id)
	return clm != nil && (clm.purged || clm.global)
}
func AddAssociation(cur realm, courtSlug string, from, to uint64, stance string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	if from == to {
		panic("kourtv3: a claim cannot bear on itself")
	}
	var st int8
	switch stance {
	case "supports":
		st = assocSupports
	case "contests":
		st = assocContests
	default:
		panic("kourtv3: a stance is \"supports\" or \"contests\"")
	}
	f := mustClaim(c, from)
	mustClaim(c, to)
	bond := int64(0)
	if f.author != who && !isActiveMod(ensureMod(c), who) {
		bond = assocBondFor(c)
	}
	ensureAssocs(c)
	k := assocKey(from, to)
	if c.assocOut.Get(k) != nil {
		panic("kourtv3: that edge already exists; remove it to change its stance")
	}
	outN := 0
	c.assocOut.Iterate(beClaimKey(from), "", func(key string, _ any) bool {
		if !strings.HasPrefix(key, beClaimKey(from)) {
			return true
		}
		outN++
		return outN > maxAssocOut
	})
	if outN >= maxAssocOut {
		panic("kourtv3: this claim already asserts " + strconv.Itoa(maxAssocOut) + " associations")
	}
	inN, mine := 0, 0
	c.assocIn.Iterate(beClaimKey(to), "", func(key string, v any) bool {
		if !strings.HasPrefix(key, beClaimKey(to)) {
			return true
		}
		inN++
		if e, ok := v.(*assocEdge); ok && e.author == who {
			mine++
		}
		return false
	})
	if inN >= maxAssocIn {
		panic("kourtv3: that claim already carries " + strconv.Itoa(maxAssocIn) + " associations")
	}
	if mine >= maxAssocInPerAuthor {
		panic("kourtv3: you already hold " + strconv.Itoa(maxAssocInPerAuthor) +
			" associations on that claim")
	}
	if bond > 0 {
		mustSpendable(c, who, bond)
		c.coin.Transfer(who, c.escrow, bond)
	}
	e := &assocEdge{stance: st, author: who, at: heightNow(), bond: bond}
	if bond > 0 {
		e.bondUntil = nowTime() + assocBondWindowSecs
	}
	c.assocOut.Set(k, e)
	c.assocIn.Set(assocKey(to, from), e)
}
func RemoveAssociation(cur realm, courtSlug string, from, to uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	if c.assocOut == nil {
		panic("kourtv3: no such association")
	}
	v := c.assocOut.Get(assocKey(from, to))
	if v == nil {
		panic("kourtv3: no such association")
	}
	e := v.(*assocEdge)
	requireEdgeRemover(c, e.author, who)
	if e.bond > 0 {
		if e.author == who {
			releaseAssocBond(c, e)
		} else {
			burnAssocBond(c, e)
		}
	}
	dropAssocEdge(c, from, to)
}
func ClaimAssociations(courtSlug string, claimID uint64) string {
	c := mustCourt(courtSlug)
	mustClaim(c, claimID)
	var b strings.Builder
	b.WriteString("out:")
	if c.assocOut != nil {
		p := beClaimKey(claimID)
		n := 0
		c.assocOut.Iterate(p, "", func(key string, v any) bool {
			if !strings.HasPrefix(key, p) {
				return true
			}
			e := v.(*assocEdge)
			other := claimIDFromKey(key[8:])
			if assocTextGone(c, other) {
				return false
			}
			if n > 0 {
				b.WriteString(",")
			}
			b.WriteString(strconv.FormatUint(other, 10) + ":" + stanceCode(e.stance))
			n++
			return false
		})
	}
	b.WriteString(";in:")
	if c.assocIn != nil {
		p := beClaimKey(claimID)
		n := 0
		c.assocIn.Iterate(p, "", func(key string, v any) bool {
			if !strings.HasPrefix(key, p) {
				return true
			}
			e := v.(*assocEdge)
			other := claimIDFromKey(key[8:])
			if assocTextGone(c, other) {
				return false
			}
			if n > 0 {
				b.WriteString(",")
			}
			b.WriteString(strconv.FormatUint(other, 10) + ":" + stanceCode(e.stance))
			n++
			return false
		})
	}
	return b.String()
}
func stanceCode(s int8) string {
	if s == assocContests {
		return "c"
	}
	return "s"
}
func claimIDFromKey(k string) uint64 {
	if len(k) < 8 {
		return 0
	}
	var id uint64
	for i := 0; i < 8; i++ {
		id = id<<8 | uint64(k[i])
	}
	return id
}

board.gno

package kourtv3
import (
	"strconv"
	"strings"
	bptree "gno.land/p/nt/bptree/v0"
	sanitize "gno.land/p/nt/markdown/sanitize/v0"
)
const (
	maxBoardTextLen = 2000
	maxBoardRowsPerClaim = 512
	maxBoardRowsPerAuthor = 8
	maxBoardRepliesShown = 8
)
type boardRow struct {
	id     uint64
	parent uint64
	author address
	text   string
	score    int64
	scoreKey string
	at int64
	hiddenByAuthor bool
	hiddenByMod    bool
	global          bool
	purged          bool
	globalClearedAt     int64
	globalClearedAtTime int64
}
func boardMark(r *boardRow) string {
	switch {
	case r.purged:
		return "x"
	case r.global:
		return "g"
	case r.hiddenByAuthor || r.hiddenByMod:
		return "h"
	}
	return "."
}
func ensureBoard(cs *claimState) {
	if cs.board == nil {
		cs.board = bptree.NewBPTree32()
		cs.boardTop = bptree.NewBPTree32()
		cs.boardWrote = bptree.NewBPTree32()
	}
}
func ensureKids(cs *claimState) *bptree.BPTree {
	if cs.boardKids == nil {
		cs.boardKids = bptree.NewBPTree32()
	}
	return cs.boardKids
}
func ensureScoreIdx(cs *claimState) *bptree.BPTree {
	if cs.boardScore == nil {
		cs.boardScore = bptree.NewBPTree32()
	}
	return cs.boardScore
}
func ensureVoted(cs *claimState) *bptree.BPTree {
	if cs.boardVoted == nil {
		cs.boardVoted = bptree.NewBPTree32()
	}
	return cs.boardVoted
}
func boardOpen(cs *claimState) bool { return cs.verdictAt == 0 && !cs.closed }
func boardWroteBy(cs *claimState, who address) int64 {
	if cs.boardWrote == nil {
		return 0
	}
	if v := cs.boardWrote.Get(string(who)); v != nil {
		return v.(int64)
	}
	return 0
}
func PostComment(cur realm, courtSlug string, claimID uint64, parentRow uint64, text string) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	if courtIsPurged(c) {
		panic("kourtv3: this court is purged; it takes no new content")
	}
	cs := mustClaim(c, claimID)
	if !boardOpen(cs) {
		panic("kourtv3: this claim is settled; its board is closed to new comments")
	}
	mustBoardWritable(c, cs, who)
	text = strings.TrimSpace(text)
	if text == "" {
		panic("kourtv3: a comment needs text")
	}
	if runeLen(text) > maxBoardTextLen {
		panic("kourtv3: a comment is at most " + strconv.Itoa(maxBoardTextLen) + " characters")
	}
	if parentRow != 0 {
		p := mustBoardRow(cs, parentRow)
		if p.parent != 0 {
			panic("kourtv3: replies are one level deep; reply to the comment, not to a reply")
		}
	}
	if boardWroteBy(cs, who) >= maxBoardRowsPerAuthor {
		panic("kourtv3: you already have " + strconv.Itoa(maxBoardRowsPerAuthor) +
			" comments on this claim")
	}
	if cs.board != nil && cs.board.Size() >= maxBoardRowsPerClaim {
		panic("kourtv3: this claim's board is full")
	}
	mustSpendPost(c, who)
	ensureBoard(cs)
	cs.boardNextID++
	r := &boardRow{
		id: cs.boardNextID, parent: parentRow, author: who, text: text,
		at: heightNow(),
	}
	k := beClaimKey(r.id)
	cs.board.Set(k, r)
	if parentRow == 0 {
		cs.boardTop.Set(k, r)
		scoreIndexPut(cs, r)
	} else {
		ensureKids(cs).Set(beClaimKey(parentRow)+k, r)
	}
	cs.boardWrote.Set(string(who), boardWroteBy(cs, who)+1)
	return r.id
}
func mustBoardRow(cs *claimState, rowID uint64) *boardRow {
	if cs.board == nil {
		panic("kourtv3: no such comment")
	}
	v := cs.board.Get(beClaimKey(rowID))
	if v == nil {
		panic("kourtv3: no such comment")
	}
	return v.(*boardRow)
}
func HideOwnComment(cur realm, courtSlug string, claimID uint64, rowID uint64, hide bool) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	cs := mustClaim(mustCourt(courtSlug), claimID)
	r := mustBoardRow(cs, rowID)
	if r.author != who {
		panic("kourtv3: only a comment's author may hide their own comment")
	}
	r.hiddenByAuthor = hide
	if hide {
		scoreIndexDrop(cs, r)
	} else {
		scoreIndexPut(cs, r)
	}
}
func BoardSize(courtSlug string, claimID uint64) int {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.board == nil {
		return 0
	}
	return cs.board.Size()
}
func BoardCounts(courtSlug string, ids string) string {
	c := mustCourt(courtSlug)
	out := strings.Builder{}
	sent := 0
	for _, part := range strings.Split(ids, ",") {
		if sent >= seriesPageMax {
			break
		}
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}
		id, err := strconv.ParseUint(part, 10, 64)
		if err != nil {
			continue
		}
		v := c.claims.Get(beClaimKey(id))
		if v == nil {
			continue
		}
		cs := v.(*claimState)
		rows, threads := 0, 0
		if cs.board != nil {
			rows = cs.board.Size()
		}
		if cs.boardTop != nil {
			threads = cs.boardTop.Size()
		}
		if sent > 0 {
			out.WriteString(";")
		}
		out.WriteString(strconv.FormatUint(id, 10))
		out.WriteString(":" + strconv.Itoa(rows))
		out.WriteString(":" + strconv.Itoa(threads))
		sent++
	}
	return out.String()
}
func BoardHiddenCount(courtSlug string, claimID uint64) int {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.boardTop == nil {
		return 0
	}
	n := 0
	cs.boardTop.Iterate("", "", func(_ string, v any) bool {
		if boardMark(v.(*boardRow)) != "." {
			n++
		}
		return false
	})
	return n
}
func BoardOpen(courtSlug string, claimID uint64) bool {
	return boardOpen(mustClaim(mustCourt(courtSlug), claimID))
}
func CommentsWrittenBy(courtSlug string, claimID uint64, who address) int64 {
	return boardWroteBy(mustClaim(mustCourt(courtSlug), claimID), who)
}
func BoardNewest(courtSlug string, claimID uint64, offset, count int) string {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.boardTop == nil || count <= 0 {
		return ""
	}
	if count > maxBoardRepliesShown*8 {
		count = maxBoardRepliesShown * 8
	}
	var b strings.Builder
	cs.boardTop.ReverseIterateByOffset(offset, count, func(_ string, v any) bool {
		r := v.(*boardRow)
		b.WriteString(strconv.FormatUint(r.id, 10) + "|" + r.author.String() + "|" +
			strconv.Itoa(boardReplyCount(cs, r.id)) + "|")
		if m := boardMark(r); m != "." {
			b.WriteString(m + "|" + strconv.FormatInt(r.at, 10) + "|\n")
			return false
		}
		b.WriteString(".|" + strconv.FormatInt(r.at, 10) + "|" + boardTextFor(r) + "\n")
		return false
	})
	return b.String()
}
func boardReplyCount(cs *claimState, parent uint64) int {
	if cs.boardKids == nil {
		return 0
	}
	pre := beClaimKey(parent)
	n := 0
	cs.boardKids.Iterate(pre, "", func(k string, _ any) bool {
		if !strings.HasPrefix(k, pre) || !boardKeyMine(pre, k) {
			return true
		}
		n++
		return false
	})
	return n
}
func boardKeyMine(pre, k string) bool { return len(k) == len(pre)+8 }
func BoardReplies(courtSlug string, claimID uint64, parent uint64) string {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.boardKids == nil {
		return ""
	}
	pre := beClaimKey(parent)
	var b strings.Builder
	n := 0
	cs.boardKids.Iterate(pre, "", func(k string, v any) bool {
		if !strings.HasPrefix(k, pre) || !boardKeyMine(pre, k) {
			return true
		}
		r := v.(*boardRow)
		b.WriteString(strconv.FormatUint(r.id, 10) + "|" + r.author.String() + "|")
		if m := boardMark(r); m != "." {
			b.WriteString(m + "|" + strconv.FormatInt(r.at, 10) + "|\n")
		} else {
			b.WriteString(".|" + strconv.FormatInt(r.at, 10) + "|" + boardTextFor(r) + "\n")
		}
		n++
		return n >= maxBoardRepliesShown
	})
	return b.String()
}
func BoardPartyRows(courtSlug string, claimID uint64) string {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.boardTop == nil {
		return ""
	}
	var b strings.Builder
	for _, r := range boardPartyRows(cs) {
		role := "answerer"
		if r.author == cs.author {
			role = "author"
		}
		b.WriteString(strconv.FormatUint(r.id, 10) + "|" + r.author.String() + "|" + role + "|")
		if m := boardMark(r); m != "." {
			b.WriteString(m + "|" + strconv.FormatInt(r.at, 10) + "|\n")
			continue
		}
		b.WriteString(".|" + strconv.FormatInt(r.at, 10) + "|" + boardTextFor(r) + "\n")
	}
	return b.String()
}
func boardTextFor(r *boardRow) string {
	if boardMark(r) != "." {
		return ""
	}
	return escapeWireText(r.text)
}
func escapeWireText(s string) string {
	if !strings.ContainsAny(s, "\\\n\r") {
		return s
	}
	var b strings.Builder
	for i := 0; i < len(s); i++ {
		switch s[i] {
		case '\\':
			b.WriteString("\\\\")
		case '\n':
			b.WriteString("\\n")
		case '\r':
			b.WriteString("\\r")
		default:
			b.WriteByte(s[i])
		}
	}
	return b.String()
}
func renderBoardPage(slug string, claimID uint64) string {
	return renderBoardIn(slug, claimID, false)
}
func renderBoardTop(slug string, claimID uint64) string {
	return renderBoardIn(slug, claimID, true)
}
func renderBoardHidden(slug string, claimID uint64) string {
	c := mustCourt(slug)
	cs := mustClaim(c, claimID)
	base := "/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/" + strconv.FormatUint(claimID, 10)
	var b strings.Builder
	b.WriteString("# Hidden comments on claim " + strconv.FormatUint(claimID, 10) + "\n\n")
	b.WriteString("[← the comments](" + base + "/board)\n\n")
	if cs.boardTop == nil {
		b.WriteString("_Nothing has been hidden here._\n")
		return b.String()
	}
	n := 0
	cs.boardTop.Iterate("", "", func(_ string, v any) bool {
		r := v.(*boardRow)
		m := boardMark(r)
		if m == "." {
			return false
		}
		n++
		b.WriteString("---\n\n**" + sanitize.InlineText(r.author.String()) + "**")
		b.WriteString(" · block " + strconv.FormatInt(r.at, 10))
		if m != "x" {
			b.WriteString(" · [#" + strconv.FormatUint(r.id, 10) + "](" + base +
				"/board/" + strconv.FormatUint(r.id, 10) + ")")
		} else {
			b.WriteString(" · #" + strconv.FormatUint(r.id, 10))
		}
		b.WriteString("\n\n")
		switch {
		case r.purged:
			b.WriteString("> _Removed on legal grounds. The text is gone from the record; " +
				"the row remains._\n\n")
		case r.global:
			b.WriteString("> _Withheld pending a legal determination._\n\n")
		case r.hiddenByMod:
			b.WriteString("> _Removed from the listing by this court's moderators._\n\n")
			b.WriteString(boardTextVisible(r) + "\n\n")
		default:
			b.WriteString("> _Withdrawn from the listing by its author._\n\n")
			b.WriteString(boardTextVisible(r) + "\n\n")
		}
		return false
	})
	if n == 0 {
		b.WriteString("_Nothing has been hidden here._\n")
	}
	return b.String()
}
func boardPostLink(slug string, claimID, parentRow uint64) string {
	return "/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3$help&func=PostComment" +
		"&courtSlug=" + slug +
		"&claimID=" + strconv.FormatUint(claimID, 10) +
		"&parentRow=" + strconv.FormatUint(parentRow, 10)
}
func renderBoardIn(slug string, claimID uint64, ranked bool) string {
	c := mustCourt(slug)
	cs := mustClaim(c, claimID)
	var b strings.Builder
	b.WriteString("# Comments on claim " + strconv.FormatUint(claimID, 10) + "\n\n")
	base := "/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/" + strconv.FormatUint(claimID, 10)
	b.WriteString("[← the claim](" + base + ")")
	if ranked {
		b.WriteString(" · **Top** · [Newest](" + base + "/board)")
	} else {
		b.WriteString(" · [Top](" + base + "/board/top) · **Newest**")
	}
	b.WriteString("\n\n")
	b.WriteString("[Write a comment](" + boardPostLink(slug, claimID, 0) + ") · " +
		"[Where you stand](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/me) · " +
		helpLink + "\n\n")
	if !boardOpen(cs) {
		b.WriteString("> This claim is settled. Its board is closed to new comments;\n" +
			"> what is here stays.\n\n")
	}
	if TextRedacted(c.id, claimID) {
		b.WriteString("> **The claim itself is withheld or removed on legal grounds.**\n" +
			"> These comments are a separate record and are not covered by that act.\n\n")
	}
	if at, until := claimBoardFrozenAt(c, claimID); until != 0 {
		when := "block " + strconv.FormatInt(until, 10)
		if at != 0 {
			when = strconv.FormatInt(at, 10) + " (" + when + ")"
		}
		b.WriteString("> **Comments are paused on this claim by this court's moderators**\n" +
			"> until " + when + ". The claim itself is\n" +
			"> unaffected: answers, stakes and the verdict continue as normal.\n\n")
	}
	if cs.boardTop == nil || cs.boardTop.Size() == 0 {
		b.WriteString("_No comments yet._\n")
		return b.String()
	}
	seen := map[uint64]bool{}
	if parties := boardPartyRows(cs); len(parties) > 0 {
		b.WriteString("## The parties\n\n")
		for _, r := range parties {
			seen[r.id] = true
			if boardMark(r) != "." {
				continue
			}
			b.WriteString(renderBoardOne(slug, claimID, cs, r, true))
		}
		if ranked {
			b.WriteString("\n## Ranked\n\n")
		} else {
			b.WriteString("\n## Newest\n\n")
		}
	}
	shown := 0
	if ranked {
		if cs.boardScore != nil {
			cs.boardScore.IterateByOffset(0, maxBoardRepliesShown*3, func(_ string, v any) bool {
				r := v.(*boardRow)
				if seen[r.id] {
					return false
				}
				b.WriteString(renderBoardOne(slug, claimID, cs, r, true))
				shown++
				return false
			})
		}
		if shown == 0 {
			b.WriteString("_Nothing else upvoted yet — [Newest](" + base +
				"/board) is the fuller view._\n")
		}
		writeHiddenLink(&b, slug, claimID, base)
		return b.String()
	}
	cs.boardTop.ReverseIterateByOffset(0, maxBoardRepliesShown*3, func(_ string, v any) bool {
		r := v.(*boardRow)
		if seen[r.id] || boardMark(r) != "." {
			return false
		}
		b.WriteString(renderBoardOne(slug, claimID, cs, r, true))
		shown++
		return false
	})
	if rest := cs.boardTop.Size() - shown - len(seen); rest > 0 {
		b.WriteString("\n_" + strconv.Itoa(rest) + " older comments._\n")
	}
	writeHiddenLink(&b, slug, claimID, base)
	return b.String()
}
func writeHiddenLink(b *strings.Builder, slug string, claimID uint64, base string) {
	if k := BoardHiddenCount(slug, claimID); k > 0 {
		b.WriteString("\n[" + strconv.Itoa(k) + " hidden comment" + plural2(k) +
			"](" + base + "/board/hidden)\n")
	}
}
func boardPartyRows(cs *claimState) []*boardRow {
	want := []address{cs.author}
	if cs.frozenAt != 0 && cs.answerer != "" && cs.answerer != cs.author {
		want = append(want, cs.answerer)
	}
	var out []*boardRow
	for _, who := range want {
		var newest *boardRow
		cs.boardTop.ReverseIterate("", "", func(_ string, v any) bool {
			r := v.(*boardRow)
			if r.author == who {
				newest = r
				return true
			}
			return false
		})
		if newest != nil {
			out = append(out, newest)
		}
	}
	return out
}
func renderBoardRow(slug string, claimID uint64, rowArg string) string {
	id, err := strconv.ParseUint(rowArg, 10, 64)
	if err != nil {
		return "## Not found\nA comment id must be a number."
	}
	c := mustCourt(slug)
	cs := mustClaim(c, claimID)
	if cs.board == nil || cs.board.Get(beClaimKey(id)) == nil {
		return "## Not found\nNo comment by that id on this claim."
	}
	r := mustBoardRow(cs, id)
	var b strings.Builder
	b.WriteString("# " + claimTitleFor(c, cs) + "\n\n")
	base := "/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/" + strconv.FormatUint(claimID, 10)
	b.WriteString("Comment " + strconv.FormatUint(id, 10) + " on this claim in " +
		"[" + courtNameFor(c) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + ")\n\n")
	b.WriteString("[← the claim](" + base + ") · [all " +
		strconv.Itoa(cs.board.Size()) + " comments](" + base + "/board)\n\n")
	b.WriteString(renderBoardOne(slug, claimID, cs, r, false))
	return b.String()
}
func renderBoardOne(slug string, claimID uint64, cs *claimState, r *boardRow, listing bool) string {
	var b strings.Builder
	b.WriteString("---\n\n**" + sanitize.InlineText(r.author.String()) + "**")
	for _, badge := range boardBadges(cs, r.author) {
		b.WriteString(" · " + badge)
	}
	b.WriteString(" · [#" + strconv.FormatUint(r.id, 10) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/" +
		strconv.FormatUint(claimID, 10) + "/board/" + strconv.FormatUint(r.id, 10) + ")" +
		" · block " + strconv.FormatInt(r.at, 10) + "\n\n")
	if (r.hiddenByAuthor || r.hiddenByMod) && !r.global && !r.purged && listing {
		if r.hiddenByMod {
			b.WriteString("> _Removed from this listing by this court's moderators. " +
				"It still reads at its own link._\n\n")
		} else {
			b.WriteString("> _Withdrawn from this listing. It still reads at its own link._\n\n")
		}
		return b.String()
	}
	b.WriteString(boardTextVisible(r) + "\n\n")
	if r.parent == 0 {
		writeBoardReplies(&b, slug, claimID, cs, r.id)
		if boardOpen(cs) {
			b.WriteString("[Reply](" + boardPostLink(slug, claimID, r.id) + ")\n\n")
		}
	}
	return b.String()
}
func writeBoardReplies(b *strings.Builder, slug string, claimID uint64, cs *claimState, parent uint64) {
	pre := beClaimKey(parent)
	n, total := 0, boardReplyCount(cs, parent)
	if total == 0 {
		return
	}
	cs.boardKids.Iterate(pre, "", func(k string, v any) bool {
		if !strings.HasPrefix(k, pre) || !boardKeyMine(pre, k) {
			return true
		}
		r := v.(*boardRow)
		if boardMark(r) != "." {
			return false
		}
		b.WriteString("> **" + sanitize.InlineText(r.author.String()) + "**")
		for _, badge := range boardBadges(cs, r.author) {
			b.WriteString(" · " + badge)
		}
		b.WriteString(" · [#" + strconv.FormatUint(r.id, 10) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug +
			"/" + strconv.FormatUint(claimID, 10) + "/board/" + strconv.FormatUint(r.id, 10) + ")\n>\n")
		{
			for _, line := range strings.Split(boardTextVisible(r), "\n") {
				b.WriteString("> " + line + "\n")
			}
			b.WriteString("\n")
		}
		n++
		return n >= maxBoardRepliesShown
	})
	if total > n {
		b.WriteString("_" + strconv.Itoa(total-n) + " more repl" + plural(total-n) +
			" at [#" + strconv.FormatUint(parent, 10) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/" +
			strconv.FormatUint(claimID, 10) + "/board/" + strconv.FormatUint(parent, 10) + ")._\n\n")
	}
}
func plural(n int) string {
	if n == 1 {
		return "y"
	}
	return "ies"
}
func boardBadges(cs *claimState, who address) []string {
	var out []string
	if who == cs.author {
		out = append(out, "author")
	}
	if cs.frozenAt != 0 && who == cs.answerer {
		out = append(out, "answerer")
	}
	for _, side := range []int{sideYES, sideNO} {
		if v := cs.stakers.Get(posKey(who, side)); v != nil {
			if p := v.(*stakePos); p.stake > 0 {
				name := "YES"
				if side == sideNO {
					name = "NO"
				}
				out = append(out, name+" "+strconv.FormatInt(p.stake, 10))
			}
		}
	}
	return out
}
func boardTextVisible(r *boardRow) string {
	if r.purged {
		return "> _Removed. The text is gone from the record; the row remains._"
	}
	if r.global {
		return "> _Withheld pending a legal determination._"
	}
	if r.text == "" {
		return "_(empty)_"
	}
	return sanitize.Block(r.text)
}
func boardScoreKey(score int64, rowID uint64) string {
	return beInv(score) + beInv(int64(rowID))
}
func scoreIndexPut(cs *claimState, r *boardRow) {
	if r.parent != 0 || boardMark(r) != "." {
		return
	}
	r.scoreKey = boardScoreKey(r.score, r.id)
	ensureScoreIdx(cs).Set(r.scoreKey, r)
}
func scoreIndexDrop(cs *claimState, r *boardRow) {
	if cs.boardScore == nil || r.scoreKey == "" {
		return
	}
	cs.boardScore.Remove(r.scoreKey)
	r.scoreKey = ""
}
func UpvoteComment(cur realm, courtSlug string, claimID uint64, rowID uint64) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	if courtIsPurged(c) {
		panic("kourtv3: this court is purged; it takes no new content")
	}
	cs := mustClaim(c, claimID)
	if !boardOpen(cs) {
		panic("kourtv3: this claim is settled; its board is closed")
	}
	mustBoardWritable(c, cs, who)
	r := mustBoardRow(cs, rowID)
	if r.parent != 0 {
		panic("kourtv3: only top-level comments are ranked; a reply is read under its parent")
	}
	if r.author == who {
		panic("kourtv3: you cannot upvote your own comment")
	}
	if r.purged {
		panic("kourtv3: that comment was destroyed on legal grounds; it takes no votes")
	}
	vk := beClaimKey(rowID) + string(who)
	if cs.boardVoted != nil && cs.boardVoted.Has(vk) {
		panic("kourtv3: you have already upvoted that comment")
	}
	var w int64
	if sr := lookupStanding(c, who); sr != nil {
		w = sr.score
	}
	if w <= 0 {
		panic("kourtv3: an upvote is weighted by standing, and you have none here yet")
	}
	mustSpendPost(c, who)
	ensureBoard(cs)
	ensureVoted(cs).Set(vk, true)
	scoreIndexDrop(cs, r)
	r.score = satAdd(r.score, w)
	scoreIndexPut(cs, r)
	return r.score
}
func HasUpvoted(courtSlug string, claimID uint64, rowID uint64, who address) bool {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.boardVoted == nil {
		return false
	}
	return cs.boardVoted.Has(beClaimKey(rowID) + string(who))
}
func CommentScore(courtSlug string, claimID uint64, rowID uint64) int64 {
	return mustBoardRow(mustClaim(mustCourt(courtSlug), claimID), rowID).score
}
func BoardTop(courtSlug string, claimID uint64, offset, count int) string {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.boardScore == nil || count <= 0 {
		return ""
	}
	if count > maxBoardRepliesShown*8 {
		count = maxBoardRepliesShown * 8
	}
	var b strings.Builder
	cs.boardScore.IterateByOffset(offset, count, func(_ string, v any) bool {
		r := v.(*boardRow)
		b.WriteString(strconv.FormatUint(r.id, 10) + "|" + r.author.String() + "|" +
			strconv.FormatInt(r.score, 10) + "|.|" + strconv.FormatInt(r.at, 10) +
			"|" + boardTextFor(r) + "\n")
		return false
	})
	return b.String()
}
func writeBoardLink(b *strings.Builder, c *Court, cs *claimState, claimID uint64) {
	n := 0
	if cs.board != nil {
		n = cs.board.Size()
	}
	link := "/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + c.id + "/" + strconv.FormatUint(claimID, 10) + "/board"
	switch {
	case n == 0 && !boardOpen(cs):
		return
	case n == 0:
		b.WriteString("## Comments\n\n[Write the first one](" +
			boardPostLink(c.id, claimID, 0) + ")\n\n")
		return
	}
	b.WriteString("## Comments\n\n")
	b.WriteString("[Write a comment](" + boardPostLink(c.id, claimID, 0) + ")\n\n")
	shown, drawn := 0, 0
	if cs.boardTop != nil {
		cs.boardTop.ReverseIterate("", "", func(_ string, v any) bool {
			r := v.(*boardRow)
			if boardMark(r) != "." {
				return false
			}
			b.WriteString(renderBoardOne(c.id, claimID, cs, r, true))
			shown += 1 + boardReplyCount(cs, r.id)
			drawn++
			return drawn >= claimBoardPreview
		})
	}
	all := ""
	if shown < n {
		all = "all "
	}
	b.WriteString("\n[" + all + strconv.Itoa(n) + " comment" + plural2(n) + "](" + link +
		") · [Top](" + link + "/top)\n\n")
	writeHiddenLink(b, c.id, claimID, "/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:"+c.id+"/"+strconv.FormatUint(claimID, 10))
}
const claimBoardPreview = 3
func plural2(n int) string {
	if n == 1 {
		return ""
	}
	return "s"
}

boardlegal.gno

package kourtv3
import "strconv"
func boardActCode(verb string, rowID uint64, categoryCode string) string {
	code := verb + "#" + strconv.FormatUint(rowID, 10)
	if categoryCode != "" {
		code += ":" + categoryCode
	}
	return code
}
const (
	boardCodeSpam      = "spam"
	boardCodeOffTopic  = "off-topic"
	boardCodeAbuse     = "abuse"
	boardCodeImpersonation = "impersonation"
	boardCodeIllegal   = "illegal-referred"
)
func mustBoardCode(code string) {
	switch code {
	case boardCodeSpam, boardCodeOffTopic, boardCodeAbuse,
		boardCodeImpersonation, boardCodeIllegal:
		return
	}
	panic("kourtv3: a board moderation code is one of: spam, off-topic, abuse, " +
		"impersonation, illegal-referred")
}
func BoardCodes() string {
	return boardCodeSpam + "," + boardCodeOffTopic + "," + boardCodeAbuse + "," +
		boardCodeImpersonation + "," + boardCodeIllegal
}
func GlobalHideRow(cur realm, courtSlug string, claimID, rowID uint64, categoryCode string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	if !isGlobalMod(who) {
		panic("kourtv3: only a global DAO member may globally hide a comment")
	}
	checkReason(categoryCode)
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	r := mustBoardRow(cs, rowID)
	if r.purged {
		panic("kourtv3: that comment was already destroyed; there is nothing to withhold")
	}
	now := heightNow()
	if !r.global && r.globalClearedAt != 0 &&
		reSetWindowOpen(r.globalClearedAtTime, r.globalClearedAt, now) {
		d := ensureGlobalDAO()
		fire, _ := approveAction(d.pending,
			"boardreset:"+c.id+":"+strconv.FormatUint(claimID, 10)+":"+strconv.FormatUint(rowID, 10),
			who, categoryCode, d.purgeM)
		if !fire {
			return
		}
	}
	r.global = true
	scoreIndexDrop(cs, r)
	ensureClaimMod(c, ensureMod(c), claimID).
		appendLog(who, boardActCode("board-global-hide", rowID, categoryCode), "")
	emitGlobalAct(c.id, claimID, "board-global-hide", who)
}
func GlobalClearRow(cur realm, courtSlug string, claimID, rowID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	if !isGlobalMod(who) {
		panic("kourtv3: only a global DAO member may clear a global comment hide")
	}
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	r := mustBoardRow(cs, rowID)
	if !r.global {
		panic("kourtv3: that comment is not globally hidden")
	}
	r.global = false
	r.globalClearedAt = heightNow()
	r.globalClearedAtTime = nowTime()
	scoreIndexPut(cs, r)
	ensureClaimMod(c, ensureMod(c), claimID).
		appendLog(who, boardActCode("board-global-clear", rowID, ""), "")
	emitGlobalAct(c.id, claimID, "board-global-clear", who)
}
func PurgeBoardRow(cur realm, courtSlug string, claimID, rowID uint64, categoryCode string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if !d.members.Has(who.String()) {
		panic("kourtv3: only a global DAO member may purge")
	}
	mustCategoryCode(categoryCode)
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	r := mustBoardRow(cs, rowID)
	if r.purged {
		return
	}
	fire, votedCode := approveAction(d.pending,
		"boardpurge:"+c.id+":"+strconv.FormatUint(claimID, 10)+":"+strconv.FormatUint(rowID, 10),
		who, categoryCode, d.purgeM)
	if !fire {
		return
	}
	r.purged = true
	r.text = ""
	scoreIndexDrop(cs, r)
	ensureClaimMod(c, ensureMod(c), claimID).
		appendLog(who, boardActCode("board-purge", rowID, votedCode), "")
	emitPurge(c.id, claimID, "board-row", who)
}
func BoardRowState(courtSlug string, claimID uint64, rowID uint64) string {
	return boardMark(mustBoardRow(mustClaim(mustCourt(courtSlug), claimID), rowID))
}
const maxBatchRows = 64
func PurgeBoardRange(cur realm, courtSlug string, claimID, fromRowID uint64, categoryCode string) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if !d.members.Has(who.String()) {
		panic("kourtv3: only a global DAO member may purge")
	}
	mustCategoryCode(categoryCode)
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	cm := ensureMod(c)
	clm := lookupClaimMod(cm, claimID)
	if clm == nil || !clm.boardPurgeAll {
		fire, _ := approveAction(d.pending,
			"boardpurgeall:"+c.id+":"+strconv.FormatUint(claimID, 10),
			who, categoryCode, d.purgeM)
		if !fire {
			return fromRowID
		}
		clm = ensureClaimMod(c, cm, claimID)
		clm.boardPurgeAll = true
		clm.appendLog(who, boardActCode("board-purge-all", 0, categoryCode), "")
		emitPurge(c.id, claimID, "board-all", who)
	}
	if cs.board == nil {
		return 0
	}
	n, next := 0, uint64(0)
	cs.board.Iterate(beClaimKey(fromRowID), "", func(_ string, v any) bool {
		r := v.(*boardRow)
		if r.purged {
			return false
		}
		if n >= maxBatchRows {
			next = r.id
			return true
		}
		r.purged = true
		r.text = ""
		scoreIndexDrop(cs, r)
		n++
		return false
	})
	return next
}
func BoardPurgeOrdered(courtSlug string, claimID uint64) bool {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return false
	}
	clm := lookupClaimMod(c.mod, claimID)
	return clm != nil && clm.boardPurgeAll
}

boardmod.gno

package kourtv3
import "strconv"
const (
	freezeMaxBlocks = int64(17_280) / 2
	freezeGapBlocks = freezeMaxBlocks
)
func mustBoardModInvariants() {
	if freezeMaxBlocks >= 17_280 {
		panic("kourtv3: a board freeze must expire inside the nomination window")
	}
	if freezeGapBlocks < freezeMaxBlocks {
		panic("kourtv3: the gap between freezes must be at least one freeze long, " +
			"or the ceiling is a formality")
	}
}
func init() { mustBoardModInvariants() }
func speechM(cm *courtMod) int {
	m := cm.m
	if m < 2 {
		m = 2
	}
	if m > cm.n {
		m = cm.n
	}
	return m
}
func SpeechThreshold(courtSlug string) int {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return 0
	}
	return speechM(c.mod)
}
func boardSanctionEpochOf(c *Court) int64 {
	if c.mod == nil {
		return 0
	}
	return c.mod.boardSanctionEpoch
}
func boardFreezeActive(r *standingRow) bool {
	passed, known := pastDeadline(r.frozenUntilTime, 0)
	return (known && !passed) || (!known && heightNow() < r.frozenUntil)
}
func boardFreezeGapOpen(r *standingRow) bool {
	passed, known := pastDeadline(r.frozenGapUntilTime, 0)
	return (known && !passed) || (!known && heightNow() < r.frozenGapUntil)
}
func boardFrozen(c *Court, who address) bool {
	r := lookupStanding(c, who)
	if r == nil || r.frozenUntil == 0 {
		return false
	}
	if r.frozenEpoch != boardSanctionEpochOf(c) {
		return false
	}
	return boardFreezeActive(r)
}
func boardFrozenAt(c *Court, who address) (at, atHeight int64) {
	if !boardFrozen(c, who) {
		return 0, 0
	}
	r := lookupStanding(c, who)
	return r.frozenUntilTime, r.frozenUntil
}
func BoardFrozenUntil(courtSlug string, who address) (at, atHeight int64) {
	return boardFrozenAt(mustCourt(courtSlug), who)
}
func claimFreezeActive(clm *claimMod) bool {
	passed, known := pastDeadline(clm.boardFrozenUntilTime, 0)
	return (known && !passed) || (!known && heightNow() < clm.boardFrozenUntil)
}
func claimFreezeGapOpen(clm *claimMod) bool {
	passed, known := pastDeadline(clm.boardFrozenGapUntilTime, 0)
	return (known && !passed) || (!known && heightNow() < clm.boardFrozenGapUntil)
}
func claimBoardFrozen(c *Court, claimID uint64) bool {
	if c.mod == nil {
		return false
	}
	clm := lookupClaimMod(c.mod, claimID)
	if clm == nil || clm.boardFrozenUntil == 0 {
		return false
	}
	if clm.boardFrozenEpoch != c.mod.boardSanctionEpoch {
		return false
	}
	return claimFreezeActive(clm)
}
func claimBoardFrozenAt(c *Court, claimID uint64) (at, atHeight int64) {
	if !claimBoardFrozen(c, claimID) {
		return 0, 0
	}
	clm := lookupClaimMod(c.mod, claimID)
	return clm.boardFrozenUntilTime, clm.boardFrozenUntil
}
func ClaimBoardFrozenUntil(courtSlug string, claimID uint64) (at, atHeight int64) {
	return claimBoardFrozenAt(mustCourt(courtSlug), claimID)
}
func HideBoardRow(cur realm, courtSlug string, claimID, rowID uint64, code string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireActiveMod(cm, who)
	mustBoardCode(code)
	cs := mustClaim(c, claimID)
	r := mustBoardRow(cs, rowID)
	if r.hiddenByMod {
		panic("kourtv3: that comment is already hidden")
	}
	fire, _ := approveAction(cm.pending,
		"boardhide:"+strconv.FormatUint(claimID, 10)+":"+strconv.FormatUint(rowID, 10),
		who, code, speechM(cm))
	if !fire {
		return
	}
	r.hiddenByMod = true
	scoreIndexDrop(cs, r)
	ensureClaimMod(c, cm, claimID).
		appendLog(who, boardActCode("board-hide", rowID, code), "")
	emitModAct(c.id, claimID, "board-hide", who)
}
func UnhideBoardRow(cur realm, courtSlug string, claimID, rowID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireMod(cm, who)
	cs := mustClaim(c, claimID)
	r := mustBoardRow(cs, rowID)
	if !r.hiddenByMod {
		panic("kourtv3: that comment is not hidden")
	}
	fire, _ := approveAction(cm.pending,
		"boardunhide:"+strconv.FormatUint(claimID, 10)+":"+strconv.FormatUint(rowID, 10),
		who, "", speechM(cm))
	if !fire {
		return
	}
	r.hiddenByMod = false
	scoreIndexPut(cs, r)
	ensureClaimMod(c, cm, claimID).
		appendLog(who, boardActCode("board-unhide", rowID, ""), "")
	emitModAct(c.id, claimID, "board-unhide", who)
}
func SlashStanding(cur realm, courtSlug string, who address, levels int64, code string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	actor := cur.Previous().Address()
	if levels < 1 || levels > 3 {
		panic("kourtv3: a slash is 1, 2 or 3 whole levels")
	}
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireActiveMod(cm, actor)
	mustBoardCode(code)
	if who == "" {
		panic("kourtv3: no such address")
	}
	fire, voted := approveAction(cm.pending,
		"slash:"+who.String()+":"+strconv.FormatInt(levels, 10),
		actor, code, speechM(cm))
	if !fire {
		return
	}
	r := getStanding(c, who)
	target := postLevel(c, who) - levels
	if target < 0 {
		target = 0
	}
	if want := levelFloor(c, target); r.score > want {
		r.score = want
	}
	if target == 0 {
		r.passHeld = false
	}
	cm.appendCourtLog(actor, "slash:"+strconv.FormatInt(levels, 10), voted)
	emitModAct(c.id, 0, "slash", actor)
}
func levelFloor(c *Court, lv int64) int64 {
	if lv <= 0 {
		return 0
	}
	l := ladderFor(c)
	sup, _ := boardSupply(c)
	switch lv {
	case 1:
		return sup * l.t1Bps / 10_000
	case 2:
		return sup * l.t2Bps / 10_000
	}
	return sup * l.t3Bps / 10_000
}
func RestoreStanding(cur realm, courtSlug string, who address) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	actor := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireMod(cm, actor)
	r := lookupStanding(c, who)
	if r == nil || r.score >= r.highWater {
		panic("kourtv3: that address has nothing to restore")
	}
	fire, _ := approveAction(cm.pending, "restore:"+who.String(), actor, "",
		speechM(cm))
	if !fire {
		return 0
	}
	r.score = r.highWater
	cm.appendCourtLog(actor, "restore", "")
	emitModAct(c.id, 0, "restore", actor)
	return r.score
}
func FreezeBoard(cur realm, courtSlug string, who address, blocks int64, code string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	actor := cur.Previous().Address()
	if blocks < 1 || blocks > freezeMaxBlocks {
		panic("kourtv3: a board freeze is at most freezeMaxBlocks long")
	}
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireActiveMod(cm, actor)
	mustBoardCode(code)
	if who == "" {
		panic("kourtv3: no such address")
	}
	now := heightNow()
	if r := lookupStanding(c, who); r != nil && boardFreezeGapOpen(r) {
		panic("kourtv3: this address was frozen too recently; the ceiling is not a formality")
	}
	fire, voted := approveAction(cm.pending, "freeze:"+who.String(), actor, code,
		speechM(cm))
	if !fire {
		return
	}
	r := getStanding(c, who)
	r.frozenUntil = now + blocks
	r.frozenUntilTime = nowTime() + blocksToSecs(blocks)
	r.frozenEpoch = boardSanctionEpochOf(c)
	r.frozenGapUntil = now + freezeMaxBlocks + freezeGapBlocks
	r.frozenGapUntilTime = nowTime() + blocksToSecs(freezeMaxBlocks+freezeGapBlocks)
	cm.appendCourtLog(actor, "freeze:"+strconv.FormatInt(blocks, 10), voted)
	emitModAct(c.id, 0, "freeze", actor)
}
func UnfreezeBoard(cur realm, courtSlug string, who address) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	actor := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireMod(cm, actor)
	if !boardFrozen(c, who) {
		panic("kourtv3: that address is not frozen")
	}
	fire, _ := approveAction(cm.pending, "unfreeze:"+who.String(), actor, "",
		speechM(cm))
	if !fire {
		return
	}
	lifted := lookupStanding(c, who)
	lifted.frozenUntil = 0
	lifted.frozenUntilTime = 0
	cm.appendCourtLog(actor, "unfreeze", "")
	emitModAct(c.id, 0, "unfreeze", actor)
}
func FreezeClaimBoard(cur realm, courtSlug string, claimID uint64, blocks int64, code string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	actor := cur.Previous().Address()
	if blocks < 1 || blocks > freezeMaxBlocks {
		panic("kourtv3: a board freeze is at most freezeMaxBlocks long")
	}
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireActiveMod(cm, actor)
	mustBoardCode(code)
	_ = mustClaim(c, claimID)
	now := heightNow()
	if prev := lookupClaimMod(cm, claimID); prev != nil && claimFreezeGapOpen(prev) {
		panic("kourtv3: this board was frozen too recently; the ceiling is not a formality")
	}
	fire, _ := approveAction(cm.pending,
		"freezeboard:"+strconv.FormatUint(claimID, 10), actor, code, speechM(cm))
	if !fire {
		return
	}
	clm := ensureClaimMod(c, cm, claimID)
	clm.boardFrozenUntil = now + blocks
	clm.boardFrozenUntilTime = nowTime() + blocksToSecs(blocks)
	clm.boardFrozenEpoch = cm.boardSanctionEpoch
	clm.boardFrozenGapUntil = now + freezeMaxBlocks + freezeGapBlocks
	clm.boardFrozenGapUntilTime = nowTime() + blocksToSecs(freezeMaxBlocks+freezeGapBlocks)
	clm.appendLog(actor, "freezeboard:"+strconv.FormatInt(blocks, 10)+":"+code, "")
	emitModAct(c.id, claimID, "freezeboard", actor)
}
func ThawClaimBoard(cur realm, courtSlug string, claimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	actor := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireMod(cm, actor)
	if !claimBoardFrozen(c, claimID) {
		panic("kourtv3: that board is not frozen")
	}
	fire, _ := approveAction(cm.pending,
		"thawboard:"+strconv.FormatUint(claimID, 10), actor, "", speechM(cm))
	if !fire {
		return
	}
	thawed := lookupClaimMod(cm, claimID)
	thawed.boardFrozenUntil = 0
	thawed.boardFrozenUntilTime = 0
	ensureClaimMod(c, cm, claimID).appendLog(actor, "thawboard", "")
	emitModAct(c.id, claimID, "thawboard", actor)
}
func GlobalClearBoardBits(cur realm, courtSlug string) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	if !isGlobalMod(who) {
		panic("kourtv3: only a global DAO member may clear board bits (recovery)")
	}
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	cm.boardSanctionEpoch++
	cm.appendCourtLog(who, "global-clear-board-bits", "")
	emitGlobalAct(c.id, 0, "clear-board-bits", who)
	return cm.boardSanctionEpoch
}
func GlobalRestoreStanding(cur realm, courtSlug string, who address) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	actor := cur.Previous().Address()
	if !isGlobalMod(actor) {
		panic("kourtv3: only a global DAO member may restore standing (recovery)")
	}
	c := mustCourt(courtSlug)
	r := lookupStanding(c, who)
	if r == nil || r.score >= r.highWater {
		panic("kourtv3: that address has nothing to restore")
	}
	r.score = r.highWater
	ensureMod(c).appendCourtLog(actor, "global-restore-standing", "")
	emitGlobalAct(c.id, 0, "restore-standing", actor)
	return r.score
}
func mustBoardWritable(c *Court, cs *claimState, who address) {
	if claimBoardFrozen(c, cs.id) {
		panic("kourtv3: this claim's board is frozen by moderators")
	}
	if boardFrozen(c, who) {
		panic("kourtv3: you are frozen out of this court's boards")
	}
}
func PurgeCourtLogRow(cur realm, courtSlug string, rowID uint64, categoryCode string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if !d.members.Has(who.String()) {
		panic("kourtv3: only a global DAO member may purge")
	}
	mustCategoryCode(categoryCode)
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	idx := -1
	for i := range cm.log {
		if cm.log[i].rowID == rowID {
			idx = i
			break
		}
	}
	if idx < 0 {
		panic("kourtv3: no such court log row")
	}
	if cm.log[idx].purged {
		return
	}
	fire, code := approveAction(d.pending,
		"purgecourtrow:"+c.id+":"+strconv.FormatUint(rowID, 10),
		who, categoryCode, d.purgeM)
	if !fire {
		return
	}
	cm.log[idx].purged = true
	cm.log[idx].reason = ""
	cm.appendCourtLog(who, "purgecourtrow:"+code, "")
	emitPurge(c.id, 0, code, who)
}
func GlobalClearCourtParams(cur realm, courtSlug string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	if !isGlobalMod(who) {
		panic("kourtv3: only a global DAO member may clear court parameters (recovery)")
	}
	c := mustCourt(courtSlug)
	if c.ladder == nil && c.creditRates == nil {
		panic("kourtv3: this court has no parameter overrides")
	}
	c.ladder, c.creditRates = nil, nil
	ensureMod(c).appendCourtLog(who, "global-clear-params", "")
	emitGlobalAct(c.id, 0, "clear-court-params", who)
}

buy.gno

package kourtv3
import (
	"chain"
	"chain/banker"
	"chain/runtime/unsafe"
	"strconv"
)
const gnotDenom = "ugnot"
const burnSinkPath = "gno.land/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:burned"
func Buy(cur realm, slug string, minUnits int64) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	prev := cur.Previous()
	if !prev.IsUserCall() {
		panic("kourtv3: a buy must be a direct user call")
	}
	buyer := prev.Address()
	c := mustCourt(slug)
	if buyer == cur.Address() {
		panic("kourtv3: the court's own address may not buy")
	}
	touch(c)
	sent := unsafe.OriginSend().AmountOf(gnotDenom)
	if sent <= 0 {
		panic("kourtv3: send GNOT to buy the coin")
	}
	delta, spent := c.crv.Minted(c.minted, sent)
	if delta <= 0 {
		panic("kourtv3: payment too small to mint a coin")
	}
	if delta < minUnits {
		panic("kourtv3: this offering would mint fewer units than your floor — " +
			strconv.FormatInt(delta, 10) + " < " + strconv.FormatInt(minUnits, 10))
	}
	c.minted += delta
	recordPrice(c)
	c.coin.Mint(buyer, delta)
	burned, reserved := splitPayment(c, spent)
	c.reserve = mustAdd(c.reserve, reserved)
	c.paidIn = mustAdd(c.paidIn, spent)
	totalReserve = mustAdd(totalReserve, reserved)
	reindexBurn(c, burned)
	accrueFranchise(c, buyer, burned)
	b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	b.SendCoins(cur.Address(), chain.PackageAddress(burnSinkPath),
		chain.Coins{chain.NewCoin(gnotDenom, burned)})
	if r := sent - spent; r > 0 {
		b.SendCoins(cur.Address(), buyer, chain.Coins{chain.NewCoin(gnotDenom, r)})
	}
	chain.Emit(boughtEvent,
		"court", c.id,
		"who", buyer.String(),
		"minted", strconv.FormatInt(delta, 10),
		"spent", strconv.FormatInt(spent, 10),
		"burned", strconv.FormatInt(burned, 10),
		"reserved", strconv.FormatInt(reserved, 10),
	)
	return delta
}
func CurvePosition(slug string) int64 { return mustCourt(slug).minted }
func BurnSink() address { return chain.PackageAddress(burnSinkPath) }
func BurnedGNOT() int64 {
	b := banker.NewReadonlyBanker()
	return b.GetCoin(chain.PackageAddress(burnSinkPath), gnotDenom)
}
func CoinBalanceOf(slug string, who address) int64 { return mustCourt(slug).coin.BalanceOf(who) }

claim.gno

package kourtv3
import (
	"chain"
	"strconv"
	"strings"
	checkpoint "gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/checkpoint/v0"
	twap "gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/twap/v0"
	bptree "gno.land/p/nt/bptree/v0"
)
const (
	sideYES = 0
	sideNO  = 1
)
const twapBuckets = 168
const maxClaimBodyLen = 2000
func runeLen(s string) int {
	n := 0
	for range s {
		n++
	}
	return n
}
type claimState struct {
	id     uint64
	title  string
	body   string
	media  []mediaItem
	author address
	deposit  int64
	fee      int64
	seeded   bool
	noAccuracy bool
	openedAt int64
	openedAtTime   int64
	answeredAtTime int64
	verdictAtTime  int64
	escrowUntilAt  int64
	closed         bool
	board      *bptree.BPTree
	boardTop   *bptree.BPTree
	boardKids  *bptree.BPTree
	boardWrote *bptree.BPTree
	boardScore *bptree.BPTree
	boardVoted *bptree.BPTree
	boardNextID uint64
	inStrip   bool
	inPending bool
	yesStake, noStake int64
	stakers           *bptree.BPTree
	yesConvHi, yesConvLo uint64
	noConvHi, noConvLo   uint64
	yesRawHi, yesRawLo   uint64
	noRawHi, noRawLo     uint64
	yesLastAcc, noLastAcc     int64
	yesLastRawAt, noLastRawAt int64
	oi  twap.Ring
	yes twap.Ring
	yesH, noH     checkpoint.Series
	yesD, noD     checkpoint.Series
	histTrimmedTo uint32
	frozenAt        int64
	rateAccAtFreeze int64
	xBarFrozen      int64
	yesStakeAtFreeze, noStakeAtFreeze int64
	answer       int8
	answerer     address
	answerBond   int64
	answerBond0  int64
	answerHeight int64
	verdictAt int64
	route     string
	tierRef int64
	disputeOpen   bool
	disputeOpenedTime int64
	round         int64
	failedRounds  int64
	decidedRounds int64
	disputer      address
	disputeBond   int64
	overturnBy address
	overturnBond int64
	proposalID    int64
	provisional   int8
	escrowUntil   int64
	provClose     bool
	credEligible bool
	voted          *bptree.BPTree
	rewardsOpened bool
	drawWinners   int64
	drawAuthor    int64
	drawAnswerer  int64
	winPoolConvCC int64
	openBlocks    int64
	carrotTotal   int64
	carrotPool    int64
	carrotChoice  string
	carrotDenom   int64
	decidedPID    int64
	spamW      int64
	spamTotalW int64
	spamClosed bool
	authorPaid    bool
	answererPaid  bool
}
func OpenClaim(cur realm, courtSlug, title string) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	if courtIsPurged(c) {
		panic("kourtv3: this court is purged; no new claims may be opened")
	}
	return openClaim(c, cur.Previous().Address(), title, "", false)
}
func OpenClaimIn(cur realm, courtSlug string, folderID uint64, title, body string) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	if courtIsPurged(c) {
		panic("kourtv3: this court is purged; no new claims may be opened")
	}
	cm := ensureMod(c)
	f := cm.mustFolder(folderID)
	if f.retired || f.purged {
		panic("kourtv3: that set is retired; a claim filed there would be unreachable")
	}
	who := cur.Previous().Address()
	id := openClaim(c, who, title, body, false)
	fileInto(f, id)
	emitModAct(c.id, id, "folder-add", who)
	return id
}
func OpenClaimP(cur realm, courtSlug, title, body string) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	if courtIsPurged(c) {
		panic("kourtv3: this court is purged; no new claims may be opened")
	}
	return openClaim(c, cur.Previous().Address(), title, body, false)
}
func OpenClaimSeeded(cur realm, courtSlug, title string) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	if courtIsPurged(c) {
		panic("kourtv3: this court is purged; no new claims may be opened")
	}
	cm := ensureMod(c)
	requireActiveMod(cm, who)
	if cm.installedByMeta {
		panic("kourtv3: a meta-installed moderator set may not seed claims; seed after a local election")
	}
	return openClaim(c, who, title, "", true)
}
func OpenClaimPM(cur realm, courtSlug, title, body, media string) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	if courtIsPurged(c) {
		panic("kourtv3: this court is purged; no new claims may be opened")
	}
	items := parseMediaArg(media)
	id := openClaim(c, cur.Previous().Address(), title, body, false)
	if len(items) > 0 {
		mustClaim(c, id).media = items
	}
	return id
}
func openClaim(c *Court, who address, title, body string, seeded bool) uint64 {
	if runeLen(title) == 0 || runeLen(title) > 200 {
		panic("kourtv3: a claim title is 1..200 characters")
	}
	if runeLen(body) > maxClaimBodyLen {
		panic("kourtv3: a claim body is at most " + strconv.Itoa(maxClaimBodyLen) + " characters")
	}
	var dep, fee int64
	if !seeded {
		dep = effMinDeposit(c)
		fee = dep * depositFeeBps / 10000
		mustSpendable(c, who, dep+fee)
		c.coin.Transfer(who, c.escrow, dep+fee)
		c.deposit += dep + fee
	}
	c.nextID++
	id := c.nextID
	cs := &claimState{
		id:           id,
		title:        title,
		body:         body,
		author:       who,
		deposit:      dep,
		fee:          fee,
		seeded:       seeded,
		openedAt:     heightNow(),
		openedAtTime: nowTime(),
		stakers:      bptree.NewBPTree32(),
		oi:           twap.New(epochBlocks, twapBuckets, 8),
		yes:          twap.New(epochBlocks, twapBuckets, 8),
		provisional:  -1,
	}
	c.claims.Set(beClaimKey(id), cs)
	if seeded {
		pendingEnter(c, cs)
	}
	onClaimOpened(c, cs)
	chain.Emit("ClaimOpened",
		"court", c.id,
		"claim", strconv.FormatUint(id, 10),
		"author", who.String(),
		"seeded", strconv.FormatBool(seeded),
	)
	return id
}
func EditClaimTitle(cur realm, courtSlug string, claimID uint64, newTitle string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if who != cs.author {
		panic("kourtv3: only the author may edit the title")
	}
	if len(newTitle) == 0 || len(newTitle) > 200 {
		panic("kourtv3: a claim title is 1..200 characters")
	}
	if cs.closed || cs.frozenAt != 0 {
		panic("kourtv3: the claim is no longer editable")
	}
	if passed, known := pastDeadline(cs.openedAtTime, blocksToSecs(c.params.stakeOpenDelayBlocks)); (known && passed) ||
		(!known && heightNow() >= cs.openedAt+c.params.stakeOpenDelayBlocks) {
		panic("kourtv3: the polish window has closed; the title is frozen")
	}
	if cs.yesStake != 0 || cs.noStake != 0 {
		panic("kourtv3: staking has begun; the title is frozen")
	}
	cs.title = newTitle
	onTitleEdited(c, cs)
	chain.Emit("ClaimTitleEdited", "court", c.id, "claim", strconv.FormatUint(claimID, 10))
}
func CloseDeadClaim(cur realm, courtSlug string, claimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if cs.closed {
		panic("kourtv3: already closed")
	}
	if cs.frozenAt != 0 {
		panic("kourtv3: this claim has an answer; it settles, it does not die")
	}
	if passed, known := pastDeadline(cs.openedAtTime, deadClaimSecs); (known && !passed) ||
		(!known && heightNow() < cs.openedAt+deadClaimTimeout) {
		panic("kourtv3: the dead-claim timeout has not passed")
	}
	cs.closed = true
	pendingExit(c, cs)
	stripExit(c, cs)
	releaseMetaLatchIfMeta(c, cs)
	if cs.deposit > 0 {
		c.coin.Transfer(c.escrow, cs.author, cs.deposit)
		c.deposit -= cs.deposit
		cs.deposit = 0
	}
	if cs.fee > 0 {
		c.coin.Burn(c.escrow, cs.fee)
		c.deposit -= cs.fee
		cs.fee = 0
	}
}
func ClaimCount(courtSlug string) uint64 { return mustCourt(courtSlug).nextID }
func ClaimTitle(courtSlug string, claimID uint64) string {
	c := mustCourt(courtSlug)
	return claimTitleFor(c, mustClaim(c, claimID))
}
func ClaimBody(courtSlug string, claimID uint64) string {
	c := mustCourt(courtSlug)
	return claimBodyFor(c, mustClaim(c, claimID))
}
func ClaimMedia(courtSlug string, claimID uint64) string {
	c := mustCourt(courtSlug)
	return encodeMedia(claimMediaVisible(c, mustClaim(c, claimID)))
}
func ClaimAuthor(courtSlug string, claimID uint64) address {
	return mustClaim(mustCourt(courtSlug), claimID).author
}
func ClaimClosed(courtSlug string, claimID uint64) bool {
	return mustClaim(mustCourt(courtSlug), claimID).closed
}
func ClaimSeeded(courtSlug string, claimID uint64) bool {
	return mustClaim(mustCourt(courtSlug), claimID).seeded
}
func StakePools(courtSlug string, claimID uint64) (yes, no int64) {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	return cs.yesStake, cs.noStake
}
func TrailingOI(courtSlug string, claimID uint64, window int64) (avg int64, mature bool) {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	return cs.oi.Average(heightNow(), window)
}
func PoolConviction(courtSlug string, claimID uint64) (yes, no int64) {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	return convToCC(cs.yesConvHi, cs.yesConvLo), convToCC(cs.noConvHi, cs.noConvLo)
}
func TrailingYes(courtSlug string, claimID uint64, window int64) (avg int64, mature bool) {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	return cs.yes.Average(heightNow(), window)
}
func DocketSeries(courtSlug string, ids string, window int64) string {
	c := mustCourt(courtSlug)
	now := heightNow()
	out := strings.Builder{}
	sent := 0
	for _, part := range strings.Split(ids, ",") {
		if sent >= seriesPageMax {
			break
		}
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}
		id, err := strconv.ParseUint(part, 10, 64)
		if err != nil {
			continue
		}
		v := c.claims.Get(beClaimKey(id))
		if v == nil {
			continue
		}
		cs := v.(*claimState)
		oi, oiMature := cs.oi.Average(now, window)
		yes, yesMature := cs.yes.Average(now, window)
		if sent > 0 {
			out.WriteString(";")
		}
		out.WriteString(strconv.FormatUint(id, 10))
		out.WriteString(":" + strconv.FormatInt(cs.yesStake, 10))
		out.WriteString(":" + strconv.FormatInt(cs.noStake, 10))
		out.WriteString(":" + strconv.FormatInt(convToCC(cs.yesConvHi, cs.yesConvLo), 10))
		out.WriteString(":" + strconv.FormatInt(convToCC(cs.noConvHi, cs.noConvLo), 10))
		out.WriteString(":" + strconv.FormatInt(oi, 10))
		out.WriteString(":" + boolDigit(oiMature))
		out.WriteString(":" + strconv.FormatInt(yes, 10))
		out.WriteString(":" + boolDigit(yesMature))
		sent++
	}
	return out.String()
}
const seriesPageMax = 60
func boolDigit(b bool) string {
	if b {
		return "1"
	}
	return "0"
}
func mustClaim(c *Court, id uint64) *claimState {
	v := c.claims.Get(beClaimKey(id))
	if v == nil {
		panic("kourtv3: no such claim")
	}
	return v.(*claimState)
}
func beClaimKey(id uint64) string {
	b := [8]byte{
		byte(id >> 56), byte(id >> 48), byte(id >> 40), byte(id >> 32),
		byte(id >> 24), byte(id >> 16), byte(id >> 8), byte(id),
	}
	return string(b[:])
}

claimhead.gno

package kourtv3
import (
	"strconv"
	"strings"
)
func ClaimHead(courtSlug string, claimID uint64, window int64) string {
	c := mustCourt(courtSlug)
	mustClaim(c, claimID)
	b := strings.Builder{}
	n := func(v int64) { b.WriteString(strconv.FormatInt(v, 10) + "\t") }
	i := func(v int) { b.WriteString(strconv.Itoa(v) + "\t") }
	f := func(v bool) { b.WriteString(boolDigit(v) + "\t") }
	t := func(v string) { b.WriteString(v + "\t") }
	yes, no := StakePools(courtSlug, claimID)
	cy, cn := PoolConviction(courtSlug, claimID)
	oi, oiM := TrailingOI(courtSlug, claimID, window)
	ty, tyM := TrailingYes(courtSlug, claimID, window)
	n(yes)
	n(no)
	n(cy)
	n(cn)
	n(oi)
	f(oiM)
	n(ty)
	f(tyM)
	answered := HasAnswer(courtSlug, claimID)
	settled := Settled(courtSlug, claimID)
	disputeOpen := DisputeOpen(courtSlug, claimID)
	provClose := ProvClose(courtSlug, claimID)
	f(answered)
	f(disputeOpen)
	f(settled)
	f(provClose)
	i(Provisional(courtSlug, claimID))
	f(ClaimClosed(courtSlug, claimID))
	if answered {
		who := Answerer(courtSlug, claimID)
		i(AnswerVerdict(courtSlug, claimID))
		n(AnswerBond(courtSlug, claimID))
		n(SettleDeadline(courtSlug, claimID))
		t(who.String())
		i(AnswerRecord(courtSlug, who))
	} else {
		i(-1)
		n(0)
		n(0)
		t("")
		i(0)
	}
	if answered && !settled {
		n(FailedRounds(courtSlug, claimID))
		n(DisputeBondNext(courtSlug, claimID))
		n(EscrowUntil(courtSlug, claimID))
		if disputeOpen {
			n(QuorumFloorOf(courtSlug, claimID))
			n(DisputeVoteCloses(courtSlug, claimID))
		} else {
			n(0)
			n(0)
		}
	} else {
		n(0)
		n(0)
		n(0)
		n(0)
		n(0)
	}
	if settled && !provClose {
		i(Verdict(courtSlug, claimID))
		t(VerdictRoute(courtSlug, claimID))
	} else {
		i(-1)
		t("")
	}
	cryst := RewardsOpened(courtSlug, claimID)
	f(cryst)
	if cryst {
		w, au, an, ca := DrawSlices(courtSlug, claimID)
		n(w)
		n(au)
		n(an)
		n(ca)
	} else {
		n(0)
		n(0)
		n(0)
		n(0)
	}
	t(ClaimAuthor(courtSlug, claimID).String())
	f(HiddenFromListing(courtSlug, claimID))
	f(TextRedacted(courtSlug, claimID))
	f(ClaimPurged(courtSlug, claimID))
	f(ClaimSeeded(courtSlug, claimID))
	n(CourtStakeOpenDelay(courtSlug))
	i(BoardSize(courtSlug, claimID))
	f(BoardOpen(courtSlug, claimID))
	return strings.TrimSuffix(b.String(), "\t")
}
const claimHeadFields = 39

clock.gno

package kourtv3
import (
	"chain/runtime"
	"strconv"
)
const (
	settleSecs    = int64(72 * 3600)
	deadClaimSecs = int64(12 * 7 * 86400)
	finalizeGraceSecs = int64(7 * 86400)
	priorityWindowSecs = int64(24 * 3600)
)
func nowTime() int64 { return tcNow() }
func deadlineTime(stamp, secs int64) int64 {
	if stamp == 0 {
		return 0
	}
	return stamp + secs
}
func pastDeadline(stamp, secs int64) (passed, known bool) {
	if stamp == 0 {
		return false, false
	}
	return nowTime() >= stamp+secs, true
}
func blocksToSecs(b int64) int64 { return b * 5 }
func heightNow() int64 {
	var h int64
	if tcArmed {
		h = tcHeightBase + tcHeightSkew
	} else {
		h = runtime.ChainHeight()
		if h < tcHeightFloor {
			h = tcHeightFloor
		}
	}
	return h
}
func itoa(v int64) string { return strconv.FormatInt(v, 10) }
func ClaimTimeline(courtSlug string, claimID uint64) string {
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	out := "opened:" + itoa(cs.openedAtTime) + ":" + itoa(cs.openedAt)
	if cs.answerHeight != 0 {
		out += ";answered:" + itoa(cs.answeredAtTime) + ":" + itoa(cs.answerHeight)
		if cs.verdictAt == 0 && !cs.closed {
			out += ";settle:" + itoa(deadlineTime(cs.answeredAtTime, settleSecs)) +
				":" + itoa(cs.answerHeight+settleDelay)
		}
	}
	if cs.verdictAt != 0 {
		out += ";verdict:" + itoa(cs.verdictAtTime) + ":" + itoa(cs.verdictAt)
	}
	if cs.escrowUntil != 0 {
		out += ";reopen:" + itoa(cs.escrowUntilAt) + ":" + itoa(cs.escrowUntil)
	}
	if cs.disputeOpen && cs.proposalID != 0 {
		opened, closes, _, _ := c.gov.Timings(cs.proposalID)
		out += ";dispute:" + itoa(cs.disputeOpenedTime) + ":" + itoa(opened)
		_, closesTime := c.gov.TimingsAt(cs.proposalID)
		out += ";voteclose:" + itoa(closesTime) + ":" + itoa(closes)
	}
	out += ";now:" + itoa(nowTime()) + ":" + itoa(heightNow())
	if TestClockFabricated() {
		out += ";testclock:" + itoa(TestClockPeakSkew()) + ":" + itoa(TestHeightPeakSkew())
	}
	return out
}
type realmClock struct{}
func (realmClock) Height() int64 { return heightNow() }
func (realmClock) Now() int64 { return nowTime() }
func eventHeight() string {
	h := strconv.FormatInt(heightNow(), 10)
	if TestClockFabricated() {
		return h + "~test"
	}
	return h
}

court.gno

package kourtv3
import (
	"strings"
	checkpoint "gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/checkpoint/v0"
	curve "gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/curve/v0"
	governor "gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/governor/v0"
	grc20votes "gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/grc20votes/v0"
	bptree "gno.land/p/nt/bptree/v0"
)
const errStaleRealm = "kourtv3: stale realm; call through a crossing function"
const (
	coinDecimals = 6
	epochBlocks  = int64(720)
	curveCap   = (int64(9223372036854775807) / grc20votes.Bps) / 2
	curveDenom = int64(1_000_000_000)
)
const (
	periodBlocks = int64(120_960)
	budgetWeeklyBps = int64(38)
	stepDownPeriods = int64(104)
	rMaxPeriods     = int64(4)
	tierRefFloorBps = int64(40)
	tierFloorBps    = int64(2500)
	tierCeilBps     = int64(20000)
	tierRefDustCC   = int64(1_000_000)
	tierEMAN = int64(16)
	tierParBps = int64(10000)
	splitWinners, splitAuthor, splitAnswerer, splitCarrot = int64(80), int64(8), int64(5), int64(7)
)
const (
	answerBondBps = int64(600)
	disputeBondXBps, disputeBondOfAnswerBps = int64(2000), int64(4000)
	maxFailedRounds                         = 3
	compOwnX, compOfBurnBps = int64(2), int64(8000)
	decideWindowBlocks = int64(120_960)
	carrotClampXBps  = int64(200)
	carrotClampMinCC = int64(1_000_000)
	bondFloorFlatBps = int64(450)
	bondFloorConvBps = int64(10700)
	depositFeeBps    = int64(1000)
	priorityNetRecord    = 3
	priorityColdStartN   = 3
	priorityWindowBlocks = int64(17_280)
	settleDelay      = int64(51_840)
	deadClaimTimeout = int64(1_451_520)
	metaSlug = "meta"
	metaWeeklyBudget = int64(100_000_000)
	answerXFloorBps = int64(50)
	depositFloorBps = int64(2)
	ordAnswerXFloorBps = int64(10)
	ordDepositFloorBps = int64(1)
	maxCourtNameLen = 100
	maxSlugLen        = 11
	maxStakeOpenDelay = int64(17_280)
)
func mustInvariants() {
	maxSupply := int64(9223372036854775807) / grc20votes.Bps
	if curveCap > (maxSupply/1785)*1000 {
		panic("kourtv3: curveCap × emission growth bound exceeds the tally-safe supply ceiling")
	}
	if metaLifetimeEmission := metaWeeklyBudget * 151; curveCap > maxSupply-metaLifetimeEmission {
		panic("kourtv3: curveCap + meta's lifetime emission exceeds the tally-safe supply ceiling")
	}
	if tierFloorBps*tierRefFloorBps != tierParBps*ordAnswerXFloorBps {
		panic("kourtv3: the multiplier's floor no longer meets the answerability floor — " +
			"a band of answerable claims would have a rate their size cannot move")
	}
	if tierCeilBps != 2*tierParBps {
		panic("kourtv3: the multiplier ceiling is no longer the old HIGH band — " +
			"this raises the per-claim draw the emission bounds were fitted to")
	}
	if tierFloorBps <= 0 || tierFloorBps >= tierParBps || tierParBps >= tierCeilBps {
		panic("kourtv3: the multiplier clamps are out of order")
	}
	if tierRefFloorBps <= ordAnswerXFloorBps {
		panic("kourtv3: the reference floor must exceed the answerability floor")
	}
	if tierEMAN <= 0 {
		panic("kourtv3: the running average's memory must be positive")
	}
	parPoints := tierParBps / 100
	if bondFloorConvBps < (parPoints+splitCarrot)*100 {
		panic("kourtv3: the slash multiple does not cover the mid draw plus the carrot — the draw cap would cut the published MID rate")
	}
	if 2*disputeBondOfAnswerBps > compOfBurnBps {
		panic("kourtv3: dispute bond arm breaks the round-1 honest-dispute bar")
	}
	if budgetWeeklyBps*52 > 2000 {
		panic("kourtv3: the weekly budget exceeds the 20%/yr inflation ceiling")
	}
	if splitWinners+splitAuthor+splitAnswerer != 93 {
		panic("kourtv3: the tier-scaled split must sum to 93 points")
	}
	maxRateBpsFP := 255 * (r0WeeklyBps*1_000_000 + budgetBpsFPStart) / 100
	maxTcWeeks := deadClaimTimeout / periodBlocks
	maxMidGrossBps := maxRateBpsFP * maxTcWeeks / 1_000_000
	if bondFloorConvBps*maxMidGrossBps/10000 <= answerBondBps {
		panic("kourtv3: the draw arm never reaches the base bond — the collateralization floor is inert and the max-keying prices nothing")
	}
	maxBondBps := bondFloorConvBps * maxMidGrossBps / 10000
	if maxBondBps < answerBondBps {
		maxBondBps = answerBondBps
	}
	if bondFloorFlatBps*4/3 > answerBondBps {
		panic("kourtv3: the flat slash arm leaves the base answer bond no settle-refund margin")
	}
	if maxAnswerBondBps() != maxBondBps {
		panic("kourtv3: maxAnswerBondBps drifted from the deploy-time worst-case bond")
	}
	for _, l := range []struct {
		name    string
		floor   int64
		deposit int64
	}{
		{"meta", answerXFloorBps, depositFloorBps},
		{"ordinary", ordAnswerXFloorBps, ordDepositFloorBps},
	} {
		filing := l.floor * (grc20votes.Bps + maxBondBps) / grc20votes.Bps
		if filing >= quorumSupplyBps {
			panic("kourtv3: the " + l.name + " answerability floor prices filing above winning the vote — incumbency lock by price")
		}
		if 50*l.deposit < filing {
			panic("kourtv3: a 50-row flood is cheaper than the self-answer escape from it (§5.3), " + l.name + " lane")
		}
		if l.deposit >= l.floor {
			panic("kourtv3: the " + l.name + " deposit floor exceeds its answerability floor")
		}
	}
}
func init() { mustInvariants() }
type Params struct {
	disputeThresholdBps  int64
	votingBlocks         int64
	graceBlocks          int64
	minAnswerX           int64
	answerBondCapCC      int64
	minClaimDepositCC    int64
	escrowMinBlocks      int64
	escrowMaxBlocks      int64
	stakeOpenDelayBlocks int64
}
func defaultParams() Params {
	return Params{
		disputeThresholdBps:  5001,
		votingBlocks:         120_960,
		graceBlocks:          17_280,
		minAnswerX:           1_000_000,
		answerBondCapCC:      0,
		minClaimDepositCC:    1_000_000,
		escrowMinBlocks:      120_960,
		escrowMaxBlocks:      362_880,
		stakeOpenDelayBlocks: 0,
	}
}
func (p Params) mustSane() Params {
	if p.disputeThresholdBps < 5001 || p.disputeThresholdBps > 10000 {
		panic("kourtv3: the overturn threshold must be in [5001, 10000]")
	}
	if p.votingBlocks < 1 || p.graceBlocks < 1 {
		panic("kourtv3: vote and grace windows must be positive")
	}
	if p.minAnswerX < 1 {
		panic("kourtv3: minAnswerX must be positive")
	}
	if p.minClaimDepositCC < 1 {
		panic("kourtv3: the claim deposit must never be zero")
	}
	if p.escrowMinBlocks < 1 || p.escrowMaxBlocks < p.escrowMinBlocks {
		panic("kourtv3: the escrow window is malformed")
	}
	if ladderWindow(p) > p.escrowMaxBlocks {
		panic("kourtv3: the escrow ceiling cannot fit the failed-round ladder a defaulted verdict must walk")
	}
	if p.answerBondCapCC < 0 {
		panic("kourtv3: answerBondCapCC must be non-negative")
	}
	if p.stakeOpenDelayBlocks < 0 || p.stakeOpenDelayBlocks > maxStakeOpenDelay {
		panic("kourtv3: the polish window must be in [0, 24h]")
	}
	return p
}
type Court struct {
	xBarAcc int64
	id   string
	name string
	desc string
	image *mediaItem
	tier  uint8
	admin address
	coin *grc20votes.Ledger
	gov  *governor.Governor
	crv  curve.Curve
	escrow address
	minted int64
	claims  *bptree.BPTree
	nextID  uint64
	params  Params
	deposit int64
	cumAccrual      int64
	accrualRem      int64
	curPeriodBudget int64
	curBudgetBpsFP  int64
	dEffBpsFP       int64
	rateAccFP       int64
	emaMinted       int64
	emittedAtRoll   int64
	lastAccrual     int64
	periodIndex     int64
	createdAt       int64
	reservedTail    int64
	juniorReserved  int64
	seniorOwed      int64
	seniorPaid      int64
	emittedTotal    int64
	queue           *bptree.BPTree
	queueSeq        uint64
	records         *bptree.BPTree
	assocOut          *bptree.BPTree
	assocIn           *bptree.BPTree
	supOf           *bptree.BPTree
	supBy           *bptree.BPTree
	locked         *bptree.BPTree
	voteLocks      *bptree.BPTree
	stakeIdx       *bptree.BPTree
	qualifiedCount int
	mod *courtMod
	csArch *checkpoint.Archive
	stripIdx   *bptree.BPTree
	pendingIdx *bptree.BPTree
	oneWay bool
	reserve      int64
	redeemedGNOT int64
	paidIn       int64
	burnedGNOT int64
	burnKey    string
	createdSeq uint64
	burnH checkpoint.Series
	priceH checkpoint.Series
	absBudget int64
	assocBond int64
	ladder *ladder
	creditRates *creditRates
	standings *bptree.BPTree
}
var courts = bptree.NewBPTree32()
func StartCourt(cur realm, slug, name string) string {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	takeCourtCreationBurn(cur)
	return startCourtUser(cur.Previous().Address(), cur.Address(), slug, name, 0, false)
}
func StartOneWayCourt(cur realm, slug, name string) string {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	takeCourtCreationBurn(cur)
	return startCourtUser(cur.Previous().Address(), cur.Address(), slug, name, 0, true)
}
func StartCourtP(cur realm, slug, name string, stakeOpenDelay int64) string {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	takeCourtCreationBurn(cur)
	return startCourtUser(cur.Previous().Address(), cur.Address(), slug, name, stakeOpenDelay, false)
}
func startCourtUser(admin, escrowAddr address, slug, name string, delay int64, oneWay bool) string {
	if slug == metaSlug {
		panic("kourtv3: the 'meta' slug is reserved")
	}
	return startCourt(admin, escrowAddr, slug, name, delay, oneWay)
}
func startCourt(admin, escrowAddr address, slug, name string, delay int64, oneWay bool) string {
	mustSlug(slug)
	mustCourtName(name)
	if courts.Has(slug) {
		panic("kourtv3: that slug is taken")
	}
	p := defaultParams()
	p.stakeOpenDelayBlocks = delay
	coin := grc20votes.NewLedgerWithClock(name, courtSymbol(slug), coinDecimals, epochBlocks, realmClock{})
	c := &Court{
		id:             slug,
		name:           name,
		tier:           tierListed,
		admin:          admin,
		coin:           coin,
		gov:            governor.New(coin, coin),
		crv:            curve.New(curveDenom, curveCap),
		escrow:         escrowAddr,
		oneWay:         oneWay,
		claims:         bptree.NewBPTree32(),
		queue:          bptree.NewBPTree32(),
		records:        bptree.NewBPTree32(),
		standings:      bptree.NewBPTree32(),
		locked:         bptree.NewBPTree32(),
		voteLocks:      bptree.NewBPTree32(),
		stakeIdx:       bptree.NewBPTree32(),
		params:         p.mustSane(),
		createdAt:      heightNow(),
		curBudgetBpsFP: budgetBpsFPStart,
	}
	c.lastAccrual = c.createdAt
	if slug == metaSlug {
		c.absBudget = metaWeeklyBudget
	}
	c.gov.Adopt(disputeKind{}, disputeRules(c.params))
	courts.Set(slug, c)
	indexNewCourt(c)
	if directoryAdmin == "" {
		directoryAdmin = admin
	}
	return slug
}
const maxCourtDescLen = 240
func SetCourtDesc(cur realm, courtSlug, desc string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	requireFolderMod(c, who)
	mustCourtDesc(desc)
	c.desc = desc
	emitModAct(c.id, 0, "court-desc", who)
}
func SetCourtImage(cur realm, courtSlug, media string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	requireFolderMod(c, who)
	items := parseMediaArg(media)
	if len(items) != 1 {
		panic("kourtv3: a court carries exactly one image")
	}
	if items[0].kind != mediaKindImage {
		panic("kourtv3: a court's image is an image, not a video link")
	}
	c.image = &items[0]
	emitModAct(c.id, 0, "court-image", who)
}
func ClearCourtImage(cur realm, courtSlug string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	requireFolderMod(c, who)
	c.image = nil
	emitModAct(c.id, 0, "court-image-clear", who)
}
func CourtImage(courtSlug string) string {
	c := mustCourt(courtSlug)
	if c.image == nil {
		return "[]"
	}
	return encodeMedia([]mediaItem{*c.image})
}
func CourtImages(slugs string) string {
	out := strings.Builder{}
	sent := 0
	for _, sl := range strings.Split(slugs, ",") {
		if sent >= seriesPageMax {
			break
		}
		sl = strings.TrimSpace(sl)
		if sl == "" {
			continue
		}
		v := courts.Get(sl)
		if v == nil {
			continue
		}
		c := v.(*Court)
		if c.image == nil {
			continue
		}
		out.WriteString(sl + "\t" + encodeMedia([]mediaItem{*c.image}) + "\n")
		sent++
	}
	return out.String()
}
func mustCourtDesc(desc string) {
	if runeLen(desc) > maxCourtDescLen {
		panic("kourtv3: a court description is at most 240 characters")
	}
	for i := 0; i < len(desc); i++ {
		if desc[i] == '\n' || desc[i] == '\r' {
			panic("kourtv3: a court description is a single paragraph")
		}
	}
}
func mustCourtName(name string) {
	if runeLen(name) == 0 || runeLen(name) > maxCourtNameLen {
		panic("kourtv3: a court name is 1..100 characters")
	}
}
func CourtDesc(courtSlug string) string {
	return courtDescFor(mustCourt(courtSlug))
}
func CourtStakeOpenDelay(courtSlug string) int64 {
	return mustCourt(courtSlug).params.stakeOpenDelayBlocks
}
func CourtCount() int { return courts.Size() }
func Exists(slug string) bool { return courts.Has(slug) }
func CourtName(slug string) string { return mustCourt(slug).name }
func CourtSymbol(slug string) string { return mustCourt(slug).coin.Symbol() }
func CoinDecimals() int { return coinDecimals }
func CoinSupply(slug string) int64   { return mustCourt(slug).coin.TotalSupply() }
func CoinPrice(slug string) int64 { return mustCourt(slug).crv.Price(mustCourt(slug).minted) }
func CourtOneWay(slug string) bool { return mustCourt(slug).oneWay }
func CourtEscrow(slug string) address { return mustCourt(slug).escrow }
func EmittedTotal(slug string) int64 { return mustCourt(slug).emittedTotal }
func effMinAnswerX(c *Court) int64 {
	if c.id == metaSlug {
		return supplyFloor(c, answerXFloorBps, c.params.minAnswerX)
	}
	return supplyFloor(c, ordAnswerXFloorBps, c.params.minAnswerX)
}
func effMinDeposit(c *Court) int64 {
	if c.id == metaSlug {
		return supplyFloor(c, depositFloorBps, c.params.minClaimDepositCC)
	}
	return supplyFloor(c, ordDepositFloorBps, c.params.minClaimDepositCC)
}
func maxAnswerBondBps() int64 {
	maxRateBpsFP := 255 * (r0WeeklyBps*1_000_000 + budgetBpsFPStart) / 100
	maxMidGrossBps := maxRateBpsFP * (deadClaimTimeout / periodBlocks) / 1_000_000
	if arm := bondFloorConvBps * maxMidGrossBps / 10000; arm > answerBondBps {
		return arm
	}
	return answerBondBps
}
func supplyFloor(c *Court, bps, dust int64) int64 {
	var supply int64
	if at := c.coin.Epoch(); at > 1 {
		supply = c.coin.PastTotal(at - 1)
	}
	v := mulDiv128(supply, bps, grc20votes.Bps)
	if v < dust {
		v = dust
	}
	if lid := mulDiv128(supply, quorumSupplyBps, grc20votes.Bps) *
		(grc20votes.Bps - 1) / (grc20votes.Bps + maxAnswerBondBps()); lid > 0 && v > lid {
		v = lid
	}
	if v < 1 {
		v = 1
	}
	return v
}
func mustCourt(slug string) *Court {
	v := courts.Get(slug)
	if v == nil {
		panic("kourtv3: no such court")
	}
	return v.(*Court)
}
func courtSymbol(slug string) string { return strings.ToUpper(slug) }
var reservedSlugs = []string{
	"kourt", "court", "gno", "gnot", "ugnot",
	"btc", "eth", "usdc", "usdt",
}
func mustSlug(slug string) {
	if len(slug) == 0 || len(slug) > maxSlugLen {
		panic("kourtv3: a slug is 1..11 characters")
	}
	for _, r := range reservedSlugs {
		if slug == r {
			panic("kourtv3: that slug is reserved")
		}
	}
	for i := 0; i < len(slug); i++ {
		ch := slug[i]
		ok := (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')
		if !ok {
			panic("kourtv3: a slug is lowercase letters and digits only")
		}
	}
}

courtburn.gno

package kourtv3
import (
	"chain"
	"chain/banker"
	"chain/runtime/unsafe"
)
const courtCreationBurnInit = int64(0)
var courtCreationBurn = courtCreationBurnInit
func CourtCreationBurn() int64 { return courtCreationBurn }
func SetCourtCreationBurn(cur realm, amount int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin prices court creation")
	}
	mustSanePrice(amount)
	courtCreationBurn = amount
}
func ugnotAmt(n int64) string { return ccAmt(n) }
func mustSanePrice(amount int64) {
	if amount < 0 {
		panic("kourtv3: a court-creation burn cannot be negative")
	}
}
func takeCourtCreationBurn(cur realm) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	price := courtCreationBurn
	prev := cur.Previous()
	if price <= 0 {
		if prev.IsUserCall() && unsafe.OriginSend().AmountOf(gnotDenom) > 0 {
			panic("kourtv3: court creation is free right now; send no GNOT")
		}
		return
	}
	if !prev.IsUserCall() {
		panic("kourtv3: starting a court burns GNOT, so it must be a direct user call")
	}
	sent := unsafe.OriginSend().AmountOf(gnotDenom)
	if sent < price {
		panic("kourtv3: starting a court burns at least " + ugnotAmt(price) +
			" GNOT, you sent " + ugnotAmt(sent))
	}
	b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	b.SendCoins(cur.Address(), chain.PackageAddress(burnSinkPath),
		chain.Coins{chain.NewCoin(gnotDenom, sent)})
}

directory.gno

package kourtv3
import "strconv"
const (
	tierHidden   uint8 = 0
	tierListed   uint8 = 1
	tierFeatured uint8 = 2
)
var directoryAdmin address
func SetTier(cur realm, courtSlug string, tier int) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	if !isGlobalMod(who) {
		panic("kourtv3: only a global DAO member may set a court's tier")
	}
	if tier < int(tierHidden) || tier > int(tierFeatured) {
		panic("kourtv3: tier is 0 (hidden), 1 (listed), or 2 (featured)")
	}
	c := mustCourt(courtSlug)
	if c.tier == uint8(tier) {
		return
	}
	c.tier = uint8(tier)
	emitGlobalAct(c.id, 0, "tier:"+strconv.Itoa(tier), who)
}
func DirectoryAdmin() address        { return directoryAdmin }
func CourtTier(courtSlug string) int { return int(mustCourt(courtSlug).tier) }
func ListCourts() []string {
	out := []string{}
	courts.Iterate("", "", func(key string, _ any) bool {
		out = append(out, key)
		return false
	})
	return out
}
func ListByTier(tier int) []string {
	out := []string{}
	courts.Iterate("", "", func(key string, v any) bool {
		if int(v.(*Court).tier) == tier {
			out = append(out, key)
		}
		return false
	})
	return out
}

dispute.gno

package kourtv3
import (
	"strconv"
	governor "gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/governor/v0"
	grc20votes "gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/grc20votes/v0"
	bptree "gno.land/p/nt/bptree/v0"
)
const disputeKindName = "dispute"
const quorumSupplyBps = int64(500)
const finalizeGraceBlocks = int64(120_960)
type disputeKind struct{}
func (disputeKind) Name() string { return disputeKindName }
func (disputeKind) Describe(payload string) string {
	return "resolve a disputed claim by a token vote (see the court page for the claim)"
}
func (disputeKind) Check(payload string) error { return nil }
func (disputeKind) Do(_ int, rlm realm, payload string) error { return nil }
func disputeRules(p Params) governor.Rules {
	return governor.NewRules(5000, p.disputeThresholdBps, p.votingBlocks, 1, p.graceBlocks, 0)
}
func OpenDispute(cur realm, courtSlug string, claimID uint64) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if cs.frozenAt == 0 {
		panic("kourtv3: there is no answer to dispute")
	}
	if who == cs.answerer {
		panic("kourtv3: the answerer cannot dispute their own answer")
	}
	if cs.disputeOpen {
		panic("kourtv3: a dispute is already open on this claim")
	}
	if cs.verdictAt != 0 {
		panic("kourtv3: the verdict is final")
	}
	now := heightNow()
	if cs.provisional < 0 {
		if passed, known := pastDeadline(cs.answeredAtTime, settleSecs); (known && passed) ||
			(!known && now >= cs.answerHeight+settleDelay) {
			panic("kourtv3: the dispute window has passed; the answer settles undisputed")
		}
	} else if escrowPassed(cs) {
		panic("kourtv3: the escrow window has passed; Finalize the verdict")
	}
	touch(c)
	bond := cs.disputeBond0()
	mustSpendable(c, who, bond)
	c.coin.Transfer(who, c.escrow, bond)
	floor := quorumFloor(c, cs.xBarFrozen)
	cs.round++
	payload := strconv.FormatUint(claimID, 10) + "|" + strconv.FormatInt(cs.round, 10)
	pid := c.gov.ProposeWithQuorum(c.escrow, disputeKindName, payload, "dispute", floor)
	cs.proposalID = pid
	cs.disputeOpen = true
	cs.disputeOpenedTime = nowTime()
	cs.disputeBond = bond
	cs.disputer = who
	return pid
}
func VoteDispute(cur realm, courtSlug string, claimID uint64, choice string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if !cs.disputeOpen {
		panic("kourtv3: no open dispute on this claim")
	}
	if isParticipant(cs, who) {
		panic("kourtv3: a participant may not vote on their own claim's verdict")
	}
	held := voteCap(c, who)
	if held <= 0 {
		panic("kourtv3: you hold none of this court's coin, and voting weight is " +
			"the lesser of what you held when the round opened and what you hold now")
	}
	govChoice := choice
	switch choice {
	case voteYes, voteNo:
	case voteSpam:
		govChoice = govAbstain
	default:
		panic("kourtv3: a dispute vote is \"yes\" to overturn, \"no\" to uphold, " +
			"or \"spam\" to say the claim was not worth judging")
	}
	c.gov.VoteWithCap(who, cs.proposalID, govChoice, held)
	if cs.voted == nil {
		cs.voted = bptree.NewBPTree32()
	}
	cs.voted.Set("d"+beClaimKey(uint64(cs.proposalID))+string(who), choice)
	_, dw, ok := c.gov.VoteOf(cs.proposalID, who)
	if !ok {
		panic("kourtv3: the governor did not record the vote it just accepted")
	}
	cs.voted.Set("dw"+beClaimKey(uint64(cs.proposalID))+string(who), dw)
	lockVote(c, who, voteLockDispute, int64(claimID), cs.proposalID, dw)
}
func ResolveDispute(cur realm, courtSlug string, claimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if !cs.disputeOpen {
		panic("kourtv3: no dispute to resolve")
	}
	if c.gov.State(cs.proposalID) == "active" {
		panic("kourtv3: the dispute vote is still open")
	}
	touch(c)
	yes, no, spamW, _ := c.gov.Tally(cs.proposalID)
	cast := yes + no + spamW
	floor := c.gov.QuorumFloor(cs.proposalID)
	firstResolution := cs.provisional < 0
	switch {
	case cast < floor:
		half := cs.disputeBond / 2
		if half > 0 {
			c.coin.Transfer(c.escrow, cs.disputer, half)
		}
		if rest := cs.disputeBond - half; rest > 0 {
			c.coin.Burn(c.escrow, rest)
		}
		cs.disputeBond = 0
		if firstResolution {
			cs.provisional = cs.answer
		}
		cs.failedRounds++
		if cs.failedRounds >= maxFailedRounds {
			provCloseClaim(c, cs)
		}
	case spamDiscards(spamW, cast):
		spamDiscardClaim(c, cs, spamW, cast)
	case yes > 0 && yes*grc20votes.Bps >= (yes+no)*c.params.disputeThresholdBps:
		posted := cs.disputeBond
		burned := cs.answerBond
		if burned > 0 {
			c.coin.Burn(c.escrow, burned)
			cs.answerBond = 0
			cs.overturnBy = cs.disputer
			cs.overturnBond = posted
		}
		if posted > 0 {
			c.coin.Transfer(c.escrow, cs.disputer, posted)
			cs.disputeBond = 0
		}
		if comp := compAmount(posted, burned); comp > 0 {
			enqueueSenior(c, cs.disputer, comp, "comp")
		}
		cs.provisional = int8(oppositeSide(int(cs.answer)))
		cs.failedRounds = 0
		cs.decidedRounds++
		cs.decidedPID, cs.carrotChoice, cs.carrotDenom = cs.proposalID, "yes", yes
		cs.spamW, cs.spamTotalW = spamW, cast
	default:
		burned := cs.disputeBond
		if burned > 0 {
			c.coin.Burn(c.escrow, burned)
			cs.disputeBond = 0
		}
		if comp := compAmount(cs.answerBond0, burned); comp > 0 {
			enqueueSenior(c, cs.answerer, comp, "comp")
		}
		if yes >= credWeightFloor(c, cs.proposalID)/4 {
			cs.credEligible = true
		}
		cs.provisional = cs.answer
		cs.failedRounds = 0
		cs.decidedRounds++
		cs.decidedPID, cs.carrotChoice, cs.carrotDenom = cs.proposalID, "no", no
		cs.spamW, cs.spamTotalW = spamW, cast
	}
	if firstResolution && !cs.provClose {
		w := escrowWindow(c, cs)
		if cs.failedRounds > 0 {
			if lw := ladderWindow(c.params); lw > w {
				w = lw
			}
		}
		cs.escrowUntil = heightNow() + w
		cs.escrowUntilAt = nowTime() + blocksToSecs(w)
	}
	cs.disputeOpen = false
}
func (cs *claimState) disputeBond0() int64 {
	base := cs.xBarFrozen * disputeBondXBps / 10000
	if arm := cs.answerBond0 * disputeBondOfAnswerBps / 10000; arm < base {
		base = arm
	}
	if base < 1 {
		base = 1
	}
	shift := cs.failedRounds
	if shift > maxFailedRounds-1 {
		shift = maxFailedRounds - 1
	}
	return mustMul(base, int64(1)<<uint(shift))
}
func compAmount(ownBond, burned int64) int64 {
	comp := mustMul(compOwnX, ownBond)
	if arm := burned * compOfBurnBps / 10000; arm < comp {
		comp = arm
	}
	if comp < 0 {
		comp = 0
	}
	return comp
}
func spamDiscards(spamW, cast int64) bool { return spamW*2 > cast }
func spamBurnsDeposit(spamW, cast int64) bool { return spamW*3 >= cast*2 }
func spamDiscardClaim(c *Court, cs *claimState, spamW, cast int64) {
	cs.spamClosed = true
	cs.provClose = true
	cs.verdictAt = heightNow()
	cs.verdictAtTime = nowTime()
	cs.route = "spam"
	cs.spamW, cs.spamTotalW = spamW, cast
	cs.decidedPID, cs.carrotChoice, cs.carrotDenom = cs.proposalID, voteSpam, spamW
	if cs.answerBond > 0 {
		settleAnswerBond(c, cs)
	}
	if cs.disputeBond > 0 {
		c.coin.Transfer(c.escrow, cs.disputer, cs.disputeBond)
		cs.disputeBond = 0
	}
	burnDeposit := spamBurnsDeposit(spamW, cast)
	if cs.deposit > 0 {
		if burnDeposit {
			c.coin.Burn(c.escrow, cs.deposit)
		} else {
			c.coin.Transfer(c.escrow, cs.author, cs.deposit)
		}
		c.deposit -= cs.deposit
		cs.deposit = 0
	}
	if cs.fee > 0 {
		c.coin.Burn(c.escrow, cs.fee)
		c.deposit -= cs.fee
		cs.fee = 0
	}
	releasePriority(c, cs.answerer, cs.id)
	stripExit(c, cs)
	releaseMetaLatchIfMeta(c, cs)
}
func provCloseClaim(c *Court, cs *claimState) {
	cs.provClose = true
	cs.verdictAt = heightNow()
	cs.verdictAtTime = nowTime()
	cs.route = "closed"
	if cs.answerBond > 0 {
		settleAnswerBond(c, cs)
	}
	if cs.deposit > 0 {
		c.coin.Transfer(c.escrow, cs.author, cs.deposit)
		c.deposit -= cs.deposit
		cs.deposit = 0
	}
	if cs.fee > 0 {
		c.coin.Transfer(c.escrow, cs.author, cs.fee)
		c.deposit -= cs.fee
		cs.fee = 0
	}
	releasePriority(c, cs.answerer, cs.id)
	stripExit(c, cs)
	releaseMetaLatchIfMeta(c, cs)
}
func Finalize(cur realm, courtSlug string, claimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if cs.verdictAt != 0 {
		panic("kourtv3: already final")
	}
	if cs.disputeOpen {
		panic("kourtv3: a dispute is active; cannot finalize")
	}
	if cs.provisional < 0 {
		panic("kourtv3: no provisional verdict to finalize")
	}
	now := heightNow()
	if !escrowPassed(cs) {
		panic("kourtv3: the escrow window has not passed")
	}
	if passed, known := pastDeadline(cs.escrowUntilAt, finalizeGraceSecs); ((known && !passed) ||
		(!known && now < cs.escrowUntil+finalizeGraceBlocks)) && !isParticipant(cs, who) {
		panic("kourtv3: Finalize is participant-only for its first week")
	}
	touch(c)
	cs.verdictAt = now
	cs.verdictAtTime = nowTime()
	cs.route = "vote"
	trimClaimHistory(c, cs, uint32(cs.frozenAt/epochBlocks)+1)
	if cs.answerBond > 0 {
		settleAnswerBond(c, cs)
	}
	if cs.provisional != cs.answer {
		resetOverturned(c, cs.answerer)
	} else if cs.decidedRounds > 0 && cs.credEligible {
		creditUpheld(c, cs.answerer)
	}
	creditDisputeResolved(c, cs)
	releasePriority(c, cs.answerer, claimID)
}
func VotableSupply(courtSlug string) (raw, escrowed, votable int64) {
	c := mustCourt(courtSlug)
	at := c.coin.Epoch()
	if at <= 1 {
		return 0, 0, 0
	}
	at--
	raw = c.coin.PastTotal(at)
	escrowed = c.coin.PastVotes(c.escrow, at)
	votable = raw - escrowed
	if votable < 0 {
		votable = 0
	}
	return raw, escrowed, votable
}
func QuorumFloorOf(courtSlug string, claimID uint64) int64 {
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if cs.disputeOpen {
		return c.gov.QuorumFloor(cs.proposalID)
	}
	return quorumFloor(c, cs.xBarFrozen)
}
func isParticipant(cs *claimState, who address) bool {
	if who == cs.author || who == cs.answerer {
		return true
	}
	return cs.stakers.Get(posKey(who, sideYES)) != nil ||
		cs.stakers.Get(posKey(who, sideNO)) != nil
}
func quorumFloor(c *Court, xbar int64) int64 {
	at := c.coin.Epoch() - 1
	supply := c.coin.PastTotal(at)
	votable := supply - c.coin.PastVotes(c.escrow, at)
	if votable < 0 {
		votable = 0
	}
	floor := xbar
	if third := votable / 3; third < floor {
		floor = third
	}
	if floor < 1 {
		floor = 1
	}
	return floor
}
func oppositeSide(side int) int {
	if side == sideYES {
		return sideNO
	}
	return sideYES
}
func escrowWindow(c *Court, cs *claimState) int64 {
	extraDays := mulDiv128(cs.xBarFrozen, c.crv.Price(c.minted), 500_000_000)
	room := (c.params.escrowMaxBlocks - c.params.escrowMinBlocks) / oneDayBlocks
	if extraDays >= room {
		return c.params.escrowMaxBlocks
	}
	return c.params.escrowMinBlocks + extraDays*oneDayBlocks
}
const (
	voteYes  = "yes"
	voteNo   = "no"
	voteSpam = "spam"
	govAbstain = "abstain"
)
const oneDayBlocks = int64(24) * epochBlocks
func DisputeOpen(courtSlug string, claimID uint64) bool {
	return mustClaim(mustCourt(courtSlug), claimID).disputeOpen
}
func DisputeProposal(courtSlug string, claimID uint64) int64 {
	return mustClaim(mustCourt(courtSlug), claimID).proposalID
}
func Provisional(courtSlug string, claimID uint64) int {
	return int(mustClaim(mustCourt(courtSlug), claimID).provisional)
}
func FailedRounds(courtSlug string, claimID uint64) int64 {
	return mustClaim(mustCourt(courtSlug), claimID).failedRounds
}
func ProvClose(courtSlug string, claimID uint64) bool {
	return mustClaim(mustCourt(courtSlug), claimID).provClose
}
func EscrowUntil(courtSlug string, claimID uint64) int64 {
	return mustClaim(mustCourt(courtSlug), claimID).escrowUntil
}
func DisputeVoteCloses(courtSlug string, claimID uint64) int64 {
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if !cs.disputeOpen || cs.proposalID == 0 {
		return 0
	}
	_, closes, _, _ := c.gov.Timings(cs.proposalID)
	return closes
}
func DisputeBondNext(courtSlug string, claimID uint64) int64 {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.frozenAt == 0 {
		return 0
	}
	return cs.disputeBond0()
}
func escrowPassed(cs *claimState) bool {
	passed, known := pastDeadline(cs.escrowUntilAt, 0)
	return (known && passed) || (!known && heightNow() >= cs.escrowUntil)
}
func Reopenable(courtSlug string, claimID uint64) bool {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	return cs.provisional >= 0 && cs.verdictAt == 0 && !cs.disputeOpen &&
		!escrowPassed(cs)
}
func ladderWindow(p Params) int64 {
	return (maxFailedRounds-2)*p.votingBlocks + (maxFailedRounds-1)*p.graceBlocks + 1
}
func credWeightFloor(c *Court, pid int64) int64 {
	engaged, _ := c.gov.Snapshot(pid)
	return mulDiv128(engaged, quorumSupplyBps, grc20votes.Bps)
}
func credWeightFloorAt(c *Court, at uint32) int64 {
	return mulDiv128(c.coin.EngagedTotal(at), quorumSupplyBps, grc20votes.Bps)
}

electionrender.gno

package kourtv3
import (
	"strconv"
	"strings"
	sanitize "gno.land/p/nt/markdown/sanitize/v0"
)
const electionPath = "election"
func renderElection(slug string) string {
	if !Exists(slug) {
		return "## Not found\nNo court by that slug."
	}
	c := mustCourt(slug)
	base := "/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug
	var b strings.Builder
	b.WriteString("# Electing the moderators of " + courtNameFor(c) + "\n\n")
	b.WriteString("[← " + courtNameFor(c) + "](" + base + ") · [moderation log](" +
		base + "/mod)\n\n")
	b.WriteString("A court's moderators answer claims, curate its folders, and can " +
		"hide a claim, hide a comment, slash somebody's standing, or freeze an " +
		"address out of the boards. **This ballot is the only way the court's " +
		"holders replace them.**\n\n")
	cm := c.mod
	if cm == nil || cm.election == nil || cm.election.resolved {
		writeNoElection(&b, c, cm)
		b.WriteString("\n" + helpLink + "\n")
		return b.String()
	}
	writeOpenElection(&b, c, cm, base)
	b.WriteString("\n" + helpLink + "\n")
	return b.String()
}
func writeNoElection(b *strings.Builder, c *Court, cm *courtMod) {
	b.WriteString("## No election is open\n\n")
	if cm == nil || cm.n == 0 {
		b.WriteString("This court has no moderator set yet — its creator holds the " +
			"seat until an election or an appointment changes that.\n")
	} else {
		b.WriteString("- seats held now: **" + strconv.Itoa(cm.n) + "**, " +
			strconv.Itoa(cm.m) + " of whom must agree for a moderation act\n")
	}
	now := heightNow()
	if cm != nil && electionCooldownOpen(cm) {
		b.WriteString("- this court is in its post-election cooldown until block **" +
			strconv.FormatInt(cm.electionCooldownUntil, 10) + "** (now " +
			strconv.FormatInt(now, 10) + "); no ballot can open before then\n\n")
		return
	}
	b.WriteString("- a ballot **can be opened now**\n\n")
	b.WriteString("Opening one takes two calls: `RegisterModCandidate` records a " +
		"proposed set of moderators and returns its id, and `OpenElection` puts " +
		"that id on a ballot. Any holder may do both.\n\n")
}
func writeOpenElection(b *strings.Builder, c *Court, cm *courtMod, base string) {
	e := cm.election
	now := heightNow()
	b.WriteString("## A ballot is open\n\n")
	switch {
	case !nominationClosed(e):
		b.WriteString("**Nominating.** Candidate sets may be added until block **" +
			strconv.FormatInt(e.nominateEnd, 10) + "**; voting runs from then " +
			"until block **" + strconv.FormatInt(e.voteEnd, 10) + "**.\n\n")
	case !votingClosed(e):
		b.WriteString("**Voting.** Nominations closed at block " +
			strconv.FormatInt(e.nominateEnd, 10) + "; the ballot closes at block **" +
			strconv.FormatInt(e.voteEnd, 10) + "**.\n\n")
	default:
		b.WriteString("**Closed and awaiting resolution.** The ballot shut at block " +
			strconv.FormatInt(e.voteEnd, 10) + ". Anyone may call `ResolveElection` " +
			"to apply the result below.\n\n")
	}
	b.WriteString("- now: block " + strconv.FormatInt(now, 10) + "\n")
	b.WriteString("- a candidate set costs a bond of **" +
		strconv.FormatInt(e.bond, 10) + " " + qualifiedSymbol(c) + "**\n")
	b.WriteString("- weights are pinned at the epoch the ballot opened, so buying " +
		"coin now does not add voting weight to it\n\n")
	writeBallotLines(b, c, e)
	writeTurnoutBar(b, c, e)
}
func writeBallotLines(b *strings.Builder, c *Court, e *election) {
	b.WriteString("## On the ballot\n\n")
	rows := 0
	e.lines.Iterate("", "", func(_ string, v any) bool {
		l, ok := v.(*ballotLine)
		if !ok {
			return false
		}
		rows++
		b.WriteString("- **set #" + strconv.FormatUint(l.candID, 10) + "** — " +
			strconv.FormatInt(l.weight, 10) + " " + qualifiedSymbol(c) + " approving\n")
		if cv := c.mod.candidates.Get(beClaimKey(l.candID)); cv != nil {
			cand := cv.(*modCandidate)
			b.WriteString("  - would seat " + strconv.Itoa(len(cand.members)) +
				", " + strconv.Itoa(cand.m) + " of whom must agree\n")
			for _, m := range cand.members {
				b.WriteString("  - `" + sanitize.InlineText(m.String()) + "`\n")
			}
		}
		return rows >= renderPageSize
	})
	if rows == 0 {
		b.WriteString("_No candidate sets yet._ Until one is nominated there is " +
			"nothing to elect, and the current moderators stay.\n\n")
	} else {
		b.WriteString("\n")
	}
	b.WriteString("- **keep the current moderators** — " +
		strconv.FormatInt(e.retainW, 10) + " " + qualifiedSymbol(c) + " approving\n\n")
}
func writeTurnoutBar(b *strings.Builder, c *Court, e *election) {
	b.WriteString("## Turnout\n\n")
	b.WriteString("- cast so far: **" + strconv.FormatInt(e.turnout, 10) + " " +
		qualifiedSymbol(c) + "**\n")
	b.WriteString("- the bar: **" + strconv.FormatInt(e.floor, 10) + " " +
		qualifiedSymbol(c) + "**, fixed when the ballot opened\n")
	if e.turnout < e.floor {
		b.WriteString("- still needed: **" + strconv.FormatInt(e.floor-e.turnout, 10) +
			" " + qualifiedSymbol(c) + "**\n\n")
	} else {
		b.WriteString("- the bar is cleared\n\n")
	}
	b.WriteString("> **Falling short is not a draw.** If the ballot closes with less " +
		"than the bar cast, nothing is installed and the current moderators keep " +
		"their seats — the same outcome as a vote to retain them.\n>\n" +
		"> And the bar is a share of this court's coin **including coin that " +
		"cannot vote**: it nets out only the court's own escrow, so coin held at " +
		"a wrapper's address counts toward the pool the bar was measured against " +
		"while no key can cast it. The share of actually-castable weight you need " +
		"is therefore larger than the bar looks.\n\n")
}

emission.gno

package kourtv3
import (
	"chain"
	"strconv"
)
const (
	seniorEnqueuedEvent = "SeniorEnqueued"
	seniorPaidEvent     = "SeniorPaid"
)
type entitlement struct {
	to      address
	amount  int64
	start   int64
	paid    int64
	purpose string
}
func touch(c *Court) {
	now := heightNow()
	for c.lastAccrual < now {
		boundary := c.createdAt + (c.periodIndex+1)*periodBlocks
		segEnd := now
		if boundary < segEnd {
			segEnd = boundary
		}
		accrueSegment(c, segEnd-c.lastAccrual)
		advanceRateAcc(c, segEnd-c.lastAccrual)
		c.lastAccrual = segEnd
		if segEnd == boundary {
			rollPeriod(c)
		}
	}
}
func accrueSegment(c *Court, blocks int64) {
	if blocks <= 0 || c.curPeriodBudget <= 0 {
		return
	}
	if c.reservoirR() >= c.rMax() && c.cumAccrual >= c.reservedTail {
		return
	}
	num := mustAdd(mustMul(c.curPeriodBudget, blocks), c.accrualRem)
	c.cumAccrual = mustAdd(c.cumAccrual, num/periodBlocks)
	c.accrualRem = num % periodBlocks
}
func advanceRateAcc(c *Court, blocks int64) {
	if blocks <= 0 {
		return
	}
	c.rateAccFP = mustAdd(c.rateAccFP, mustMul(rateBpsFP(c), blocks))
}
func rollPeriod(c *Court) {
	c.periodIndex++
	c.curBudgetBpsFP = c.curBudgetBpsFP * stepDownNum / stepDownDen
	minted := c.emittedTotal - c.emittedAtRoll
	c.emittedAtRoll = c.emittedTotal
	c.emaMinted = (3*c.emaMinted + minted) / 4
	s := c.coin.TotalSupply()
	if s > 0 {
		if c.emaMinted < 0 {
			panic("kourtv3: negative realized mint")
		}
		dReal := mulDiv128(c.emaMinted, 10_000*1_000_000, s)
		if dReal < c.curBudgetBpsFP {
			c.dEffBpsFP = dReal
		} else {
			c.dEffBpsFP = c.curBudgetBpsFP
		}
		if c.absBudget > 0 {
			c.absBudget = c.absBudget * stepDownNum / stepDownDen
			c.curPeriodBudget = c.absBudget
		} else {
			c.curPeriodBudget = mulDiv128(s, c.curBudgetBpsFP, 10_000*1_000_000)
		}
	} else {
		c.dEffBpsFP = 0
		c.curPeriodBudget = 0
	}
}
func (c *Court) reservoirR() int64 {
	past := c.cumAccrual - c.reservedTail
	if past < 0 {
		past = 0
	}
	r := past - c.juniorReserved
	if r < 0 {
		r = 0
	}
	return r
}
func (c *Court) rMax() int64 { return rMaxPeriods * c.curPeriodBudget }
func enqueueSenior(c *Court, to address, amount int64, purpose string) uint64 {
	if amount <= 0 {
		panic("kourtv3: a senior entitlement must be positive")
	}
	start := mustAdd(c.reservedTail, c.juniorReserved)
	e := &entitlement{to: to, amount: amount, start: start, purpose: purpose}
	c.reservedTail = mustAdd(c.reservedTail, amount)
	c.seniorOwed = mustAdd(c.seniorOwed, amount)
	c.queueSeq++
	c.queue.Set(beClaimKey(c.queueSeq), e)
	chain.Emit(seniorEnqueuedEvent,
		"court", c.id,
		"seq", strconv.FormatUint(c.queueSeq, 10),
		"to", to.String(),
		"amount", strconv.FormatInt(amount, 10),
		"purpose", purpose,
	)
	return c.queueSeq
}
func reserveJunior(c *Court, want int64) int64 {
	touch(c)
	r := c.reservoirR()
	if want > r {
		want = r
	}
	if want < 0 {
		want = 0
	}
	c.juniorReserved = mustAdd(c.juniorReserved, want)
	return want
}
func mintEmission(c *Court, to address, amount int64) {
	if amount <= 0 {
		return
	}
	c.coin.Mint(to, amount)
	c.emittedTotal = mustAdd(c.emittedTotal, amount)
}
func PullSenior(cur realm, courtSlug string, seq uint64) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	touch(c)
	v := c.queue.Get(beClaimKey(seq))
	if v == nil {
		panic("kourtv3: no such entitlement")
	}
	e := v.(*entitlement)
	covered := c.cumAccrual - e.start
	if covered > e.amount {
		covered = e.amount
	}
	pay := covered - e.paid
	if pay <= 0 {
		return 0
	}
	e.paid += pay
	c.seniorOwed -= pay
	c.seniorPaid = mustAdd(c.seniorPaid, pay)
	mintEmission(c, e.to, pay)
	chain.Emit(seniorPaidEvent,
		"court", c.id,
		"seq", strconv.FormatUint(seq, 10),
		"to", e.to.String(),
		"paid", strconv.FormatInt(pay, 10),
		"remaining", strconv.FormatInt(e.amount-e.paid, 10),
	)
	return pay
}
func Reservoir(courtSlug string) int64  { return mustCourt(courtSlug).reservoirR() }
func SeniorOwed(courtSlug string) int64 { return mustCourt(courtSlug).seniorOwed }
func SeniorEntitlement(courtSlug string, seq uint64) (to address, amount, paid, payable int64) {
	c := mustCourt(courtSlug)
	v := c.queue.Get(beClaimKey(seq))
	if v == nil {
		panic("kourtv3: no such entitlement")
	}
	e := v.(*entitlement)
	covered := c.cumAccrual - e.start
	if covered > e.amount {
		covered = e.amount
	}
	p := covered - e.paid
	if p < 0 {
		p = 0
	}
	return e.to, e.amount, e.paid, p
}
func QueueLen(courtSlug string) uint64 { return mustCourt(courtSlug).queueSeq }
func Poke(cur realm, courtSlug string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	touch(mustCourt(courtSlug))
}

folders.gno

package kourtv3
import (
	"strconv"
	"strings"
	bptree "gno.land/p/nt/bptree/v0"
)
const maxFolderTextLen = 200
const (
	maxFolderDepth = 4
	maxFolderItems = 200
	maxFolders = 100
)
type folder struct {
	id     uint64
	name   string
	desc   string
	items  []uint64
	purged bool
	code   string
	retired bool
	bornOf uint64
	focusByDefault bool
	parent uint64
	ord int
	image *mediaItem
}
func (cm *courtMod) folderDepth(id uint64) int {
	d := 0
	for id != 0 && d <= maxFolders {
		d++
		v := cm.folders.Get(beClaimKey(id))
		if v == nil {
			break
		}
		id = v.(*folder).parent
	}
	return d
}
func (cm *courtMod) folderHeight(id uint64) int {
	h := 1
	cm.folders.Iterate("", "", func(_ string, v any) bool {
		f, ok := v.(*folder)
		if !ok || f.parent != id {
			return false
		}
		if ch := 1 + cm.folderHeight(f.id); ch > h {
			h = ch
		}
		return false
	})
	return h
}
func (cm *courtMod) mustNestable(id, parent uint64, height int) {
	if parent == 0 {
		return
	}
	if parent == id {
		panic("kourtv3: a folder cannot contain itself")
	}
	cm.mustFolder(parent)
	for up, n := parent, 0; up != 0 && n <= maxFolders; n++ {
		if up == id {
			panic("kourtv3: that would put a folder inside itself")
		}
		v := cm.folders.Get(beClaimKey(up))
		if v == nil {
			break
		}
		up = v.(*folder).parent
	}
	if cm.folderDepth(parent)+height > maxFolderDepth {
		panic("kourtv3: folders nest at most " + strconv.Itoa(maxFolderDepth) + " deep")
	}
}
func folderAfter(a, b *folder) bool {
	ap, bp := a.ord > 0, b.ord > 0
	if ap != bp {
		return bp
	}
	if ap && a.ord != b.ord {
		return a.ord > b.ord
	}
	return a.id > b.id
}
func (cm *courtMod) folderRows() []*folder {
	out := make([]*folder, 0, maxFolders)
	cm.folders.Iterate("", "", func(_ string, v any) bool {
		if f, ok := v.(*folder); ok {
			out = append(out, f)
		}
		return false
	})
	for i := range out {
		first := true
		for j := 0; j < i; j++ {
			if out[j].parent == out[i].parent {
				first = false
				break
			}
		}
		if !first {
			continue
		}
		p := out[i].parent
		slots := make([]int, 0, len(out))
		grp := make([]*folder, 0, len(out))
		for j, g := range out {
			if g.parent == p {
				slots = append(slots, j)
				grp = append(grp, g)
			}
		}
		for a := 1; a < len(grp); a++ {
			f := grp[a]
			b := a - 1
			for b >= 0 && folderAfter(grp[b], f) {
				grp[b+1] = grp[b]
				b--
			}
			grp[b+1] = f
		}
		for k, g := range grp {
			out[slots[k]] = g
		}
	}
	return out
}
func (cm *courtMod) mustFolder(id uint64) *folder {
	v := cm.folders.Get(beClaimKey(id))
	if v == nil {
		panic("kourtv3: no such folder")
	}
	return v.(*folder)
}
func requireFolderMod(c *Court, who address) *courtMod {
	cm := ensureMod(c)
	requireActiveMod(cm, who)
	return cm
}
func folderTextOK(name, desc string) bool {
	return runeLen(name) > 0 && runeLen(name) <= maxFolderTextLen && runeLen(desc) <= maxFolderTextLen
}
func folderNameTaken(cm *courtMod, name string) bool {
	taken := false
	if cm.folders == nil {
		return false
	}
	cm.folders.Iterate("", "", func(_ string, v any) bool {
		f := v.(*folder)
		if !f.retired && f.name == name {
			taken = true
			return true
		}
		return false
	})
	return taken
}
func newFolderCore(cm *courtMod, name, desc string, parent uint64) uint64 {
	if cm.folders.Size() >= maxFolders {
		panic("kourtv3: this court already has " + strconv.Itoa(maxFolders) + " folders")
	}
	if !folderTextOK(name, desc) {
		panic("kourtv3: a folder name is 1..200 and a description at most 200 characters")
	}
	if parent != 0 {
		cm.mustNestable(0, parent, 1)
	}
	cm.folderSeq++
	id := cm.folderSeq
	cm.folders.Set(beClaimKey(id), &folder{id: id, name: name, desc: desc, parent: parent})
	return id
}
type folderProposal struct {
	id     uint64
	name   string
	desc   string
	parent uint64
	by     address
	at     int64
}
func RegisterFolderProposal(cur realm, courtSlug, name, desc string, parentID uint64) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	if !folderTextOK(name, desc) {
		panic("kourtv3: a folder name is 1..200 and a description at most 200 characters")
	}
	if parentID != 0 {
		cm.mustNestable(0, parentID, 1)
	}
	if folderNameTaken(cm, name) {
		panic("kourtv3: this court already has a folder by that name")
	}
	if cm.folderProps == nil {
		cm.folderProps = bptree.NewBPTree32()
	}
	cm.folderPropSeq++
	id := cm.folderPropSeq
	cm.folderProps.Set(beClaimKey(id), &folderProposal{
		id: id, name: name, desc: desc, parent: parentID, by: who, at: heightNow(),
	})
	return id
}
func (cm *courtMod) mustFolderProposal(id uint64) *folderProposal {
	if cm.folderProps == nil {
		panic("kourtv3: no such folder proposal")
	}
	v := cm.folderProps.Get(beClaimKey(id))
	if v == nil {
		panic("kourtv3: no such folder proposal")
	}
	return v.(*folderProposal)
}
func CreateFolder(cur realm, courtSlug, name, desc string) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	id := newFolderCore(cm, name, desc, 0)
	emitModAct(c.id, 0, "folder-create", who)
	return id
}
func CreateFolderIn(cur realm, courtSlug string, parentID uint64, name, desc string) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	id := newFolderCore(cm, name, desc, parentID)
	emitModAct(c.id, 0, "folder-create", who)
	return id
}
func MoveFolder(cur realm, courtSlug string, folderID, newParent uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	f := cm.mustFolder(folderID)
	cm.mustNestable(folderID, newParent, cm.folderHeight(folderID))
	f.parent = newParent
	emitModAct(c.id, 0, "folder-move", who)
}
func AddToFolder(cur realm, courtSlug string, folderID, claimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	_ = mustClaim(c, claimID)
	f := cm.mustFolder(folderID)
	fileInto(f, claimID)
	emitModAct(c.id, claimID, "folder-add", who)
}
func fileInto(f *folder, claimID uint64) {
	for _, x := range f.items {
		if x == claimID {
			return
		}
	}
	if len(f.items) >= maxFolderItems {
		panic("kourtv3: a folder holds at most " + strconv.Itoa(maxFolderItems) + " claims")
	}
	f.items = append(f.items, claimID)
}
func RemoveFromFolder(cur realm, courtSlug string, folderID, claimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	f := cm.mustFolder(folderID)
	out := f.items[:0]
	found := false
	for _, x := range f.items {
		if x == claimID {
			found = true
			continue
		}
		out = append(out, x)
	}
	if !found {
		panic("kourtv3: that claim is not in the folder")
	}
	f.items = out
	emitModAct(c.id, claimID, "folder-remove", who)
}
func RenameFolder(cur realm, courtSlug string, folderID uint64, name, desc string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	if runeLen(name) == 0 || runeLen(name) > maxFolderTextLen || runeLen(desc) > maxFolderTextLen {
		panic("kourtv3: a folder name is 1..200 and a description at most 200 characters")
	}
	f := cm.mustFolder(folderID)
	if f.purged {
		panic("kourtv3: this folder's text was purged and cannot be re-set")
	}
	f.name = name
	f.desc = desc
	emitModAct(c.id, 0, "folder-rename", who)
}
func SetFolderImage(cur realm, courtSlug string, folderID uint64, media string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	f := cm.mustFolder(folderID)
	if f.purged {
		panic("kourtv3: this folder's text was purged and cannot be re-set")
	}
	items := parseMediaArg(media)
	if len(items) != 1 {
		panic("kourtv3: a folder carries exactly one image")
	}
	if items[0].kind != mediaKindImage {
		panic("kourtv3: a folder's image is an image, not a video link")
	}
	f.image = &items[0]
	emitModAct(c.id, 0, "folder-image", who)
}
func ClearFolderImage(cur realm, courtSlug string, folderID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	cm.mustFolder(folderID).image = nil
	emitModAct(c.id, 0, "folder-image-clear", who)
}
func FolderImage(courtSlug string, folderID uint64) string {
	c := mustCourt(courtSlug)
	cm := c.mod
	if cm == nil {
		return "[]"
	}
	f := cm.mustFolder(folderID)
	if f.image == nil {
		return "[]"
	}
	return encodeMedia([]mediaItem{*f.image})
}
func PurgeFolder(cur realm, courtSlug string, folderID uint64, categoryCode string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if !d.members.Has(who.String()) {
		panic("kourtv3: only a global DAO member may purge")
	}
	mustCategoryCode(categoryCode)
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	f := cm.mustFolder(folderID)
	fire, code := approveAction(d.pending, "purgefolder:"+c.id+":"+strconv.FormatUint(folderID, 10), who, categoryCode, d.purgeM)
	if !fire {
		return
	}
	f.purged = true
	f.code = code
	f.name = ""
	f.desc = ""
	f.image = nil
	emitPurge(c.id, 0, code, who)
}
func FolderCount(courtSlug string) int {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return 0
	}
	return c.mod.folders.Size()
}
func FolderName(courtSlug string, folderID uint64) string {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		panic("kourtv3: no such folder")
	}
	f := c.mod.mustFolder(folderID)
	if f.purged {
		return "[purged:" + f.code + "]"
	}
	return f.name
}
func FolderDesc(courtSlug string, folderID uint64) string {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		panic("kourtv3: no such folder")
	}
	return c.mod.mustFolder(folderID).desc
}
func FolderItems(courtSlug string, folderID uint64) []uint64 {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		panic("kourtv3: no such folder")
	}
	f := c.mod.mustFolder(folderID)
	out := make([]uint64, len(f.items))
	copy(out, f.items)
	return out
}
func ClaimFolders(courtSlug string, claimID uint64) []uint64 {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return nil
	}
	var out []uint64
	for _, f := range c.mod.folderRows() {
		if f.purged {
			continue
		}
		for _, it := range f.items {
			if it == claimID {
				out = append(out, f.id)
				break
			}
		}
	}
	return out
}
func RetireFolder(cur realm, courtSlug string, folderID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	f := cm.mustFolder(folderID)
	if cm.folderHeight(folderID) > 1 {
		panic("kourtv3: retire the folders inside it first")
	}
	f.retired = true
	f.items = nil
	emitModAct(c.id, 0, "folder-retire", who)
}
func RestoreFolder(cur realm, courtSlug string, folderID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	f := cm.mustFolder(folderID)
	if f.purged {
		panic("kourtv3: a purged folder cannot be restored")
	}
	f.retired = false
	emitModAct(c.id, 0, "folder-restore", who)
}
func MoveItemInFolder(cur realm, courtSlug string, folderID, claimID uint64, to int) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	f := cm.mustFolder(folderID)
	at := -1
	for i, x := range f.items {
		if x == claimID {
			at = i
			break
		}
	}
	if at < 0 {
		panic("kourtv3: that claim is not in the folder")
	}
	if to < 0 || to >= len(f.items) {
		panic("kourtv3: that position is outside the folder")
	}
	if to == at {
		return
	}
	out := make([]uint64, 0, len(f.items))
	for i, x := range f.items {
		if i == at {
			continue
		}
		if len(out) == to {
			out = append(out, claimID)
		}
		out = append(out, x)
	}
	if len(out) == to {
		out = append(out, claimID)
	}
	f.items = out
	emitModAct(c.id, claimID, "folder-order", who)
}
func OrderFolders(cur realm, courtSlug string, parentID uint64, ids string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := requireFolderMod(c, who)
	if parentID != 0 {
		cm.mustFolder(parentID)
	}
	if len(ids) > maxFolders*21 {
		panic("kourtv3: that is too long to be a list of folder ids")
	}
	sibs := make([]*folder, 0, maxFolders)
	cm.folders.Iterate("", "", func(_ string, v any) bool {
		if f, ok := v.(*folder); ok && f.parent == parentID {
			sibs = append(sibs, f)
		}
		return false
	})
	if len(sibs) == 0 {
		panic("kourtv3: there are no folders under that heading to order")
	}
	parts := strings.Split(ids, ",")
	if len(parts) != len(sibs) {
		panic("kourtv3: that heading holds " + strconv.Itoa(len(sibs)) +
			" folders and the order lists " + strconv.Itoa(len(parts)) +
			"; it must list every one of them, exactly once")
	}
	order := make([]*folder, 0, len(parts))
	for _, p := range parts {
		id, err := strconv.ParseUint(strings.TrimSpace(p), 10, 64)
		if err != nil {
			panic("kourtv3: an order is a comma-separated list of folder ids")
		}
		var f *folder
		for _, s := range sibs {
			if s.id == id {
				f = s
				break
			}
		}
		if f == nil {
			panic("kourtv3: folder " + strconv.FormatUint(id, 10) +
				" is not under that heading")
		}
		for _, x := range order {
			if x.id == id {
				panic("kourtv3: folder " + strconv.FormatUint(id, 10) +
					" is listed twice")
			}
		}
		order = append(order, f)
	}
	for i, f := range order {
		f.ord = i + 1
	}
	emitModAct(c.id, 0, "folder-sort", who)
}
func FolderTree(courtSlug string) string {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return ""
	}
	var b strings.Builder
	n := 0
	for _, f := range c.mod.folderRows() {
		if n > 0 {
			b.WriteString(",")
		}
		flags := ""
		if f.retired {
			flags += "r"
		}
		if f.purged {
			flags += "p"
		}
		if f.focusByDefault {
			flags += "f"
		}
		if f.image != nil {
			flags += "i"
		}
		if flags == "" {
			flags = "-"
		}
		b.WriteString(strconv.FormatUint(f.id, 10) + ":" +
			strconv.FormatUint(f.parent, 10) + ":" + flags + ":" +
			strconv.FormatUint(f.bornOf, 10))
		n++
	}
	return b.String()
}
func FolderRetired(courtSlug string, folderID uint64) bool {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return false
	}
	v := c.mod.folders.Get(beClaimKey(folderID))
	if v == nil {
		return false
	}
	return v.(*folder).retired
}
func FolderParent(courtSlug string, folderID uint64) uint64 {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return 0
	}
	v := c.mod.folders.Get(beClaimKey(folderID))
	if v == nil {
		return 0
	}
	return v.(*folder).parent
}
func FolderPurged(courtSlug string, folderID uint64) bool {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		panic("kourtv3: no such folder")
	}
	return c.mod.mustFolder(folderID).purged
}

gnomod.toml

module = "gno.land/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3"
gno = "0.9"

[addpkg]
  creator = "g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr"
  height = 152027
  max_deposit = "300000000ugnot"

governedset.gno

package kourtv3
import (
	"strconv"
	"strings"
	"chain"
)
const (
	setMark   = "\U00013080"
	shutMark  = "\U0001307C"
	setPrefix = setMark + " "
	shutPrefix = shutMark + " "
)
func parseSetTitle(title string) (name string, shown bool, ok bool) {
	pre := ""
	switch {
	case strings.HasPrefix(title, setPrefix):
		pre, shown = setPrefix, true
	case strings.HasPrefix(title, shutPrefix):
		pre, shown = shutPrefix, false
	default:
		return "", false, false
	}
	name = title[len(pre):]
	if !folderTextOK(name, "") {
		return "", false, false
	}
	return name, shown, true
}
func IsSetClaim(courtSlug string, claimID uint64) bool {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	_, _, ok := parseSetTitle(cs.title)
	return ok
}
func ClaimSet(courtSlug string, claimID uint64) uint64 {
	c := mustCourt(courtSlug)
	if c.mod == nil || c.mod.folders == nil {
		return 0
	}
	var out uint64
	c.mod.folders.Iterate("", "", func(_ string, v any) bool {
		f := v.(*folder)
		if f.bornOf == claimID {
			out = f.id
			return true
		}
		return false
	})
	return out
}
func SetBornOf(courtSlug string, folderID uint64) uint64 {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return 0
	}
	return c.mod.mustFolder(folderID).bornOf
}
func New(cur realm, courtSlug string, claimID uint64) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	name, shown, ok := parseSetTitle(cs.title)
	if !ok {
		panic("kourtv3: this claim's title is not a set heading")
	}
	if cs.verdictAt == 0 || cs.provClose {
		panic("kourtv3: no final verdict")
	}
	if cs.provisional != 0 {
		panic("kourtv3: the verdict was not YES")
	}
	if prior := ClaimSet(courtSlug, claimID); prior != 0 {
		panic("kourtv3: this claim already carries set " + strconv.FormatUint(prior, 10))
	}
	cm := ensureMod(c)
	if folderNameTaken(cm, name) {
		panic("kourtv3: a folder by that name already exists")
	}
	var parent uint64
	if in := ClaimFolders(courtSlug, claimID); len(in) == 1 {
		parent = in[0]
	} else if len(in) > 1 {
		panic("kourtv3: this claim is filed in more than one set; a born set needs exactly one parent")
	}
	if parent != 0 && cm.mustFolder(parent).retired {
		panic("kourtv3: the set this claim is filed in has been retired")
	}
	fid := newFolderCore(cm, name, "", parent)
	f := cm.mustFolder(fid)
	f.bornOf = claimID
	f.focusByDefault = shown
	emitModAct(c.id, claimID, "new", cs.author)
	chain.Emit("SetAffirmed",
		"court", c.id,
		"claim", strconv.FormatUint(claimID, 10),
		"folder", strconv.FormatUint(fid, 10),
		"parent", strconv.FormatUint(parent, 10),
		"name", name,
		"height", eventHeight(),
	)
	return fid
}

handover.gno

package kourtv3
func HandOver(cur realm, to address) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	if !to.IsValid() {
		panic("kourtv3: not a valid address")
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if who != d.admin {
		panic("kourtv3: only the global DAO admin hands over")
	}
	if to == who {
		panic("kourtv3: hand over to a different address")
	}
	seatGlobalMember(d, to)
	d.admin = to
	if d.members.Has(who.String()) {
		d.members.Remove(who.String())
		d.n--
		if d.purgeM > d.n {
			d.purgeM = d.n
		}
		clearPendingOnMembershipChange(&d.pending)
	}
	directoryAdmin = to
	courts.Iterate("", "", func(_ string, v any) bool {
		c := v.(*Court)
		if c.admin != who {
			return false
		}
		c.admin = to
		if cm := c.mod; cm != nil && !cm.creatorUnseated {
			if cm.members.Has(who.String()) {
				cm.members.Remove(who.String())
				cm.n--
			}
			if !cm.members.Has(to.String()) {
				cm.members.Set(to.String(), true)
				cm.n++
			}
			if cm.m > cm.n {
				cm.m = cm.n
			}
			clearPendingOnMembershipChange(&cm.pending)
		}
		return false
	})
}

help.gno

package kourtv3
import "strings"
const helpPath = "how-it-works"
const helpLink = "[New here? How Kourt works](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + helpPath + ")"
func renderHelp() string {
	var b strings.Builder
	b.WriteString("# How Kourt works\n\n")
	b.WriteString("Kourt is a place to put money behind whether a factual claim is " +
		"true — without being able to lose the money.\n\n")
	b.WriteString("It works in two steps. **GNOT buys a court's coin**, one way; " +
		"**that coin is what you stake** on the court's claims.\n\n")
	b.WriteString("## You cannot lose your stake\n\n")
	b.WriteString("Stake the court's coin on YES or NO and the stake stays yours. " +
		"It is locked where it is, not handed to anybody: when the claim is " +
		"answered you withdraw exactly what you put in — 1×, always, whichever " +
		"side you took and whichever side turned out to be right. No one's stake " +
		"pays anyone else's winnings.\n\n")
	b.WriteString("Then what is at stake? Being right pays you more of the court's " +
		"coin, out of the reserve it set aside for exactly that — and being wrong " +
		"pays you none. Nothing of yours is taken either way.\n\n")
	b.WriteString("Being right also earns **standing**, which is a separate thing " +
		"from a balance: a score you cannot buy, and what actually gives you a " +
		"voice here.\n\n")
	b.WriteString("## A court is a subject\n\n")
	b.WriteString("A court covers one subject — an epidemic, an election, a company. " +
		"Each court has its own coin, and coins never cross between courts. Being " +
		"right about virology earns you nothing in a court about monetary policy. " +
		"That is the point: standing is earned subject by subject, by the people who " +
		"follow that subject.\n\n")
	b.WriteString("## A claim is a statement that can be settled\n\n")
	b.WriteString("A claim is a sentence that is either true or false, written so it " +
		"can actually be answered. You stake YES or NO, and you can move your stake " +
		"freely until an answer posts.\n\n")
	b.WriteString("A claim's page always says where it stands. The wordings you will see:\n\n")
	b.WriteString("- **settled YES** or **settled NO** — answered, and the page " +
		"says which way; every stake withdraws 1×\n")
	b.WriteString("- **disputed** — a sealed vote is deciding; principal is never withheld\n")
	b.WriteString("- **closed** — never answered; every stake exited 1×, the deposit refunded\n")
	b.WriteString("- **closed without a decision** — three dispute rounds failed quorum; " +
		"everyone withdraws 1×, deposit and fee refunded\n\n")
	b.WriteString("## Comments are where the argument is\n\n")
	b.WriteString("Every claim has a comment board. A YES/NO number cannot carry a " +
		"reason, a source, or an objection; the board is where those go.\n\n")
	b.WriteString("Writing takes standing — the score you earned by being right in " +
		"this court, not the coin you hold. If you have none yet, you can buy a " +
		"one-off entry pass by burning a little of the court's coin, which is the " +
		"single place money substitutes for it. Standing sets how many comments a " +
		"day you get, not how loudly they land: nothing is hidden for being new, " +
		"and nothing is ranked by wealth.\n\n")
	b.WriteString("If you have money on the claim you are commenting on, your comment " +
		"says so — which side, and how much. The board deliberately does *not* order " +
		"by it. You are told, and you decide what it is worth.\n\n")
	b.WriteString("## Two things you can actually lose\n\n")
	b.WriteString("Everything above is about a stake that always comes back. " +
		"There are exactly two actions here that risk money, and both are " +
		"challenges — you are putting up a **bond** to say the court got " +
		"something wrong.\n\n")
	b.WriteString("- **Challenging an answer.** If you think a claim was answered " +
		"the wrong way, you can dispute it by posting a bond. Win and the " +
		"answerer's bond is burned and you are compensated; lose and yours is " +
		"burned instead. Nothing passes between you — a forfeit is destroyed, a " +
		"compensation is newly issued.\n")
	b.WriteString("- **Challenging a rating.** Every answered claim gets rated " +
		"low, mid or high, and that rating decides what it pays. Anyone may " +
		"challenge the rating once, also by posting a bond, which calls a vote " +
		"on it.\n\n")
	b.WriteString("**Your stake is never at risk in either.** A bond is separate " +
		"money you choose to put up; the coin you staked on the claim still " +
		"comes back 1×, whatever the challenge decides.\n\n")
	b.WriteString("## What things cost\n\n")
	b.WriteString("- **Staking** costs only the stake, which you get back.\n")
	b.WriteString("- **Opening a claim** takes a deposit, refunded when the claim is " +
		"answered or closed.\n")
	b.WriteString("- **Receiving a court's coin** takes GNOT on a rising curve. A " +
		"share of it (" + pct(burnBps, bpsDenom) + " today, set by the " +
		"platform's governing court within fixed bounds) is burned for good; the " +
		"rest is held by the court and paid back pro-rata to anyone who returns " +
		"coin — less than they put in, right after they put it in, and below " +
		"the next coin's price unless coin has been destroyed by bonds since the " +
		"last offering. A one-way court burns all of it. The price " +
		"only rises as more is minted.\n\n")
	b.WriteString("## Who is in charge\n\n")
	b.WriteString("Each court elects its own moderators. They answer claims, organise " +
		"them into folders, and can hide comments. What they do to a claim or a " +
		"comment is written to that court's moderation log, which anyone can read " +
		"without asking. The serious powers need several moderators to agree — one " +
		"moderator acting alone cannot use them.\n\n")
	b.WriteString("[← all courts](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:)\n")
	return b.String()
}

holders.gno

package kourtv3
const topHoldersMax = 50
func HolderCount(courtSlug string) int {
	c := mustCourt(courtSlug)
	esc := c.escrow
	n := 0
	c.coin.WalkAccounts(func(who address, bal int64) bool {
		if bal > 0 && who != esc {
			n++
		}
		return false
	})
	return n
}
func TopHolders(courtSlug string, limit int) string {
	if limit <= 0 || limit > topHoldersMax {
		limit = topHoldersMax
	}
	c := mustCourt(courtSlug)
	esc := c.escrow
	who := make([]address, 0, limit)
	bal := make([]int64, 0, limit)
	c.coin.WalkAccounts(func(a address, b int64) bool {
		if b <= 0 || a == esc {
			return false
		}
		pos := len(who)
		for pos > 0 && b > bal[pos-1] {
			pos--
		}
		if pos >= limit {
			return false
		}
		if len(who) < limit {
			who = append(who, address(""))
			bal = append(bal, 0)
		}
		for i := len(who) - 1; i > pos; i-- {
			who[i], bal[i] = who[i-1], bal[i-1]
		}
		who[pos], bal[pos] = a, b
		return false
	})
	out := ""
	for i := range who {
		if bal[i] <= 0 {
			continue
		}
		out += ";" + string(who[i]) + ":" + itoa(bal[i])
	}
	if out == "" {
		return ""
	}
	return out[1:]
}
func TopHoldersNote() string {
	return "Ranked by coin held. Coin staked on a claim sits in the court's custody until the claim resolves, so it is not counted here."
}

lock.gno

package kourtv3
import (
	"strconv"
	bptree "gno.land/p/nt/bptree/v0"
)
func lockedOf(c *Court, who address) int64 {
	if c.locked == nil {
		return 0
	}
	if v := c.locked.Get(string(who)); v != nil {
		return v.(int64)
	}
	return 0
}
func spendable(c *Court, who address) int64 {
	s := c.coin.BalanceOf(who) - lockedOf(c, who)
	if s < 0 {
		return 0
	}
	return s
}
func disposable(c *Court, who address) int64 {
	claim := lockedOf(c, who)
	if v := voteLockedOf(c, who); v > claim {
		claim = v
	}
	d := c.coin.BalanceOf(who) - claim
	if d < 0 {
		return 0
	}
	return d
}
func DisposableOf(courtSlug string, who address) int64 {
	return disposable(mustCourt(courtSlug), who)
}
func ccAmt(n int64) string {
	if n < 0 {
		return "-" + ccAmt(-n)
	}
	whole := strconv.FormatInt(n/1_000_000, 10)
	frac := n % 1_000_000
	if frac == 0 {
		return whole
	}
	f := strconv.FormatInt(frac, 10)
	for len(f) < 6 {
		f = "0" + f
	}
	for len(f) > 1 && f[len(f)-1] == '0' {
		f = f[:len(f)-1]
	}
	return whole + "." + f
}
func mustSpendable(c *Court, who address, amount int64) {
	if disposable(c, who) >= amount {
		return
	}
	vl, sl := voteLockedOf(c, who), lockedOf(c, who)
	short := "need " + ccAmt(amount) + " CC, you have " + ccAmt(disposable(c, who))
	switch {
	case vl <= 0 && sl <= 0:
		panic("kourtv3: not enough CC — " + short)
	case vl > sl:
		panic("kourtv3: not enough uncommitted CC — " + short +
			" free; " + ccAmt(vl) + " is committed by voting")
	case sl > vl:
		panic("kourtv3: not enough unstaked CC — " + short +
			" free; " + ccAmt(sl) + " is staked")
	default:
		panic("kourtv3: not enough free CC — " + short +
			" free; " + ccAmt(sl) + " is both staked and committed by voting")
	}
}
func mustStakable(c *Court, who address, amount int64) {
	if s := spendable(c, who); s < amount {
		tail := ""
		if l := lockedOf(c, who); l > 0 {
			tail = "; " + ccAmt(l) + " is staked"
		}
		panic("kourtv3: not enough unstaked CC — need " + ccAmt(amount) +
			" CC, you have " + ccAmt(s) + tail)
	}
}
func lockStake(c *Court, who address, amount int64) {
	if amount <= 0 {
		return
	}
	if c.locked == nil {
		c.locked = bptree.NewBPTree32()
	}
	c.locked.Set(string(who), mustAdd(lockedOf(c, who), amount))
}
func releaseStake(c *Court, who address, amount int64) {
	if amount <= 0 {
		return
	}
	l := lockedOf(c, who)
	if amount > l {
		panic("kourtv3: releasing more stake than is locked")
	}
	if amount == l {
		c.locked.Remove(string(who))
		return
	}
	c.locked.Set(string(who), l-amount)
}
func LockedOf(courtSlug string, who address) int64 {
	return lockedOf(mustCourt(courtSlug), who)
}
func SpendableOf(courtSlug string, who address) int64 {
	return spendable(mustCourt(courtSlug), who)
}
func TransferCC(cur realm, courtSlug string, to address, amount int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	if amount <= 0 {
		panic("kourtv3: transfer amount must be positive")
	}
	from := cur.Previous().Address()
	if from == to {
		panic("kourtv3: cannot transfer to yourself")
	}
	c := mustCourt(courtSlug)
	if to == c.escrow || from == c.escrow {
		panic("kourtv3: the court escrow is not a transfer endpoint")
	}
	touch(c)
	mustSpendable(c, from, amount)
	c.coin.Transfer(from, to, amount)
}
func ApproveCC(cur realm, courtSlug string, spender address, amount int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	if amount < 0 {
		panic("kourtv3: negative allowance")
	}
	c := mustCourt(courtSlug)
	owner := cur.Previous().Address()
	if spender == c.escrow || owner == c.escrow {
		panic("kourtv3: the court escrow is not a transfer endpoint")
	}
	touch(c)
	c.coin.Approve(owner, spender, amount)
}
func TransferFromCC(cur realm, courtSlug string, from, to address, amount int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	if amount <= 0 {
		panic("kourtv3: transfer amount must be positive")
	}
	if from == to {
		panic("kourtv3: cannot transfer to yourself")
	}
	c := mustCourt(courtSlug)
	if to == c.escrow || from == c.escrow {
		panic("kourtv3: the court escrow is not a transfer endpoint")
	}
	touch(c)
	mustSpendable(c, from, amount)
	c.coin.TransferFrom(cur.Previous().Address(), from, to, amount)
}
func AllowanceCC(courtSlug string, owner, spender address) int64 {
	return mustCourt(courtSlug).coin.Allowance(owner, spender)
}

media.gno

package kourtv3
import (
	"chain"
	"strconv"
	"strings"
	sanitize "gno.land/p/nt/markdown/sanitize/v0"
)
func mediaDestination(m *mediaItem) string {
	if m.kind == mediaKindImage && m.sha256 != "" &&
		siteDomain != "" && siteDomainFault(siteDomain) == "" {
		return "https://" + siteDomain + "/m/" + m.sha256
	}
	for _, u := range m.mirrors {
		if mirrorFault(u) == "" {
			return u
		}
	}
	return ""
}
func verifyElsewhere() string {
	if siteDomain == "" || siteDomainFault(siteDomain) != "" {
		return ""
	}
	return " [" + siteDomain + "](https://" + siteDomain + ") checks it."
}
func writeClaimMedia(b *strings.Builder, c *Court, cs *claimState) {
	items := claimMediaVisible(c, cs)
	if len(items) == 0 {
		return
	}
	total := strconv.Itoa(len(items))
	b.WriteString("## Evidence filed with this claim\n\n")
	b.WriteString("_The court recorded a fingerprint of each image when the claim " +
		"was filed, so a swap can be detected — but not on this page._" + verifyElsewhere() + "\n\n")
	for i := range items {
		m := &items[i]
		pos := strconv.Itoa(i+1) + " of " + total
		if m.purged {
			b.WriteString("_Exhibit " + pos + " was taken down._\n\n")
			continue
		}
		dest := mediaDestination(m)
		if dest == "" {
			b.WriteString("_Exhibit " + pos + " is not currently available._\n\n")
			continue
		}
		caption := ""
		if m.caption != "" {
			caption = " — " + sanitize.InlineText(m.caption)
		}
		if m.kind == mediaKindVideo {
			b.WriteString("[▶ Exhibit " + pos + caption + "](" + dest +
				") _(a link; the court holds no copy and cannot vouch for it)_\n\n")
			continue
		}
		b.WriteString("![Exhibit " + pos + "](" + dest + ")\n\n")
		b.WriteString("_Exhibit " + pos + caption + "_\n\n")
	}
}
func ClaimMediaPage(courtSlug string, fromID uint64, count int) string {
	c := mustCourt(courtSlug)
	if count < 1 {
		return "[]"
	}
	if count > maxMediaPage {
		count = maxMediaPage
	}
	var b strings.Builder
	b.WriteString("[")
	for i := 0; i < count; i++ {
		if i > 0 {
			b.WriteString(",")
		}
		id := fromID + uint64(i)
		v := c.claims.Get(beClaimKey(id))
		if v == nil {
			b.WriteString("[]")
			continue
		}
		b.WriteString(encodeMedia(claimMediaVisible(c, v.(*claimState))))
	}
	b.WriteString("]")
	return b.String()
}
func PurgeClaimMedia(cur realm, courtSlug string, claimID uint64, idx uint64, categoryCode string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if !d.members.Has(who.String()) {
		panic("kourtv3: only a global DAO member may purge")
	}
	mustCategoryCode(categoryCode)
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if idx >= uint64(len(cs.media)) {
		panic("kourtv3: this claim carries no media item at that position")
	}
	if cs.media[idx].purged {
		return
	}
	fire, votedCode := approveAction(d.pending,
		"mediapurge:"+c.id+":"+strconv.FormatUint(claimID, 10)+":"+strconv.FormatUint(idx, 10),
		who, categoryCode, d.purgeM)
	if !fire {
		return
	}
	m := &cs.media[idx]
	m.purged = true
	m.sha256 = ""
	m.mirrors = nil
	m.caption = ""
	m.mime = ""
	ensureClaimMod(c, ensureMod(c), claimID).
		appendLog(who, boardActCode("media-purge", idx, votedCode), "")
	emitPurge(c.id, claimID, "media-item", who)
}
const (
	maxClaimMediaCount = 7
	maxMirrorsPerItem  = 4
	maxMediaURLLen     = 300
	maxCaptionLen      = 120
	maxMediaBytes = 262144
	maxMediaDim   = 20000
	maxMediaPage = 64
)
const (
	mediaKindImage = "img"
	mediaKindVideo = "vid"
)
type mediaItem struct {
	kind    string
	sha256  string
	mime    string
	w, h    int
	bytes   int
	caption string
	mirrors []string
	purged bool
}
func mediaCharFault(s string) string {
	for i := 0; i < len(s); i++ {
		c := s[i]
		if c < 0x21 || c > 0x7e {
			return "a mirror is printable ASCII with no spaces"
		}
		switch c {
		case '"', '\'', '<', '>', '(', ')', '\\', ',', '|', '`':
			return "a mirror may not contain " + string(rune(c))
		}
	}
	return ""
}
func isHexLower(s string) bool {
	for i := 0; i < len(s); i++ {
		c := s[i]
		if (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') {
			continue
		}
		return false
	}
	return true
}
func mirrorFault(u string) string {
	if len(u) == 0 || len(u) > maxMediaURLLen {
		return "a mirror is 1.." + strconv.Itoa(maxMediaURLLen) + " characters"
	}
	if fault := mediaCharFault(u); fault != "" {
		return fault
	}
	const scheme = "https://"
	if !strings.HasPrefix(u, scheme) {
		return "a mirror is https — plain http is blocked as mixed content"
	}
	host := u[len(scheme):]
	for _, sep := range []byte{'/', '?', '#'} {
		if i := strings.IndexByte(host, sep); i >= 0 {
			host = host[:i]
		}
	}
	if host == "" {
		return "a mirror needs a host"
	}
	if !mediaHostAllowed(host) {
		return "the browser will not load images from " + host +
			"; see the allowed hosts on the help page"
	}
	return ""
}
var defaultMediaHostsExact = []string{
	"gnolang.github.io",
	"assets.gnoteam.com",
	"sa.gno.services",
	"imgur.com",
	"github.com",
	"imgflip.com",
	"ipfs.io",
	"cloudflare-ipfs.com",
}
var defaultMediaHostSuffixes = []string{
	".imgur.com",
	".github.io",
	".githubusercontent.com",
	".imgflip.com",
}
var mediaHostsExact = appendAll(nil, defaultMediaHostsExact)
var mediaHostSuffixes = appendAll(nil, defaultMediaHostSuffixes)
func appendAll(dst, src []string) []string {
	for _, v := range src {
		dst = append(dst, v)
	}
	return dst
}
const maxMediaHosts = 32
func mediaHostEntryFault(h string, suffix bool) string {
	if h == "" {
		return "a host may not be empty"
	}
	if len(h) > 100 {
		return "a host is at most 100 characters"
	}
	if suffix && h[0] != '.' {
		return "a suffix begins with a dot: " + h
	}
	if !suffix && h[0] == '.' {
		return "an exact host does not begin with a dot: " + h
	}
	for i := 0; i < len(h); i++ {
		c := h[i]
		ok := (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-'
		if !ok {
			return "a host is lowercase letters, digits, dots and hyphens: " + h
		}
	}
	if strings.Contains(h, "..") || h[len(h)-1] == '.' {
		return "a host has no empty label: " + h
	}
	return ""
}
func parseMediaHosts(list string, suffix bool) []string {
	if strings.TrimSpace(list) == "" {
		return nil
	}
	parts := strings.Split(list, ",")
	if len(parts) > maxMediaHosts {
		panic("kourtv3: at most " + strconv.Itoa(maxMediaHosts) + " hosts in a list")
	}
	out := []string{}
	for _, p := range parts {
		h := strings.TrimSpace(p)
		if fault := mediaHostEntryFault(h, suffix); fault != "" {
			panic("kourtv3: " + fault)
		}
		for _, seen := range out {
			if seen == h {
				panic("kourtv3: " + h + " is listed twice")
			}
		}
		out = append(out, h)
	}
	return out
}
func SetMediaHosts(cur realm, exact, suffixes string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin sets the media hosts")
	}
	ex := parseMediaHosts(exact, false)
	sf := parseMediaHosts(suffixes, true)
	if len(ex) == 0 && len(sf) == 0 {
		panic("kourtv3: to allow no third-party host, call ClearMediaHosts")
	}
	mediaHostsExact = ex
	mediaHostSuffixes = sf
	chain.Emit(globalActEvent,
		"court", "*",
		"claim", "0",
		"act", "set-media-hosts:"+strconv.Itoa(len(ex))+"+"+strconv.Itoa(len(sf)),
		"by", cur.Previous().Address().String(),
		"height", eventHeight(),
	)
}
func ClearMediaHosts(cur realm) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin sets the media hosts")
	}
	mediaHostsExact = nil
	mediaHostSuffixes = nil
	chain.Emit(globalActEvent,
		"court", "*",
		"claim", "0",
		"act", "clear-media-hosts",
		"by", cur.Previous().Address().String(),
		"height", eventHeight(),
	)
}
func MediaHosts() string {
	return strings.Join(mediaHostsExact, ",") + "|" + strings.Join(mediaHostSuffixes, ",")
}
func mediaHostAllowed(host string) bool {
	if host == "" {
		return false
	}
	if siteDomain != "" && host == siteDomain && siteDomainFault(siteDomain) == "" {
		return true
	}
	for _, h := range mediaHostsExact {
		if host == h {
			return true
		}
	}
	for _, s := range mediaHostSuffixes {
		if len(host) > len(s) && strings.HasSuffix(host, s) {
			return true
		}
	}
	return false
}
func captionFault(s string) string {
	if runeLen(s) > maxCaptionLen {
		return "a caption is at most " + strconv.Itoa(maxCaptionLen) + " characters"
	}
	for _, r := range s {
		if (r >= 0x202A && r <= 0x202E) || (r >= 0x2066 && r <= 0x2069) {
			return "a caption may not contain text-direction controls"
		}
	}
	for i := 0; i < len(s); i++ {
		switch s[i] {
		case '\n', '\r':
			return "a caption is one line"
		case '|':
			return "a caption may not contain a vertical bar"
		}
		if s[i] < 0x20 && s[i] != '\t' {
			return "a caption may not contain control characters"
		}
	}
	return ""
}
func mediaItemFault(m *mediaItem) string {
	switch m.kind {
	case mediaKindImage:
		if len(m.sha256) != 64 || !isHexLower(m.sha256) {
			return "an image needs a sha256: 64 lowercase hex characters"
		}
		if m.w <= 0 || m.h <= 0 || m.w > maxMediaDim || m.h > maxMediaDim {
			return "an image needs real dimensions"
		}
		if m.bytes <= 0 || m.bytes > maxMediaBytes {
			return "an image is 1.." + strconv.Itoa(maxMediaBytes) + " bytes"
		}
		if m.mime == "" {
			return "an image needs a media type"
		}
	case mediaKindVideo:
		if m.sha256 != "" {
			return "a video link carries no hash"
		}
	default:
		return "a media item is " + mediaKindImage + " or " + mediaKindVideo
	}
	if fault := captionFault(m.caption); fault != "" {
		return fault
	}
	if len(m.mirrors) == 0 {
		return "a media item needs somewhere to find it"
	}
	if len(m.mirrors) > maxMirrorsPerItem {
		return "a media item lists at most " + strconv.Itoa(maxMirrorsPerItem) + " mirrors"
	}
	for _, u := range m.mirrors {
		if fault := mirrorFault(u); fault != "" {
			return fault
		}
	}
	return ""
}
func parseMediaFault(arg string) ([]mediaItem, string) {
	trimmed := strings.TrimSpace(arg)
	if trimmed == "" {
		return nil, ""
	}
	lines := strings.Split(trimmed, "\n")
	if len(lines) > maxClaimMediaCount {
		return nil, "a claim carries at most " +
			strconv.Itoa(maxClaimMediaCount) + " media items"
	}
	out := make([]mediaItem, 0, len(lines))
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		f := strings.Split(line, "|")
		if len(f) != 8 {
			return nil, "a media item has 8 fields separated by |"
		}
		m := mediaItem{
			kind:    f[0],
			sha256:  f[1],
			mime:    f[2],
			w:       atoiOr0(f[3]),
			h:       atoiOr0(f[4]),
			bytes:   atoiOr0(f[5]),
			caption: f[6],
		}
		for _, u := range strings.Split(f[7], ",") {
			if u != "" {
				m.mirrors = append(m.mirrors, u)
			}
		}
		if fault := mediaItemFault(&m); fault != "" {
			return nil, fault
		}
		out = append(out, m)
	}
	return out, ""
}
func parseMediaArg(arg string) []mediaItem {
	items, fault := parseMediaFault(arg)
	if fault != "" {
		panic("kourtv3: " + fault)
	}
	return items
}
func atoiOr0(s string) int {
	n, err := strconv.Atoi(s)
	if err != nil {
		return 0
	}
	return n
}
func jsonString(s string) string {
	var b strings.Builder
	b.WriteString(`"`)
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch c {
		case '"':
			b.WriteString(`\"`)
		case '\\':
			b.WriteString(`\\`)
		case '\n':
			b.WriteString(`\n`)
		case '\r':
			b.WriteString(`\r`)
		case '\t':
			b.WriteString(`\t`)
		default:
			if c < 0x20 {
				b.WriteString(`\u00`)
				const hex = "0123456789abcdef"
				b.WriteByte(hex[c>>4])
				b.WriteByte(hex[c&0xf])
				continue
			}
			b.WriteByte(c)
		}
	}
	b.WriteString(`"`)
	return b.String()
}
func encodeMedia(items []mediaItem) string {
	if len(items) == 0 {
		return "[]"
	}
	var b strings.Builder
	b.WriteString("[")
	for i := range items {
		if i > 0 {
			b.WriteString(",")
		}
		m := &items[i]
		b.WriteString(`{"kind":`)
		b.WriteString(jsonString(m.kind))
		if m.purged {
			b.WriteString(`,"purged":true}`)
			continue
		}
		b.WriteString(`,"sha256":`)
		b.WriteString(jsonString(m.sha256))
		b.WriteString(`,"mime":`)
		b.WriteString(jsonString(m.mime))
		b.WriteString(`,"w":`)
		b.WriteString(strconv.Itoa(m.w))
		b.WriteString(`,"h":`)
		b.WriteString(strconv.Itoa(m.h))
		b.WriteString(`,"bytes":`)
		b.WriteString(strconv.Itoa(m.bytes))
		b.WriteString(`,"caption":`)
		b.WriteString(jsonString(m.caption))
		b.WriteString(`,"mirrors":[`)
		n := 0
		for _, u := range m.mirrors {
			if mirrorFault(u) != "" {
				continue
			}
			if n > 0 {
				b.WriteString(",")
			}
			b.WriteString(jsonString(u))
			n++
		}
		b.WriteString(`]}`)
	}
	b.WriteString("]")
	return b.String()
}

meta.gno

package kourtv3
import (
	"chain"
	"strconv"
	"strings"
	unsafe "chain/runtime/unsafe"
	"math/overflow"
	bptree "gno.land/p/nt/bptree/v0"
)
const metaRealmPath = "gno.land/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3"
const (
	metaPrefix   = "mod:"
	metaCourtNm  = "Meta"
	metaExecuted = "MetaExecuted"
)
const (
	verbUnhide    = "unhide"
	verbClear     = "clear"
	verbHide      = "hide"
	verbSuspend   = "suspend"
	verbUnsuspend = "unsuspend"
	verbSetmods   = "setmods"
	verbNewset = "newset"
)
func verbIsAggressive(v string) bool {
	return v == verbHide || v == verbSuspend || v == verbUnsuspend || v == verbSetmods
}
type modParse struct {
	valid     bool
	verb      string
	court     string
	target    uint64
	hasTarget bool
	poisoned  bool
}
type metaState struct {
	parses   *bptree.BPTree
	bindings *bptree.BPTree
	latches  *bptree.BPTree
	executed *bptree.BPTree
}
var meta = &metaState{
	parses:   bptree.NewBPTree32(),
	bindings: bptree.NewBPTree32(),
	latches:  bptree.NewBPTree32(),
	executed: bptree.NewBPTree32(),
}
func init() {
	startCourt(unsafe.OriginCaller(), chain.PackageAddress(metaRealmPath), metaSlug, metaCourtNm, 0, true)
}
func parseModTitle(title string) modParse {
	p := modParse{}
	if !strings.HasPrefix(title, metaPrefix) {
		return p
	}
	rest := title[len(metaPrefix):]
	slash := strings.Index(rest, ":")
	if slash < 0 {
		return p
	}
	verb := rest[:slash]
	arg := rest[slash+1:]
	switch verb {
	case verbUnhide, verbClear, verbHide, verbSetmods, verbNewset:
		cut := strings.Index(arg, "/")
		if cut <= 0 || cut == len(arg)-1 {
			return p
		}
		id, err := strconv.ParseUint(arg[cut+1:], 10, 64)
		if err != nil || id == 0 {
			return p
		}
		p.court, p.target, p.hasTarget = arg[:cut], id, true
	case verbSuspend, verbUnsuspend:
		if arg == "" || strings.Contains(arg, "/") {
			return p
		}
		p.court = arg
	default:
		return p
	}
	for i := 0; i < len(p.court); i++ {
		ch := p.court[i]
		if !((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '-') {
			return modParse{}
		}
	}
	p.verb, p.valid = verb, true
	return p
}
func latchKey(p modParse) string {
	switch p.verb {
	case verbSetmods:
		return "set:" + p.court
	case verbNewset:
		return "fold:" + p.court
	case verbSuspend, verbUnsuspend:
		return "sus:" + p.court
	default:
		return "item:" + p.court + ":" + strconv.FormatUint(p.target, 10)
	}
}
func onClaimOpened(c *Court, cs *claimState) {
	if c.id != metaSlug {
		return
	}
	p := parseModTitle(cs.title)
	meta.parses.Set(beClaimKey(cs.id), &p)
	cs.noAccuracy = p.valid && p.verb == verbNewset
	if p.valid {
		pendingEnter(c, cs)
	}
}
func onTitleEdited(c *Court, cs *claimState) {
	if c.id != metaSlug {
		return
	}
	p := parseModTitle(cs.title)
	if prev := meta.parses.Get(beClaimKey(cs.id)); prev != nil && prev.(*modParse).poisoned {
		p.poisoned = true
	}
	meta.parses.Set(beClaimKey(cs.id), &p)
	cs.noAccuracy = p.valid && p.verb == verbNewset
	if p.valid || cs.seeded {
		pendingEnter(c, cs)
	} else {
		pendingExit(c, cs)
	}
}
func onClaimAnswered(c *Court, cs *claimState) {
	if c.id != metaSlug {
		return
	}
	v := meta.parses.Get(beClaimKey(cs.id))
	if v == nil {
		return
	}
	p := v.(*modParse)
	if !p.valid || p.poisoned {
		return
	}
	k := latchKey(*p)
	if held := meta.latches.Get(k); held != nil {
		if held.(uint64) != cs.id {
			panic("kourtv3: another appeal already holds this target's review slot")
		}
	}
	meta.latches.Set(k, cs.id)
	bind := *p
	meta.bindings.Set(beClaimKey(cs.id), &bind)
}
func releaseMetaLatchIfMeta(c *Court, cs *claimState) {
	if c.id != metaSlug {
		return
	}
	releaseMetaLatch(cs)
}
func releaseMetaLatch(cs *claimState) {
	v := meta.bindings.Get(beClaimKey(cs.id))
	if v == nil {
		return
	}
	k := latchKey(*v.(*modParse))
	if held := meta.latches.Get(k); held != nil && held.(uint64) == cs.id {
		meta.latches.Remove(k)
	}
}
func poisonMetaParse(claimID uint64) {
	if v := meta.parses.Get(beClaimKey(claimID)); v != nil {
		v.(*modParse).poisoned = true
	}
}
func metaVerdictExpired(cs *claimState, votingBlocks int64) bool {
	passed, known := pastDeadline(cs.verdictAtTime, blocksToSecs(votingBlocks)+1)
	return (known && passed) || (!known && heightNow() > cs.verdictAt+votingBlocks)
}
func ExecuteMetaVerdict(cur realm, metaClaimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	mc := mustCourt(metaSlug)
	cs := mustClaim(mc, metaClaimID)
	bv := meta.bindings.Get(beClaimKey(metaClaimID))
	if bv == nil {
		panic("kourtv3: this claim carries no binding appeal")
	}
	p := *bv.(*modParse)
	if !Exists(p.court) {
		panic("kourtv3: the target court does not exist")
	}
	tc := mustCourt(p.court)
	if tc.createdAt >= cs.openedAt {
		panic("kourtv3: the target court does not predate this appeal")
	}
	var target *claimState
	if p.hasTarget && p.verb != verbSetmods && p.verb != verbNewset {
		target = mustClaim(tc, p.target)
		if target.openedAt >= cs.openedAt {
			panic("kourtv3: the target claim does not predate this appeal")
		}
	}
	if p.verb == verbSetmods {
		if cand := ensureMod(tc).mustCandidate(p.target); cand.at >= cs.openedAt {
			panic("kourtv3: the candidate set does not predate this appeal")
		}
	}
	if p.verb == verbNewset {
		if prop := ensureMod(tc).mustFolderProposal(p.target); prop.at >= cs.openedAt {
			panic("kourtv3: the folder proposal does not predate this appeal")
		}
	}
	if cs.verdictAt == 0 || cs.provClose {
		panic("kourtv3: no final verdict")
	}
	if int(cs.provisional) != sideYES {
		panic("kourtv3: the verdict was not YES")
	}
	if verbIsAggressive(p.verb) {
		if cs.route != "vote" || cs.decidedRounds == 0 {
			panic("kourtv3: this verb needs a decided contested vote, not silence")
		}
		if p.verb != verbHide && !cs.credEligible {
			panic("kourtv3: a manufactured contest cannot seize authority — this verb needs weight voted against it")
		}
	}
	if meta.executed.Has(beClaimKey(metaClaimID)) {
		panic("kourtv3: already executed")
	}
	if metaVerdictExpired(cs, mc.params.votingBlocks) {
		panic("kourtv3: this verdict has expired; re-appeal")
	}
	cm := ensureMod(tc)
	switch p.verb {
	case verbSetmods:
		if cm.setActHeight > cs.verdictAt {
			panic("kourtv3: the moderator set changed after this verdict; re-appeal")
		}
		if cm.suspended && cm.suspendActByGlobal > cs.openedAt {
			panic("kourtv3: the global DAO changed this court's suspension under this appeal; re-appeal")
		}
	case verbSuspend, verbUnsuspend:
		if cm.lastElectionAt > cs.openedAt || cm.setActHeight > cs.verdictAt {
			panic("kourtv3: the moderator set changed under this appeal; re-appeal")
		}
		if cm.suspendActByGlobal > cs.openedAt &&
			cm.suspended == (p.verb == verbUnsuspend) {
			panic("kourtv3: the global DAO changed this court's suspension under this appeal; re-appeal")
		}
	case verbUnhide:
		if cm.lastElectionAt > cs.openedAt {
			panic("kourtv3: the moderator set changed under this appeal; re-appeal")
		}
	}
	meta.executed.Set(beClaimKey(metaClaimID), true)
	applyMetaVerb(mc, tc, cm, p, cs, target)
	releaseMetaLatch(cs)
	chain.Emit(metaExecuted,
		"appeal", strconv.FormatUint(metaClaimID, 10),
		"verb", p.verb, "court", p.court,
		"target", strconv.FormatUint(p.target, 10),
	)
}
func applyMetaVerb(mc, tc *Court, cm *courtMod, p modParse, cs, target *claimState) {
	by := cs.answerer
	switch p.verb {
	case verbUnhide:
		clm := lookupClaimMod(cm, p.target)
		if clm == nil || !clm.court {
			return
		}
		clearCourtBitByMeta(tc, p.target, by)
	case verbClear:
		clearMetaBit(tc, p.target, by)
	case verbHide:
		setMetaBit(tc, p.target, by)
	case verbSuspend:
		suspendSet(tc, by)
	case verbUnsuspend:
		unsuspendSet(tc, by)
	case verbNewset:
		prop := cm.mustFolderProposal(p.target)
		if folderNameTaken(cm, prop.name) {
			panic("kourtv3: a folder by that name already exists")
		}
		if prop.parent != 0 {
			if pf := cm.mustFolder(prop.parent); pf.retired || pf.purged {
				panic("kourtv3: the parent heading is no longer in the tree")
			}
		}
		fid := newFolderCore(cm, prop.name, prop.desc, prop.parent)
		emitModAct(tc.id, 0, "folder-create", by)
		chain.Emit("FolderCreated",
			"court", tc.id, "by", "meta",
			"folder", strconv.FormatUint(fid, 10),
			"proposal", strconv.FormatUint(p.target, 10),
			"height", eventHeight(),
		)
	case verbSetmods:
		cand := cm.mustCandidate(p.target)
		installModSet(tc, cm, cand, heightNow(), false)
		chain.Emit("ModSetInstalled",
			"court", tc.id, "by", "meta",
			"candidate", strconv.FormatUint(cand.id, 10),
			"height", eventHeight(),
		)
	}
}
func AppealParse(claimID uint64) (verb, court string, target uint64, valid bool) {
	v := meta.parses.Get(beClaimKey(claimID))
	if v == nil {
		return "", "", 0, false
	}
	p := v.(*modParse)
	return p.verb, p.court, p.target, p.valid
}
func AppealExecuted(claimID uint64) bool { return meta.executed.Has(beClaimKey(claimID)) }
func AppealLatchHolder(verb, court string, target uint64) uint64 {
	p := modParse{verb: verb, court: court, target: target}
	if v := meta.latches.Get(latchKey(p)); v != nil {
		return v.(uint64)
	}
	return 0
}
var franchise = bptree.NewBPTree32()
func accrueFranchise(c *Court, who address, spent int64) {
	if c.id == metaSlug || spent <= 0 {
		return
	}
	k := who.String()
	prev := int64(0)
	if v := franchise.Get(k); v != nil {
		prev = v.(int64)
	}
	sum, ok := overflow.Add64(prev, spent)
	if !ok {
		return
	}
	franchise.Set(k, sum)
}
func ClaimMetaFranchise(cur realm) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	k := who.String()
	v := franchise.Get(k)
	if v == nil {
		return 0
	}
	owed := v.(int64)
	if owed <= 0 {
		return 0
	}
	mc := mustCourt(metaSlug)
	touch(mc)
	delta, used := mc.crv.Minted(mc.minted, owed)
	if delta <= 0 {
		return 0
	}
	mc.minted += delta
	recordPrice(mc)
	mc.coin.Mint(who, delta)
	if used >= owed {
		franchise.Remove(k)
	} else {
		franchise.Set(k, owed-used)
	}
	chain.Emit("FranchiseClaimed",
		"who", who.String(),
		"burned", strconv.FormatInt(used, 10),
		"minted", strconv.FormatInt(delta, 10),
	)
	return delta
}
func FranchiseOf(who address) int64 {
	if v := franchise.Get(who.String()); v != nil {
		return v.(int64)
	}
	return 0
}

moderation.gno

package kourtv3
import (
	"chain"
	"strconv"
	"strings"
	bptree "gno.land/p/nt/bptree/v0"
)
const (
	maxReasonLen = 200
	maxModSetSize = 32
	reSetWindowBlocks = int64(241_920)
	modActEvent    = "ModAct"
	globalActEvent = "GlobalAct"
	purgeEvent     = "Purge"
)
type daoState struct {
	admin   address
	members *bptree.BPTree
	n       int
	purgeM  int
	pending *bptree.BPTree
}
var globalDAO *daoState
const (
	daoBootstrapN = 1
	daoBootstrapM = 1
)
func ensureGlobalDAO() *daoState {
	if globalDAO != nil {
		return globalDAO
	}
	if directoryAdmin == "" {
		panic("kourtv3: no court exists yet; the global DAO has no admin")
	}
	d := &daoState{
		admin:   directoryAdmin,
		members: bptree.NewBPTree32(),
		n:       daoBootstrapN,
		purgeM:  daoBootstrapM,
		pending: bptree.NewBPTree32(),
	}
	d.members.Set(directoryAdmin.String(), true)
	globalDAO = d
	return d
}
func isGlobalMod(who address) bool {
	d := ensureGlobalDAO()
	return d.members.Has(who.String())
}
func AddGlobalMod(cur realm, who address) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin manages membership")
	}
	seatGlobalMember(d, who)
}
func seatGlobalMember(d *daoState, who address) {
	if !who.IsValid() {
		panic("kourtv3: not a valid address")
	}
	if d.members.Has(who.String()) {
		return
	}
	d.members.Set(who.String(), true)
	d.n++
	clearPendingOnMembershipChange(&d.pending)
}
func RemoveGlobalMod(cur realm, who address) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin manages membership")
	}
	if who == d.admin {
		panic("kourtv3: the admin cannot be removed; transfer admin first")
	}
	if d.members.Has(who.String()) {
		d.members.Remove(who.String())
		d.n--
		if d.purgeM > d.n {
			d.purgeM = d.n
		}
		clearPendingOnMembershipChange(&d.pending)
	}
}
func SetPurgeThreshold(cur realm, m int) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin sets the purge threshold")
	}
	if m < 1 || m > d.n {
		panic("kourtv3: the purge threshold must be in 1..n")
	}
	if m != d.purgeM {
		clearPendingOnMembershipChange(&d.pending)
	}
	d.purgeM = m
}
func TransferGlobalAdmin(cur realm, to address) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin transfers the seat")
	}
	seatGlobalMember(d, to)
	d.admin = to
}
type courtMod struct {
	members *bptree.BPTree
	n       int
	m       int
	suspended   bool
	suspendedAt int64
	suspendActByGlobal int64
	suspendedSetID     string
	suspendedM         int
	setActHeight       int64
	lastElectionAt     int64
	installedByMeta bool
	courtPurged    bool
	courtTombstone string
	claims  *bptree.BPTree
	pending *bptree.BPTree
	boardSanctionEpoch int64
	log    []modAct
	logSeq uint64
	folders   *bptree.BPTree
	folderSeq uint64
	folderProps   *bptree.BPTree
	folderPropSeq uint64
	candidates            *bptree.BPTree
	candSeq               uint64
	election              *election
	electionSeq           uint64
	electionCooldownUntil     int64
	electionCooldownUntilTime int64
	creatorUnseated       bool
}
type claimMod struct {
	court  bool
	meta   bool
	global bool
	purged    bool
	tombstone string
	boardFrozenUntil     int64
	boardFrozenUntilTime int64
	boardFrozenEpoch     int64
	boardFrozenGapUntil     int64
	boardFrozenGapUntilTime int64
	boardPurgeAll bool
	globalClearedAt     int64
	globalClearedAtTime int64
	executedAt      int64
	executedAtTime  int64
	logSeq uint64
	log    []modAct
}
type modAct struct {
	rowID  uint64
	actor  address
	code   string
	reason string
	height int64
	purged bool
}
func reSetWindowOpen(clearedAtTime, clearedAt, now int64) bool {
	passed, known := pastDeadline(clearedAtTime, blocksToSecs(reSetWindowBlocks))
	return (known && !passed) || (!known && now < clearedAt+reSetWindowBlocks)
}
const pendingTTLBlocks = decideWindowBlocks
type approval struct {
	approvers    *bptree.BPTree
	reason       string
	openedAt     int64
	openedAtTime int64
}
func approvalStale(a *approval) bool {
	passed, known := pastDeadline(a.openedAtTime, blocksToSecs(pendingTTLBlocks))
	return (known && passed) || (!known && heightNow() >= a.openedAt+pendingTTLBlocks)
}
func ensureMod(c *Court) *courtMod {
	if c.mod != nil {
		return c.mod
	}
	cm := &courtMod{
		members: bptree.NewBPTree32(),
		n:       1,
		m:       1,
		claims:  bptree.NewBPTree32(),
		pending: bptree.NewBPTree32(),
		folders: bptree.NewBPTree32(),
	}
	cm.members.Set(c.admin.String(), true)
	c.mod = cm
	return cm
}
func AppointMods(cur realm, courtSlug string, m int, mods ...address) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	if cur.Previous().Address() != c.admin {
		panic("kourtv3: only the court creator appoints moderators (until an election)")
	}
	if c.mod != nil && c.mod.creatorUnseated {
		panic("kourtv3: an election has installed a set; the creator's appointment power is spent")
	}
	if c.mod != nil && c.mod.suspended {
		panic("kourtv3: this moderator set is suspended; only an election or a meta verdict may reinstate it")
	}
	canon := canonicalMembers(mods)
	if len(canon) == 0 {
		panic("kourtv3: a moderator set may not be empty")
	}
	if m < 1 || m > len(canon) {
		panic("kourtv3: the m-of-n threshold must be in 1..n")
	}
	cm := ensureMod(c)
	fresh := bptree.NewBPTree32()
	n := 0
	for _, a := range canon {
		fresh.Set(a.String(), true)
		n++
	}
	cm.members = fresh
	cm.n = n
	cm.m = m
	cm.setActHeight = heightNow()
	cm.installedByMeta = false
	clearPendingOnMembershipChange(&cm.pending)
}
func requireMod(cm *courtMod, who address) {
	if !cm.members.Has(who.String()) {
		panic("kourtv3: not a moderator of this court")
	}
}
func clearPendingOnMembershipChange(pending **bptree.BPTree) {
	*pending = bptree.NewBPTree32()
}
func requireActiveMod(cm *courtMod, who address) {
	requireMod(cm, who)
	if cm.suspended {
		panic("kourtv3: this moderator set is suspended; only clearing its own bits is allowed")
	}
}
func isActiveMod(cm *courtMod, who address) bool {
	return !cm.suspended && cm.members.Has(who.String())
}
func requireEdgeRemover(c *Court, author, who address) {
	if author == who {
		return
	}
	cm := ensureMod(c)
	if !cm.members.Has(who.String()) {
		panic("kourtv3: only the edge's author or a court moderator may remove it")
	}
	requireActiveMod(cm, who)
}
func mustCategoryCode(code string) {
	if len(code) == 0 || runeLen(code) > maxReasonLen {
		panic("kourtv3: purge needs a statutory category code")
	}
}
func checkReason(reason string) {
	if runeLen(reason) > maxReasonLen {
		panic("kourtv3: a moderation reason is at most 200 characters")
	}
}
func ensureClaimMod(c *Court, cm *courtMod, claimID uint64) *claimMod {
	_ = mustClaim(c, claimID)
	k := beClaimKey(claimID)
	if v := cm.claims.Get(k); v != nil {
		return v.(*claimMod)
	}
	clm := &claimMod{}
	cm.claims.Set(k, clm)
	return clm
}
func lookupClaimMod(cm *courtMod, claimID uint64) *claimMod {
	if v := cm.claims.Get(beClaimKey(claimID)); v != nil {
		return v.(*claimMod)
	}
	return nil
}
func (clm *claimMod) appendLog(actor address, code, reason string) uint64 {
	clm.logSeq++
	clm.log = append(clm.log, modAct{
		rowID:  clm.logSeq,
		actor:  actor,
		code:   code,
		reason: reason,
		height: heightNow(),
	})
	return clm.logSeq
}
func (cm *courtMod) appendCourtLog(actor address, code, reason string) uint64 {
	cm.logSeq++
	cm.log = append(cm.log, modAct{
		rowID:  cm.logSeq,
		actor:  actor,
		code:   code,
		reason: reason,
		height: heightNow(),
	})
	return cm.logSeq
}
func approveAction(pending *bptree.BPTree, key string, who address, reason string, m int) (bool, string) {
	now := heightNow()
	var a *approval
	if v := pending.Get(key); v != nil {
		a = v.(*approval)
		if approvalStale(a) {
			a = nil
		}
	}
	if a == nil {
		a = &approval{approvers: bptree.NewBPTree32(), reason: reason,
			openedAt: now, openedAtTime: nowTime()}
	}
	if a.approvers.Has(who.String()) {
		return false, ""
	}
	a.approvers.Set(who.String(), true)
	if a.approvers.Size() >= m {
		pending.Remove(key)
		return true, a.reason
	}
	pending.Set(key, a)
	return false, ""
}
func pendingOpenedAt(pending *bptree.BPTree, key string) int64 {
	v := pending.Get(key)
	if v == nil {
		return 0
	}
	a := v.(*approval)
	if approvalStale(a) {
		return 0
	}
	return a.openedAt
}
func HideItem(cur realm, courtSlug string, claimID uint64, reason string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireActiveMod(cm, who)
	checkReason(reason)
	_ = mustClaim(c, claimID)
	if clm := lookupClaimMod(cm, claimID); clm != nil && clm.executedAt != 0 {
		if passed, known := pastDeadline(clm.executedAtTime, blocksToSecs(c.params.votingBlocks)); (known && !passed) ||
			(!known && heightNow() < clm.executedAt+c.params.votingBlocks) {
			panic("kourtv3: a review verdict just cleared this; the set may not re-hide yet")
		}
	}
	fire, r := approveAction(cm.pending, "hide:"+strconv.FormatUint(claimID, 10), who, reason, cm.m)
	if !fire {
		return
	}
	clm := ensureClaimMod(c, cm, claimID)
	clm.court = true
	clm.appendLog(who, "hide", r)
	emitModAct(c.id, claimID, "hide", who)
}
func UnhideItem(cur realm, courtSlug string, claimID uint64, reason string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireMod(cm, who)
	checkReason(reason)
	clm := lookupClaimMod(cm, claimID)
	if clm == nil || !clm.court {
		panic("kourtv3: this court is not hiding that claim")
	}
	fire, r := approveAction(cm.pending, "unhide:"+strconv.FormatUint(claimID, 10), who, reason, cm.m)
	if !fire {
		return
	}
	clm.court = false
	clm.appendLog(who, "unhide", r)
	emitModAct(c.id, claimID, "unhide", who)
}
func GlobalHide(cur realm, courtSlug string, claimID uint64, categoryCode string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	if !isGlobalMod(who) {
		panic("kourtv3: only a global DAO member may global-hide")
	}
	checkReason(categoryCode)
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	_ = mustClaim(c, claimID)
	now := heightNow()
	if prev := lookupClaimMod(cm, claimID); prev != nil && !prev.global &&
		prev.globalClearedAt != 0 && reSetWindowOpen(prev.globalClearedAtTime, prev.globalClearedAt, now) {
		d := ensureGlobalDAO()
		fire, _ := approveAction(d.pending, "reset:"+c.id+":"+strconv.FormatUint(claimID, 10), who, categoryCode, d.purgeM)
		if !fire {
			return
		}
	}
	clm := ensureClaimMod(c, cm, claimID)
	clm.global = true
	clm.appendLog(who, "global-hide:"+categoryCode, "")
	emitGlobalAct(c.id, claimID, "global-hide", who)
}
func GlobalClear(cur realm, courtSlug string, claimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	if !isGlobalMod(who) {
		panic("kourtv3: only a global DAO member may clear a global hide")
	}
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	clm := lookupClaimMod(cm, claimID)
	if clm == nil || !clm.global {
		panic("kourtv3: no global hide on that claim")
	}
	clm.global = false
	clm.globalClearedAt = heightNow()
	clm.globalClearedAtTime = nowTime()
	clm.appendLog(who, "global-clear", "")
	emitGlobalAct(c.id, claimID, "global-clear", who)
}
func ClearAnyBit(cur realm, courtSlug string, claimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	if !isGlobalMod(who) {
		panic("kourtv3: only a global DAO member may clear bits (recovery)")
	}
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	clm := lookupClaimMod(cm, claimID)
	if clm == nil {
		panic("kourtv3: nothing to clear on that claim")
	}
	clm.court = false
	clm.meta = false
	clm.appendLog(who, "clear-any", "")
	emitGlobalAct(c.id, claimID, "clear-any", who)
}
func ClearCourtSuspension(cur realm, courtSlug string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	if !isGlobalMod(who) {
		panic("kourtv3: only a global DAO member may clear a suspension (recovery)")
	}
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	if !cm.suspended {
		panic("kourtv3: that court's set is not suspended")
	}
	cm.suspended = false
	cm.suspendActByGlobal = heightNow()
	emitGlobalAct(c.id, 0, "clear-suspension", who)
}
func PurgeClaim(cur realm, courtSlug string, claimID uint64, categoryCode string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if !d.members.Has(who.String()) {
		panic("kourtv3: only a global DAO member may purge")
	}
	mustCategoryCode(categoryCode)
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	_ = mustClaim(c, claimID)
	fire, code := approveAction(d.pending, "purge:"+c.id+":"+strconv.FormatUint(claimID, 10), who, categoryCode, d.purgeM)
	if !fire {
		return
	}
	clm := ensureClaimMod(c, cm, claimID)
	clm.purged = true
	clm.tombstone = code
	if c.id == metaSlug {
		poisonMetaParse(claimID)
	}
	clm.appendLog(who, "purge:"+code, "")
	emitPurge(c.id, claimID, code, who)
}
func GlobalSuspendSet(cur realm, courtSlug string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if !d.members.Has(who.String()) {
		panic("kourtv3: only a global DAO member may suspend a moderator set")
	}
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	if cm.suspended {
		panic("kourtv3: that set is already suspended")
	}
	fire, _ := approveAction(d.pending, "gsuspend:"+c.id, who, "", d.purgeM)
	if !fire {
		return
	}
	suspendSet(c, who)
	cm.suspendActByGlobal = heightNow()
	emitGlobalAct(c.id, 0, "global-suspend-set", who)
}
func ResetModSet(cur realm, courtSlug string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if !d.members.Has(who.String()) {
		panic("kourtv3: only a global DAO member may reset a moderator set")
	}
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	fire, _ := approveAction(d.pending, "resetmods:"+c.id, who, "", d.purgeM)
	if !fire {
		return
	}
	cm.members = bptree.NewBPTree32()
	cm.n = 0
	cm.m = 1
	clearPendingOnMembershipChange(&cm.pending)
	cm.suspended = false
	cm.boardSanctionEpoch++
	cm.setActHeight = heightNow()
	emitGlobalAct(c.id, 0, "reset-mod-set", who)
}
func PurgeCourt(cur realm, courtSlug string, categoryCode string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if !d.members.Has(who.String()) {
		panic("kourtv3: only a global DAO member may purge")
	}
	mustCategoryCode(categoryCode)
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	fire, code := approveAction(d.pending, "purgecourt:"+c.id, who, categoryCode, d.purgeM)
	if !fire {
		return
	}
	cm.courtPurged = true
	cm.courtTombstone = code
	emitPurge(c.id, 0, code, who)
}
func courtIsPurged(c *Court) bool {
	return c.mod != nil && c.mod.courtPurged
}
func CourtPurged(courtSlug string) bool {
	return courtIsPurged(mustCourt(courtSlug))
}
func setMetaBit(c *Court, claimID uint64, by address) {
	cm := ensureMod(c)
	clm := ensureClaimMod(c, cm, claimID)
	clm.meta = true
	clm.executedAt = heightNow()
	clm.executedAtTime = nowTime()
	clm.appendLog(by, "meta-hide", "")
	emitModAct(c.id, claimID, "meta-hide", by)
}
func clearMetaBit(c *Court, claimID uint64, by address) {
	cm := ensureMod(c)
	clm := lookupClaimMod(cm, claimID)
	if clm == nil || !clm.meta {
		return
	}
	clm.meta = false
	clm.appendLog(by, "meta-clear", "")
	emitModAct(c.id, claimID, "meta-clear", by)
}
func clearCourtBitByMeta(c *Court, claimID uint64, by address) {
	cm := ensureMod(c)
	clm := lookupClaimMod(cm, claimID)
	if clm == nil || !clm.court {
		return
	}
	clm.court = false
	clm.executedAt = heightNow()
	clm.executedAtTime = nowTime()
	clm.appendLog(by, "meta-unhide", "")
	emitModAct(c.id, claimID, "meta-unhide", by)
}
func suspendSet(c *Court, by address) {
	cm := ensureMod(c)
	cm.suspended = true
	cm.suspendedAt = heightNow()
	cm.suspendedSetID = currentSetID(cm)
	cm.suspendedM = cm.m
	emitModAct(c.id, 0, "suspend", by)
}
func currentSetID(cm *courtMod) string {
	var b strings.Builder
	cm.members.Iterate("", "", func(k string, _ any) bool {
		b.WriteString(k)
		b.WriteByte(',')
		return false
	})
	return b.String()
}
func unsuspendSet(c *Court, by address) {
	cm := ensureMod(c)
	cm.suspended = false
	emitModAct(c.id, 0, "unsuspend", by)
}
func HiddenFromListing(courtSlug string, claimID uint64) bool {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return false
	}
	clm := lookupClaimMod(c.mod, claimID)
	if clm == nil {
		return false
	}
	return clm.court || clm.meta || clm.global
}
func TextRedacted(courtSlug string, claimID uint64) bool {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return false
	}
	clm := lookupClaimMod(c.mod, claimID)
	if clm == nil {
		return false
	}
	return clm.global || clm.purged
}
func ClaimPurged(courtSlug string, claimID uint64) bool {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return false
	}
	clm := lookupClaimMod(c.mod, claimID)
	return clm != nil && clm.purged
}
func PurgeModLogRow(cur realm, courtSlug string, claimID, rowID uint64, categoryCode string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	d := ensureGlobalDAO()
	if !d.members.Has(who.String()) {
		panic("kourtv3: only a global DAO member may purge")
	}
	mustCategoryCode(categoryCode)
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	clm := lookupClaimMod(cm, claimID)
	if clm == nil {
		panic("kourtv3: that claim has no moderation log")
	}
	idx := -1
	for i := range clm.log {
		if clm.log[i].rowID == rowID {
			idx = i
			break
		}
	}
	if idx < 0 {
		panic("kourtv3: no such moderation-log row")
	}
	if clm.log[idx].purged {
		return
	}
	key := "purgerow:" + c.id + ":" + strconv.FormatUint(claimID, 10) + ":" +
		strconv.FormatUint(rowID, 10)
	fire, code := approveAction(d.pending, key, who, categoryCode, d.purgeM)
	if !fire {
		return
	}
	clm.log[idx].purged = true
	clm.log[idx].reason = ""
	clm.appendLog(who, "purgerow:"+code, "")
	emitPurge(c.id, claimID, code, who)
}
func PendingApproval(courtSlug, actionKey string) (approvals int, expiresAt, expiresAtHeight int64) {
	var pending *bptree.BPTree
	if courtSlug == "" {
		if globalDAO == nil {
			return 0, 0, 0
		}
		pending = globalDAO.pending
	} else {
		c := mustCourt(courtSlug)
		if c.mod == nil {
			return 0, 0, 0
		}
		pending = c.mod.pending
	}
	v := pending.Get(actionKey)
	if v == nil {
		return 0, 0, 0
	}
	a := v.(*approval)
	if approvalStale(a) {
		return 0, 0, 0
	}
	return a.approvers.Size(),
		deadlineTime(a.openedAtTime, blocksToSecs(pendingTTLBlocks)),
		a.openedAt + pendingTTLBlocks
}
func CourtSuspended(courtSlug string) bool {
	c := mustCourt(courtSlug)
	return c.mod != nil && c.mod.suspended
}
func IsCourtMod(courtSlug string, who address) bool {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return who == c.admin
	}
	return c.mod.members.Has(who.String())
}
func ModThreshold(courtSlug string) (m, n int) {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return 1, 1
	}
	return c.mod.m, c.mod.n
}
func GlobalModCount() int {
	if globalDAO == nil {
		return 0
	}
	return globalDAO.n
}
func ModLogLen(courtSlug string, claimID uint64) int {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return 0
	}
	clm := lookupClaimMod(c.mod, claimID)
	if clm == nil {
		return 0
	}
	return len(clm.log)
}
func emitModAct(slug string, claimID uint64, code string, actor address) {
	chain.Emit(modActEvent,
		"court", slug,
		"claim", strconv.FormatUint(claimID, 10),
		"act", code,
		"by", actor.String(),
		"height", eventHeight(),
	)
}
func emitGlobalAct(slug string, claimID uint64, code string, actor address) {
	chain.Emit(globalActEvent,
		"court", slug,
		"claim", strconv.FormatUint(claimID, 10),
		"act", code,
		"by", actor.String(),
		"height", eventHeight(),
	)
}
func emitPurge(slug string, claimID uint64, categoryCode string, actor address) {
	chain.Emit(purgeEvent,
		"court", slug,
		"claim", strconv.FormatUint(claimID, 10),
		"code", categoryCode,
		"by", actor.String(),
		"height", eventHeight(),
	)
}

modrender.gno

package kourtv3
import (
	"math/overflow"
	"strconv"
	"strings"
	bptree "gno.land/p/nt/bptree/v0"
	sanitize "gno.land/p/nt/markdown/sanitize/v0"
)
var (
	burnIdx    = bptree.NewBPTree32()
	createdIdx = bptree.NewBPTree32()
	courtSeq   uint64
)
func beInv(v int64) string {
	if v < 0 {
		v = 0
	}
	return beClaimKey(^uint64(v))
}
func reindexBurn(c *Court, spent int64) {
	sum, ok := overflow.Add64(c.burnedGNOT, spent)
	if !ok {
		return
	}
	if c.burnedGNOT > 0 || c.burnKey != "" {
		burnIdx.Remove(c.burnKey)
	}
	c.burnedGNOT = sum
	c.burnKey = beInv(c.burnedGNOT) + c.id
	burnIdx.Set(c.burnKey, c.id)
	recordBurn(c)
}
func indexNewCourt(c *Court) {
	courtSeq++
	c.createdSeq = courtSeq
	createdIdx.Set(beClaimKey(c.createdSeq), c.id)
	c.burnKey = beInv(0) + c.id
	burnIdx.Set(c.burnKey, c.id)
}
func listedPage(order string, offset, limit int) []string {
	out := []string{}
	if limit <= 0 {
		return out
	}
	skipped := 0
	take := func(_ string, v any) bool {
		slug, ok := v.(string)
		if !ok || !Exists(slug) {
			return false
		}
		c := mustCourt(slug)
		if c.tier == tierHidden {
			return false
		}
		if skipped < offset {
			skipped++
			return false
		}
		out = append(out, slug)
		return len(out) >= limit
	}
	if order == "new" {
		createdIdx.ReverseIterate("", "", take)
	} else {
		burnIdx.Iterate("", "", take)
	}
	return out
}
func ListedCourtsBy(order string, offset, limit int) []string {
	return listedPage(order, offset, limit)
}
func CourtBurnedGNOT(courtSlug string) int64 { return mustCourt(courtSlug).burnedGNOT }
func claimTitleFor(c *Court, cs *claimState) string {
	if c.mod != nil {
		if clm := lookupClaimMod(c.mod, cs.id); clm != nil {
			if clm.purged {
				return "[removed · " + sanitize.InlineText(clm.tombstone) + "]"
			}
			if clm.global {
				return "[text withheld]"
			}
		}
	}
	return sanitize.InlineText(cs.title)
}
func claimBodyVisible(c *Court, cs *claimState) string {
	if cs.body == "" {
		return ""
	}
	if c.mod != nil {
		if clm := lookupClaimMod(c.mod, cs.id); clm != nil {
			if clm.purged || clm.global {
				return ""
			}
		}
	}
	return cs.body
}
func claimMediaVisible(c *Court, cs *claimState) []mediaItem {
	if len(cs.media) == 0 {
		return nil
	}
	if c.mod != nil {
		if clm := lookupClaimMod(c.mod, cs.id); clm != nil {
			if clm.purged || clm.global {
				return nil
			}
		}
	}
	return cs.media
}
func claimBodyFor(c *Court, cs *claimState) string {
	body := claimBodyVisible(c, cs)
	if body == "" {
		return ""
	}
	return sanitize.Block(body)
}
func claimBodyQuoted(c *Court, cs *claimState) string {
	body := claimBodyVisible(c, cs)
	if body == "" {
		return ""
	}
	return sanitize.Blockquote(body)
}
const (
	platformName   = "Kourt"
	platformTicker = "KOURT"
)
func qualifiedSymbol(c *Court) string {
	return platformTicker + ":" + sanitize.InlineText(c.coin.Symbol())
}
func courtNameFor(c *Court) string {
	if c.mod != nil && c.mod.courtPurged {
		return "[removed · " + sanitize.InlineText(c.mod.courtTombstone) + "]"
	}
	return sanitize.InlineText(c.name)
}
func courtDescFor(c *Court) string {
	if c.desc == "" {
		return ""
	}
	if c.mod != nil && c.mod.courtPurged {
		return ""
	}
	return sanitize.InlineText(c.desc)
}
func hideBanner(c *Court, cs *claimState) string {
	if c.mod == nil {
		return ""
	}
	clm := lookupClaimMod(c.mod, cs.id)
	if clm == nil {
		return ""
	}
	switch {
	case clm.purged:
		return "> **Removed on legal grounds** (" + sanitize.InlineText(clm.tombstone) +
			"). The claim's lifecycle is unaffected: stakes, verdict and refunds proceed.\n\n"
	case clm.global:
		return "> **Text withheld pending review.** The claim's id, its state, its deadlines and every balance are still shown, so you can always act on a position.\n\n"
	case clm.meta:
		return "> **Hidden by the review court.** Listed nowhere, reachable here; the lifecycle is unaffected.\n\n"
	case clm.court:
		return "> **Hidden by this court's moderators.** Listed nowhere, reachable here; the lifecycle is unaffected.\n\n"
	}
	return ""
}
const (
	stripHeading = "Still flaggable"
	stripBlurb   = "Answered claims that can still be flagged as spam — nearest deadline first. A claim leaves this list when its rewards are opened, not when it settles, so a settled claim stays here while it can still be flagged. This list ignores moderation: a claim hidden from the lists above still appears here."
)
func writeStrip(b *strings.Builder, slug string) {
	c := mustCourt(slug)
	n := StripSize(slug)
	if n == 0 {
		return
	}
	b.WriteString("## " + stripHeading + "\n\n" + stripBlurb + "\n\n")
	ids := StripPage(slug, 0, renderPageSize)
	for _, id := range ids {
		cs := mustClaim(c, id)
		b.WriteString("- [" + claimTitleFor(c, cs) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/" +
			strconv.FormatUint(id, 10) + ") — settles at block " +
			strconv.FormatInt(cs.answerHeight+settleDelay, 10) + "\n")
	}
	if n > len(ids) {
		b.WriteString("- _…and " + strconv.Itoa(n-len(ids)) + " more_\n")
	}
	b.WriteString("\n")
}
func writePending(b *strings.Builder, slug string) {
	c := mustCourt(slug)
	n := PendingSize(slug)
	if n == 0 {
		return
	}
	b.WriteString("## Awaiting an answer\n\nSeeded and appeal claims that no one has answered yet.\n\n")
	ids := PendingPage(slug, 0, renderPageSize)
	for _, id := range ids {
		cs := mustClaim(c, id)
		tag := ""
		if cs.seeded {
			tag = " — seeded by a moderator"
		}
		b.WriteString("- [" + claimTitleFor(c, cs) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/" +
			strconv.FormatUint(id, 10) + ")" + tag + "\n")
	}
	if n > len(ids) {
		b.WriteString("- _…and " + strconv.Itoa(n-len(ids)) + " more_\n")
	}
	b.WriteString("\n")
}
func writeAppeal(b *strings.Builder, c *Court, cs *claimState) {
	if c.id != metaSlug {
		return
	}
	verb, court, target, valid := AppealParse(cs.id)
	if !valid {
		b.WriteString("> _Not a valid review request — this is an ordinary claim on the review court._\n\n")
		return
	}
	b.WriteString("## Review request\n\n")
	b.WriteString("- action: **" + sanitize.InlineText(verb) + "** — " +
		appealVerbGloss(verb) + "\n")
	b.WriteString("- court: " + sanitize.InlineText(court) + "\n")
	if verbIsAggressive(verb) {
		b.WriteString("- this is an **aggressive** act: it can only carry on a " +
			"contested vote that real opposition turned out for. Silence " +
			"defeats it.\n")
	} else {
		b.WriteString("- this is a **restorative** act: it undoes a restriction, so " +
			"it can carry undisputed. Silence lets it through.\n")
	}
	if verb == verbSetmods {
		b.WriteString("- installs candidate set #" + strconv.FormatUint(target, 10) + ":\n")
		if !Exists(court) {
			b.WriteString("  - _that court does not exist_\n\n")
			return
		}
		tc := mustCourt(court)
		if tc.mod == nil || tc.mod.candidates == nil ||
			tc.mod.candidates.Get(beClaimKey(target)) == nil {
			b.WriteString("  - **this candidate set does not exist yet — do not approve**\n\n")
			return
		}
		cand := tc.mod.candidates.Get(beClaimKey(target)).(*modCandidate)
		for _, a := range cand.members {
			b.WriteString("  - " + sanitize.InlineText(a.String()) + "\n")
		}
		b.WriteString("  - threshold: " + strconv.Itoa(cand.m) + " of " +
			strconv.Itoa(len(cand.members)) + " must agree\n")
	} else if target != 0 {
		b.WriteString("- claim: " + strconv.FormatUint(target, 10) + "\n")
	}
	b.WriteString("\n")
}
func modActLine(a modAct, kind string) string {
	line := "- " + kind + " " + strconv.FormatUint(a.rowID, 10) +
		" · block " + strconv.FormatInt(a.height, 10) + " · " +
		sanitize.InlineText(a.code) + " · by " + sanitize.InlineText(a.actor.String())
	switch {
	case a.purged:
		line += " — _[reason removed on legal grounds]_"
	case a.reason != "":
		line += " — " + sanitize.InlineText(a.reason)
	}
	return line
}
func renderModLog(slug string) string {
	if !Exists(slug) {
		return "## Not found\nNo court by that slug."
	}
	c := mustCourt(slug)
	b := strings.Builder{}
	b.WriteString("# Moderation log — " + courtNameFor(c) + "\n\n")
	b.WriteString("Every moderation act on this court's CLAIMS and COMMENTS is recorded here: who acted, what they did, and when. Moderation controls what is listed; it never moves a coin or changes a verdict.\n\n")
	b.WriteString("[Who holds these seats, and how to challenge them](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" +
		sanitize.InlineText(slug) + "/election)\n\n")
	b.WriteString("Curation — which claims a moderator filed under which heading — is " +
		"not in this list. The tree it produced is on the [court page](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + sanitize.InlineText(slug) + "); the acts themselves are in " +
		"the chain's event stream.\n\n")
	if c.mod == nil {
		b.WriteString("## Moderators\n\n1-of-1 — " + c.admin.String() +
			" (the court's creator, until an election or an appointment changes it)\n\n")
		b.WriteString("_No moderation acts yet._\n")
		return b.String()
	}
	cm := c.mod
	if cm.courtPurged {
		b.WriteString("> **This court was removed on legal grounds** (" +
			sanitize.InlineText(cm.courtTombstone) + "). No new claims may be opened; existing claims settle and pay out normally.\n\n")
	}
	b.WriteString("## Moderators\n\n")
	if cm.n == 0 {
		b.WriteString("_None — the set is empty; the court's holders can elect one._\n\n")
	} else {
		b.WriteString("- " + strconv.Itoa(cm.m) + " of " + strconv.Itoa(cm.n) +
			" must agree for a moderation act\n")
		if sm := speechM(cm); sm != cm.m {
			b.WriteString("- " + strconv.Itoa(sm) + " of " + strconv.Itoa(cm.n) +
				" for a **board** act — hiding a comment, slashing standing, " +
				"freezing an address — because speech takes a wider agreement " +
				"than the set's own threshold\n")
		}
		if cm.suspended {
			b.WriteString("- **suspended** — they cannot take new moderation acts. " +
				"The hides and freezes already in place stand until cleared, and " +
				"any member may still lift their own\n")
		}
		if cm.installedByMeta {
			b.WriteString("- seated by the review court; may not seed claims until a local election\n")
		}
		b.WriteString("\n")
	}
	pendingRows := []string{}
	pendingSeen := 0
	pendingMore := false
	cm.pending.Iterate("", "", func(key string, v any) bool {
		pendingSeen++
		if a, ok := v.(*approval); ok {
			deadline := a.openedAt + pendingTTLBlocks
			if !approvalStale(a) {
				when := " (block " + strconv.FormatInt(deadline, 10) + ")"
				if at := deadlineTime(a.openedAtTime, blocksToSecs(pendingTTLBlocks)); at != 0 {
					when = " " + strconv.FormatInt(at, 10) + when
				}
				pendingRows = append(pendingRows,
					"- "+sanitize.InlineCode(key)+" — "+strconv.Itoa(a.approvers.Size())+
						" of "+strconv.Itoa(cm.m)+" approved, expires at"+when)
			}
		}
		if len(pendingRows) >= renderPageSize || pendingSeen >= renderPageSize {
			pendingMore = true
			return true
		}
		return false
	})
	if len(pendingRows) > 0 {
		b.WriteString("## Awaiting approval\n\nProposals this set has started and not yet carried. An approval expires if the set does not reach its threshold in time; the reason is withheld until the act carries.\n\n")
		for _, r := range pendingRows {
			b.WriteString(r + "\n")
		}
		if pendingMore {
			b.WriteString("- _…more not shown_\n")
		}
		b.WriteString("\n")
	}
	rows := []string{}
	visited := 0
	truncated := false
	for i := len(cm.log) - 1; i >= 0 && len(rows) < renderPageSize; i-- {
		rows = append(rows, modActLine(cm.log[i], "court row"))
	}
	if len(rows) >= renderPageSize {
		truncated = true
	}
	cm.claims.ReverseIterate("", "", func(_ string, v any) bool {
		if len(rows) >= renderPageSize {
			truncated = true
			return true
		}
		clm, ok := v.(*claimMod)
		if !ok {
			return false
		}
		visited++
		for i := len(clm.log) - 1; i >= 0; i-- {
			rows = append(rows, modActLine(clm.log[i], "row"))
			if len(rows) >= renderPageSize {
				truncated = true
				return true
			}
		}
		if visited >= renderPageSize {
			truncated = true
			return true
		}
		return false
	})
	b.WriteString("## Acts\n\n")
	if len(rows) == 0 {
		b.WriteString("_No moderation acts yet._\n")
		return b.String()
	}
	for _, r := range rows {
		b.WriteString(r + "\n")
	}
	if truncated {
		b.WriteString("\n_Showing the " + strconv.Itoa(len(rows)) +
			" most recent acts. This court has moderated " + strconv.Itoa(cm.claims.Size()) +
			" claims; older acts are not shown._\n")
	}
	return b.String()
}
func appealVerbGloss(verb string) string {
	switch verb {
	case verbUnhide:
		return "un-hides a claim its own court's moderators hid"
	case verbClear:
		return "clears a hide the review court itself placed"
	case verbHide:
		return "hides a claim across the platform, over its court's head"
	case verbSuspend:
		return "disarms a court's moderator set — they can take no further act"
	case verbUnsuspend:
		return "re-arms a suspended moderator set, and re-applies the hides that " +
			"were masked while it was disarmed"
	case verbSetmods:
		return "installs a moderator set on that court, replacing whoever holds " +
			"the seats now"
	}
	return "an action this page does not recognise"
}

modvote.gno

package kourtv3
import (
	"chain"
	"strconv"
	grc20votes "gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/grc20votes/v0"
	bptree "gno.land/p/nt/bptree/v0"
)
const (
	nominationWindow = int64(17_280)
	maxBallotLines = 64
	electionBondBps = int64(50)
)
func mustElectionInvariants() {
	if electionBondBps <= 0 {
		panic("kourtv3: the election bond must be positive")
	}
	if electionBondBps >= quorumSupplyBps {
		panic("kourtv3: the election bond must stay below the quorum floor — else affording the ballot is harder than winning the vote (incumbency lock by price)")
	}
	if nominationWindow < 17_280 {
		panic("kourtv3: the nomination window must be at least a day")
	}
}
func init() { mustElectionInvariants() }
type modCandidate struct {
	id      uint64
	members []address
	m       int
	by      address
	at      int64
}
type ballotLine struct {
	candID uint64
	weight int64
	nomAt  int64
	bond   int64
	poster address
}
type election struct {
	seq         uint64
	epoch       uint32
	openedAt    int64
	nominateEnd int64
	voteEnd     int64
	nominateEndTime int64
	voteEndTime     int64
	floor       int64
	bond        int64
	lines       *bptree.BPTree
	retainW     int64
	nominators  *bptree.BPTree
	voters      *bptree.BPTree
	approvals   *bptree.BPTree
	turnout     int64
	resolved    bool
}
func electionFloor(c *Court, at uint32) int64 {
	f := mulDiv128(votableAt(c, at), quorumSupplyBps, grc20votes.Bps)
	if f < 1 {
		f = 1
	}
	return f
}
func votableAt(c *Court, at uint32) int64 {
	v := c.coin.PastTotal(at) - c.coin.PastVotes(c.escrow, at)
	if v < 0 {
		v = 0
	}
	return v
}
func electionBond(c *Court, at uint32) int64 {
	b := mulDiv128(votableAt(c, at), electionBondBps, grc20votes.Bps)
	if b < carrotClampMinCC {
		b = carrotClampMinCC
	}
	if f := electionFloor(c, at); b > f {
		b = f
	}
	return b
}
func RegisterModCandidate(cur realm, courtSlug string, m int, members ...address) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	canon := canonicalMembers(members)
	if len(canon) == 0 {
		panic("kourtv3: a candidate set may not be empty")
	}
	if m < 1 || m > len(canon) {
		panic("kourtv3: the m-of-n threshold must be in 1..n")
	}
	if cm.candidates == nil {
		cm.candidates = bptree.NewBPTree32()
	}
	cm.candSeq++
	id := cm.candSeq
	cm.candidates.Set(beClaimKey(id), &modCandidate{
		id: id, members: canon, m: m, by: who, at: heightNow(),
	})
	return id
}
func canonicalMembers(in []address) []address {
	if len(in) > maxModSetSize {
		panic("kourtv3: a moderator set is at most 32 members")
	}
	out := []address{}
	for _, a := range in {
		if a == "" {
			panic("kourtv3: a moderator address may not be zero")
		}
		if !a.IsValid() {
			panic("kourtv3: not a valid address for a moderator set")
		}
		dup := false
		for _, b := range out {
			if b == a {
				dup = true
				break
			}
		}
		if dup {
			continue
		}
		pos := len(out)
		out = append(out, a)
		for pos > 0 && out[pos-1].String() > a.String() {
			out[pos] = out[pos-1]
			pos--
		}
		out[pos] = a
	}
	return out
}
func (cm *courtMod) mustCandidate(id uint64) *modCandidate {
	if cm.candidates == nil {
		panic("kourtv3: no such candidate")
	}
	v := cm.candidates.Get(beClaimKey(id))
	if v == nil {
		panic("kourtv3: no such candidate")
	}
	return v.(*modCandidate)
}
func electionCooldownOpen(cm *courtMod) bool {
	passed, known := pastDeadline(cm.electionCooldownUntilTime, 0)
	return (known && !passed) || (!known && heightNow() < cm.electionCooldownUntil)
}
func nominationClosed(e *election) bool {
	passed, known := pastDeadline(e.nominateEndTime, 0)
	return (known && passed) || (!known && heightNow() >= e.nominateEnd)
}
func votingClosed(e *election) bool {
	passed, known := pastDeadline(e.voteEndTime, 0)
	return (known && passed) || (!known && heightNow() >= e.voteEnd)
}
func OpenElection(cur realm, courtSlug string, candidateID uint64) uint64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	if cm.election != nil && !cm.election.resolved {
		panic("kourtv3: an election is already open for this court")
	}
	now := heightNow()
	if electionCooldownOpen(cm) {
		panic("kourtv3: this court is in its post-election cooldown")
	}
	cand := cm.mustCandidate(candidateID)
	at := c.coin.Epoch() - 1
	cm.electionSeq++
	e := &election{
		seq:         cm.electionSeq,
		epoch:       at,
		openedAt:    now,
		nominateEnd: now + nominationWindow,
		voteEnd:     now + nominationWindow + c.params.votingBlocks,
		nominateEndTime: nowTime() + blocksToSecs(nominationWindow),
		voteEndTime:     nowTime() + blocksToSecs(nominationWindow+c.params.votingBlocks),
		floor:       electionFloor(c, at),
		bond:        electionBond(c, at),
		lines:       bptree.NewBPTree32(),
		nominators:  bptree.NewBPTree32(),
		voters:      bptree.NewBPTree32(),
		approvals:   bptree.NewBPTree32(),
	}
	cm.election = e
	addNomination(c, cm, e, cand, who)
	return e.seq
}
func NominateCandidate(cur realm, courtSlug string, candidateID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	e := cm.mustOpenElection()
	if nominationClosed(e) {
		panic("kourtv3: the nomination window has closed")
	}
	cand := cm.mustCandidate(candidateID)
	addNomination(c, cm, e, cand, who)
}
func addNomination(c *Court, cm *courtMod, e *election, cand *modCandidate, who address) {
	if e.lines.Size() >= maxBallotLines {
		panic("kourtv3: this ballot is full; open the next election instead")
	}
	if e.nominators.Has(who.String()) {
		panic("kourtv3: one nomination per address per election")
	}
	if e.lines.Has(beClaimKey(cand.id)) {
		panic("kourtv3: that candidate is already on the ballot")
	}
	mustSpendable(c, who, e.bond)
	c.coin.Transfer(who, c.escrow, e.bond)
	e.nominators.Set(who.String(), true)
	e.lines.Set(beClaimKey(cand.id), &ballotLine{
		candID: cand.id, nomAt: heightNow(), bond: e.bond, poster: who,
	})
}
func (cm *courtMod) mustOpenElection() *election {
	if cm.election == nil || cm.election.resolved {
		panic("kourtv3: no election is open")
	}
	return cm.election
}
func ApproveCandidate(cur realm, courtSlug string, candidateID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	approve(cur.Previous().Address(), courtSlug, candidateID, false)
}
func ApproveRetain(cur realm, courtSlug string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	approve(cur.Previous().Address(), courtSlug, 0, true)
}
func approve(who address, courtSlug string, candidateID uint64, retain bool) {
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	e := cm.mustOpenElection()
	if !nominationClosed(e) {
		panic("kourtv3: voting opens when the nomination window closes")
	}
	if votingClosed(e) {
		panic("kourtv3: voting has closed")
	}
	var w int64
	if prior := e.voters.Get(who.String()); prior != nil {
		w = prior.(int64)
	} else {
		var snapshot int64
		w, snapshot = votingWeight(c, who, e.epoch)
		if snapshot <= 0 {
			panic("kourtv3: no voting weight at the pinned epoch")
		}
		if w <= 0 {
			panic("kourtv3: you no longer hold the coin you would vote with")
		}
	}
	key := beClaimKey(candidateID) + who.String()
	if retain {
		key = "retain" + who.String()
	}
	if e.approvals.Has(key) {
		panic("kourtv3: already approved that line")
	}
	if !retain {
		v := e.lines.Get(beClaimKey(candidateID))
		if v == nil {
			panic("kourtv3: that candidate is not on the ballot")
		}
		line := v.(*ballotLine)
		line.weight += w
	} else {
		e.retainW += w
	}
	e.approvals.Set(key, true)
	if !e.voters.Has(who.String()) {
		e.voters.Set(who.String(), w)
		e.turnout += w
		lockVote(c, who, voteLockElection, int64(e.seq), 0, w)
	}
}
func ResolveElection(cur realm, courtSlug string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	e := cm.mustOpenElection()
	now := heightNow()
	if !votingClosed(e) {
		panic("kourtv3: the voting window has not closed")
	}
	e.resolved = true
	maxW := int64(0)
	e.lines.Iterate("", "", func(_ string, v any) bool {
		if l, ok := v.(*ballotLine); ok && l.weight > maxW {
			maxW = l.weight
		}
		return false
	})
	install := maxW > 0 && e.turnout >= e.floor && maxW-e.retainW >= e.floor
	var winner *ballotLine
	if install {
		e.lines.Iterate("", "", func(_ string, v any) bool {
			l, ok := v.(*ballotLine)
			if !ok || l.weight < maxW-e.floor || l.weight-e.retainW < e.floor {
				return false
			}
			if winner == nil || l.nomAt < winner.nomAt ||
				(l.nomAt == winner.nomAt && l.candID < winner.candID) {
				winner = l
			}
			return false
		})
	}
	e.lines.Iterate("", "", func(_ string, v any) bool {
		l, ok := v.(*ballotLine)
		if !ok || l.bond <= 0 {
			return false
		}
		if winner != nil && l.candID == winner.candID {
			c.coin.Transfer(c.escrow, l.poster, l.bond)
		} else {
			half := l.bond / 2
			if half > 0 {
				c.coin.Transfer(c.escrow, l.poster, half)
			}
			if burn := l.bond - half; burn > 0 {
				c.coin.Burn(c.escrow, burn)
			}
		}
		l.bond = 0
		return false
	})
	if winner != nil {
		cand := cm.mustCandidate(winner.candID)
		installModSet(c, cm, cand, now, true)
		chain.Emit("ModSetInstalled",
			"court", c.id, "by", "election",
			"candidate", strconv.FormatUint(cand.id, 10),
			"height", strconv.FormatInt(now, 10),
		)
		return
	}
	cm.electionCooldownUntil = now + decideWindowBlocks
	cm.electionCooldownUntilTime = nowTime() + blocksToSecs(decideWindowBlocks)
}
func installModSet(c *Court, cm *courtMod, cand *modCandidate, at int64, byElection bool) {
	fresh := bptree.NewBPTree32()
	for _, a := range cand.members {
		fresh.Set(a.String(), true)
	}
	cm.members = fresh
	cm.n = len(cand.members)
	cm.m = cand.m
	clearPendingOnMembershipChange(&cm.pending)
	cm.setActHeight = at
	cm.installedByMeta = !byElection
	if currentSetID(cm) != cm.suspendedSetID || cm.m > cm.suspendedM {
		cm.suspended = false
		cm.suspendedSetID = ""
		cm.suspendedM = 0
	}
	if byElection {
		cm.lastElectionAt = at
		cm.creatorUnseated = true
	}
}
func mustModRead(courtSlug string) *courtMod {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		panic("kourtv3: this court has no moderation state yet")
	}
	return c.mod
}
func ElectionOpen(courtSlug string) bool {
	c := mustCourt(courtSlug)
	return c.mod != nil && c.mod.election != nil && !c.mod.election.resolved
}
func ElectionWindows(courtSlug string) (int64, int64) {
	e := mustModRead(courtSlug).mustOpenElection()
	return e.nominateEnd, e.voteEnd
}
func ElectionFloorOf(courtSlug string) int64 {
	return mustModRead(courtSlug).mustOpenElection().floor
}
func ElectionBondOf(courtSlug string) int64 {
	return mustModRead(courtSlug).mustOpenElection().bond
}
func ElectionTally(courtSlug string, candidateID uint64) (candW, retainW, turnout int64) {
	e := mustModRead(courtSlug).mustOpenElection()
	if v := e.lines.Get(beClaimKey(candidateID)); v != nil {
		candW = v.(*ballotLine).weight
	}
	return candW, e.retainW, e.turnout
}
func CandidateMembers(courtSlug string, candidateID uint64) []address {
	cand := mustModRead(courtSlug).mustCandidate(candidateID)
	out := make([]address, len(cand.members))
	copy(out, cand.members)
	return out
}
func CandidateThreshold(courtSlug string, candidateID uint64) int {
	return mustModRead(courtSlug).mustCandidate(candidateID).m
}
func ElectionCooldownUntil(courtSlug string) int64 {
	c := mustCourt(courtSlug)
	if c.mod == nil {
		return 0
	}
	return c.mod.electionCooldownUntil
}

openrewards.gno

package kourtv3
import (
	"math/bits"
)
func OpenRewards(cur realm, courtSlug string, claimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if cs.rewardsOpened {
		panic("kourtv3: already rewardsOpened")
	}
	if cs.verdictAt == 0 {
		panic("kourtv3: no final verdict yet")
	}
	if cs.closed {
		panic("kourtv3: dead claims have no draw")
	}
	now := heightNow()
	if passed, known := pastDeadline(cs.verdictAtTime, finalizeGraceSecs); ((known && !passed) ||
		(!known && now < cs.verdictAt+finalizeGraceBlocks)) && !isParticipant(cs, who) {
		panic("kourtv3: OpenRewards is participant-only for its first week")
	}
	touch(c)
	advancePools(c, cs)
	cs.rewardsOpened = true
	stripExit(c, cs)
	releaseMetaLatchIfMeta(c, cs)
	cs.openBlocks = cs.frozenAt - (cs.openedAt + c.params.stakeOpenDelayBlocks)
	if cs.openBlocks < 1 {
		cs.openBlocks = 1
	}
	var midGross int64
	if int(cs.provisional) == sideYES {
		midGross = convToCC(cs.yesConvHi, cs.yesConvLo)
	} else {
		midGross = convToCC(cs.noConvHi, cs.noConvLo)
	}
	cs.winPoolConvCC = midGross
	want := drawWant(c, cs, midGross)
	d := reserveJunior(c, want)
	cs.drawWinners, cs.drawAuthor, cs.drawAnswerer = drawSplit(cs, d)
	cs.carrotTotal = mulDiv128(midGross, splitCarrot, 100)
	cs.carrotPool = cs.carrotTotal
	if cs.deposit > 0 {
		c.coin.Transfer(c.escrow, cs.author, cs.deposit)
		c.deposit -= cs.deposit
		cs.deposit = 0
	}
	if cs.fee > 0 {
		c.coin.Transfer(c.escrow, cs.author, cs.fee)
		c.deposit -= cs.fee
		cs.fee = 0
	}
	if cs.answerBond > 0 {
		settleAnswerBond(c, cs)
	}
}
func WithdrawBonus(cur realm, courtSlug string, claimID uint64, side int) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	mustSide(side)
	if !cs.rewardsOpened {
		panic("kourtv3: the draw has not rewardsOpened")
	}
	if side != int(cs.provisional) {
		panic("kourtv3: only the winning side draws (principal came back either way)")
	}
	v := cs.stakers.Get(posKey(who, side))
	if v == nil {
		panic("kourtv3: no position on that side")
	}
	p := v.(*stakePos)
	if p.bonusPaid {
		panic("kourtv3: this position's bonus was already drawn")
	}
	touch(c)
	accrue(c, cs, p, side)
	p.bonusPaid = true
	convCC := convToCC(p.convHi, p.convLo)
	creditWinConviction(c, cs, who, p)
	if convCC <= 0 || cs.winPoolConvCC <= 0 {
		return 0
	}
	gross := mulDiv128(cs.drawWinners, convCC, cs.winPoolConvCC)
	pay := capBonus(cs, gross, p.rawHi, p.rawLo)
	mintEmission(c, who, pay)
	return pay
}
func AuthorBonus(cur realm, courtSlug string, claimID uint64) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if !cs.rewardsOpened {
		panic("kourtv3: the draw has not rewardsOpened")
	}
	if who != cs.author {
		panic("kourtv3: only the author draws this slice")
	}
	if cs.authorPaid {
		panic("kourtv3: the author slice was already drawn")
	}
	touch(c)
	cs.authorPaid = true
	var pay int64
	if cs.seeded {
		mintEmission(c, who, 0)
		return 0
	}
	if v := cs.stakers.Get(posKey(who, int(cs.provisional))); v != nil {
		p := v.(*stakePos)
		accrue(c, cs, p, int(cs.provisional))
		pay = capBonus(cs, cs.drawAuthor, p.rawHi, p.rawLo)
	}
	mintEmission(c, who, pay)
	return pay
}
func AnswererBonus(cur realm, courtSlug string, claimID uint64) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if !cs.rewardsOpened {
		panic("kourtv3: the draw has not rewardsOpened")
	}
	if who != cs.answerer {
		panic("kourtv3: only the answerer draws this slice")
	}
	if cs.answererPaid {
		panic("kourtv3: the answerer slice was already drawn")
	}
	touch(c)
	cs.answererPaid = true
	pay := cs.drawAnswerer
	if bound := mulDiv128(cs.answerBond0, tierBpsFor(cs), 2*tierParBps); pay > bound {
		pay = bound
	}
	mintEmission(c, who, pay)
	return pay
}
func timeAvgStake(cs *claimState, rawHi, rawLo uint64) int64 {
	if cs.openBlocks <= 0 || rawHi >= uint64(cs.openBlocks) {
		return 0
	}
	return div128(rawHi, rawLo, cs.openBlocks)
}
func capBonus(cs *claimState, gross int64, rawHi, rawLo uint64) int64 {
	rawAvg := timeAvgStake(cs, rawHi, rawLo)
	bound := mulDiv128(rawAvg, tierBpsFor(cs), 2*tierParBps)
	if gross > bound {
		gross = bound
	}
	if gross < 0 {
		gross = 0
	}
	return gross
}
func PullCarrot(cur realm, courtSlug string, claimID uint64) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if !cs.rewardsOpened {
		panic("kourtv3: the draw has not rewardsOpened")
	}
	if isParticipant(cs, who) {
		panic("kourtv3: participants take their own slices, never the carrot")
	}
	if cs.voted == nil {
		panic("kourtv3: nobody voted on this claim")
	}
	if cs.decidedPID == 0 {
		panic("kourtv3: no vote resolved this claim; there is no carrot")
	}
	v := cs.voted.Get("d" + beClaimKey(uint64(cs.decidedPID)) + string(who))
	if v == nil || v.(string) != cs.carrotChoice {
		panic("kourtv3: the carrot pays with-verdict voters of the deciding round")
	}
	vw := cs.voted.Get("dw" + beClaimKey(uint64(cs.decidedPID)) + string(who))
	if vw == nil {
		panic("kourtv3: no recorded weight for that voter on the deciding round")
	}
	w, denom := vw.(int64), cs.carrotDenom
	claimedKey := "c" + beClaimKey(uint64(cs.decidedPID)) + string(who)
	if cs.voted.Has(claimedKey) {
		panic("kourtv3: carrot already claimed")
	}
	cs.voted.Set(claimedKey, true)
	if w <= 0 || denom <= 0 {
		return 0
	}
	touch(c)
	share := mulDiv128(cs.carrotTotal, w, denom)
	b0 := cs.xBarFrozen * carrotClampXBps / 10000
	if b0 < carrotClampMinCC {
		b0 = carrotClampMinCC
	}
	if clamp := b0/2 - 1; share > clamp {
		share = clamp
	}
	if share > cs.carrotPool {
		share = cs.carrotPool
	}
	if share <= 0 {
		return 0
	}
	cs.carrotPool -= share
	enqueueSenior(c, who, share, "carrot")
	return share
}
func div128(hi, lo uint64, den int64) int64 {
	if den <= 0 {
		panic("kourtv3: div128 domain")
	}
	if hi >= uint64(den) {
		panic("kourtv3: div128 quotient overflow")
	}
	q, _ := bits.Div64(hi, lo, uint64(den))
	return int64(q)
}
func RewardsOpened(courtSlug string, claimID uint64) bool {
	return mustClaim(mustCourt(courtSlug), claimID).rewardsOpened
}
func drawEntitlement(c *Court, cs *claimState, midGross int64) int64 {
	tierBps := tierBpsFor(cs)
	want := mulDiv128(midGross, tierBps, tierParBps)
	want = mulDiv128(want, spamNetBps(cs), tierParBps)
	if int(cs.provisional) == int(cs.answer) {
		if capd := cs.answerBond0 - mulDiv128(midGross, splitCarrot, 100); want > capd {
			want = capd
			if want < 0 {
				want = 0
			}
		}
	}
	return want
}
func drawWant(c *Court, cs *claimState, midGross int64) int64 {
	want := drawEntitlement(c, cs, midGross)
	if want > c.curPeriodBudget {
		want = c.curPeriodBudget
	}
	return want
}
func drawSplit(cs *claimState, d int64) (winners, author, answerer int64) {
	winners = d * splitWinners / (splitWinners + splitAuthor + splitAnswerer)
	author = d * splitAuthor / (splitWinners + splitAuthor + splitAnswerer)
	answerer = d * splitAnswerer / (splitWinners + splitAuthor + splitAnswerer)
	if int(cs.provisional) != int(cs.answer) {
		answerer = 0
	}
	if cs.seeded {
		author = 0
	}
	if cs.noAccuracy {
		winners = 0
	}
	return winners, author, answerer
}
func DrawQuote(courtSlug string, claimID uint64) (winners, author, answerer int64) {
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if cs.verdictAt == 0 || cs.rewardsOpened || cs.provisional < 0 {
		return 0, 0, 0
	}
	var midGross int64
	if cs.provisional == sideYES {
		midGross = convToCC(cs.yesConvHi, cs.yesConvLo)
	} else {
		midGross = convToCC(cs.noConvHi, cs.noConvLo)
	}
	return drawSplit(cs, drawEntitlement(c, cs, midGross))
}
func DrawSlices(courtSlug string, claimID uint64) (winners, author, answerer, carrotLeft int64) {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	return cs.drawWinners, cs.drawAuthor, cs.drawAnswerer, cs.carrotPool
}
func PullState(courtSlug string, claimID uint64, who address) (winnerPaid, authorPaid, answererPaid bool) {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.provisional >= 0 {
		if v := cs.stakers.Get(posKey(who, int(cs.provisional))); v != nil {
			winnerPaid = v.(*stakePos).bonusPaid
		}
	}
	return winnerPaid, cs.authorPaid && who == cs.author, cs.answererPaid && who == cs.answerer
}

posting.gno

package kourtv3
import (
	"chain"
	"strconv"
	"strings"
	sanitize "gno.land/p/nt/markdown/sanitize/v0"
)
const (
	ladderT1BpsInit = int64(5)
	ladderT2BpsInit = int64(25)
	ladderT3BpsInit = int64(100)
	postsEntryInit = int64(3)
	postsT2Init    = int64(10)
	postsT3Init    = int64(30)
	ladderTopRatio = int64(10)
	passPriceMinCC = int64(100_000)
	passPriceBps   = int64(1)
	passPriceOfT3 = int64(100)
)
func mustPostingInvariants() {
	if postsT3Init != postsEntryInit*ladderTopRatio {
		panic("kourtv3: the top rung must be exactly ladderTopRatio x entry — the ratio is the bound, not a suggestion")
	}
	if !(0 < ladderT1BpsInit && ladderT1BpsInit < ladderT2BpsInit && ladderT2BpsInit < ladderT3BpsInit) {
		panic("kourtv3: the ladder must be strictly increasing")
	}
	if !(0 < postsEntryInit && postsEntryInit < postsT2Init && postsT2Init < postsT3Init) {
		panic("kourtv3: the rates must be strictly increasing")
	}
	if ladderT3BpsInit < passPriceOfT3*passPriceBps {
		panic("kourtv3: t3 must be at least 100x the pass price, or a unit of standing is worth more than the flag lane's burn can cover")
	}
}
func init() { mustPostingInvariants() }
type ladder struct {
	t1Bps, t2Bps, t3Bps int64
	postsEntry, postsT2 int64
}
var ladderDefault = ladder{
	t1Bps: ladderT1BpsInit, t2Bps: ladderT2BpsInit, t3Bps: ladderT3BpsInit,
	postsEntry: postsEntryInit, postsT2: postsT2Init,
}
func (l ladder) postsT3() int64 { return l.postsEntry * ladderTopRatio }
func ladderFor(c *Court) ladder {
	if c.ladder != nil {
		return *c.ladder
	}
	return ladderDefault
}
func mustLadder(l ladder) {
	if !(0 < l.t1Bps && l.t1Bps < l.t2Bps && l.t2Bps < l.t3Bps && l.t3Bps <= 10_000) {
		panic("kourtv3: the ladder must be strictly increasing within 0..10000 bps")
	}
	if !(0 < l.postsEntry && l.postsEntry < l.postsT2 && l.postsT2 < l.postsT3()) {
		panic("kourtv3: the posting rates must be strictly increasing")
	}
	if l.t3Bps < passPriceOfT3*passPriceBps {
		panic("kourtv3: t3 must stay at least 100x the pass price — lowering it alone would make a unit of standing worth more than the flag lane's burn can cover")
	}
}
func SetLadderDefault(cur realm, t1Bps, t2Bps, t3Bps, postsEntry, postsT2 int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin sets the default ladder")
	}
	l := ladder{t1Bps, t2Bps, t3Bps, postsEntry, postsT2}
	mustLadder(l)
	ladderDefault = l
	chain.Emit(globalActEvent,
		"court", "*",
		"claim", "0",
		"act", "set-ladder-default:"+ladderKey(l),
		"by", cur.Previous().Address().String(),
		"height", eventHeight(),
	)
}
func SetCourtLadder(cur realm, courtSlug string, t1Bps, t2Bps, t3Bps, postsEntry, postsT2 int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireActiveMod(cm, who)
	l := ladder{t1Bps, t2Bps, t3Bps, postsEntry, postsT2}
	mustLadder(l)
	if fire, _ := approveAction(cm.pending, "setladder:"+ladderKey(l), who, "",
		speechM(cm)); !fire {
		return
	}
	c.ladder = &l
	cm.appendCourtLog(who, "setladder:"+ladderKey(l), "")
	emitModAct(c.id, 0, "setladder", who)
}
func ladderKey(l ladder) string {
	return strconv.FormatInt(l.t1Bps, 10) + ":" + strconv.FormatInt(l.t2Bps, 10) +
		":" + strconv.FormatInt(l.t3Bps, 10) + ":" +
		strconv.FormatInt(l.postsEntry, 10) + ":" + strconv.FormatInt(l.postsT2, 10)
}
func ClearCourtLadder(cur realm, courtSlug string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireMod(cm, who)
	if c.ladder == nil {
		panic("kourtv3: this court has no ladder override")
	}
	if fire, _ := approveAction(cm.pending, "clearladder:"+c.id, who, "",
		speechM(cm)); !fire {
		return
	}
	c.ladder = nil
	cm.appendCourtLog(who, "clearladder", "")
	emitModAct(c.id, 0, "clearladder", who)
}
func boardSupply(c *Court) (int64, bool) {
	if c.coin.Epoch() < 2 {
		return 0, false
	}
	return c.coin.PastTotal(c.coin.Epoch() - 1), true
}
func passPriceFor(c *Court) int64 {
	sup, sealed := boardSupply(c)
	if !sealed {
		return 0
	}
	p := sup * passPriceBps / 10_000
	if p < passPriceMinCC {
		p = passPriceMinCC
	}
	if lid := sup * ladderFor(c).t3Bps / 10_000 / passPriceOfT3; p > lid {
		p = lid
	}
	if p < 0 {
		p = 0
	}
	return p
}
func PassPrice(courtSlug string) int64 { return passPriceFor(mustCourt(courtSlug)) }
func Ladder(courtSlug string) string {
	c := mustCourt(courtSlug)
	l := ladderFor(c)
	inherited := "1"
	if c.ladder != nil {
		inherited = "0"
	}
	return "t1:" + strconv.FormatInt(l.t1Bps, 10) +
		";t2:" + strconv.FormatInt(l.t2Bps, 10) +
		";t3:" + strconv.FormatInt(l.t3Bps, 10) +
		";entry:" + strconv.FormatInt(l.postsEntry, 10) +
		";l2:" + strconv.FormatInt(l.postsT2, 10) +
		";l3:" + strconv.FormatInt(l.postsT3(), 10) +
		";inherited:" + inherited
}
func postLevel(c *Court, who address) int64 {
	l := ladderFor(c)
	sup, sealed := boardSupply(c)
	if !sealed {
		return 0
	}
	var s int64
	if r := lookupStanding(c, who); r != nil {
		s = r.score
	}
	switch {
	case s >= sup*l.t3Bps/10_000:
		return 3
	case s >= sup*l.t2Bps/10_000:
		return 2
	case s >= sup*l.t1Bps/10_000:
		return 1
	}
	if r := lookupStanding(c, who); r != nil && r.passHeld {
		return 1
	}
	return 0
}
func postsPerDayAt(l ladder, level int64) int64 {
	switch level {
	case 3:
		return l.postsT3()
	case 2:
		return l.postsT2
	case 1:
		return l.postsEntry
	}
	return 0
}
func PostLevel(courtSlug string, who address) int64 {
	return postLevel(mustCourt(courtSlug), who)
}
func PostsPerDay(courtSlug string, who address) int64 {
	c := mustCourt(courtSlug)
	return postsPerDayAt(ladderFor(c), postLevel(c, who))
}
func BuyCommentPass(cur realm, courtSlug string) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	touch(c)
	if r := lookupStanding(c, who); r != nil && r.passHeld {
		panic("kourtv3: this address already holds a pass in this court")
	}
	price := passPriceFor(c)
	if price <= 0 {
		if _, sealed := boardSupply(c); !sealed {
			panic("kourtv3: this court has not completed a sealed epoch yet; its board is not open")
		}
		panic("kourtv3: this court cannot price a pass yet — it has no supply")
	}
	mustSpendable(c, who, price)
	c.coin.Burn(who, price)
	getStanding(c, who).passHeld = true
	return price
}
func HoldsPass(courtSlug string, who address) bool {
	r := lookupStanding(mustCourt(courtSlug), who)
	return r != nil && r.passHeld
}
const secsPerDay = int64(86_400)
func bucketAt(tokens, lastRefill, rate, now int64) (avail, stamp int64) {
	if rate <= 0 {
		return 0, lastRefill
	}
	if lastRefill == 0 {
		return rate, now
	}
	stamp = lastRefill
	if gain := (now - lastRefill) * rate / secsPerDay; gain > 0 {
		tokens = satAdd(tokens, gain)
		stamp += gain * secsPerDay / rate
	}
	if tokens > rate {
		tokens = rate
	}
	if tokens < 0 {
		tokens = 0
	}
	return tokens, stamp
}
func refill(c *Court, who address, r *standingRow) int64 {
	rate := postsPerDayAt(ladderFor(c), postLevel(c, who))
	r.tokens, r.lastRefill = bucketAt(r.tokens, r.lastRefill, rate, nowTime())
	return r.tokens
}
func mustSpendPost(c *Court, who address) {
	lvl := postLevel(c, who)
	if lvl == 0 {
		if _, sealed := boardSupply(c); !sealed {
			panic("kourtv3: this court has not completed a sealed epoch yet; its board is not open")
		}
		panic("kourtv3: you cannot post in this court yet — earn standing, or buy an entry pass")
	}
	r := getStanding(c, who)
	if refill(c, who, r) < 1 {
		panic("kourtv3: your posting allowance for now is spent — level " +
			strconv.FormatInt(lvl, 10) + " allows " +
			strconv.FormatInt(postsPerDayAt(ladderFor(c), lvl), 10) + " a day")
	}
	r.tokens--
}
func PostsAvailable(courtSlug string, who address) int64 {
	c := mustCourt(courtSlug)
	r := lookupStanding(c, who)
	if r == nil {
		return 0
	}
	avail, _ := bucketAt(r.tokens, r.lastRefill, postsPerDayAt(ladderFor(c), postLevel(c, who)), nowTime())
	return avail
}
func renderStanding(slug, addrArg string) string {
	c := mustCourt(slug)
	who := address(addrArg)
	if !who.IsValid() {
		return "## Not found\nThat is not a valid address."
	}
	l := ladderFor(c)
	sup, sealed := boardSupply(c)
	lvl := postLevel(c, who)
	var b strings.Builder
	b.WriteString("# Standing in " + courtNameFor(c) + "\n\n")
	b.WriteString("`" + sanitize.InlineText(who.String()) + "`\n\n")
	if !sealed {
		b.WriteString("This court is too new to have a board. Its thresholds are quoted\n" +
			"against a sealed epoch and it has not completed one yet; comments open\n" +
			"as soon as it has.\n\n")
		b.WriteString(helpLink + "\n")
		return b.String()
	}
	var score, hw int64
	if r := lookupStanding(c, who); r != nil {
		score, hw = r.score, r.highWater
	}
	frozenAt, frozenUntil := boardFrozenAt(c, who)
	if frozenUntil != 0 {
		when := "block " + strconv.FormatInt(frozenUntil, 10)
		if frozenAt != 0 {
			when = strconv.FormatInt(frozenAt, 10) + " (" + when + ")"
		}
		b.WriteString("> **This court's moderators have frozen you out of its boards**\n" +
			"> until " + when + ".\n>\n" +
			"> It reaches comments and upvotes and nothing else: you may still stake,\n" +
			"> vote, answer, dispute, flag, open claims, withdraw, draw emission, and\n" +
			"> take every election action. An entry pass will not lift it, and buying\n" +
			"> one now would burn coin for nothing.\n>\n" +
			"> The court's [moderation log](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug +
			"/mod) records who acted and why.\n\n")
	}
	b.WriteString("## What you may do\n\n")
	b.WriteString("- level: **" + strconv.FormatInt(lvl, 10) + "** of 3\n")
	b.WriteString("- comments: **" + strconv.FormatInt(postsPerDayAt(l, lvl), 10) +
		" a day**, " + strconv.FormatInt(PostsAvailable(slug, who), 10) + " available now\n")
	b.WriteString("- per claim: at most " + strconv.Itoa(maxBoardRowsPerAuthor) + " comments\n")
	if lvl == 0 {
		if hw > score {
			b.WriteString("\nA moderator slash took your standing to zero, and with it the\n" +
				"entry pass if you held one — the burn is not refunded. A successor\n" +
				"set, or the platform, can restore up to the high-water mark below.\n")
		}
		if frozenUntil == 0 {
			if hw > score {
				b.WriteString("You can also earn back from zero, or buy a new pass for " +
					strconv.FormatInt(passPriceFor(c), 10) + " " + qualifiedSymbol(c) + ".\n")
			} else {
				b.WriteString("\nYou cannot comment here yet. Earn standing below, or buy an entry\n" +
					"pass for " + strconv.FormatInt(passPriceFor(c), 10) + " " +
					qualifiedSymbol(c) + " (burned, one-off).\n")
			}
		}
	}
	b.WriteString("\n## Standing\n\n")
	b.WriteString("- earned: **" + strconv.FormatInt(score, 10) + "**\n")
	b.WriteString("- high-water mark: " + strconv.FormatInt(hw, 10) +
		" — what a moderator slash can be restored toward\n")
	b.WriteString("- entry pass: " + yesNo(HoldsPass(slug, who)) + "\n")
	writeStandingFrom(&b, c, who)
	b.WriteString("\n## The rungs, in this court\n\n")
	for _, k := range []struct {
		name string
		bps  int64
		rate int64
	}{{"1", l.t1Bps, l.postsEntry}, {"2", l.t2Bps, l.postsT2}, {"3", l.t3Bps, l.postsT3()}} {
		b.WriteString("- level " + k.name + ": " + strconv.FormatInt(sup*k.bps/10_000, 10) +
			" standing (" + strconv.FormatInt(k.bps, 10) + " bps of supply) → " +
			strconv.FormatInt(k.rate, 10) + " a day\n")
	}
	b.WriteString("\nEach rung is a **share of this court's supply**, not a fixed " +
		"number, so the bar rises as the court grows. Standing itself is never " +
		"taken except by a logged moderator slash — but a score that does not " +
		"move can still fall below a rung it used to clear.\n")
	b.WriteString("\n## How standing is earned\n\n")
	b.WriteString("Only where the court adjudicated something, and always in proportion\n" +
		"to your own capital that the act committed or destroyed:\n\n")
	b.WriteString("- a quality flag whose slash **settled** — the full bar, two thirds low\n")
	b.WriteString("- **prevailing in a dispute** — an uphold against real opposition, or an overturn\n")
	b.WriteString("- authoring a claim the court rated **HIGH** — seeded claims earn nothing\n")
	b.WriteString("- **winning conviction** on a resolved claim; half where nobody disputed it\n\n")
	b.WriteString("Never earned: commenting, being upvoted, buying " +
		qualifiedSymbol(c) + ", or buying the pass.\n")
	b.WriteString("Standing does not decay. A moderator may slash it for abuse; the\n")
	b.WriteString("high-water mark above is what a successor set can restore.\n")
	b.WriteString("\n## The answer record\n\n")
	b.WriteString("- contested-and-upheld answers: **" +
		strconv.FormatInt(int64(AnswerRecord(slug, who)), 10) + "**\n")
	b.WriteString("\n_Adjudicated — moderators cannot change this._\n")
	return b.String()
}
func renderStandingIndex(slug string) string {
	c := mustCourt(slug)
	l := ladderFor(c)
	var b strings.Builder
	b.WriteString("# Standing in " + courtNameFor(c) + "\n\n")
	b.WriteString("To see an address's standing, put it on the end of this " +
		"page's path: `/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + sanitize.InlineText(slug) +
		"/me/<address>`\n\n")
	b.WriteString("An entry pass costs " + strconv.FormatInt(passPriceFor(c), 10) +
		" " + qualifiedSymbol(c) + ", burned, once. Standing is earned and " +
		"cannot be bought.\n\n")
	b.WriteString("Standing is measured against this court's coin supply, in " +
		"basis points — one bp is a hundredth of a percent.\n\n")
	b.WriteString("- level 1 at " + strconv.FormatInt(l.t1Bps, 10) + " bps of supply → " +
		strconv.FormatInt(l.postsEntry, 10) + " comments a day\n")
	b.WriteString("- level 2 at " + strconv.FormatInt(l.t2Bps, 10) + " bps → " +
		strconv.FormatInt(l.postsT2, 10) + " a day\n")
	b.WriteString("- level 3 at " + strconv.FormatInt(l.t3Bps, 10) + " bps → " +
		strconv.FormatInt(l.postsT3(), 10) + " a day\n")
	return b.String()
}
func writeStandingFrom(b *strings.Builder, c *Court, who address) {
	r := lookupStanding(c, who)
	if r == nil {
		return
	}
	labels := [standingCatN]string{
		"quality flags whose slash settled",
		"disputes you prevailed in",
		"claims of yours the court rated HIGH",
		"conviction on resolved claims",
	}
	listed := false
	for i := 0; i < standingCatN; i++ {
		if r.from[i] == 0 {
			continue
		}
		if !listed {
			b.WriteString("- from: ")
			listed = true
		} else {
			b.WriteString("; ")
		}
		b.WriteString(strconv.FormatInt(r.from[i], 10) + " from " + labels[i])
	}
	if listed {
		b.WriteString("\n")
	}
}
func yesNo(b bool) string {
	if b {
		return "held"
	}
	return "none"
}

records.gno

package kourtv3
type answerRecord struct {
	score          int
	activePriority uint64
}
func creditUpheld(c *Court, who address) {
	r := getRecord(c, who)
	wasQualified := r.score >= priorityNetRecord
	r.score++
	if !wasQualified && r.score >= priorityNetRecord {
		c.qualifiedCount++
	}
}
func resetOverturned(c *Court, who address) {
	r := getRecord(c, who)
	if r.score >= priorityNetRecord {
		c.qualifiedCount--
	}
	r.score = 0
}
func priorityGateActive(c *Court) bool { return c.qualifiedCount >= priorityColdStartN }
func mayAnswerInPriority(c *Court, who address) bool {
	r := getRecord(c, who)
	return r.score >= priorityNetRecord && r.activePriority == 0
}
func holdPriority(c *Court, who address, claimID uint64) {
	getRecord(c, who).activePriority = claimID
}
func releasePriority(c *Court, who address, claimID uint64) {
	r := getRecord(c, who)
	if r.activePriority == claimID {
		r.activePriority = 0
	}
}
func getRecord(c *Court, who address) *answerRecord {
	if v := c.records.Get(string(who)); v != nil {
		return v.(*answerRecord)
	}
	r := &answerRecord{}
	c.records.Set(string(who), r)
	return r
}
func AnswerRecord(courtSlug string, who address) int {
	c := mustCourt(courtSlug)
	if v := c.records.Get(string(who)); v != nil {
		return v.(*answerRecord).score
	}
	return 0
}
func PriorityGateActive(courtSlug string) bool {
	return priorityGateActive(mustCourt(courtSlug))
}

redeem.gno

package kourtv3
import (
	"chain"
	"chain/banker"
	"chain/runtime/unsafe"
	"strconv"
	"gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/grc20votes/v0"
)
const (
	burnBpsInit = int64(1000)
	minBurnBps = int64(500)
	maxBurnBps = int64(5000)
	bpsDenom = grc20votes.Bps
	coinUnit = int64(1_000_000)
	boughtEvent   = "Bought"
	redeemedEvent = "Redeemed"
)
var burnBps = burnBpsInit
var totalReserve int64
func BurnBps() int64 { return burnBps }
func SetBurnBps(cur realm, bps int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin sets the burn share")
	}
	mustSaneBurnBps(bps)
	old := burnBps
	burnBps = bps
	chain.Emit(globalActEvent,
		"court", "*",
		"claim", "0",
		"act", "set-burn-bps:"+strconv.FormatInt(old, 10)+"->"+strconv.FormatInt(bps, 10),
		"by", cur.Previous().Address().String(),
		"height", eventHeight(),
	)
}
func mustSaneBurnBps(bps int64) {
	if bps < minBurnBps || bps > maxBurnBps {
		panic("kourtv3: the burn share must be between " + strconv.FormatInt(minBurnBps, 10) +
			" and " + strconv.FormatInt(maxBurnBps, 10) + " bps")
	}
}
func splitPayment(c *Court, spent int64) (burned, reserved int64) {
	if c.oneWay {
		return spent, 0
	}
	reserved = mulDiv128(spent, bpsDenom-burnBps, bpsDenom)
	return spent - reserved, reserved
}
func redeemQuote(c *Court, amount int64) (payout, supply int64) {
	supply = c.coin.TotalSupply()
	if c.oneWay || amount <= 0 || c.reserve <= 0 || supply <= 0 || amount > supply {
		return 0, supply
	}
	return mulDiv128(c.reserve, amount, supply), supply
}
func mustReturnAMicroGNOT(c *Court, payout, supply int64) {
	if payout > 0 {
		return
	}
	least := supply / c.reserve
	if supply%c.reserve != 0 {
		least++
	}
	panic("kourtv3: too small to return a µGNOT — redeem at least " + ccAmt(least) + " CC")
}
func Redeem(cur realm, courtSlug string, amount int64) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	if amount <= 0 {
		panic("kourtv3: redeem amount must be positive")
	}
	if unsafe.OriginSend().AmountOf(gnotDenom) > 0 {
		panic("kourtv3: Redeem takes no GNOT")
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	if c.oneWay {
		panic("kourtv3: this court's coin is one-way; nothing returns GNOT")
	}
	if who == c.escrow {
		panic("kourtv3: the court escrow cannot redeem")
	}
	touch(c)
	if c.reserve <= 0 {
		panic("kourtv3: this court holds no reserve")
	}
	mustSpendable(c, who, amount)
	payout, supply := redeemQuote(c, amount)
	mustReturnAMicroGNOT(c, payout, supply)
	c.coin.Burn(who, amount)
	if payout > c.reserve {
		panic("kourtv3: reserve accounting")
	}
	c.reserve -= payout
	totalReserve -= payout
	c.redeemedGNOT = mustAdd(c.redeemedGNOT, payout)
	b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	b.SendCoins(cur.Address(), who, chain.Coins{chain.NewCoin(gnotDenom, payout)})
	chain.Emit(redeemedEvent,
		"court", c.id,
		"who", who.String(),
		"amount", strconv.FormatInt(amount, 10),
		"ugnot", strconv.FormatInt(payout, 10),
	)
	return payout
}
func ReserveGNOT(courtSlug string) int64 { return mustCourt(courtSlug).reserve }
func TotalReserveGNOT() int64 { return totalReserve }
func RedeemedGNOT(courtSlug string) int64 { return mustCourt(courtSlug).redeemedGNOT }
func RedeemValue(courtSlug string, amount int64) int64 {
	p, _ := redeemQuote(mustCourt(courtSlug), amount)
	return p
}

relrender.gno

package kourtv3
import (
	"strconv"
	"strings"
)
func writeRelations(b *strings.Builder, c *Court, claimID uint64) {
	base := "/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + c.id + "/"
	sup := writeSupersedes(b, c, claimID, base)
	arg := writeArguments(b, c, claimID, base)
	if sup || arg {
		b.WriteString("\n")
	}
}
func writeSupersedes(b *strings.Builder, c *Court, claimID uint64, base string) bool {
	wrote := false
	if c.supBy != nil {
		p := beClaimKey(claimID)
		n := 0
		c.supBy.Iterate(p, "", func(key string, v any) bool {
			if !strings.HasPrefix(key, p) {
				return true
			}
			from := claimIDFromKey(key[len(p):])
			if from == 0 || from > c.nextID || assocTextGone(c, from) {
				return false
			}
			if n == 0 {
				b.WriteString("> **This question was asked again.** It died here " +
					"without an answer and was re-filed as:\n")
			}
			n++
			cs := mustClaim(c, from)
			b.WriteString(">\n> - [" + claimTitleFor(c, cs) + "](" + base +
				strconv.FormatUint(from, 10) + ") — " + claimStatus(cs) + "\n")
			return n >= renderPageSize
		})
		if n > 0 {
			b.WriteString("\n")
			wrote = true
		}
	}
	if c.supOf != nil {
		if v := c.supOf.Get(beClaimKey(claimID)); v != nil {
			e := v.(*supEdge)
			if e.to != 0 && e.to <= c.nextID && !assocTextGone(c, e.to) {
				cs := mustClaim(c, e.to)
				b.WriteString("_Re-files [" + claimTitleFor(c, cs) + "](" + base +
					strconv.FormatUint(e.to, 10) + "), which died unanswered._\n\n")
				wrote = true
			}
		}
	}
	return wrote
}
func writeArguments(b *strings.Builder, c *Court, claimID uint64, base string) bool {
	var out, in strings.Builder
	nOut := writeEdgeSide(&out, c, claimID, base, true)
	nIn := writeEdgeSide(&in, c, claimID, base, false)
	if nOut+nIn == 0 {
		return false
	}
	b.WriteString("## Related claims\n\n")
	b.WriteString("_Anyone may draw these links, and the court does not rule on " +
		"them — they are what readers have asserted, not findings._\n\n")
	if nOut > 0 {
		b.WriteString("This claim says:\n\n")
		b.WriteString(out.String() + "\n")
	}
	if nIn > 0 {
		b.WriteString("Others say about this claim:\n\n")
		b.WriteString(in.String() + "\n")
	}
	return true
}
func writeEdgeSide(b *strings.Builder, c *Court, claimID uint64, base string, outgoing bool) int {
	t := c.assocIn
	if outgoing {
		t = c.assocOut
	}
	if t == nil {
		return 0
	}
	p := beClaimKey(claimID)
	n := 0
	t.Iterate(p, "", func(key string, v any) bool {
		if !strings.HasPrefix(key, p) {
			return true
		}
		e, ok := v.(*assocEdge)
		if !ok {
			return false
		}
		other := claimIDFromKey(key[len(p):])
		if other == 0 || other > c.nextID || assocTextGone(c, other) {
			return false
		}
		verb := "supports"
		if e.stance == assocContests {
			verb = "contests"
		}
		if !outgoing {
			verb += " it"
		}
		n++
		cs := mustClaim(c, other)
		b.WriteString("- " + verb + " [" + claimTitleFor(c, cs) + "](" + base +
			strconv.FormatUint(other, 10) + ")\n")
		return n >= renderPageSize
	})
	return n
}

render.gno

package kourtv3
import (
	"strconv"
	"strings"
	sanitize "gno.land/p/nt/markdown/sanitize/v0"
)
func Render(path string) string {
	return withSiteBanner(render(path), path)
}
func render(path string) string {
	path = strings.Trim(path, "/")
	if path == "" {
		return renderDirectory()
	}
	parts := strings.SplitN(path, "/", 4)
	if len(parts) == 1 {
		if parts[0] == helpPath {
			return renderHelp()
		}
		if parts[0] == adminParamsPath {
			return renderAdminParams()
		}
		return renderCourt(parts[0])
	}
	if parts[1] == "mod" {
		return renderModLog(parts[0])
	}
	if parts[1] == electionPath {
		if len(parts) != 2 {
			return "## Not found\nThe ballot is /<court>/election."
		}
		return renderElection(parts[0])
	}
	if parts[1] == "folder" {
		if len(parts) != 3 {
			return "## Not found\nA folder is /<court>/folder/<id>."
		}
		fid, ferr := strconv.ParseUint(parts[2], 10, 64)
		if ferr != nil {
			return "## Not found\nA folder id must be a number."
		}
		return renderFolderPage(parts[0], fid)
	}
	if parts[1] == "me" {
		if len(parts) == 3 {
			return renderStanding(parts[0], parts[2])
		}
		return renderStandingIndex(parts[0])
	}
	id, err := strconv.ParseUint(parts[1], 10, 64)
	if err != nil {
		return "## Not found\nA claim id must be a number."
	}
	if len(parts) >= 3 && parts[2] == "board" {
		if len(parts) == 4 {
			if parts[3] == "top" {
				return renderBoardTop(parts[0], id)
			}
			if parts[3] == "hidden" {
				return renderBoardHidden(parts[0], id)
			}
			return renderBoardRow(parts[0], id, parts[3])
		}
		return renderBoardPage(parts[0], id)
	}
	if len(parts) == 4 {
		return "## Not found\nThat is not a page."
	}
	if len(parts) == 3 {
		return renderPositions(parts[0], id, parts[2])
	}
	return renderClaim(parts[0], id)
}
func renderDirectory() string {
	b := strings.Builder{}
	b.WriteString("# " + platformName + "\n\nLet Truth be told.\n\n")
	b.WriteString("Stake on claims of fact. Your principal always returns 1×.\n\n")
	b.WriteString(helpLink + "\n\n")
	afterHeader := b.Len()
	writeTier(&b, "Featured", tierFeatured)
	writeListedByBurn(&b)
	if b.Len() == afterHeader {
		b.WriteString("_No courts yet._\n")
	}
	return b.String()
}
func writeListedByBurn(b *strings.Builder) {
	slugs := listedPage("burn", 0, renderPageSize)
	if len(slugs) == 0 {
		return
	}
	b.WriteString("## Courts\n\n")
	shown := 0
	for _, s := range slugs {
		c := mustCourt(s)
		if c.tier != tierListed {
			continue
		}
		shown++
		b.WriteString("- [" + courtNameFor(c) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + s + ") · " +
			qualifiedSymbol(c) + " — " + strconv.FormatUint(c.nextID, 10) + " claims\n")
	}
	if total := len(ListByTier(int(tierListed))); total > shown {
		b.WriteString("- _…and " + strconv.Itoa(total-shown) +
			" more; open any court directly at /r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:<slug>_\n")
	}
	b.WriteString("\n")
}
const renderPageSize = 50
func writeTier(b *strings.Builder, heading string, tier uint8) {
	slugs := ListByTier(int(tier))
	if len(slugs) == 0 {
		return
	}
	b.WriteString("## " + heading + "\n\n")
	shown := len(slugs)
	if shown > renderPageSize {
		shown = renderPageSize
	}
	for _, s := range slugs[:shown] {
		c := mustCourt(s)
		b.WriteString("- [" + courtNameFor(c) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + s + ") · " +
			qualifiedSymbol(c) + " — " + strconv.FormatUint(c.nextID, 10) + " claims\n")
	}
	if len(slugs) > shown {
		b.WriteString("- _…and " + strconv.Itoa(len(slugs)-shown) +
			" more; open any court directly at /r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:<slug>_\n")
	}
	b.WriteString("\n")
}
func renderCourt(slug string) string {
	if !Exists(slug) {
		return "## Not found\nNo court by that slug."
	}
	c := mustCourt(slug)
	b := strings.Builder{}
	b.WriteString("# " + courtNameFor(c) + "\n\n")
	if c.tier == tierHidden {
		b.WriteString("> **Delisted by the global DAO.** This court appears in no " +
			"listing and is reachable only by direct link. Nothing else changes: " +
			"its claims still stake, answer, settle and pay out as usual.\n\n")
	}
	if d := courtDescFor(c); d != "" {
		b.WriteString(d + "\n\n")
	}
	writeFolderIndex(&b, c, slug)
	b.WriteString("## Claims\n\n")
	if c.nextID == 0 {
		b.WriteString("_No claims yet._\n\n")
		writeCourtCoin(&b, c)
		return b.String()
	}
	lo := uint64(1)
	if c.nextID > renderPageSize {
		lo = c.nextID - renderPageSize + 1
	}
	for id := c.nextID; id >= lo; id-- {
		cs := mustClaim(c, id)
		if HiddenFromListing(slug, id) {
			continue
		}
		b.WriteString("- [" + claimTitleFor(c, cs) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/" +
			strconv.FormatUint(id, 10) + ") — " + claimStatus(cs) + "\n")
	}
	if lo > 1 {
		b.WriteString("- _…and " + strconv.FormatUint(lo-1, 10) +
			" older; open any by id at /r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/<id>_\n")
	}
	b.WriteString("\n")
	writeStrip(&b, slug)
	writePending(&b, slug)
	writeCourtCoin(&b, c)
	b.WriteString("[Moderation log](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + "/mod)\n")
	return b.String()
}
func writeCourtCoin(b *strings.Builder, c *Court) {
	b.WriteString("## This court's coin\n\n")
	b.WriteString("- " + qualifiedSymbol(c) +
		" — this court's own coin, not interchangeable with any other court's\n")
	nextCoin, ok := c.crv.Cost(c.minted, coinUnit)
	if ok {
		b.WriteString("- price: " + strconv.FormatInt(nextCoin, 10) +
			" ugnot per coin — the next coin's price, and it only rises\n")
	} else {
		b.WriteString("- price: the curve is at its cap; no more coin can be minted\n")
	}
	if c.oneWay {
		b.WriteString("- one-way: every payment burns in full; nothing is held and " +
			"nothing returns GNOT\n")
	} else {
		perCoin, _ := redeemQuote(c, coinUnit)
		b.WriteString("- held for the coin: " + ugnotAmt(c.reserve) + " GNOT · " +
			"one coin returns " + strconv.FormatInt(perCoin, 10) +
			" ugnot right now (what is held × coin ÷ supply, rounded down; " +
			"below the next coin's price unless coin has been destroyed by bonds " +
			"since the last offering) · " + pct(burnBps, bpsDenom) +
			" of each payment burns\n")
	}
	b.WriteString("- in circulation: " + strconv.FormatInt(c.coin.TotalSupply(), 10) +
		" · paid out as rewards so far: " + strconv.FormatInt(c.emittedTotal, 10) + "\n")
	b.WriteString("- reward reservoir: " + strconv.FormatInt(c.reservoirR(), 10) +
		" waiting to be earned · " + strconv.FormatInt(c.seniorOwed, 10) +
		" already owed to earlier earners\n\n")
	b.WriteString(helpLink + "\n\n")
}
func renderClaim(slug string, id uint64) string {
	if !Exists(slug) {
		return "## Not found\nNo court by that slug."
	}
	c := mustCourt(slug)
	if id == 0 || id > c.nextID {
		return "## Not found\nNo claim by that id."
	}
	cs := mustClaim(c, id)
	b := strings.Builder{}
	b.WriteString("# " + claimTitleFor(c, cs) + "\n\n")
	if body := claimBodyQuoted(c, cs); body != "" {
		b.WriteString(body)
	}
	writeClaimMedia(&b, c, cs)
	b.WriteString(hideBanner(c, cs))
	writeRelations(&b, c, id)
	writeAppeal(&b, c, cs)
	if cs.seeded {
		b.WriteString("_Seeded by a moderator to start this court; the author earns nothing from it._\n\n")
	}
	b.WriteString("## Signal\n\n")
	if cs.frozenAt != 0 {
		fTotal := cs.yesStakeAtFreeze + cs.noStakeAtFreeze
		b.WriteString("- staked when answered: " + strconv.FormatInt(fTotal, 10) +
			" " + qualifiedSymbol(c) + " (YES " + strconv.FormatInt(cs.yesStakeAtFreeze, 10) +
			" / NO " + strconv.FormatInt(cs.noStakeAtFreeze, 10) + ")\n")
		if fTotal > 0 {
			b.WriteString("- lean when answered: " + pct(cs.yesStakeAtFreeze, fTotal) + " YES\n")
		}
		if live := cs.yesStake + cs.noStake; live > 0 {
			b.WriteString("- still unwithdrawn: " + strconv.FormatInt(live, 10) +
				" " + qualifiedSymbol(c) + "\n")
		}
	} else {
		total := cs.yesStake + cs.noStake
		b.WriteString("- staked now: " + strconv.FormatInt(total, 10) +
			" " + qualifiedSymbol(c) + " (YES " + strconv.FormatInt(cs.yesStake, 10) +
			" / NO " + strconv.FormatInt(cs.noStake, 10) + ")\n")
		if total > 0 {
			b.WriteString("- right now: " + pct(cs.yesStake, total) + " YES\n")
		}
		b.WriteString("- pays: not set until the claim is answered — it is " +
			"this claim's total stake against a typical claim in this court, " +
			"so staking now is what sets it\n")
	}
	h := heightNow()
	if yAvg, ym := cs.yes.Average(h, periodBlocks); ym {
		if tAvg, tm := cs.oi.Average(h, periodBlocks); tm && tAvg > 0 {
			b.WriteString("- trailing week: " + pct(yAvg, tAvg) + " YES\n")
		}
	}
	yc := convToCC(cs.yesConvHi, cs.yesConvLo)
	nc := convToCC(cs.noConvHi, cs.noConvLo)
	if yc+nc > 0 {
		b.WriteString("- lifetime, weighted by how long each stake was held: " + pct(yc, yc+nc) + " YES\n")
	}
	b.WriteString("\n## Status\n\n" + claimStatus(cs) + "\n")
	if cs.frozenAt != 0 {
		b.WriteString("\n## Resolution\n\n")
		b.WriteString("- answer: " + sideName(int(cs.answer)) + " (bond " +
			strconv.FormatInt(cs.answerBond0, 10) + " " + qualifiedSymbol(c) + ")\n")
		b.WriteString("- the answerer has been challenged and upheld " +
			strconv.FormatInt(int64(AnswerRecord(slug, cs.answerer)), 10) +
			" time(s) in this court — answers nobody contested do not count\n")
		if PriorityGateActive(slug) {
			b.WriteString("- answer priority is live here — a record of " +
				strconv.FormatInt(int64(priorityNetRecord), 10) +
				"+ earns a 24h head start on new claims\n")
		}
		if cs.failedRounds > 0 {
			b.WriteString("- failed dispute rounds: " + strconv.FormatInt(cs.failedRounds, 10) +
				" of " + strconv.FormatInt(int64(maxFailedRounds), 10) +
				" — the next dispute bond doubles\n")
		}
		if cs.disputeOpen {
			b.WriteString("- dispute round " + strconv.FormatInt(cs.round, 10) +
				" vote open — no running total is shown here until it closes\n")
		} else if cs.verdictAt == 0 {
			b.WriteString("- disputing this answer costs a bond of " +
				strconv.FormatInt(cs.disputeBond0(), 10) + " " + qualifiedSymbol(c) +
				", doubling for each round that fails to reach a quorum\n")
			b.WriteString("  - win and the answerer's bond is burned and you are " +
				"compensated, up to twice your own bond; lose and yours burns " +
				"instead. Nothing passes between the two of you — a forfeit is " +
				"burned, a compensation is newly issued\n")
			b.WriteString("  - if the round draws no quorum, half your bond burns " +
				"and half returns; three such rounds close the claim undecided, " +
				"with every stake out at 1× and the deposit and fee refunded\n")
			b.WriteString("  - **your stake is not at risk either way** — only the " +
				"bond is\n")
		}
		if cs.verdictAt != 0 && !cs.provClose {
			b.WriteString("- verdict: " + sideName(int(cs.provisional)) + " — " + cs.route + "\n")
		}
		if cs.tierRef <= 0 {
			b.WriteString("- pays " + tierText(tierParBps) +
				" — this claim was answered before ratings were recorded, so it " +
				"pays the standard amount\n")
		} else {
			b.WriteString("- pays " + tierText(tierBpsFor(cs)) +
				" — this claim held " + strconv.FormatInt(cs.xBarFrozen, 10) +
				" " + qualifiedSymbol(c) + " against a typical " +
				strconv.FormatInt(cs.tierRef, 10) + " " + qualifiedSymbol(c) + " here\n")
			b.WriteString("- the rating is the money that showed up, not a vote: " +
				"a claim of typical size pays 1.00×, and it is capped at 0.25× and 2.00×\n")
			if cs.spamTotalW > 0 && cs.spamW > 0 {
				b.WriteString("- and " + tierText(spamNetBps(cs)) +
					" of that, because " + strconv.FormatInt(cs.spamW, 10) +
					" of " + strconv.FormatInt(cs.spamTotalW, 10) +
					" of the weight cast flagged it as spam\n")
			}
		}
		switch {
		}
		if cs.rewardsOpened {
			w, a, ans, carrot := cs.drawWinners, cs.drawAuthor, cs.drawAnswerer, cs.carrotPool
			b.WriteString("- rewards open — pools (" + qualifiedSymbol(c) +
				"): accuracy " + strconv.FormatInt(w, 10) +
				", author " + strconv.FormatInt(a, 10) + ", answerer " + strconv.FormatInt(ans, 10) +
				", participation remaining " + strconv.FormatInt(carrot, 10) + "\n")
		}
	}
	b.WriteString("\n_To see your own stake on this claim, put your address on " +
		"the end of this page's path:_ `/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + sanitize.InlineText(slug) +
		"/" + strconv.FormatUint(id, 10) + "/<your address>`\n\n")
	writeBoardLink(&b, c, cs, id)
	return b.String()
}
func renderPositions(slug string, id uint64, addrStr string) string {
	if !Exists(slug) {
		return "## Not found\nNo court by that slug."
	}
	c := mustCourt(slug)
	if id == 0 || id > c.nextID {
		return "## Not found\nNo claim by that id."
	}
	who := address(addrStr)
	if !who.IsValid() {
		return "## Not found\nThat is not a valid address."
	}
	cs := mustClaim(c, id)
	b := strings.Builder{}
	b.WriteString("# Positions on this claim\n\n")
	b.WriteString(hideBanner(c, cs))
	b.WriteString("Claim: [" + claimTitleFor(c, cs) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug +
		"/" + strconv.FormatUint(id, 10) + ") in [" + courtNameFor(c) +
		"](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug + ")\n\n")
	b.WriteString("Address: " + sanitize.InlineText(addrStr) + "\n\n")
	yStake := StakeOf(slug, id, sideYES, who)
	nStake := StakeOf(slug, id, sideNO, who)
	yConv := ConvictionOf(slug, id, sideYES, who)
	nConv := ConvictionOf(slug, id, sideNO, who)
	b.WriteString("## Stake (what you have in, and always get back)\n\n")
	b.WriteString("- YES: " + strconv.FormatInt(yStake, 10) +
		"   NO: " + strconv.FormatInt(nStake, 10) + " (" + qualifiedSymbol(c) +
		" base units)\n")
	b.WriteString("- conviction so far — YES: " + strconv.FormatInt(yConv, 10) +
		"   NO: " + strconv.FormatInt(nConv, 10) + " (the reward weight)\n")
	bal := c.coin.BalanceOf(who)
	locked := lockedOf(c, who)
	voted := voteLockedOf(c, who)
	b.WriteString("\n## This address's " + qualifiedSymbol(c) +
		" in this court (all claims)\n\n")
	b.WriteString("- held: " + strconv.FormatInt(bal, 10) +
		" — every unit votes, committed or not\n")
	b.WriteString("- committed as stake: " + strconv.FormatInt(locked, 10) + "\n")
	b.WriteString("- committed by voting: " + strconv.FormatInt(voted, 10) +
		" — until each question resolves\n")
	b.WriteString("- free to stake: " + strconv.FormatInt(spendable(c, who), 10) + "\n")
	b.WriteString("- free to bond, deposit or transfer: " +
		strconv.FormatInt(disposable(c, who), 10) + "\n")
	roles := ""
	if who == cs.author {
		roles += "author "
	}
	if cs.frozenAt != 0 && who == cs.answerer {
		roles += "answerer "
	}
	if roles != "" {
		b.WriteString("- roles: " + roles + "\n")
	}
	if rec := AnswerRecord(slug, who); rec > 0 {
		b.WriteString("- answers challenged and upheld in this court: " + strconv.FormatInt(int64(rec), 10) + "\n")
	}
	b.WriteString("\n## What you can do\n\n")
	switch {
	case cs.verdictAt == 0 && cs.frozenAt == 0:
		b.WriteString("- staking is open — stake or unstake freely until an answer posts\n")
	case cs.verdictAt == 0:
		b.WriteString("- answered, awaiting the verdict — principal is never withheld; withdraw once it is final\n")
	default:
		b.WriteString("- the verdict is final — withdraw your principal on either side (1×)\n")
		if cs.rewardsOpened {
			win := int(cs.provisional)
			if !cs.provClose && ((win == sideYES && yStake+yConv > 0) || (win == sideNO && nStake+nConv > 0)) {
				b.WriteString("- you backed the winning side — pull your accuracy reward\n")
			}
			if who == cs.author && cs.drawAuthor > 0 {
				b.WriteString("- author reward available — pull it\n")
			}
			if who == cs.answerer && cs.drawAnswerer > 0 {
				b.WriteString("- answerer reward available — pull it\n")
			}
		}
	}
	return b.String()
}
func tierText(bps int64) string {
	if bps < 0 {
		bps = 0
	}
	frac := (bps % tierParBps) / 100
	out := strconv.FormatInt(bps/tierParBps, 10) + "."
	if frac < 10 {
		out += "0"
	}
	return out + strconv.FormatInt(frac, 10) + "×"
}
func sideName(side int) string {
	if side == sideYES {
		return "YES"
	}
	return "NO"
}
func ClaimStatus(courtSlug string, claimID uint64) string {
	return claimStatus(mustClaim(mustCourt(courtSlug), claimID))
}
func claimStatus(cs *claimState) string {
	switch {
	case cs.closed:
		return "closed — never answered; every stake exited 1×, the deposit refunded"
	case cs.spamClosed:
		return "discarded — more than half the weight cast called this claim spam; " +
			"every stake withdraws 1×, the answerer's and disputer's bonds return, " +
			"the filing fee burns"
	case cs.provClose:
		return "closed without a decision — three dispute rounds failed quorum; everyone withdraws 1×, deposit and fee refunded"
	case cs.verdictAt != 0:
		return "settled " + sideName(int(cs.provisional)) + " — every stake withdraws 1×"
	case cs.disputeOpen:
		disputed := int(cs.answer)
		if cs.provisional >= 0 {
			disputed = int(cs.provisional)
		}
		return "disputed " + sideName(disputed) +
			" — a sealed vote is deciding; principal is never withheld"
	case cs.provisional >= 0:
		return "provisional verdict " + sideName(int(cs.provisional)) +
			" — reopenable by a new dispute until block " + strconv.FormatInt(cs.escrowUntil, 10) +
			"; the side it is against may withdraw 1× now"
	case cs.frozenAt != 0:
		return "answered " + sideName(int(cs.answer)) +
			" — staking frozen; disputable until block " +
			strconv.FormatInt(cs.answerHeight+settleDelay, 10) + ", then it settles undisputed"
	default:
		return "open — stake YES or NO; unstake freely until an answer posts"
	}
}
func pct(num, den int64) string {
	if den <= 0 || num < 0 {
		return "—"
	}
	bps := mulDiv128(num, 10000, den)
	return strconv.FormatInt(bps/100, 10) + "." + pad2(bps%100) + "%"
}
func pad2(v int64) string {
	if v < 10 {
		return "0" + strconv.FormatInt(v, 10)
	}
	return strconv.FormatInt(v, 10)
}
func writeFolderIndex(b *strings.Builder, c *Court, slug string) {
	if c.mod == nil {
		return
	}
	shown := 0
	for _, f := range c.mod.folderRows() {
		if f.parent != 0 || f.retired || f.purged {
			continue
		}
		if shown == 0 {
			b.WriteString("Filed under: ")
		} else {
			b.WriteString(" · ")
		}
		b.WriteString("[" + sanitize.InlineText(f.name) + "](/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" +
			slug + "/folder/" + strconv.FormatUint(f.id, 10) + ")")
		shown++
	}
	if shown > 0 {
		b.WriteString("\n\n")
	}
}
func renderFolderPage(slug string, fid uint64) string {
	if !Exists(slug) {
		return "## Not found\nNo court by that slug."
	}
	c := mustCourt(slug)
	if c.mod == nil {
		return "## Not found\nThis court has no folders."
	}
	v := c.mod.folders.Get(beClaimKey(fid))
	if v == nil {
		return "## Not found\nNo folder by that id."
	}
	f := v.(*folder)
	base := "/r/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/kourtv3:" + slug
	var b strings.Builder
	if f.purged {
		b.WriteString("# [purged:" + sanitize.InlineText(f.code) + "]\n\n")
		b.WriteString("_This heading was purged by the global DAO. Its name and " +
			"description were erased, not hidden._\n\n")
		b.WriteString("[← " + courtNameFor(c) + "](" + base + ")\n")
		return b.String()
	}
	b.WriteString("# " + sanitize.InlineText(f.name) + "\n\n")
	b.WriteString("[← " + courtNameFor(c) + "](" + base + ")")
	for up, n := f.parent, 0; up != 0 && n <= maxFolders; n++ {
		pv := c.mod.folders.Get(beClaimKey(up))
		if pv == nil {
			break
		}
		pf := pv.(*folder)
		b.WriteString(" · [" + sanitize.InlineText(pf.name) + "](" + base +
			"/folder/" + strconv.FormatUint(pf.id, 10) + ")")
		up = pf.parent
	}
	b.WriteString("\n\n")
	if f.retired {
		b.WriteString("> This heading was retired by a moderator. It is kept so " +
			"links to it still resolve.\n\n")
	}
	if f.bornOf != 0 {
		b.WriteString("> The court voted this heading into existence: [claim #" +
			strconv.FormatUint(f.bornOf, 10) + "](" + base + "/" +
			strconv.FormatUint(f.bornOf, 10) + ") settled YES, and carrying it was " +
			"a second act anyone could take.\n\n")
	}
	if f.desc != "" {
		b.WriteString(sanitize.Block(f.desc) + "\n")
	}
	kids := 0
	for _, k := range c.mod.folderRows() {
		if k.parent != f.id || k.retired || k.purged {
			continue
		}
		if kids == 0 {
			b.WriteString("## Under this heading\n\n")
		}
		kids++
		b.WriteString("- [" + sanitize.InlineText(k.name) + "](" + base + "/folder/" +
			strconv.FormatUint(k.id, 10) + ")\n")
	}
	if kids > 0 {
		b.WriteString("\n")
	}
	b.WriteString("## Claims filed here\n\n")
	filed := 0
	for _, id := range f.items {
		if id == 0 || id > c.nextID {
			continue
		}
		cs := mustClaim(c, id)
		filed++
		b.WriteString("- [" + claimTitleFor(c, cs) + "](" + base + "/" +
			strconv.FormatUint(id, 10) + ") — " + claimStatus(cs) + "\n")
	}
	if filed == 0 {
		b.WriteString("_Nothing filed here yet._\n")
	}
	b.WriteString("\n_A folder curates and can never bury: every claim above is " +
		"also on the court's own newest-first list, and nothing is reachable only " +
		"from here._\n\n")
	b.WriteString(helpLink + "\n")
	return b.String()
}

session.gno

package kourtv3
func SettleUndisputed(cur realm, courtSlug string, claimID uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if cs.frozenAt == 0 {
		panic("kourtv3: there is no answer to settle")
	}
	if cs.disputeOpen || cs.round > 0 {
		panic("kourtv3: this claim was disputed; it settles by vote")
	}
	if cs.verdictAt != 0 {
		panic("kourtv3: already settled")
	}
	if passed, known := pastDeadline(cs.answeredAtTime, settleSecs); (known && !passed) ||
		(!known && heightNow() < cs.answerHeight+settleDelay) {
		panic("kourtv3: the answer has not aged the 72h settlement minimum")
	}
	touch(c)
	cs.verdictAt = heightNow()
	cs.verdictAtTime = nowTime()
	cs.route = "undisputed"
	trimClaimHistory(c, cs, uint32(cs.frozenAt/epochBlocks)+1)
	cs.provisional = cs.answer
	if cs.answerBond > 0 {
		settleAnswerBond(c, cs)
	}
	releasePriority(c, cs.answerer, claimID)
}
func WithdrawStake(cur realm, courtSlug string, claimID uint64, side int) int64 {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	mustSide(side)
	if cs.verdictAt == 0 && !(cs.provisional >= 0 && side != int(cs.provisional)) {
		panic("kourtv3: no verdict yet — unstake freely before an answer, withdraw after the verdict")
	}
	touch(c)
	advancePools(c, cs)
	p := getPos(c, cs, who, side)
	if p.stake <= 0 {
		panic("kourtv3: nothing staked on that side")
	}
	accrue(c, cs, p, side)
	amount := p.stake
	p.stake = 0
	if side == sideYES {
		cs.yesStake -= amount
	} else {
		cs.noStake -= amount
	}
	releaseStake(c, who, amount)
	return amount
}
func Settled(courtSlug string, claimID uint64) bool {
	return mustClaim(mustCourt(courtSlug), claimID).verdictAt != 0
}
func Verdict(courtSlug string, claimID uint64) int {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.verdictAt == 0 {
		panic("kourtv3: no verdict yet")
	}
	if cs.provClose {
		panic("kourtv3: closed without a decision (three failed dispute rounds)")
	}
	return int(cs.provisional)
}
func VerdictRoute(courtSlug string, claimID uint64) string {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.verdictAt == 0 {
		panic("kourtv3: no verdict yet")
	}
	return cs.route
}
func SettleDeadline(courtSlug string, claimID uint64) int64 {
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if cs.frozenAt == 0 {
		return 0
	}
	return cs.answerHeight + settleDelay
}

sitelink.gno

package kourtv3
import (
	"chain"
	"strconv"
	"strings"
)
const maxSiteDomainLen = 100
var siteDomain string
func siteDomainFault(d string) string {
	if len(d) < 4 || len(d) > maxSiteDomainLen {
		return "a site domain is 4..100 characters"
	}
	if !strings.Contains(d, ".") {
		return "a site domain needs a dot — it is a hostname, not a word"
	}
	if d[0] == '.' || d[0] == '-' || d[len(d)-1] == '.' || d[len(d)-1] == '-' {
		return "a site domain may not begin or end with a dot or a hyphen"
	}
	for i := 0; i < len(d); i++ {
		c := d[i]
		ok := (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-'
		if !ok {
			return "a site domain is lowercase letters, digits, dots and " +
				"hyphens only — no scheme, no path, no port"
		}
	}
	if strings.Contains(d, "..") {
		return "a site domain may not contain an empty label"
	}
	return ""
}
func mustSiteDomain(d string) {
	if fault := siteDomainFault(d); fault != "" {
		panic("kourtv3: " + fault)
	}
}
func SetSiteDomain(cur realm, domain string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin sets the site domain")
	}
	mustSiteDomain(domain)
	siteDomain = domain
	chain.Emit(globalActEvent,
		"court", "*",
		"claim", "0",
		"act", "set-site-domain:"+domain,
		"by", cur.Previous().Address().String(),
		"height", eventHeight(),
	)
}
func ClearSiteDomain(cur realm) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin clears the site domain")
	}
	if siteDomain == "" {
		panic("kourtv3: no site domain is set")
	}
	siteDomain = ""
	chain.Emit(globalActEvent,
		"court", "*",
		"claim", "0",
		"act", "clear-site-domain",
		"by", cur.Previous().Address().String(),
		"height", eventHeight(),
	)
}
func SiteDomain() string { return siteDomain }
func sitePath(path string) string {
	parts := strings.SplitN(path, "/", 4)
	if path == "" || parts[0] == "" {
		return "#/"
	}
	if len(parts) == 1 {
		if parts[0] == helpPath {
			return "#/"
		}
		if parts[0] == adminParamsPath {
			return "#/params"
		}
		return "#/c/" + parts[0]
	}
	switch parts[1] {
	case "me":
		return "#/me"
	case "mod":
		return "#/c/" + parts[0]
	}
	if _, err := strconv.ParseUint(parts[1], 10, 64); err != nil {
		return "#/c/" + parts[0]
	}
	return "#/c/" + parts[0] + "/" + parts[1]
}
func withSiteBanner(body, path string) string {
	bar := siteBanner(path)
	if bar == "" {
		return body
	}
	if !strings.HasPrefix(body, "# ") {
		return bar + body
	}
	i := strings.Index(body, "\n")
	if i < 0 {
		return body + "\n\n" + bar
	}
	return body[:i+1] + "\n" + bar + strings.TrimLeft(body[i+1:], "\n")
}
func siteBanner(path string) string {
	if siteDomain == "" || siteDomainFault(siteDomain) != "" {
		return ""
	}
	return "[Read this on " + siteDomain + " →](https://" + siteDomain + "/" +
		sitePath(path) + ")\n\n"
}

stake.gno

package kourtv3
import (
	"math/bits"
	"math/overflow"
)
const r0WeeklyBps = int64(25)
const (
	stepDownNum = int64(9_933_575)
	stepDownDen = int64(10_000_000)
)
const budgetBpsFPStart = budgetWeeklyBps * 1_000_000
type stakePos struct {
	stake       int64
	convHi      uint64
	convLo      uint64
	lastRateAcc int64
	rawHi, rawLo uint64
	lastRawAt    int64
	bonusPaid    bool
}
func rateBpsFP(c *Court) int64 {
	return 255 * (r0WeeklyBps*1_000_000 + c.dEffBpsFP) / 100
}
func effectiveRateAcc(c *Court, cs *claimState) int64 {
	acc := c.rateAccFP
	if cs.frozenAt != 0 && cs.rateAccAtFreeze < acc {
		acc = cs.rateAccAtFreeze
	}
	return acc
}
func accrue(c *Court, cs *claimState, p *stakePos, side int) {
	acc := effectiveRateAcc(c, cs)
	delta := acc - p.lastRateAcc
	p.lastRateAcc = acc
	if delta > 0 && p.stake > 0 {
		hi, lo := bits.Mul64(uint64(p.stake), uint64(delta))
		p.convHi, p.convLo = add128(p.convHi, p.convLo, hi, lo)
	}
	rh := rawHeight(cs)
	rawDelta := rh - p.lastRawAt
	p.lastRawAt = rh
	if rawDelta > 0 && p.stake > 0 {
		hi, lo := bits.Mul64(uint64(p.stake), uint64(rawDelta))
		p.rawHi, p.rawLo = add128(p.rawHi, p.rawLo, hi, lo)
	}
	_ = side
}
func advancePools(c *Court, cs *claimState) {
	acc := effectiveRateAcc(c, cs)
	rh := rawHeight(cs)
	if d := acc - cs.yesLastAcc; d > 0 && cs.yesStake > 0 {
		hi, lo := bits.Mul64(uint64(cs.yesStake), uint64(d))
		cs.yesConvHi, cs.yesConvLo = add128(cs.yesConvHi, cs.yesConvLo, hi, lo)
	}
	if d := acc - cs.noLastAcc; d > 0 && cs.noStake > 0 {
		hi, lo := bits.Mul64(uint64(cs.noStake), uint64(d))
		cs.noConvHi, cs.noConvLo = add128(cs.noConvHi, cs.noConvLo, hi, lo)
	}
	if d := rh - cs.yesLastRawAt; d > 0 && cs.yesStake > 0 {
		hi, lo := bits.Mul64(uint64(cs.yesStake), uint64(d))
		cs.yesRawHi, cs.yesRawLo = add128(cs.yesRawHi, cs.yesRawLo, hi, lo)
	}
	if d := rh - cs.noLastRawAt; d > 0 && cs.noStake > 0 {
		hi, lo := bits.Mul64(uint64(cs.noStake), uint64(d))
		cs.noRawHi, cs.noRawLo = add128(cs.noRawHi, cs.noRawLo, hi, lo)
	}
	cs.yesLastAcc, cs.noLastAcc = acc, acc
	cs.yesLastRawAt, cs.noLastRawAt = rh, rh
}
func rawHeight(cs *claimState) int64 {
	h := heightNow()
	if cs.frozenAt != 0 && cs.frozenAt < h {
		h = cs.frozenAt
	}
	return h
}
func lifeAvgStake(cs *claimState, now int64) int64 {
	hi, lo := add128(cs.yesRawHi, cs.yesRawLo, cs.noRawHi, cs.noRawLo)
	den := now - cs.openedAt
	if den < 1 {
		den = 1
	}
	return div128(hi, lo, den)
}
func Stake(cur realm, courtSlug string, claimID uint64, side int, amount int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	mustSide(side)
	if amount <= 0 {
		panic("kourtv3: stake must be positive")
	}
	if cs.closed {
		panic("kourtv3: this claim is closed")
	}
	if cs.frozenAt != 0 {
		panic("kourtv3: staking is frozen — this claim has an answer")
	}
	if passed, known := pastDeadline(cs.openedAtTime, blocksToSecs(c.params.stakeOpenDelayBlocks)); (known && !passed) ||
		(!known && heightNow() < cs.openedAt+c.params.stakeOpenDelayBlocks) {
		panic("kourtv3: the polish window is open; staking has not started yet")
	}
	touch(c)
	mustStakable(c, who, amount)
	lockStake(c, who, amount)
	advancePools(c, cs)
	p := getPos(c, cs, who, side)
	accrue(c, cs, p, side)
	p.stake = mustAdd(p.stake, amount)
	if side == sideYES {
		cs.yesStake = mustAdd(cs.yesStake, amount)
	} else {
		cs.noStake = mustAdd(cs.noStake, amount)
	}
	observePools(cs)
	recordPools(c, cs)
}
func Unstake(cur realm, courtSlug string, claimID uint64, side int, amount int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	mustSide(side)
	if amount <= 0 {
		panic("kourtv3: unstake must be positive")
	}
	if cs.frozenAt != 0 {
		panic("kourtv3: stakes are frozen — withdraw at settlement (principal is never withheld)")
	}
	touch(c)
	advancePools(c, cs)
	p := getPos(c, cs, who, side)
	if p.stake < amount {
		panic("kourtv3: unstaking more than is staked")
	}
	accrue(c, cs, p, side)
	if amount > 0 && p.stake > 0 {
		keep := p.stake - amount
		convPer := div128(p.convHi, p.convLo, p.stake)
		nCHi, nCLo := bits.Mul64(uint64(convPer), uint64(keep))
		dCHi, dCLo := sub128(p.convHi, p.convLo, nCHi, nCLo)
		p.convHi, p.convLo = nCHi, nCLo
		if side == sideYES {
			cs.yesConvHi, cs.yesConvLo = sub128(cs.yesConvHi, cs.yesConvLo, dCHi, dCLo)
		} else {
			cs.noConvHi, cs.noConvLo = sub128(cs.noConvHi, cs.noConvLo, dCHi, dCLo)
		}
	}
	p.stake -= amount
	releaseStake(c, who, amount)
	if side == sideYES {
		cs.yesStake -= amount
	} else {
		cs.noStake -= amount
	}
	observePools(cs)
	recordPools(c, cs)
}
func observePools(cs *claimState) {
	h := heightNow()
	cs.oi = cs.oi.Observe(h, mustAdd(cs.yesStake, cs.noStake))
	cs.yes = cs.yes.Observe(h, cs.yesStake)
}
func StakeOf(courtSlug string, claimID uint64, side int, who address) int64 {
	mustSide(side)
	cs := mustClaim(mustCourt(courtSlug), claimID)
	if v := cs.stakers.Get(posKey(who, side)); v != nil {
		return v.(*stakePos).stake
	}
	return 0
}
func ConvictionOf(courtSlug string, claimID uint64, side int, who address) int64 {
	mustSide(side)
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	v := cs.stakers.Get(posKey(who, side))
	if v == nil {
		return 0
	}
	return convPreviewCC(cs, v.(*stakePos), ratePreview(c))
}
func ratePreview(c *Court) int64 {
	acc := c.rateAccFP
	if tail := heightNow() - c.lastAccrual; tail > 0 {
		acc = mustAdd(acc, mustMul(rateBpsFP(c), tail))
	}
	return acc
}
func convPreviewCC(cs *claimState, p *stakePos, acc int64) int64 {
	if cs.frozenAt != 0 && cs.rateAccAtFreeze < acc {
		acc = cs.rateAccAtFreeze
	}
	hi, lo := p.convHi, p.convLo
	if delta := acc - p.lastRateAcc; delta > 0 && p.stake > 0 {
		mh, ml := bits.Mul64(uint64(p.stake), uint64(delta))
		hi, lo = add128(hi, lo, mh, ml)
	}
	return convToCC(hi, lo)
}
func convToCC(hi, lo uint64) int64 {
	den := uint64(periodBlocks) * 10_000 * 1_000_000
	if hi >= den {
		panic("kourtv3: conviction exceeds payable range")
	}
	q, _ := bits.Div64(hi, lo, den)
	return int64(q)
}
func getPos(c *Court, cs *claimState, who address, side int) *stakePos {
	k := posKey(who, side)
	if v := cs.stakers.Get(k); v != nil {
		return v.(*stakePos)
	}
	p := &stakePos{lastRateAcc: c.rateAccFP, lastRawAt: rawHeight(cs)}
	cs.stakers.Set(k, p)
	indexPosition(c, cs.id, who, side)
	return p
}
func posKey(who address, side int) string {
	if side == sideYES {
		return string(who) + "|y"
	}
	return string(who) + "|n"
}
func mustSide(side int) {
	if side != sideYES && side != sideNO {
		panic("kourtv3: side is 0 (YES) or 1 (NO)")
	}
}
func mustMul(a, b int64) int64 {
	m, ok := overflow.Mul64(a, b)
	if !ok {
		panic("kourtv3: multiply overflow")
	}
	return m
}
func mulDiv128(a, b, den int64) int64 {
	if a < 0 || b < 0 || den <= 0 {
		panic("kourtv3: mulDiv128 domain")
	}
	hi, lo := bits.Mul64(uint64(a), uint64(b))
	if hi >= uint64(den) {
		panic("kourtv3: mulDiv128 quotient overflow")
	}
	q, _ := bits.Div64(hi, lo, uint64(den))
	if q > 9223372036854775807 {
		panic("kourtv3: mulDiv128 quotient exceeds int64")
	}
	return int64(q)
}
func mustAdd(a, b int64) int64 {
	s, ok := overflow.Add64(a, b)
	if !ok {
		panic("kourtv3: amount overflow")
	}
	return s
}
func sub128(aHi, aLo, bHi, bLo uint64) (hi, lo uint64) {
	if aHi < bHi || (aHi == bHi && aLo < bLo) {
		panic("kourtv3: 128-bit conviction underflow")
	}
	lo = aLo - bLo
	hi = aHi - bHi
	if aLo < bLo {
		hi--
	}
	return hi, lo
}
func add128(aHi, aLo, bHi, bLo uint64) (hi, lo uint64) {
	lo = aLo + bLo
	carry := uint64(0)
	if lo < aLo {
		carry = 1
	}
	hi = aHi + bHi + carry
	if hi < aHi || (hi == aHi && carry == 1 && bHi == ^uint64(0)) {
		panic("kourtv3: 128-bit conviction overflow")
	}
	return hi, lo
}

stakeindex.gno

package kourtv3
const stakeIdxPage = 64
const stakeIdxEntry = 9
const stakePageMax = 200
type stakeRow struct {
	packed string
}
func stakeIdxKey(who address, claimID uint64) string {
	return string(who) + beClaimKey(claimID/stakeIdxPage)
}
func sideByte(side int) string {
	if side == sideYES {
		return "y"
	}
	return "n"
}
func stakeIdxMine(pre, k string) bool { return len(k) == len(pre)+8 }
func indexPosition(c *Court, claimID uint64, who address, side int) {
	k := stakeIdxKey(who, claimID)
	entry := beClaimKey(claimID) + sideByte(side)
	if v := c.stakeIdx.Get(k); v != nil {
		r := v.(*stakeRow)
		r.packed += entry
		return
	}
	c.stakeIdx.Set(k, &stakeRow{packed: entry})
}
func stakeIdxWalk(c *Court, who address, fn func(claimID uint64, side int) bool) {
	if c.stakeIdx == nil {
		return
	}
	pre := string(who)
	c.stakeIdx.Iterate(pre, pre+"\xff", func(k string, v any) bool {
		if !stakeIdxMine(pre, k) {
			return false
		}
		r, ok := v.(*stakeRow)
		if !ok {
			return false
		}
		for i := 0; i+stakeIdxEntry <= len(r.packed); i += stakeIdxEntry {
			side := sideNO
			if r.packed[i+8] == 'y' {
				side = sideYES
			}
			if fn(beClaimID(r.packed[i:i+8]), side) {
				return true
			}
		}
		return false
	})
}
func stakeIdxCount(c *Court, who address) int {
	if c.stakeIdx == nil {
		return 0
	}
	n, pre := 0, string(who)
	c.stakeIdx.Iterate(pre, pre+"\xff", func(k string, v any) bool {
		if !stakeIdxMine(pre, k) {
			return false
		}
		if r, ok := v.(*stakeRow); ok {
			n += len(r.packed) / stakeIdxEntry
		}
		return false
	})
	return n
}
func StakedSize(courtSlug string, who address) int {
	if !who.IsValid() {
		return 0
	}
	return stakeIdxCount(mustCourt(courtSlug), who)
}
func StakedPage(courtSlug string, who address, offset, limit int) string {
	if !who.IsValid() {
		return ""
	}
	if limit <= 0 || limit > stakePageMax {
		limit = stakePageMax
	}
	c := mustCourt(courtSlug)
	acc := ratePreview(c)
	out, seen, sent := "", 0, 0
	stakeIdxWalk(c, who, func(claimID uint64, side int) bool {
		if seen < offset {
			seen++
			return false
		}
		seen++
		var live, conv int64
		if cv := c.claims.Get(beClaimKey(claimID)); cv != nil {
			cs := cv.(*claimState)
			if pv := cs.stakers.Get(posKey(who, side)); pv != nil {
				pos := pv.(*stakePos)
				live = pos.stake
				conv = convPreviewCC(cs, pos, acc)
			}
		}
		out += ";c:" + itoa(int64(claimID)) + ":" + itoa(int64(side)) +
			":" + itoa(live) + ":" + itoa(conv)
		sent++
		return sent >= limit
	})
	if out == "" {
		return ""
	}
	return out[1:]
}

stakeseries.gno

package kourtv3
import (
	"strconv"
	"strings"
	checkpoint "gno.land/p/g1leu8d2vsplhehcfkjg50mwgdpxdkt8tztu95wr/checkpoint/v0"
)
const (
	hourlyKeep = uint32(168)
	trimBudget = 2
	dailyBlocks = int64(17_280)
	seriesRowCap = 400
)
func csKey(id uint64, suffix string) string {
	return "cs:" + strconv.FormatUint(id, 10) + ":" + suffix
}
func ensureCSArch(c *Court) *checkpoint.Archive {
	if c.csArch == nil {
		c.csArch = checkpoint.NewArchive()
	}
	return c.csArch
}
func setIfChanged(a *checkpoint.Archive, s *checkpoint.Series, key string, e uint32, v int64) {
	if v != s.Value() {
		s.SetAt(a, key, e, v)
	}
}
func recordPools(c *Court, cs *claimState) {
	h := heightNow()
	a := ensureCSArch(c)
	hE := uint32(h/epochBlocks) + 1
	dE := uint32(h/dailyBlocks) + 1
	setIfChanged(a, &cs.yesH, csKey(cs.id, "yh"), hE, cs.yesStake)
	setIfChanged(a, &cs.noH, csKey(cs.id, "nh"), hE, cs.noStake)
	setIfChanged(a, &cs.yesD, csKey(cs.id, "yd"), dE, cs.yesStake)
	setIfChanged(a, &cs.noD, csKey(cs.id, "nd"), dE, cs.noStake)
	if hE > cs.histTrimmedTo {
		cs.histTrimmedTo = hE
		trimClaimHistory(c, cs, hE)
	}
}
func trimClaimHistory(c *Court, cs *claimState, hE uint32) {
	if c.csArch == nil || hE <= hourlyKeep+1 {
		return
	}
	keep := hE - hourlyKeep
	c.csArch.Trim(csKey(cs.id, "yh"), keep, trimBudget)
	c.csArch.Trim(csKey(cs.id, "nh"), keep, trimBudget)
}
type histPoint struct {
	e uint32
	v int64
}
func collectSeriesKeyed(a *checkpoint.Archive, s *checkpoint.Series, key string) ([]histPoint, bool) {
	pts := []histPoint{}
	more := false
	if a != nil && key != "" {
		a.WalkDesc(key, func(e uint32, v int64) bool {
			if len(pts) >= seriesRowCap {
				more = true
				return true
			}
			pts = append(pts, histPoint{e, v})
			return false
		})
	}
	for i, j := 0, len(pts)-1; i < j; i, j = i+1, j-1 {
		pts[i], pts[j] = pts[j], pts[i]
	}
	if e1, pv := s.Prev(); e1 != 0 {
		pts = append(pts, histPoint{e1, pv})
	}
	if e0 := s.Since(); e0 != 0 {
		pts = append(pts, histPoint{e0, s.Value()})
	}
	return pts, more
}
func ClaimSeries(courtSlug string, claimID uint64, grain string) string {
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	var width int64
	var yS, nS *checkpoint.Series
	var yKey, nKey string
	switch grain {
	case "hourly":
		width = epochBlocks
		yS, nS = &cs.yesH, &cs.noH
		yKey, nKey = csKey(claimID, "yh"), csKey(claimID, "nh")
	case "daily":
		width = dailyBlocks
		yS, nS = &cs.yesD, &cs.noD
		yKey, nKey = csKey(claimID, "yd"), csKey(claimID, "nd")
	default:
		panic(`kourtv3: grain is "hourly" or "daily"`)
	}
	now := uint32(heightNow()/width) + 1
	ys, moreY := collectSeriesKeyed(c.csArch, yS, yKey)
	ns, moreN := collectSeriesKeyed(c.csArch, nS, nKey)
	start := uint32(0)
	if moreY && len(ys) > 0 && ys[0].e > start {
		start = ys[0].e
	}
	if moreN && len(ns) > 0 && ns[0].e > start {
		start = ns[0].e
	}
	more := moreY || moreN
	curY, curN := int64(0), int64(0)
	i, j := 0, 0
	for i < len(ys) && ys[i].e < start {
		curY = ys[i].v
		i++
	}
	for j < len(ns) && ns[j].e < start {
		curN = ns[j].v
		j++
	}
	rows := []string{}
	for i < len(ys) || j < len(ns) {
		var e uint32
		switch {
		case i >= len(ys):
			e = ns[j].e
		case j >= len(ns):
			e = ys[i].e
		case ys[i].e < ns[j].e:
			e = ys[i].e
		default:
			e = ns[j].e
		}
		if i < len(ys) && ys[i].e == e {
			curY = ys[i].v
			i++
		}
		if j < len(ns) && ns[j].e == e {
			curN = ns[j].v
			j++
		}
		rows = append(rows, strconv.FormatUint(uint64(e), 10)+":"+
			strconv.FormatInt(curY, 10)+":"+strconv.FormatInt(curN, 10))
	}
	if len(rows) > seriesRowCap {
		rows = rows[len(rows)-seriesRowCap:]
		more = true
	}
	m := "0"
	if more {
		m = "1"
	}
	return grain + "," + strconv.FormatInt(width, 10) + "," +
		strconv.FormatUint(uint64(now), 10) + "," + m + ";" +
		strings.Join(rows, ",")
}

standing.gno

package kourtv3
import (
	"chain"
	"strconv"
	"strings"
	bptree "gno.land/p/nt/bptree/v0"
)
const (
	standingFlagBps = int64(10_000)
	standingDisputeBps = int64(10_000)
	standingAuthorHighBps = int64(2_000)
	standingConvictionBps = int64(1_000)
	standingUnadjudicatedBps = int64(5_000)
)
type creditRates struct {
	flag, dispute, authorHigh, conviction, unadjudicated int64
}
var creditRatesDefault = creditRates{
	flag:          standingFlagBps,
	dispute:       standingDisputeBps,
	authorHigh:    standingAuthorHighBps,
	conviction:    standingConvictionBps,
	unadjudicated: standingUnadjudicatedBps,
}
func creditRatesFor(c *Court) creditRates {
	if c.creditRates != nil {
		return *c.creditRates
	}
	return creditRatesDefault
}
func mustCreditRates(r creditRates) {
	for _, v := range []int64{r.flag, r.dispute, r.authorHigh, r.conviction, r.unadjudicated} {
		if v < 0 || v > 10_000 {
			panic("kourtv3: a standing rate is 0..10000 bps")
		}
	}
	if r.flag < r.authorHigh || r.dispute < r.authorHigh {
		panic("kourtv3: policing must credit at least as much as authorship")
	}
	if r.authorHigh <= r.conviction {
		panic("kourtv3: authorship must credit more than staking — it is the harder gate")
	}
	if r.unadjudicated <= 0 || r.unadjudicated >= 10_000 {
		panic("kourtv3: the unadjudicated rate must be a real fraction of the adjudicated one")
	}
}
func SetCreditRatesDefault(cur realm, flag, dispute, authorHigh, conviction, unadjudicated int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	d := ensureGlobalDAO()
	if cur.Previous().Address() != d.admin {
		panic("kourtv3: only the global DAO admin sets the default standing rates")
	}
	r := creditRates{flag, dispute, authorHigh, conviction, unadjudicated}
	mustCreditRates(r)
	creditRatesDefault = r
	chain.Emit(globalActEvent,
		"court", "*",
		"claim", "0",
		"act", "set-rates-default:"+creditRatesKey(r),
		"by", cur.Previous().Address().String(),
		"height", eventHeight(),
	)
}
func SetCourtCreditRates(cur realm, courtSlug string, flag, dispute, authorHigh, conviction, unadjudicated int64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireActiveMod(cm, who)
	r := creditRates{flag, dispute, authorHigh, conviction, unadjudicated}
	mustCreditRates(r)
	if fire, _ := approveAction(cm.pending, "setrates:"+creditRatesKey(r), who, "",
		speechM(cm)); !fire {
		return
	}
	c.creditRates = &r
	cm.appendCourtLog(who, "setrates:"+creditRatesKey(r), "")
	emitModAct(c.id, 0, "setrates", who)
}
func creditRatesKey(r creditRates) string {
	return strconv.FormatInt(r.flag, 10) + ":" + strconv.FormatInt(r.dispute, 10) +
		":" + strconv.FormatInt(r.authorHigh, 10) + ":" +
		strconv.FormatInt(r.conviction, 10) + ":" +
		strconv.FormatInt(r.unadjudicated, 10)
}
func ClearCourtCreditRates(cur realm, courtSlug string) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	cm := ensureMod(c)
	requireMod(cm, who)
	if c.creditRates == nil {
		panic("kourtv3: this court has no standing-rate override")
	}
	if fire, _ := approveAction(cm.pending, "clearrates:"+c.id, who, "",
		speechM(cm)); !fire {
		return
	}
	c.creditRates = nil
	cm.appendCourtLog(who, "clearrates", "")
	emitModAct(c.id, 0, "clearrates", who)
}
func CreditRates(courtSlug string) string {
	c := mustCourt(courtSlug)
	r := creditRatesFor(c)
	inherited := "1"
	if c.creditRates != nil {
		inherited = "0"
	}
	return "flag:" + strconv.FormatInt(r.flag, 10) +
		";dispute:" + strconv.FormatInt(r.dispute, 10) +
		";author:" + strconv.FormatInt(r.authorHigh, 10) +
		";conviction:" + strconv.FormatInt(r.conviction, 10) +
		";unadjudicated:" + strconv.FormatInt(r.unadjudicated, 10) +
		";inherited:" + inherited
}
var standingCats = [standingCatN]string{"flag", "dispute", "author", "conviction"}
const (
	standingCatFlag = iota
	standingCatDispute
	standingCatAuthor
	standingCatConv
	standingCatN
)
type standingRow struct {
	score int64
	highWater int64
	passHeld bool
	tokens     int64
	lastRefill int64
	frozenUntil     int64
	frozenUntilTime int64
	frozenEpoch     int64
	frozenGapUntil     int64
	frozenGapUntilTime int64
	from [standingCatN]int64
}
func getStanding(c *Court, who address) *standingRow {
	if c.standings == nil {
		c.standings = bptree.NewBPTree32()
	}
	if v := c.standings.Get(string(who)); v != nil {
		return v.(*standingRow)
	}
	r := &standingRow{}
	c.standings.Set(string(who), r)
	return r
}
func lookupStanding(c *Court, who address) *standingRow {
	if c.standings == nil {
		return nil
	}
	if v := c.standings.Get(string(who)); v != nil {
		return v.(*standingRow)
	}
	return nil
}
func creditStanding(c *Court, who address, amount int64, cat int) {
	if amount <= 0 || who == "" || cat < 0 || cat >= standingCatN {
		return
	}
	r := getStanding(c, who)
	r.score = satAdd(r.score, amount)
	r.from[cat] = satAdd(r.from[cat], amount)
	if r.score > r.highWater {
		r.highWater = r.score
	}
}
func satAdd(a, b int64) int64 {
	const maxInt64 = int64(9223372036854775807)
	if b > 0 && a > maxInt64-b {
		return maxInt64
	}
	return a + b
}
func scaleBps(base, bps int64) int64 {
	if base <= 0 || bps <= 0 {
		return 0
	}
	if bps > 10_000 {
		bps = 10_000
	}
	return mulDiv128(base, bps, 10_000)
}
func creditDisputeResolved(c *Court, cs *claimState) {
	if cs.decidedRounds <= 0 {
		return
	}
	if cs.provisional != cs.answer {
		creditStanding(c, cs.overturnBy, scaleBps(cs.overturnBond, creditRatesFor(c).dispute), standingCatDispute)
		return
	}
	if cs.credEligible {
		creditStanding(c, cs.answerer, scaleBps(cs.answerBond0, creditRatesFor(c).dispute), standingCatDispute)
	}
}
func creditWinConviction(c *Court, cs *claimState, who address, p *stakePos) {
	r := creditRatesFor(c)
	bps := r.conviction
	if !adjudicated(cs) {
		bps = bps * r.unadjudicated / 10_000
	}
	creditStanding(c, who, scaleBps(timeAvgStake(cs, p.rawHi, p.rawLo), bps), standingCatConv)
}
func adjudicated(cs *claimState) bool { return cs.decidedPID != 0 }
func Standing(courtSlug string, who address) int64 {
	if r := lookupStanding(mustCourt(courtSlug), who); r != nil {
		return r.score
	}
	return 0
}
func StandingBreakdown(courtSlug string, who address) string {
	var row standingRow
	if r := lookupStanding(mustCourt(courtSlug), who); r != nil {
		row = *r
	}
	var b strings.Builder
	b.WriteString("score:" + strconv.FormatInt(row.score, 10))
	b.WriteString(";highwater:" + strconv.FormatInt(row.highWater, 10))
	for i, name := range standingCats {
		b.WriteString(";" + name + ":" + strconv.FormatInt(row.from[i], 10))
	}
	return b.String()
}

strips.gno

package kourtv3
import bptree "gno.land/p/nt/bptree/v0"
const stripActorCap = 5
type stripRow struct {
	slug    string
	claimID uint64
}
var globalStripIdx = bptree.NewBPTree32()
func beHeightKey(h int64) string {
	if h < 0 {
		h = 0
	}
	return beClaimKey(uint64(h))
}
func stripDeadline(cs *claimState) int64 { return cs.answerHeight + settleDelay }
func stripKey(cs *claimState) string {
	return beHeightKey(stripDeadline(cs)) + beClaimKey(cs.id)
}
func globalStripKey(slug string, cs *claimState) string {
	return beHeightKey(stripDeadline(cs)) + slug + beClaimKey(cs.id)
}
func pendingKey(cs *claimState) string {
	return beHeightKey(cs.openedAt) + beClaimKey(cs.id)
}
func stripEnter(c *Court, cs *claimState) {
	if cs.inStrip {
		return
	}
	if c.stripIdx == nil {
		c.stripIdx = bptree.NewBPTree32()
	}
	c.stripIdx.Set(stripKey(cs), cs.id)
	globalStripIdx.Set(globalStripKey(c.id, cs), &stripRow{slug: c.id, claimID: cs.id})
	cs.inStrip = true
}
func stripExit(c *Court, cs *claimState) {
	if !cs.inStrip {
		return
	}
	if c.stripIdx != nil {
		c.stripIdx.Remove(stripKey(cs))
	}
	globalStripIdx.Remove(globalStripKey(c.id, cs))
	cs.inStrip = false
}
func pendingEnter(c *Court, cs *claimState) {
	if cs.inPending {
		return
	}
	if c.pendingIdx == nil {
		c.pendingIdx = bptree.NewBPTree32()
	}
	c.pendingIdx.Set(pendingKey(cs), cs.id)
	cs.inPending = true
}
func pendingExit(c *Court, cs *claimState) {
	if !cs.inPending {
		return
	}
	if c.pendingIdx != nil {
		c.pendingIdx.Remove(pendingKey(cs))
	}
	cs.inPending = false
}
func stripPageIDs(c *Court, offset, limit int) []uint64 {
	out := []uint64{}
	if c.stripIdx == nil || limit <= 0 {
		return out
	}
	capBinds := c.stripIdx.Size() > renderPageSize
	perAnswerer := map[string]int{}
	perAuthor := map[string]int{}
	skipped := 0
	c.stripIdx.Iterate("", "", func(_ string, v any) bool {
		id, ok := v.(uint64)
		if !ok {
			return false
		}
		cv := c.claims.Get(beClaimKey(id))
		if cv == nil {
			return false
		}
		cs := cv.(*claimState)
		if capBinds && !cs.seeded {
			a := cs.answerer.String()
			b := cs.author.String()
			if perAnswerer[a] >= stripActorCap || perAuthor[b] >= stripActorCap {
				return false
			}
			perAnswerer[a]++
			perAuthor[b]++
		}
		if skipped < offset {
			skipped++
			return false
		}
		out = append(out, id)
		return len(out) >= limit
	})
	return out
}
func StripPage(courtSlug string, offset, limit int) []uint64 {
	return stripPageIDs(mustCourt(courtSlug), offset, limit)
}
func StripSize(courtSlug string) int {
	c := mustCourt(courtSlug)
	if c.stripIdx == nil {
		return 0
	}
	return c.stripIdx.Size()
}
func PendingPage(courtSlug string, offset, limit int) []uint64 {
	out := []uint64{}
	c := mustCourt(courtSlug)
	if c.pendingIdx == nil || limit <= 0 {
		return out
	}
	c.pendingIdx.IterateByOffset(offset, limit, func(_ string, v any) bool {
		if id, ok := v.(uint64); ok {
			out = append(out, id)
		}
		return false
	})
	return out
}
func PendingSize(courtSlug string) int {
	c := mustCourt(courtSlug)
	if c.pendingIdx == nil {
		return 0
	}
	return c.pendingIdx.Size()
}
func DirectoryStripPage(offset, limit int) ([]string, []uint64) {
	slugs := []string{}
	ids := []uint64{}
	if limit <= 0 {
		return slugs, ids
	}
	capBinds := globalStripIdx.Size() > renderPageSize
	perCourt := map[string]int{}
	skipped := 0
	globalStripIdx.Iterate("", "", func(_ string, v any) bool {
		r, ok := v.(*stripRow)
		if !ok {
			return false
		}
		if capBinds {
			if perCourt[r.slug] >= stripActorCap {
				return false
			}
			perCourt[r.slug]++
		}
		if skipped < offset {
			skipped++
			return false
		}
		slugs = append(slugs, r.slug)
		ids = append(ids, r.claimID)
		return len(slugs) >= limit
	})
	return slugs, ids
}
func DirectoryStripSize() int { return globalStripIdx.Size() }
func OnStrip(courtSlug string, claimID uint64) bool {
	return mustClaim(mustCourt(courtSlug), claimID).inStrip
}
func OnPending(courtSlug string, claimID uint64) bool {
	return mustClaim(mustCourt(courtSlug), claimID).inPending
}

supersede.gno

package kourtv3
import (
	"strconv"
	"strings"
	bptree "gno.land/p/nt/bptree/v0"
)
const (
	maxSupIn = 8
	maxSupInPerAuthor = 2
)
type supEdge struct {
	to     uint64
	author address
	at     int64
}
func ensureSup(c *Court) {
	if c.supOf == nil {
		c.supOf = bptree.NewBPTree32()
	}
	if c.supBy == nil {
		c.supBy = bptree.NewBPTree32()
	}
}
func supersedeOrdered(from, to *claimState) bool {
	if from.openedAtTime != 0 && to.openedAtTime != 0 {
		return from.openedAtTime >= to.openedAtTime+deadClaimSecs
	}
	return from.openedAt >= to.openedAt+deadClaimTimeout
}
func SupersedeClaim(cur realm, courtSlug string, from, to uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	if from == to {
		panic("kourtv3: a claim cannot supersede itself")
	}
	f := mustClaim(c, from)
	t := mustClaim(c, to)
	if f.author != who {
		cm := ensureMod(c)
		if !cm.members.Has(who.String()) {
			panic("kourtv3: only the re-filing claim's author or a court moderator may record it")
		}
		requireActiveMod(cm, who)
	}
	if !t.closed {
		panic("kourtv3: only a claim that died unanswered can be superseded")
	}
	if !supersedeOrdered(f, t) {
		panic("kourtv3: a re-filing must come after the claim it re-files could have died")
	}
	ensureSup(c)
	if c.supOf.Get(beClaimKey(from)) != nil {
		panic("kourtv3: that claim already re-files one; remove that edge first")
	}
	inN, mine := 0, 0
	p := beClaimKey(to)
	c.supBy.Iterate(p, "", func(key string, v any) bool {
		if !strings.HasPrefix(key, p) {
			return true
		}
		inN++
		if e, ok := v.(*supEdge); ok && e.author == who {
			mine++
		}
		return false
	})
	if inN >= maxSupIn {
		panic("kourtv3: that claim has already been re-filed " + strconv.Itoa(maxSupIn) + " times")
	}
	if mine >= maxSupInPerAuthor {
		panic("kourtv3: you already record " + strconv.Itoa(maxSupInPerAuthor) +
			" re-filings of that claim")
	}
	e := &supEdge{to: to, author: who, at: heightNow()}
	c.supOf.Set(beClaimKey(from), e)
	c.supBy.Set(beClaimKey(to)+beClaimKey(from), e)
}
func RemoveSupersede(cur realm, courtSlug string, from uint64) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	who := cur.Previous().Address()
	c := mustCourt(courtSlug)
	if c.supOf == nil {
		panic("kourtv3: that claim re-files nothing")
	}
	v := c.supOf.Get(beClaimKey(from))
	if v == nil {
		panic("kourtv3: that claim re-files nothing")
	}
	e := v.(*supEdge)
	requireEdgeRemover(c, e.author, who)
	c.supOf.Remove(beClaimKey(from))
	c.supBy.Remove(beClaimKey(e.to) + beClaimKey(from))
}
func ClaimSupersedes(courtSlug string, claimID uint64) string {
	c := mustCourt(courtSlug)
	mustClaim(c, claimID)
	var b strings.Builder
	b.WriteString("of:")
	if c.supOf != nil {
		if v := c.supOf.Get(beClaimKey(claimID)); v != nil {
			e := v.(*supEdge)
			if !assocTextGone(c, e.to) {
				b.WriteString(strconv.FormatUint(e.to, 10))
			}
		}
	}
	b.WriteString(";by:")
	if c.supBy != nil {
		p := beClaimKey(claimID)
		n := 0
		c.supBy.Iterate(p, "", func(key string, v any) bool {
			if !strings.HasPrefix(key, p) {
				return true
			}
			other := claimIDFromKey(key[8:])
			if assocTextGone(c, other) {
				return false
			}
			if n > 0 {
				b.WriteString(",")
			}
			b.WriteString(strconv.FormatUint(other, 10))
			n++
			return false
		})
	}
	return b.String()
}

supplyseries.gno

package kourtv3
import (
	"strconv"
	"strings"
)
const (
	burnSeriesKey  = "burn"
	priceSeriesKey = "price"
)
func recordPrice(c *Court) {
	setIfChanged(ensureCSArch(c), &c.priceH, priceSeriesKey,
		uint32(heightNow()/epochBlocks)+1, c.crv.Price(c.minted))
}
func recordBurn(c *Court) {
	setIfChanged(ensureCSArch(c), &c.burnH, burnSeriesKey,
		uint32(heightNow()/epochBlocks)+1, c.burnedGNOT)
}
func formatSeries(width int64, now uint32, pts []histPoint, more bool) string {
	rows := make([]string, 0, len(pts))
	for _, p := range pts {
		rows = append(rows, strconv.FormatUint(uint64(p.e), 10)+":"+
			strconv.FormatInt(p.v, 10))
	}
	m := "0"
	if more {
		m = "1"
	}
	return strconv.FormatInt(width, 10) + "," +
		strconv.FormatUint(uint64(now), 10) + "," + m + ";" +
		strings.Join(rows, ",")
}
func SupplySeries(courtSlug string) string {
	c := mustCourt(courtSlug)
	pts := []histPoint{}
	more := false
	c.coin.WalkSupply(func(e uint32, v int64) bool {
		if len(pts) >= seriesRowCap {
			more = true
			return true
		}
		pts = append(pts, histPoint{e, v})
		return false
	})
	for i, j := 0, len(pts)-1; i < j; i, j = i+1, j-1 {
		pts[i], pts[j] = pts[j], pts[i]
	}
	return formatSeries(c.coin.EpochBlocks(), c.coin.Epoch(), pts, more)
}
func BurnSeries(courtSlug string) string {
	c := mustCourt(courtSlug)
	pts, more := collectSeriesKeyed(c.csArch, &c.burnH, burnSeriesKey)
	return formatSeries(epochBlocks, uint32(heightNow()/epochBlocks)+1, pts, more)
}
func PriceSeries(courtSlug string) string {
	c := mustCourt(courtSlug)
	pts, more := collectSeriesKeyed(c.csArch, &c.priceH, priceSeriesKey)
	return formatSeries(epochBlocks, uint32(heightNow()/epochBlocks)+1, pts, more)
}

testclock.gno

package kourtv3
import (
	"time"
	runtime "chain/runtime"
	unsafe "chain/runtime/unsafe"
)
const (
	maxAdvanceStep  = int64(10 * 365 * 86400)
	maxAdvanceTotal = int64(100 * 365 * 86400)
	maxHeightStep  = 2 * periodBlocks
	maxHeightTotal = 10 * periodBlocks
	maxBase = int64(4102444800)
)
var (
	tcDeployer address
	tcArmed    bool
	tcSealed   bool
	tcSkew     int64
	tcBase     int64
	tcFloor    int64
	tcEverArmed bool
	tcPeakSkew  int64
	tcHeightSkew int64
	tcHeightPeak int64
	tcHeightBase  int64
	tcHeightFloor int64
)
func init() { tcDeployer = unsafe.OriginCaller() }
func mustDeployer(cur realm) {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	if cur.Previous().Address() != tcDeployer {
		panic("kourtv3: only the deployer may drive the test clock")
	}
}
func EnableTestClock(cur realm) {
	mustDeployer(cur)
	if tcSealed {
		panic("kourtv3: the test clock is sealed; this realm is not a test chain")
	}
	if tcArmed {
		panic("kourtv3: the test clock is already armed")
	}
	if CourtCount() > 1 {
		panic("kourtv3: this realm already has courts; the test clock cannot be armed")
	}
	m := mustCourt(metaSlug)
	if m.nextID > 1 || m.coin.TotalSupply() > 0 {
		panic("kourtv3: this realm has been used; the test clock cannot be armed")
	}
	tcArmed = true
	tcEverArmed = true
	tcBase = time.Now().Unix()
	if tcBase > maxBase {
		panic("kourtv3: this chain's own clock reads past 2100; check its genesis time")
	}
	tcFloor = tcBase
	tcHeightBase = runtime.ChainHeight()
	tcHeightFloor = tcHeightBase
}
func EnableTestClockAt(cur realm, base int64) {
	mustDeployer(cur)
	if base <= 0 {
		panic("kourtv3: the test clock's base must be a positive instant")
	}
	if base > maxBase {
		panic("kourtv3: the test clock's base must be an instant before 2100")
	}
	EnableTestClock(cur)
	tcBase = base
	if base > tcFloor {
		tcFloor = base
	}
}
func AdvanceTestClock(cur realm, secs int64) {
	mustDeployer(cur)
	if !tcArmed {
		panic("kourtv3: the test clock is not armed")
	}
	if secs <= 0 || secs > maxAdvanceStep {
		panic("kourtv3: the test clock moves forward, by at most ten years a step")
	}
	if tcSkew > maxAdvanceTotal-secs {
		panic("kourtv3: the test clock has advanced as far as it may")
	}
	tcSkew += secs
	if tcSkew > tcPeakSkew {
		tcPeakSkew = tcSkew
	}
	if n := tcBase + tcSkew; n > tcFloor {
		tcFloor = n
	}
}
func AdvanceTestHeight(cur realm, n int64) {
	mustDeployer(cur)
	if !tcArmed {
		panic("kourtv3: the test clock is not armed")
	}
	if n <= 0 || n > maxHeightStep {
		panic("kourtv3: the test height moves forward, by at most two emission periods a step")
	}
	if tcHeightSkew > maxHeightTotal-n {
		panic("kourtv3: the test height has advanced as far as it may")
	}
	tcHeightSkew += n
	if tcHeightSkew > tcHeightPeak {
		tcHeightPeak = tcHeightSkew
	}
	if h := tcHeightBase + tcHeightSkew; h > tcHeightFloor {
		tcHeightFloor = h
	}
}
func TestHeightSkew() int64 { return tcHeightSkew }
func TestHeightPeakSkew() int64 { return tcHeightPeak }
func SealTestClock(cur realm) {
	mustDeployer(cur)
	if !tcArmed {
		panic("kourtv3: the test clock was never armed; there is nothing to seal")
	}
	sealTestClock()
}
func sealTestClock() {
	tcSealed = true
	tcArmed = false
	tcSkew = 0
	tcBase = 0
	tcHeightSkew = 0
}
func TestClockActive() bool { return tcArmed }
func TestClockFabricated() bool { return tcEverArmed }
func TestClockSkew() int64 { return tcSkew }
func TestClockPeakSkew() int64 { return tcPeakSkew }
func tcNow() int64 {
	var n int64
	if tcArmed {
		n = tcBase + tcSkew
	} else {
		n = time.Now().Unix()
		if n < tcFloor {
			n = tcFloor
		}
	}
	if n <= 0 {
		panic("kourtv3: the clock read a non-positive instant")
	}
	return n
}

tier.gno

package kourtv3
func tierBpsFor(cs *claimState) int64 {
	if cs.tierRef <= 0 {
		return tierParBps
	}
	v := mulDiv128(cs.xBarFrozen, tierParBps, cs.tierRef)
	if v < tierFloorBps {
		return tierFloorBps
	}
	if v > tierCeilBps {
		return tierCeilBps
	}
	return v
}
func tierRefAt(c *Court) int64 {
	ref := c.xBarAcc / tierEMAN
	if floor := supplyFloor(c, tierRefFloorBps, tierRefDustCC); ref < floor {
		ref = floor
	}
	return ref
}
func observeClaimSize(c *Court, xbar int64) {
	c.xBarAcc = mustAdd(c.xBarAcc, xbar-c.xBarAcc/tierEMAN)
}
func ClaimTierBps(courtSlug string, claimID uint64) int64 {
	return tierBpsFor(mustClaim(mustCourt(courtSlug), claimID))
}
func ClaimTierRef(courtSlug string, claimID uint64) int64 {
	return mustClaim(mustCourt(courtSlug), claimID).tierRef
}
func spamNetBps(cs *claimState) int64 {
	if cs.spamTotalW <= 0 {
		return tierParBps
	}
	net := cs.spamTotalW - mustMul(2, cs.spamW)
	if net <= 0 {
		return 0
	}
	return mulDiv128(net, tierParBps, cs.spamTotalW)
}

votelock.gno

package kourtv3
import "gno.land/p/nt/bptree/v0"
const (
	voteLockDispute  = "d"
	voteLockElection = "e"
)
func voteLockKey(who address, kind string, id, sub uint64) string {
	return string(who) + kind + beClaimKey(id) + beClaimKey(sub)
}
func voteLockParts(who address, key string) (kind string, id, sub uint64, ok bool) {
	tail := key[len(string(who)):]
	if len(tail) != 1+8+8 {
		return "", 0, 0, false
	}
	return tail[0:1], beClaimID(tail[1:9]), beClaimID(tail[9:17]), true
}
func voteLockOpen(c *Court, who address, key string) bool {
	kind, id, sub, ok := voteLockParts(who, key)
	if !ok {
		return false
	}
	switch kind {
	case voteLockDispute:
		v := c.claims.Get(beClaimKey(id))
		if v == nil {
			return false
		}
		cs := v.(*claimState)
		return cs.disputeOpen && cs.proposalID == int64(sub)
	case voteLockElection:
		if c.mod == nil || c.mod.election == nil {
			return false
		}
		e := c.mod.election
		return e.seq == id && !e.resolved
	}
	return false
}
func voteLockedOf(c *Court, who address) int64 {
	if c.voteLocks == nil {
		return 0
	}
	var most int64
	pre := string(who)
	c.voteLocks.Iterate(pre, pre+"\xff", func(k string, v any) bool {
		if w := v.(int64); w > most && voteLockOpen(c, who, k) {
			most = w
		}
		return false
	})
	return most
}
func lockVote(c *Court, who address, kind string, id, sub, amount int64) {
	if amount <= 0 {
		return
	}
	if c.voteLocks == nil {
		c.voteLocks = bptree.NewBPTree32()
	}
	pruneVoteLocks(c, who)
	c.voteLocks.Set(voteLockKey(who, kind, uint64(id), uint64(sub)), amount)
}
func pruneVoteLocks(c *Court, who address) int {
	if c.voteLocks == nil {
		return 0
	}
	var stale []string
	pre := string(who)
	c.voteLocks.Iterate(pre, pre+"\xff", func(k string, _ any) bool {
		if _, _, _, ok := voteLockParts(who, k); !ok {
			return false
		}
		if !voteLockOpen(c, who, k) {
			stale = append(stale, k)
		}
		return false
	})
	for _, k := range stale {
		c.voteLocks.Remove(k)
	}
	return len(stale)
}
func beClaimID(s string) uint64 {
	var v uint64
	for i := 0; i < 8; i++ {
		v = v<<8 | uint64(s[i])
	}
	return v
}
func PruneVoteLocks(cur realm, courtSlug string, who address) int {
	if !cur.IsCurrent() {
		panic(errStaleRealm)
	}
	if !who.IsValid() {
		panic("kourtv3: that is not a valid address")
	}
	return pruneVoteLocks(mustCourt(courtSlug), who)
}
func CommitmentsOf(courtSlug string, who address) string {
	c := mustCourt(courtSlug)
	out := "stake:" + itoa(lockedOf(c, who)) +
		";vote:" + itoa(voteLockedOf(c, who)) +
		";free:" + itoa(disposable(c, who))
	if c.voteLocks == nil {
		return out
	}
	pre := string(who)
	c.voteLocks.Iterate(pre, pre+"\xff", func(k string, v any) bool {
		if !voteLockOpen(c, who, k) {
			return false
		}
		kind, id, sub, ok := voteLockParts(who, k)
		if !ok {
			return false
		}
		out += ";q:" + kind + ":" + itoa(int64(id)) + ":" + itoa(int64(sub)) +
			":" + itoa(v.(int64))
		return false
	})
	return out
}
func VoteLockedOf(courtSlug string, who address) int64 {
	return voteLockedOf(mustCourt(courtSlug), who)
}

voteweight.gno

package kourtv3
func votingWeight(c *Court, who address, at uint32) (w, snapshot int64) {
	snapshot = c.coin.PastVotes(who, at)
	w = snapshot
	if held := c.coin.BalanceOf(who); held < w {
		w = held
	}
	if w < 0 {
		w = 0
	}
	return w, snapshot
}
func voteCap(c *Court, who address) int64 { return c.coin.BalanceOf(who) }
func ClaimVoteWeightOf(courtSlug string, who address, claimID uint64) (verdict, quality int64) {
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	if cs.disputeOpen {
		verdict, _ = votingWeight(c, who, c.gov.EpochOf(cs.proposalID))
	}
	return verdict, quality
}
func ElectionVoteWeightOf(courtSlug string, who address) int64 {
	c := mustCourt(courtSlug)
	if c.mod == nil || c.mod.election == nil || c.mod.election.resolved {
		return 0
	}
	e := c.mod.election
	if prior := e.voters.Get(who.String()); prior != nil {
		return prior.(int64)
	}
	w, _ := votingWeight(c, who, e.epoch)
	return w
}
func VoteWeightWhy(courtSlug string, who address, claimID uint64) (verdict, quality string) {
	c := mustCourt(courtSlug)
	cs := mustClaim(c, claimID)
	verdict = "no verdict vote is open on this claim"
	if cs.disputeOpen {
		verdict = whyWeighed(c, who, c.gov.EpochOf(cs.proposalID))
	}
	quality = "the quality vote no longer exists"
	return verdict, quality
}
func whyWeighed(c *Court, who address, at uint32) string {
	w, snapshot := votingWeight(c, who, at)
	switch {
	case snapshot <= 0:
		return "you had none when this vote started; coin bought since counts in later votes"
	case w <= 0:
		return "you had some when this vote started but have none now, and your say is the smaller of the two"
	case w < snapshot:
		return "limited to what you still hold, which is less than when this vote started"
	}
	return "counted in full"
}