Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

api.gno

package reputation

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

	"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/jsonw/v0"
	"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/trust/v0"
	"gno.land/p/nt/avl/v0"
)

const apiMaxLimit = 50

// renderAPI serves JSON for the web app, under Render("api/..."):
//
//	api/stats                                   totals, parameters, admin
//	api/top?limit=                              leaderboard
//	api/profile/<address>                       one contributor
//	api/records?addr=&kind=work|reviews&page=&limit=   newest first; all records without addr
//	api/record/<id>                             one record
//	api/seeds                                   seed reviewers
func renderAPI(route string, q url.Values) string {
	parts := strings.Split(route, "/")
	switch {
	case route == "api/stats":
		return jsonw.Obj(
			"records", jsonw.Int(int64(records.Size())),
			"contributors", jsonw.Int(int64(leaderboard.Size())),
			"seeds", jsonw.Int(int64(seeds.Size())),
			"admin", jsonw.String(Admin().String()),
			"params", jsonw.Obj(
				"base", jsonw.Int(params.Base),
				"trustThreshold", jsonw.Int(params.TrustThreshold),
				"trustFloorBps", jsonw.Int(params.TrustFloorBps),
				"selfFundedFactorBps", jsonw.Int(params.SelfFundedFactorBps),
			),
			"writers", jsonw.Strings(keys(&writers)),
		)
	case route == "api/top":
		var items []string
		for i, s := range Top(apiLimit(q)) {
			items = append(items, jsonw.Obj(
				"rank", jsonw.Int(int64(i+1)),
				"address", jsonw.String(s.Addr.String()),
				"score", jsonw.Int(s.Score),
				"level", jsonw.String(trust.Level(s.Score)),
				"completed", jsonw.Int(int64(CompletedCount(s.Addr))),
				"reviews", jsonw.Int(int64(ReviewCount(s.Addr))),
				"seed", jsonw.Bool(IsSeed(s.Addr)),
			))
		}
		return jsonw.Obj("items", jsonw.Arr(items))
	case len(parts) == 3 && parts[1] == "profile":
		return apiProfile(address(parts[2]))
	case route == "api/records":
		return apiRecords(q)
	case len(parts) == 3 && parts[1] == "record":
		id, err := strconv.ParseUint(parts[2], 10, 64)
		if err != nil {
			return apiError("invalid id")
		}
		r := getRecord(id)
		if r == nil {
			return apiError("not found")
		}
		return recordJSON(r)
	case route == "api/seeds":
		return jsonw.Obj("items", jsonw.Strings(keys(&seeds)))
	}
	return apiError("unknown endpoint")
}

func apiProfile(addr address) string {
	if !addr.IsValid() {
		return apiError("invalid address")
	}
	p := getProfile(addr)
	var earned []string
	score, first, last := int64(0), jsonw.Null, jsonw.Null
	if p != nil {
		score, first, last = p.Score, jsonw.Time(p.First), jsonw.Time(p.Last)
		if p.earned != nil {
			p.earned.Iterate("", "", func(k string, v any) bool {
				earned = append(earned, jsonw.Obj("denom", jsonw.String(k), "amount", jsonw.Int(v.(int64))))
				return false
			})
		}
	}
	return jsonw.Obj(
		"address", jsonw.String(addr.String()),
		"score", jsonw.Int(score),
		"level", jsonw.String(trust.Level(score)),
		"rank", jsonw.Int(int64(Rank(addr))),
		"seed", jsonw.Bool(IsSeed(addr)),
		"completed", jsonw.Int(int64(CompletedCount(addr))),
		"reviews", jsonw.Int(int64(ReviewCount(addr))),
		"earned", jsonw.Arr(earned),
		"firstAt", first,
		"lastAt", last,
	)
}

func apiRecords(q url.Values) string {
	limit := apiLimit(q)
	page := 1
	if n, err := strconv.Atoi(q.Get("page")); err == nil && n > 0 {
		page = n
	}
	offset := (page - 1) * limit

	var rs []Record
	total := 0
	if a := q.Get("addr"); a != "" {
		addr := address(a)
		if !addr.IsValid() {
			return apiError("invalid address")
		}
		if q.Get("kind") == "reviews" {
			rs = ReviewsOf(addr, offset, limit)
			total = ReviewCount(addr)
		} else {
			rs = RecordsOf(addr, offset, limit)
			total = CompletedCount(addr)
		}
	} else {
		rs = latest(offset, limit)
		total = records.Size()
	}
	items := make([]string, len(rs))
	for i := range rs {
		items[i] = recordJSON(&rs[i])
	}
	return jsonw.Obj("items", jsonw.Arr(items), "more", jsonw.Bool(total > page*limit), "total", jsonw.Int(int64(total)))
}

func recordJSON(r *Record) string {
	return jsonw.Obj(
		"id", jsonw.Uint(r.ID),
		"worker", jsonw.String(r.Worker.String()),
		"poster", jsonw.String(r.Poster.String()),
		"reviewers", jsonw.Addresses(r.Reviewers),
		"reviewerTrustBps", int64s(r.ReviewerTrust),
		"points", jsonw.Int(r.Points),
		"shareBps", jsonw.Int(r.ShareBps),
		"amount", jsonw.Int(r.Amount),
		"denom", jsonw.String(r.Denom),
		"title", jsonw.String(r.Title),
		"link", jsonw.String(r.Link),
		"ref", jsonw.String(r.Ref),
		"source", jsonw.String(r.Source),
		"signedBy", jsonw.String(r.SignedBy.String()),
		"arbitrated", jsonw.Bool(r.Arbitrated),
		"height", jsonw.Int(r.Height),
		"at", jsonw.Time(r.At),
		"voided", jsonw.Bool(r.Voided),
		"voidReason", jsonw.String(r.VoidReason),
	)
}

func int64s(ns []int64) string {
	out := make([]string, len(ns))
	for i, n := range ns {
		out[i] = jsonw.Int(n)
	}
	return jsonw.Arr(out)
}

func keys(t *avl.Tree) []string {
	var out []string
	t.Iterate("", "", func(k string, _ any) bool {
		out = append(out, k)
		return false
	})
	return out
}

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

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

gnomod.toml

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

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

render.gno

package reputation

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

	"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/trust/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
	"gno.land/p/nt/ufmt/v0"
)

const (
	realmURL  = "/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation"
	pageSize  = 20
	boardSize = 25
)

// Render serves the reputation pages:
//
//	""            leaderboard and latest records
//	u/<address>   contributor profile
//	record/<id>   a single record
//	records       every record, newest first (?page=N)
//	seeds         seed reviewers
//	about         scoring rules
func Render(path string) string {
	route, query := splitQuery(path)
	parts := strings.Split(route, "/")
	switch {
	case parts[0] == "api":
		return renderAPI(route, query)
	case route == "":
		return renderHome()
	case len(parts) == 2 && parts[0] == "u":
		return renderProfile(address(parts[1]))
	case len(parts) == 2 && parts[0] == "record":
		id, err := strconv.ParseUint(parts[1], 10, 64)
		if err != nil {
			return notFound()
		}
		return renderRecord(id)
	case route == "records":
		return renderRecords(pageOf(query))
	case route == "seeds":
		return renderSeeds()
	case route == "about":
		return renderAbout()
	}
	return notFound()
}

func renderHome() string {
	var b strings.Builder
	b.WriteString("# Guildhall Reputation\n\n")
	b.WriteString("Reputation earned from paid, reviewed work. Every point traces back to a record, and every record to the people who vouched for it.\n\n")
	b.WriteString(ufmt.Sprintf("**%d** records · **%d** ranked contributors · **%d** seed reviewers · [scoring rules](%s:about) · [all records](%s:records)\n\n",
		records.Size(), leaderboard.Size(), seeds.Size(), realmURL, realmURL))

	b.WriteString("## Leaderboard\n\n")
	top := Top(boardSize)
	if len(top) == 0 {
		b.WriteString("_No reputation has been earned yet. Complete a [bounty](/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounties) to be the first._\n\n")
	} else {
		b.WriteString("| # | Contributor | Score | Level | Work | Reviews |\n|---:|---|---:|---|---:|---:|\n")
		for i, s := range top {
			b.WriteString(ufmt.Sprintf("| %d | %s | %d | %s | %d | %d |\n",
				i+1, userLink(s.Addr), s.Score, trust.Level(s.Score), CompletedCount(s.Addr), ReviewCount(s.Addr)))
		}
		b.WriteString("\n")
	}

	b.WriteString("## Latest records\n\n")
	b.WriteString(recordTable(latest(0, 10)))
	b.WriteString("\n## Use it in your realm\n\n")
	b.WriteString("```go\nimport \"gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation\"\n\nreputation.AssertScore(cur.Previous().Address(), 300)\n```\n")
	return b.String()
}

func renderProfile(addr address) string {
	if !addr.IsValid() {
		return notFound()
	}
	var b strings.Builder
	b.WriteString(ufmt.Sprintf("# %s\n\n", addr.String()))
	p := getProfile(addr)
	if p == nil {
		b.WriteString("_No recorded work or reviews yet._\n\n")
		b.WriteString(ufmt.Sprintf("[Browse open bounties](/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounties?status=open) · [Leaderboard](%s)\n", realmURL))
		return b.String()
	}

	rank := "unranked"
	if r := Rank(addr); r > 0 {
		rank = "#" + strconv.Itoa(r)
	}
	seed := ""
	if IsSeed(addr) {
		seed = " · seed reviewer"
	}
	b.WriteString(ufmt.Sprintf("**%d** points · %s · %s%s\n\n", p.Score, trust.Level(p.Score), rank, seed))
	b.WriteString(ufmt.Sprintf("- Completed work: **%d**\n- Reviews given: **%d**\n", len(p.Records), len(p.Reviews)))
	if p.earned != nil && p.earned.Size() > 0 {
		var parts []string
		p.earned.Iterate("", "", func(k string, v any) bool {
			parts = append(parts, formatAmount(v.(int64), k))
			return false
		})
		b.WriteString("- Earned: " + strings.Join(parts, ", ") + "\n")
	}
	if !p.First.IsZero() {
		b.WriteString("- Active since: " + p.First.Format("2006-01-02") + "\n")
	}
	b.WriteString(ufmt.Sprintf("- Bounties: [%s](/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounties:u/%s)\n\n", "view", addr.String()))

	b.WriteString("## Work\n\n")
	b.WriteString(recordTable(RecordsOf(addr, 0, pageSize)))
	b.WriteString("\n## Reviews\n\n")
	b.WriteString(recordTable(ReviewsOf(addr, 0, pageSize)))
	return b.String()
}

func renderRecord(id uint64) string {
	r := getRecord(id)
	if r == nil {
		return notFound()
	}
	var b strings.Builder
	b.WriteString(ufmt.Sprintf("# Record #%d\n\n", r.ID))
	if r.Voided {
		b.WriteString("> **Voided:** " + sanitize.InlineText(r.VoidReason) + "\n\n")
	}
	b.WriteString("**" + sanitize.InlineText(r.Title) + "**\n\n")
	b.WriteString("| | |\n|---|---|\n")
	b.WriteString("| Worker | " + userLink(r.Worker) + " |\n")
	b.WriteString("| Funded by | " + userLink(r.Poster) + " |\n")
	b.WriteString("| Paid | " + formatAmount(r.Amount, r.Denom) + " |\n")
	if r.ShareBps < trust.MaxBps {
		b.WriteString(ufmt.Sprintf("| Share of milestone | %s |\n", bpsPercent(r.ShareBps)))
	}
	b.WriteString(ufmt.Sprintf("| Points | %d |\n", r.Points))
	if r.Link != "" {
		b.WriteString("| Work | " + linkOrText(r.Link) + " |\n")
	}
	b.WriteString("| Source | " + sourceLink(r) + " |\n")
	b.WriteString("| Released by | " + userLink(r.SignedBy) + " |\n")
	b.WriteString(ufmt.Sprintf("| Block | %d · %s |\n", r.Height, r.At.UTC().Format("2006-01-02 15:04 UTC")))
	if r.Arbitrated {
		b.WriteString("| Settled by | arbitration |\n")
	}

	b.WriteString("\n## Vouched for by\n\n| Reviewer | Trust at approval |\n|---|---:|\n")
	for i, rv := range r.Reviewers {
		t := int64(0)
		if i < len(r.ReviewerTrust) {
			t = r.ReviewerTrust[i]
		}
		b.WriteString("| " + userLink(rv) + " | " + bpsPercent(t) + " |\n")
	}
	return b.String()
}

func renderRecords(page int) string {
	var b strings.Builder
	b.WriteString("# All records\n\n")
	b.WriteString(recordTable(latest((page-1)*pageSize, pageSize)))
	b.WriteString("\n" + pager("records", page, records.Size()))
	return b.String()
}

func renderSeeds() string {
	var b strings.Builder
	b.WriteString("# Seed reviewers\n\n")
	b.WriteString("Seeds carry full trust when they approve work. Everyone else earns trust by completing work that trusted people approved. ")
	b.WriteString(ufmt.Sprintf("Seeds are curated by %s.\n\n", userLink(Admin())))
	if seeds.Size() == 0 {
		b.WriteString("_No seeds yet._\n")
		return b.String()
	}
	seeds.Iterate("", "", func(k string, _ any) bool {
		b.WriteString("- " + userLink(address(k)) + "\n")
		return false
	})
	return b.String()
}

func renderAbout() string {
	p := params
	var b strings.Builder
	b.WriteString("# How reputation is scored\n\n")
	b.WriteString("1. Reputation is only created when escrowed funds are released for finished work. Writing records is restricted to allowlisted realms:\n")
	writers.Iterate("", "", func(k string, _ any) bool {
		b.WriteString("   - [" + k + "](" + strings.TrimPrefix(k, "gno.land") + ")\n")
		return false
	})
	b.WriteString(ufmt.Sprintf("2. A record is worth up to **%d** points, scaled by the average trust of the reviewers who approved it.\n", p.Base))
	b.WriteString(ufmt.Sprintf("3. Seed reviewers carry full trust. Anyone else carries trust in proportion to their own score, reaching full trust at **%d** points.\n", p.TrustThreshold))
	b.WriteString(ufmt.Sprintf("4. Reviewers with no score carry **%s** trust, so a ring of fresh accounts approving each other earns nothing.\n", bpsPercent(p.TrustFloorBps)))
	b.WriteString(ufmt.Sprintf("5. Work funded by the worker themselves is scaled to **%s**. Nobody can vouch for their own work.\n", bpsPercent(p.SelfFundedFactorBps)))
	b.WriteString("6. When a dispute ends in a split, the record's points scale with the share the arbiter awarded.\n")
	b.WriteString("7. Points are fixed when the record is written. The Guildhall admin may void a fraudulent record, which removes its points.\n\n")
	b.WriteString("## Levels\n\n| Score | Level |\n|---:|---|\n| 0 | Newcomer |\n| 1+ | Apprentice |\n| 300+ | Journeyman |\n| 800+ | Artisan |\n| 2000+ | Master |\n| 5000+ | Grandmaster |\n")
	return b.String()
}

func recordTable(rs []Record) string {
	if len(rs) == 0 {
		return "_Nothing here yet._\n"
	}
	var b strings.Builder
	b.WriteString("| # | Work | Worker | Paid | Points |\n|---:|---|---|---:|---:|\n")
	for _, r := range rs {
		title := sanitize.TableCell(r.Title)
		if r.Voided {
			title = "~~" + title + "~~"
		}
		b.WriteString(ufmt.Sprintf("| [%d](%s:record/%d) | %s | %s | %s | %d |\n",
			r.ID, realmURL, r.ID, title, userLink(r.Worker), formatAmount(r.Amount, r.Denom), r.Points))
	}
	return b.String()
}

func latest(offset, limit int) []Record {
	var out []Record
	records.ReverseIterateByOffset(offset, limit, func(_ string, v any) bool {
		out = append(out, copyRecord(v.(*Record)))
		return false
	})
	return out
}

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

func sourceLink(r *Record) string {
	path := strings.TrimPrefix(r.Source, "gno.land")
	if r.Source == BountiesPath && r.Ref != "" {
		id := r.Ref
		if i := strings.Index(id, "/"); i >= 0 {
			id = id[:i]
		}
		return "[bounty " + sanitize.InlineText(r.Ref) + "](" + path + ":" + url.PathEscape(id) + ")"
	}
	return "[" + r.Source + "](" + path + ")"
}

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

func formatAmount(amount int64, denom string) string {
	if denom == "ugnot" {
		return decimal(amount, 6) + " GNOT"
	}
	return strconv.FormatInt(amount, 10) + " " + sanitize.InlineText(denom)
}

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

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

func pager(route string, page, total int) string {
	pages := (total + pageSize - 1) / pageSize
	if pages <= 1 {
		return ""
	}
	var parts []string
	if page > 1 {
		parts = append(parts, ufmt.Sprintf("[← newer](%s:%s?page=%d)", realmURL, route, page-1))
	}
	parts = append(parts, ufmt.Sprintf("page %d of %d", page, pages))
	if page < pages {
		parts = append(parts, ufmt.Sprintf("[older →](%s:%s?page=%d)", realmURL, route, page+1))
	}
	return strings.Join(parts, " · ") + "\n"
}

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

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

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

reputation.gno

// Package reputation is Guildhall's record of completed work.
//
// Every record says that a piece of work was paid for, who did it, who vouched
// for it, how much it paid and where the work lives (a PR, a realm path, a
// proposal). Records can only be written by allowlisted writer realms, the
// Guildhall bounty escrow first among them, and only at the moment escrowed
// funds are released. Each record also keeps the address whose signed
// transaction released the funds.
//
// Scores are derived from those records with the rules in
// gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/trust: a record is worth more when the people who
// approved it are themselves trusted. Any realm can consume the result with a
// single import:
//
//	import "gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation"
//
//	func Vote(cur realm, ...) {
//		reputation.AssertScore(cur.Previous().Address(), 300)
//		...
//	}
package reputation

import (
	"chain"
	"chain/runtime"
	"chain/runtime/unsafe"
	"errors"
	"strconv"
	"time"

	"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/trust/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/ownable/v0"
	"gno.land/p/nt/ufmt/v0"
)

// BountiesPath is the escrow realm allowed to write records at launch.
const BountiesPath = "gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounties"

const (
	maxReviewers = 16
	maxTextLen   = 300
	maxRank      = 1000
)

// entry is what a writer realm submits when work is paid for.
type entry struct {
	Worker     address
	Poster     address
	Reviewers  []address
	ShareBps   int64
	Amount     int64
	Denom      string
	Title      string
	Link       string
	Ref        string
	Arbitrated bool
}

// Record is a stored, immutable account of paid work. Only Voided can change,
// and only by the Guildhall admin.
type Record struct {
	ID            uint64
	Worker        address
	Poster        address
	Reviewers     []address
	ReviewerTrust []int64
	Points        int64
	ShareBps      int64
	Amount        int64
	Denom         string
	Title         string
	Link          string
	Ref           string
	Source        string
	SignedBy      address
	Arbitrated    bool
	Height        int64
	At            time.Time
	Voided        bool
	VoidReason    string
}

// Profile aggregates a contributor's records.
type Profile struct {
	Addr    address
	Score   int64
	Records []uint64
	Reviews []uint64
	First   time.Time
	Last    time.Time
	earned  *avl.Tree // denom -> int64
}

// Standing is a leaderboard entry.
type Standing struct {
	Addr  address
	Score int64
}

var (
	records     avl.Tree // padded id -> *Record
	lastID      uint64
	profiles    avl.Tree // address -> *Profile
	leaderboard avl.Tree // inverted score key -> address
	seeds       avl.Tree // address -> struct{}
	writers     avl.Tree // pkgpath -> struct{}
	params      = trust.DefaultParams()
	admin       *ownable.Ownable
)

// InitialAdmin owns this namespace and is the only key that can deploy here.
// It starts out as the admin; TransferAdmin can hand the role on.
const InitialAdmin address = "g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm"

func init() {
	admin = ownable.NewWithAddress(InitialAdmin)
	writers.Set(BountiesPath, struct{}{})
}

// ---------------------------------------------------------------------------
// Writing

// AddRecord stores a piece of paid work and credits the worker. It may only be
// called by an allowlisted writer realm, at the moment it releases funds.
//
// worker was paid amount of denom for work funded by poster and approved by
// reviewers. shareBps is the fraction of the milestone the worker received
// (10000 unless a dispute split it). title, link and ref describe the work:
// link points at the PR, realm path or proposal, and ref identifies the
// work within the writer realm (for bounties, "<id>/<milestone>").
func AddRecord(cur realm, worker, poster address, reviewers []address, shareBps, amount int64, denom, title, link, ref string, arbitrated bool) uint64 {
	e := entry{
		Worker:     worker,
		Poster:     poster,
		Reviewers:  reviewers,
		ShareBps:   shareBps,
		Amount:     amount,
		Denom:      denom,
		Title:      title,
		Link:       link,
		Ref:        ref,
		Arbitrated: arbitrated,
	}
	src := cur.Previous().PkgPath()
	if src == "" || !writers.Has(src) {
		panic("reputation: " + strconv.Quote(src) + " is not an allowed writer")
	}
	if err := validateEntry(e); err != nil {
		panic(err.Error())
	}

	vouchers := make([]trust.Reviewer, len(e.Reviewers))
	for i, r := range e.Reviewers {
		vouchers[i] = trust.Reviewer{Addr: r, Score: Score(r), Seed: IsSeed(r)}
	}
	res, err := trust.Evaluate(trust.Input{
		Worker:    e.Worker,
		Poster:    e.Poster,
		Reviewers: vouchers,
		ShareBps:  e.ShareBps,
	}, params)
	if err != nil {
		panic(err.Error())
	}

	lastID++
	rec := &Record{
		ID:            lastID,
		Worker:        e.Worker,
		Poster:        e.Poster,
		Reviewers:     append([]address{}, e.Reviewers...),
		ReviewerTrust: res.TrustBps,
		Points:        res.Points,
		ShareBps:      e.ShareBps,
		Amount:        e.Amount,
		Denom:         e.Denom,
		Title:         e.Title,
		Link:          e.Link,
		Ref:           e.Ref,
		Source:        src,
		SignedBy:      unsafe.OriginCaller(),
		Arbitrated:    e.Arbitrated,
		Height:        runtime.ChainHeight(),
		At:            time.Now(),
	}
	records.Set(idKey(rec.ID), rec)

	wp := getOrCreateProfile(e.Worker)
	wp.Records = append(wp.Records, rec.ID)
	addEarned(wp, e.Denom, e.Amount)
	touch(wp, rec.At)
	setScore(wp, wp.Score+rec.Points)

	seen := map[address]bool{}
	for _, r := range e.Reviewers {
		if seen[r] || r == e.Worker {
			continue
		}
		seen[r] = true
		rp := getOrCreateProfile(r)
		rp.Reviews = append(rp.Reviews, rec.ID)
		touch(rp, rec.At)
	}

	chain.Emit("GuildhallRecord",
		"id", strconv.FormatUint(rec.ID, 10),
		"worker", e.Worker.String(),
		"points", strconv.FormatInt(rec.Points, 10),
		"source", src,
		"ref", e.Ref,
	)
	return rec.ID
}

func validateEntry(e entry) error {
	if !e.Worker.IsValid() {
		return errors.New("reputation: invalid worker address")
	}
	if !e.Poster.IsValid() {
		return errors.New("reputation: invalid poster address")
	}
	if len(e.Reviewers) == 0 || len(e.Reviewers) > maxReviewers {
		return errors.New("reputation: a record needs 1..16 reviewers")
	}
	for _, r := range e.Reviewers {
		if !r.IsValid() {
			return errors.New("reputation: invalid reviewer address")
		}
	}
	if e.Amount < 0 {
		return errors.New("reputation: negative amount")
	}
	if len(e.Title) > maxTextLen || len(e.Link) > maxTextLen || len(e.Ref) > maxTextLen || len(e.Denom) > maxTextLen {
		return errors.New("reputation: field too long")
	}
	return nil
}

// ---------------------------------------------------------------------------
// Reading: the API other realms import.

// Score returns addr's current reputation score.
func Score(addr address) int64 {
	p := getProfile(addr)
	if p == nil {
		return 0
	}
	return p.Score
}

// Level returns a display name for addr's score band.
func Level(addr address) string {
	return trust.Level(Score(addr))
}

// HasScore reports whether addr's score is at least min.
func HasScore(addr address, min int64) bool {
	return Score(addr) >= min
}

// AssertScore panics unless addr's score is at least min. It is the one-line
// gate for realms that want reputation-weighted access.
func AssertScore(addr address, min int64) {
	if s := Score(addr); s < min {
		panic(ufmt.Sprintf("guildhall: reputation %d is below the required %d", s, min))
	}
}

// CompletedCount returns how many paid records addr has as a worker.
func CompletedCount(addr address) int {
	p := getProfile(addr)
	if p == nil {
		return 0
	}
	return len(p.Records)
}

// ReviewCount returns how many records addr has vouched for.
func ReviewCount(addr address) int {
	p := getProfile(addr)
	if p == nil {
		return 0
	}
	return len(p.Reviews)
}

// Earned returns the total addr has been paid in denom through records.
func Earned(addr address, denom string) int64 {
	p := getProfile(addr)
	if p == nil || p.earned == nil {
		return 0
	}
	v := p.earned.Get(denom)
	if v == nil {
		return 0
	}
	return v.(int64)
}

// IsSeed reports whether addr is a seed reviewer.
func IsSeed(addr address) bool {
	return seeds.Has(addr.String())
}

// IsWriter reports whether pkgPath may write records.
func IsWriter(pkgPath string) bool {
	return writers.Has(pkgPath)
}

// RecordCount returns the number of records ever written.
func RecordCount() int {
	return records.Size()
}

// ContributorCount returns the number of addresses with a positive score.
func ContributorCount() int {
	return leaderboard.Size()
}

// GetRecord returns a copy of the record with the given id.
func GetRecord(id uint64) (Record, bool) {
	r := getRecord(id)
	if r == nil {
		return Record{}, false
	}
	return copyRecord(r), true
}

// RecordsOf returns up to limit of addr's work records, newest first,
// skipping the first offset.
func RecordsOf(addr address, offset, limit int) []Record {
	p := getProfile(addr)
	if p == nil {
		return nil
	}
	return collect(p.Records, offset, limit)
}

// ReviewsOf returns up to limit of the records addr vouched for, newest first.
func ReviewsOf(addr address, offset, limit int) []Record {
	p := getProfile(addr)
	if p == nil {
		return nil
	}
	return collect(p.Reviews, offset, limit)
}

// Top returns the n highest scores, highest first. Ties are ordered by
// address.
func Top(n int) []Standing {
	var out []Standing
	leaderboard.Iterate("", "", func(_ string, v any) bool {
		addr := v.(address)
		out = append(out, Standing{Addr: addr, Score: Score(addr)})
		return len(out) >= n
	})
	return out
}

// Rank returns addr's 1-based leaderboard position, or 0 if unranked.
func Rank(addr address) int {
	p := getProfile(addr)
	if p == nil || p.Score <= 0 {
		return 0
	}
	key := boardKey(p.Score, addr)
	rank := 0
	leaderboard.Iterate("", key, func(_ string, _ any) bool {
		rank++
		return rank > maxRank
	})
	if rank > maxRank {
		return 0
	}
	return rank + 1
}

// Params returns the scoring parameters in force.
func Params() trust.Params {
	return params
}

// Admin returns the address allowed to curate seeds, writers and parameters.
func Admin() address {
	return admin.Owner()
}

// ---------------------------------------------------------------------------
// Governance

//
// Guildhall governs itself: the admin, and nobody else, curates seeds,
// writers, parameters and voids. No outside realm has authority here. Hand
// the role to a multisig with TransferAdmin to share it.

// AddSeed marks addr as a seed reviewer with full trust.
func AddSeed(cur realm, addr address) {
	assertAdmin(cur)
	addSeed(addr)
}

// RemoveSeed revokes addr's seed status. Existing records keep the points
// they were awarded; only future reviews are affected.
func RemoveSeed(cur realm, addr address) {
	assertAdmin(cur)
	removeSeed(addr)
}

// AddWriter allows another realm to write records.
func AddWriter(cur realm, pkgPath string) {
	assertAdmin(cur)
	addWriter(pkgPath)
}

// RemoveWriter revokes a realm's right to write records.
func RemoveWriter(cur realm, pkgPath string) {
	assertAdmin(cur)
	removeWriter(pkgPath)
}

// SetParams changes the scoring rules for future records.
func SetParams(cur realm, base, trustThreshold, trustFloorBps, selfFundedFactorBps int64) {
	assertAdmin(cur)
	setParams(newParams(base, trustThreshold, trustFloorBps, selfFundedFactorBps))
}

// VoidRecord cancels a fraudulent record and removes its points from the
// worker. Trust the worker lent to others while holding those points is not
// unwound; voiding is for correcting abuse, not rewriting history.
func VoidRecord(cur realm, id uint64, reason string) {
	assertAdmin(cur)
	checkVoid(id, reason)
	voidRecord(id, reason)
}

// TransferAdmin hands the admin key to another address, such as a multisig.
func TransferAdmin(cur realm, newAdmin address) {
	if err := admin.TransferOwnership(0, cur, newAdmin); err != nil {
		panic(err.Error())
	}
}

// RenounceAdmin gives up the admin key for good. Nothing can curate
// reputation afterwards: seeds, writers and parameters are frozen and no
// record can be voided. Prefer TransferAdmin unless that is the intent.
func RenounceAdmin(cur realm) {
	if err := admin.DropOwnership(0, cur); err != nil {
		panic(err.Error())
	}
}

func addSeed(addr address) {
	if !addr.IsValid() {
		panic("reputation: invalid address")
	}
	seeds.Set(addr.String(), struct{}{})
	chain.Emit("GuildhallSeedAdded", "addr", addr.String())
}

func removeSeed(addr address) {
	if _, ok := seeds.Remove(addr.String()); !ok {
		panic("reputation: not a seed")
	}
	chain.Emit("GuildhallSeedRemoved", "addr", addr.String())
}

func addWriter(pkgPath string) {
	if pkgPath == "" {
		panic("reputation: empty pkgpath")
	}
	writers.Set(pkgPath, struct{}{})
	chain.Emit("GuildhallWriterAdded", "pkgpath", pkgPath)
}

func removeWriter(pkgPath string) {
	if _, ok := writers.Remove(pkgPath); !ok {
		panic("reputation: not a writer")
	}
	chain.Emit("GuildhallWriterRemoved", "pkgpath", pkgPath)
}

func newParams(base, trustThreshold, trustFloorBps, selfFundedFactorBps int64) trust.Params {
	p := trust.Params{
		Base:                base,
		TrustThreshold:      trustThreshold,
		TrustFloorBps:       trustFloorBps,
		SelfFundedFactorBps: selfFundedFactorBps,
	}
	if err := p.Validate(); err != nil {
		panic(err.Error())
	}
	return p
}

func setParams(p trust.Params) {
	params = p
	chain.Emit("GuildhallParamsChanged")
}

func checkVoid(id uint64, reason string) {
	r := getRecord(id)
	if r == nil {
		panic("reputation: unknown record")
	}
	if r.Voided {
		panic("reputation: record already voided")
	}
	if reason == "" || len(reason) > maxTextLen {
		panic("reputation: a reason of 1..300 bytes is required")
	}
}

func voidRecord(id uint64, reason string) {
	checkVoid(id, reason)
	r := getRecord(id)
	r.Voided = true
	r.VoidReason = reason
	p := getProfile(r.Worker)
	setScore(p, p.Score-r.Points)
	chain.Emit("GuildhallRecordVoided", "id", strconv.FormatUint(id, 10), "reason", reason)
}

func assertAdmin(cur realm) {
	admin.AssertOwnedBy(cur.Previous().Address())
}

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

func getProfile(addr address) *Profile {
	v := profiles.Get(addr.String())
	if v == nil {
		return nil
	}
	return v.(*Profile)
}

func getOrCreateProfile(addr address) *Profile {
	if p := getProfile(addr); p != nil {
		return p
	}
	p := &Profile{Addr: addr, earned: avl.NewTree()}
	profiles.Set(addr.String(), p)
	return p
}

func getRecord(id uint64) *Record {
	v := records.Get(idKey(id))
	if v == nil {
		return nil
	}
	return v.(*Record)
}

func touch(p *Profile, at time.Time) {
	if p.First.IsZero() {
		p.First = at
	}
	p.Last = at
}

func addEarned(p *Profile, denom string, amount int64) {
	cur := int64(0)
	if v := p.earned.Get(denom); v != nil {
		cur = v.(int64)
	}
	p.earned.Set(denom, cur+amount)
}

func setScore(p *Profile, score int64) {
	if p.Score > 0 {
		leaderboard.Remove(boardKey(p.Score, p.Addr))
	}
	if score < 0 {
		score = 0
	}
	p.Score = score
	if score > 0 {
		leaderboard.Set(boardKey(score, p.Addr), p.Addr)
	}
}

// boardKey sorts higher scores first under avl's ascending iteration.
func boardKey(score int64, addr address) string {
	return pad(9223372036854775807-score, 19) + ":" + addr.String()
}

func idKey(id uint64) string {
	return pad(int64(id), 12)
}

func pad(n int64, width int) string {
	s := strconv.FormatInt(n, 10)
	for len(s) < width {
		s = "0" + s
	}
	return s
}

func collect(ids []uint64, offset, limit int) []Record {
	var out []Record
	if offset < 0 {
		offset = 0
	}
	for i := len(ids) - 1 - offset; i >= 0 && len(out) < limit; i-- {
		if r := getRecord(ids[i]); r != nil {
			out = append(out, copyRecord(r))
		}
	}
	return out
}

func copyRecord(r *Record) Record {
	c := *r
	c.Reviewers = append([]address{}, r.Reviewers...)
	c.ReviewerTrust = append([]int64{}, r.ReviewerTrust...)
	return c
}