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 gauntlet

import (
	"strconv"
	"strings"
	"time"

	"gno.land/p/g188c5k6v0tmfyevfzj962jkajjqt4ddtml8zw0x/gauntlet"
)

// The functions below return JSON for the web app (vm/qeval). They only read.

// StatsJSON returns board totals.
func StatsJSON() string {
	open, escrow := 0, int64(0)
	board.Iterate(func(c *gauntlet.Challenge) bool {
		if c.Status == gauntlet.Open {
			open++
			escrow += c.Pot()
		}
		return false
	})
	return `{"challenges":` + strconv.Itoa(board.Size()) + `,"open":` + strconv.Itoa(open) +
		`,"escrow":` + i64toa(escrow) + `,"paid":` + i64toa(totalPaid) + `,"players":` + strconv.Itoa(profiles.Size()) +
		`,"judges":` + strconv.Itoa(judges.Size()) + `,"now":` + i64toa(time.Now().Unix()) + `}`
}

// ListJSON returns up to limit challenges, newest first, skipping offset.
func ListJSON(offset, limit int) string {
	if limit <= 0 || limit > 50 {
		limit = 50
	}
	var parts []string
	i := 0
	board.Iterate(func(c *gauntlet.Challenge) bool {
		if i >= offset {
			parts = append(parts, summaryJSON(c))
		}
		i++
		return len(parts) >= limit
	})
	return "[" + strings.Join(parts, ",") + "]"
}

func summaryJSON(c *gauntlet.Challenge) string {
	return `{"id":` + itoa(c.ID) + `,"title":` + jstr(c.Title) + `,"status":` + jstr(c.Status.String()) +
		`,"pot":` + i64toa(c.Pot()) + `,"bond":` + i64toa(c.Bond) + `,"deadline":` + i64toa(c.Deadline.Unix()) +
		`,"attempts":` + strconv.Itoa(len(c.Attempts)) + `,"judged":` + strconv.FormatBool(c.Judge != nil) +
		`,"cases":` + strconv.Itoa(len(c.Cases)) + `}`
}

// ChallengeJSON returns one challenge in full, or "null".
func ChallengeJSON(id uint64) string {
	c := board.Get(id)
	if c == nil {
		return "null"
	}
	var b strings.Builder
	b.WriteString(`{"id":` + itoa(c.ID) + `,"title":` + jstr(c.Title) + `,"spec":` + jstr(c.Spec) +
		`,"status":` + jstr(c.Status.String()) + `,"poster":` + jstr(c.Poster.String()) +
		`,"reward":` + i64toa(c.Reward) + `,"pot":` + i64toa(c.Pot()) + `,"bond":` + i64toa(c.Bond) +
		`,"boosts":` + i64toa(c.Boosts) + `,"forfeited":` + i64toa(c.Forfeited) +
		`,"created":` + i64toa(c.Created.Unix()) + `,"deadline":` + i64toa(c.Deadline.Unix()) +
		`,"window":` + i64toa(int64(c.Window/time.Second)) + `,"judge":` + jstr(c.JudgePath) + `,"cases":[`)
	for i, tc := range c.Cases {
		if i > 0 {
			b.WriteString(",")
		}
		b.WriteString(`{"in":` + jstr(tc.In) + `,"want":` + jstr(tc.Want) + `}`)
	}
	b.WriteString(`],"attempts":[`)
	for i, a := range c.Attempts {
		if i > 0 {
			b.WriteString(",")
		}
		b.WriteString(`{"seq":` + itoa(a.Seq) + `,"solver":` + jstr(a.Solver.String()) + `,"hash":` + jstr(a.Hash) +
			`,"committed":` + i64toa(a.CommittedAt.Unix()) + `,"state":` + jstr(a.State.String()) +
			`,"pkgpath":` + jstr(a.PkgPath) + `,"passed":` + strconv.Itoa(a.Report.Passed) +
			`,"total":` + strconv.Itoa(a.Report.Total) + `,"failIn":` + jstr(a.Report.FailIn) +
			`,"failGot":` + jstr(a.Report.FailGot) + `,"failWant":` + jstr(a.Report.FailWant) +
			`,"winner":` + strconv.FormatBool(c.Winner == a) + `}`)
	}
	b.WriteString(`]}`)
	return b.String()
}

// ProfileJSON returns an address's stats, or "null".
func ProfileJSON(addr address) string {
	v := profiles.Get(addr.String())
	if v == nil {
		return "null"
	}
	return profileJSON(v.(*Profile))
}

func profileJSON(p *Profile) string {
	return `{"addr":` + jstr(p.Addr.String()) + `,"attempts":` + strconv.Itoa(p.Attempts) + `,"solved":` +
		strconv.Itoa(p.Solved) + `,"earned":` + i64toa(p.Earned) + `,"posted":` + strconv.Itoa(p.Posted) +
		`,"funded":` + i64toa(p.Funded) + `}`
}

// LeaderboardJSON returns the top solvers by earnings.
func LeaderboardJSON() string {
	var parts []string
	for _, p := range topSolvers(25) {
		parts = append(parts, profileJSON(p))
	}
	return "[" + strings.Join(parts, ",") + "]"
}

// JudgesJSON lists registered judges.
func JudgesJSON() string {
	var parts []string
	judges.Iterate("", "", func(_ string, v any) bool {
		j := v.(*JudgeInfo)
		parts = append(parts, `{"path":`+jstr(j.Path)+`,"name":`+jstr(j.Name)+`,"about":`+jstr(j.About)+`,"uses":`+strconv.Itoa(j.Uses)+`}`)
		return false
	})
	return "[" + strings.Join(parts, ",") + "]"
}

gauntlet.gno

// Package gauntlet is a bounty board where the chain grades the answers.
//
// Post a coding challenge with a GNOT reward. Solvers commit a hash, deploy a
// realm with a Solve function, and reveal it. This realm runs the tests itself
// and pays the earliest commit that passes. No reviewer, no disputes.
package gauntlet

import (
	"chain"
	"chain/banker"
	"chain/runtime/unsafe"
	"strings"
	"time"

	"gno.land/p/g188c5k6v0tmfyevfzj962jkajjqt4ddtml8zw0x/gauntlet"
	"gno.land/p/nt/avl/v0"
)

const denom = "ugnot"

var (
	board    gauntlet.Board
	profiles avl.Tree // address -> *Profile
	judges   avl.Tree // judge realm path -> *JudgeInfo

	pkgPath = unsafe.CurrentRealm().PkgPath()

	totalPaid int64 // ugnot paid to winners
	paidOut   []*PaidRecord
)

// Profile tracks what an address has done on the board.
type Profile struct {
	Addr     address
	Attempts int
	Solved   int
	Earned   int64
	Posted   int
	Funded   int64
}

// JudgeInfo is a registered judge: reusable, immutable test logic.
type JudgeInfo struct {
	Path  string
	Name  string
	About string
	Judge *gauntlet.Judge
	Uses  int
}

// PaidRecord is one winner payout, for the activity feed.
type PaidRecord struct {
	ChallengeID uint64
	To          address
	Amount      int64
	At          time.Time
}

// Post creates a challenge with fixed test cases. Send the reward in ugnot
// with the call. cases has one test per line: `input => expected output`.
func Post(cur realm, title, spec, cases string, hours int, bond int64, windowMinutes int) uint64 {
	poster := mustUser(cur)
	reward := sentUgnot()
	parsed, err := gauntlet.ParseCases(cases)
	if err != nil {
		panic(err)
	}
	return post(poster, gauntlet.PostParams{
		Title: title, Spec: spec, Poster: poster, Reward: reward, Bond: bond,
		Deadline: time.Now().Add(time.Duration(hours) * time.Hour),
		Window:   time.Duration(windowMinutes) * time.Minute,
		Cases:    parsed,
	})
}

// PostJudged creates a challenge graded by a registered judge (see
// RegisterJudge), plus optional fixed cases. Send the reward with the call.
func PostJudged(cur realm, title, spec, judgePath, cases string, hours int, bond int64, windowMinutes int) uint64 {
	poster := mustUser(cur)
	reward := sentUgnot()
	v := judges.Get(judgePath)
	if v == nil {
		panic("gauntlet: no judge registered at " + judgePath)
	}
	ji := v.(*JudgeInfo)
	var parsed []gauntlet.Case
	if strings.TrimSpace(cases) != "" {
		var err error
		parsed, err = gauntlet.ParseCases(cases)
		if err != nil {
			panic(err)
		}
	}
	id := post(poster, gauntlet.PostParams{
		Title: title, Spec: spec, Poster: poster, Reward: reward, Bond: bond,
		Deadline:  time.Now().Add(time.Duration(hours) * time.Hour),
		Window:    time.Duration(windowMinutes) * time.Minute,
		Cases:     parsed,
		Judge:     ji.Judge,
		JudgePath: ji.Path,
	})
	ji.Uses++
	return id
}

func post(poster address, p gauntlet.PostParams) uint64 {
	c, err := board.Post(p, time.Now())
	if err != nil {
		panic(err)
	}
	pr := profile(poster)
	pr.Posted++
	pr.Funded += p.Reward
	chain.Emit("Posted", "id", itoa(c.ID), "poster", poster.String(), "reward", i64toa(p.Reward))
	return c.ID
}

// RegisterJudge is called by a judge realm, usually from its init. The judge
// is stored under the caller's package path and can never change, so every
// bounty that uses it is graded by exactly the code anyone can read.
func RegisterJudge(cur realm, name, about string, inputs func(seed uint64) []string, check func(in, out string) bool) {
	prev := cur.Previous()
	if prev.IsUser() {
		panic("gauntlet: judges must be registered by a deployed realm")
	}
	path := prev.PkgPath()
	if judges.Has(path) {
		panic("gauntlet: judge already registered for " + path)
	}
	if inputs == nil || check == nil {
		panic("gauntlet: judge needs both inputs and check")
	}
	judges.Set(path, &JudgeInfo{
		Path: path, Name: name, About: about,
		Judge: &gauntlet.Judge{Inputs: inputs, Check: check},
	})
	chain.Emit("JudgeRegistered", "path", path)
}

// Commit reserves your place in line with sha256(solutionPath + ":" + salt).
// Send the challenge's bond with the call. Use HashFor to compute the hash.
func Commit(cur realm, id uint64, hash string) {
	solver := mustUser(cur)
	if _, err := board.Commit(id, solver, hash, sentUgnot(), time.Now()); err != nil {
		panic(err)
	}
	profile(solver).Attempts++
	chain.Emit("Committed", "id", itoa(id), "solver", solver.String())
}

// Reveal is called by your solution realm, never by a wallet directly:
//
//	func Submit(cur realm, id uint64, salt string) {
//		gauntlet.Reveal(cross(cur), id, salt, Solve)
//	}
//
// The realm path of the caller is read from the runtime, so nobody can reveal
// on behalf of a commit they do not own. The tests run here, on-chain.
func Reveal(cur realm, id uint64, salt string, solve func(string) string) {
	prev := cur.Previous()
	if !prev.IsCode() || prev.IsUser() {
		panic(gauntlet.ErrNotRealm)
	}
	if solve == nil {
		panic("gauntlet: nil solver")
	}
	a, payouts, err := board.Reveal(id, prev.PkgPath(), salt, solve, time.Now())
	if err != nil {
		panic(err)
	}
	chain.Emit("Revealed", "id", itoa(id), "solver", a.Solver.String(), "state", a.State.String(),
		"passed", itoa(uint64(a.Report.Passed)), "total", itoa(uint64(a.Report.Total)))
	pay(cur, id, payouts)
}

// Settle expires late commits and pays out when the result is final.
// Anyone can call it.
func Settle(cur realm, id uint64) {
	payouts, err := board.Settle(id, time.Now())
	if err != nil {
		panic(err)
	}
	pay(cur, id, payouts)
}

// Boost adds the ugnot sent with the call to an open challenge's reward.
func Boost(cur realm, id uint64) {
	from := mustUser(cur)
	amt := sentUgnot()
	if err := board.Boost(id, amt, time.Now()); err != nil {
		panic(err)
	}
	profile(from).Funded += amt
	chain.Emit("Boosted", "id", itoa(id), "from", from.String(), "amount", i64toa(amt))
}

// HashFor computes the commit hash for a solution realm path and a salt.
// Keep the salt secret until you reveal.
func HashFor(pkgPath, salt string) string {
	return gauntlet.HashSolution(pkgPath, salt)
}

func pay(cur realm, id uint64, payouts []gauntlet.Payout) {
	if len(payouts) == 0 {
		return
	}
	bk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	self := cur.Address()
	c := board.Get(id)
	for _, p := range payouts {
		if p.Amount <= 0 {
			continue
		}
		bk.SendCoins(self, p.To, chain.Coins{chain.NewCoin(denom, p.Amount)})
		if p.Reason == "bounty won" {
			totalPaid += p.Amount
			pr := profile(p.To)
			pr.Solved++
			pr.Earned += p.Amount
			paidOut = append(paidOut, &PaidRecord{ChallengeID: c.ID, To: p.To, Amount: p.Amount, At: time.Now()})
			chain.Emit("Won", "id", itoa(c.ID), "winner", p.To.String(), "amount", i64toa(p.Amount))
		}
	}
}

func mustUser(cur realm) address {
	prev := cur.Previous()
	if !prev.IsUserCall() {
		panic("gauntlet: call this directly from a wallet (maketx call)")
	}
	return prev.Address()
}

// sentUgnot returns the ugnot sent with a direct wallet call. Other denoms
// are rejected so nothing gets stuck.
func sentUgnot() int64 {
	var amt int64
	for _, c := range unsafe.OriginSend() {
		if c.Denom != denom {
			panic("gauntlet: only ugnot is accepted")
		}
		amt += c.Amount
	}
	return amt
}

func profile(a address) *Profile {
	if v := profiles.Get(a.String()); v != nil {
		return v.(*Profile)
	}
	p := &Profile{Addr: a}
	profiles.Set(a.String(), p)
	return p
}

func selfPkgPath() string { return pkgPath }

gnomod.toml

module = "gno.land/r/g188c5k6v0tmfyevfzj962jkajjqt4ddtml8zw0x/gauntlet"
gno = "0.9"

[addpkg]
  creator = "g188c5k6v0tmfyevfzj962jkajjqt4ddtml8zw0x"
  height = 1373033
  max_deposit = "100000000ugnot"

render.gno

package gauntlet

import (
	"strconv"
	"strings"
	"time"

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

// Render serves the board in gnoweb.
//
//	""             open bounties and recent winners
//	"c/<id>"       one challenge: spec, tests, queue, result
//	"u/<address>"  a solver's or poster's profile
//	"leaderboard"  top earners
//	"judges"       registered judges
//	"solve"        how to submit a solution
func Render(path string) string {
	now := time.Now()
	switch {
	case path == "":
		return renderHome(now)
	case strings.HasPrefix(path, "c/"):
		id, err := strconv.ParseUint(path[2:], 10, 64)
		if err != nil {
			return "# Not found\n\n[Back to the board](" + home() + ")"
		}
		return renderChallenge(id, now)
	case strings.HasPrefix(path, "u/"):
		a := address(path[2:])
		if !a.IsValid() {
			return "# Not found\n\n[Back to the board](" + home() + ")"
		}
		return renderProfile(a)
	case path == "leaderboard":
		return renderLeaderboard()
	case path == "judges":
		return renderJudges()
	case path == "solve":
		return renderSolveGuide()
	}
	return "# Not found\n\n[Back to the board](" + home() + ")"
}

func self() string { return webPath(selfPkgPath()) }
func home() string { return self() }

// tx builds a transaction link to this realm, whatever path it is deployed at.
func tx(fn string) *txlink.TxBuilder { return txlink.Realm(selfPkgPath()).NewLink(fn) }

func nav() string {
	return "[Board](" + home() + ") · [Leaderboard](" + self() + ":leaderboard) · [Judges](" + self() +
		":judges) · [How to solve](" + self() + ":solve)\n\n"
}

func renderHome(now time.Time) string {
	var b strings.Builder
	b.WriteString("# Gauntlet\n\n")
	b.WriteString("**Coding bounties graded by the chain, not by people.** Post a challenge with a GNOT reward. ")
	b.WriteString("Solvers deploy a function, this realm runs the tests on-chain, and the earliest passing commit is paid instantly. ")
	b.WriteString("No reviewer can refuse to pay, and copying someone's deployed code never wins.\n\n")
	b.WriteString(nav())

	open, escrow, solvers := 0, int64(0), profiles.Size()
	board.Iterate(func(c *gauntlet.Challenge) bool {
		if c.Status == gauntlet.Open {
			open++
			escrow += c.Pot()
		}
		return false
	})
	b.WriteString("| Open bounties | In escrow | Paid to solvers | Players |\n|---|---|---|---|\n")
	b.WriteString("| " + strconv.Itoa(open) + " | " + gnot(escrow) + " | " + gnot(totalPaid) + " | " + strconv.Itoa(solvers) + " |\n\n")

	b.WriteString("## Open bounties\n\n")
	if open == 0 {
		b.WriteString("_No open bounties right now. [Post one](" + tx("Post").URL() + ")._\n\n")
	} else {
		b.WriteString("| # | Challenge | Reward | Graded by | Attempts | Time |\n|---|---|---|---|---|---|\n")
		board.Iterate(func(c *gauntlet.Challenge) bool {
			if c.Status == gauntlet.Open {
				b.WriteString("| " + itoa(c.ID) + " | [" + sanitize.TableCell(c.Title) + "](" + self() + ":c/" + itoa(c.ID) + ") | " +
					gnot(c.Pot()) + " | " + gradedBy(c) + " | " + strconv.Itoa(len(c.Attempts)) + " | " + left(now, c.Deadline) + " |\n")
			}
			return false
		})
		b.WriteString("\n")
	}

	b.WriteString("## Recent winners\n\n")
	if len(paidOut) == 0 {
		b.WriteString("_Nobody has won yet. Be first._\n\n")
	} else {
		for i := len(paidOut) - 1; i >= 0 && i >= len(paidOut)-10; i-- {
			p := paidOut[i]
			c := board.Get(p.ChallengeID)
			b.WriteString("- [" + short(p.To) + "](" + self() + ":u/" + p.To.String() + ") won **" + gnot(p.Amount) +
				"** on [" + sanitize.InlineText(c.Title) + "](" + self() + ":c/" + itoa(c.ID) + ")\n")
		}
		b.WriteString("\n")
	}

	closed := 0
	b.WriteString("## Finished\n\n")
	board.Iterate(func(c *gauntlet.Challenge) bool {
		if c.Status != gauntlet.Open {
			closed++
			b.WriteString("- [#" + itoa(c.ID) + " " + sanitize.InlineText(c.Title) + "](" + self() + ":c/" + itoa(c.ID) + ") · " + c.Status.String() + "\n")
		}
		return closed >= 20
	})
	if closed == 0 {
		b.WriteString("_None yet._\n")
	}
	b.WriteString("\n---\n\n[Post a bounty with test cases](" + tx("Post").URL() + ") · " +
		"[Post a judged bounty](" + tx("PostJudged").URL() + ")\n")
	return b.String()
}

func gradedBy(c *gauntlet.Challenge) string {
	if c.Judge != nil {
		return "judge"
	}
	return strconv.Itoa(len(c.Cases)) + " tests"
}

func renderChallenge(id uint64, now time.Time) string {
	c := board.Get(id)
	if c == nil {
		return "# Not found\n\n[Back to the board](" + home() + ")"
	}
	var b strings.Builder
	b.WriteString("# #" + itoa(c.ID) + " " + sanitize.InlineText(c.Title) + "\n\n")
	b.WriteString(nav())

	switch c.Status {
	case gauntlet.Open:
		b.WriteString("> **Open** · reward **" + gnot(c.Pot()) + "** · commits close " + when(c.Deadline) + " (" + left(now, c.Deadline) + ")\n\n")
	case gauntlet.Won:
		w := c.Winner
		b.WriteString("> **Won** by [" + short(w.Solver) + "](" + self() + ":u/" + w.Solver.String() + ") for **" + gnot(c.Pot()) +
			"**. Winning code: [" + webPath(w.PkgPath) + "](" + webPath(w.PkgPath) + "$source)\n\n")
	case gauntlet.Closed:
		b.WriteString("> **Closed.** Nobody passed before the deadline; the reward went back to the poster.\n\n")
	}

	b.WriteString("| Reward | Bond per commit | Reveal window | Posted by | Posted |\n|---|---|---|---|---|\n")
	b.WriteString("| " + gnot(c.Pot()) + " | " + gnot(c.Bond) + " | " + c.Window.String() + " | [" + short(c.Poster) + "](" +
		self() + ":u/" + c.Poster.String() + ") | " + when(c.Created) + " |\n\n")
	if c.Boosts > 0 || c.Forfeited > 0 {
		b.WriteString("_Includes " + gnot(c.Boosts) + " in boosts and " + gnot(c.Forfeited) + " in forfeited bonds._\n\n")
	}

	b.WriteString("## The challenge\n\n")
	if strings.TrimSpace(c.Spec) == "" {
		b.WriteString("_No description._\n\n")
	} else {
		b.WriteString(sanitize.Block(c.Spec) + "\n\n")
	}
	b.WriteString("Write `func Solve(in string) string`.\n\n")

	b.WriteString("## How it is graded\n\n")
	if c.Judge != nil {
		b.WriteString("A **judge** generates fresh inputs at the moment you reveal and checks each answer, so a lookup table cannot pass. ")
		b.WriteString("Read the judge's code: [" + webPath(c.JudgePath) + "](" + webPath(c.JudgePath) + "$source).\n\n")
	}
	if len(c.Cases) > 0 {
		b.WriteString("Every one of these must match exactly:\n\n")
		for i, tc := range c.Cases {
			if i >= 8 {
				b.WriteString("_…and " + strconv.Itoa(len(c.Cases)-8) + " more. See them all in the realm source data or the web app._\n\n")
				break
			}
			b.WriteString(sanitize.CodeBlock("Solve("+strconv.Quote(tc.In)+")\n// want "+strconv.Quote(tc.Want)) + "\n")
		}
	}

	if c.Status == gauntlet.Open {
		b.WriteString("## Enter\n\n")
		b.WriteString("1. Pick a realm path for your solution, e.g. `gno.land/r/<your-address>/solve" + itoa(c.ID) + "`, and a secret salt.\n")
		b.WriteString("2. Get your hash: `HashFor(\"<your realm path>\", \"<salt>\")` and [commit it](" +
			tx("Commit").AddArgs("id", itoa(c.ID)).SetSend(i64toa(c.Bond)+"ugnot").URL() + ") with the " + gnot(c.Bond) + " bond.\n")
		b.WriteString("3. Deploy your realm (template below), then call its `Submit(" + itoa(c.ID) + ", \"<salt>\")` within " + c.Window.String() + ".\n\n")
		b.WriteString(sanitize.LanguageCodeBlock("go", solverTemplate(c.ID)) + "\n\n")
		b.WriteString("[Boost the reward](" + tx("Boost").AddArgs("id", itoa(c.ID)).URL() + ") · " +
			"[Settle](" + tx("Settle").AddArgs("id", itoa(c.ID)).URL() + ")\n\n")
	}

	b.WriteString("## Queue\n\n")
	if len(c.Attempts) == 0 {
		b.WriteString("_No commits yet._\n")
		return b.String()
	}
	b.WriteString("Earlier commits always rank first. A later commit cannot win while an earlier one can still reveal.\n\n")
	b.WriteString("| Place | Solver | Committed | Result | Solution |\n|---|---|---|---|---|\n")
	for i, a := range c.Attempts {
		result := a.State.String()
		if a.State == gauntlet.Passed || a.State == gauntlet.Failed {
			result += " (" + strconv.Itoa(a.Report.Passed) + "/" + strconv.Itoa(a.Report.Total) + ")"
		}
		if c.Winner == a {
			result = "**winner** " + result
		}
		sol := "—"
		if a.PkgPath != "" {
			sol = "[source](" + webPath(a.PkgPath) + "$source)"
		}
		b.WriteString("| " + strconv.Itoa(i+1) + " | [" + short(a.Solver) + "](" + self() + ":u/" + a.Solver.String() + ") | " +
			when(a.CommittedAt) + " | " + result + " | " + sol + " |\n")
	}
	for _, a := range c.Attempts {
		if a.State == gauntlet.Failed && a.Report.FailIn != "" {
			b.WriteString("\n**Failure** (" + short(a.Solver) + "): " + sanitize.InlineCode("Solve("+strconv.Quote(a.Report.FailIn)+")") +
				" returned " + sanitize.InlineCode(strconv.Quote(a.Report.FailGot)))
			if a.Report.FailWant != "" {
				b.WriteString(", wanted " + sanitize.InlineCode(strconv.Quote(a.Report.FailWant)))
			}
			b.WriteString("\n")
		}
	}
	return b.String()
}

func solverTemplate(id uint64) string {
	return "package solve" + itoa(id) + "\n\n" +
		"import \"" + selfPkgPath() + "\"\n\n" +
		"func Solve(in string) string {\n\t// your code\n\treturn in\n}\n\n" +
		"func Submit(cur realm, id uint64, salt string) {\n\tgauntlet.Reveal(cross(cur), id, salt, Solve)\n}"
}

func renderProfile(a address) string {
	var b strings.Builder
	b.WriteString("# " + short(a) + "\n\n" + nav())
	v := profiles.Get(a.String())
	if v == nil {
		b.WriteString("_No activity yet._\n")
		return b.String()
	}
	p := v.(*Profile)
	b.WriteString("`" + a.String() + "`\n\n")
	b.WriteString("| Solved | Earned | Attempts | Posted | Funded |\n|---|---|---|---|---|\n")
	b.WriteString("| " + strconv.Itoa(p.Solved) + " | " + gnot(p.Earned) + " | " + strconv.Itoa(p.Attempts) + " | " +
		strconv.Itoa(p.Posted) + " | " + gnot(p.Funded) + " |\n\n")
	b.WriteString("## Wins\n\n")
	wins := 0
	for _, r := range paidOut {
		if r.To == a {
			c := board.Get(r.ChallengeID)
			b.WriteString("- [" + sanitize.InlineText(c.Title) + "](" + self() + ":c/" + itoa(c.ID) + ") · " + gnot(r.Amount) + "\n")
			wins++
		}
	}
	if wins == 0 {
		b.WriteString("_None yet._\n")
	}
	return b.String()
}

func renderLeaderboard() string {
	var b strings.Builder
	b.WriteString("# Leaderboard\n\n" + nav())
	top := topSolvers(25)
	if len(top) == 0 {
		b.WriteString("_Nobody has solved a bounty yet._\n")
		return b.String()
	}
	b.WriteString("| Rank | Solver | Solved | Earned |\n|---|---|---|---|\n")
	for i, p := range top {
		b.WriteString("| " + strconv.Itoa(i+1) + " | [" + short(p.Addr) + "](" + self() + ":u/" + p.Addr.String() + ") | " +
			strconv.Itoa(p.Solved) + " | " + gnot(p.Earned) + " |\n")
	}
	return b.String()
}

// topSolvers returns profiles with at least one win, by earnings.
func topSolvers(n int) []*Profile {
	var out []*Profile
	profiles.Iterate("", "", func(_ string, v any) bool {
		p := v.(*Profile)
		if p.Solved > 0 {
			out = append(out, p)
		}
		return false
	})
	// insertion sort: small n, no allocations beyond the slice
	for i := 1; i < len(out); i++ {
		for j := i; j > 0 && better(out[j], out[j-1]); j-- {
			out[j], out[j-1] = out[j-1], out[j]
		}
	}
	if len(out) > n {
		out = out[:n]
	}
	return out
}

func better(a, b *Profile) bool {
	if a.Earned != b.Earned {
		return a.Earned > b.Earned
	}
	return a.Solved > b.Solved
}

func renderJudges() string {
	var b strings.Builder
	b.WriteString("# Judges\n\n" + nav())
	b.WriteString("A judge is a realm with two functions: one generates inputs from a seed, one checks an answer. ")
	b.WriteString("It registers itself once and can never change, so anyone can post a bounty graded by it and trust the rules will not move.\n\n")
	if judges.Size() == 0 {
		b.WriteString("_No judges registered yet._\n")
		return b.String()
	}
	b.WriteString("| Judge | About | Used by | Code |\n|---|---|---|---|\n")
	judges.Iterate("", "", func(_ string, v any) bool {
		j := v.(*JudgeInfo)
		b.WriteString("| " + sanitize.TableCell(j.Name) + " | " + sanitize.TableCell(j.About) + " | " + strconv.Itoa(j.Uses) + " bounties | [" +
			webPath(j.Path) + "](" + webPath(j.Path) + "$source) |\n")
		return false
	})
	b.WriteString("\n[Post a judged bounty](" + tx("PostJudged").URL() + ")\n")
	return b.String()
}

func renderSolveGuide() string {
	var b strings.Builder
	b.WriteString("# How to solve a bounty\n\n" + nav())
	b.WriteString("Gauntlet uses **commit, deploy, reveal** so nobody can copy your answer.\n\n")
	b.WriteString("1. **Commit.** Choose your solution's realm path and a secret salt. Compute `HashFor(path, salt)` and call `Commit(id, hash)` with the bond. Your place in line is now fixed.\n")
	b.WriteString("2. **Deploy.** Publish your realm with `Solve` and `Submit` (template below). Anyone can now read it, but anyone who copies it commits after you.\n")
	b.WriteString("3. **Reveal.** Call your realm's `Submit(id, salt)` before your reveal window ends. This realm reads your package path from the runtime, checks the hash, runs the tests and records the result. Your bond comes back either way.\n\n")
	b.WriteString("The earliest commit that passes wins the whole pot. If you skip the reveal, your bond is added to the reward.\n\n")
	b.WriteString(sanitize.LanguageCodeBlock("go", solverTemplate(1)) + "\n\n")
	b.WriteString("## Rules the code enforces\n\n")
	b.WriteString("- Solutions must live in a deployed `/r/` realm, so the winning code stays public on-chain.\n")
	b.WriteString("- One pending commit per address per bounty. Failed? Commit again with a new realm.\n")
	b.WriteString("- Your `Solve` cannot touch this realm's funds or state: Gno runs it under your realm's authority, and it never receives this realm's `cur`.\n")
	b.WriteString("- The poster cannot cancel or change the tests. The reward is locked until someone wins or the deadline passes.\n")
	return b.String()
}

util.gno

package gauntlet

import (
	"strconv"
	"strings"
	"time"
)

func itoa(n uint64) string  { return strconv.FormatUint(n, 10) }
func i64toa(n int64) string { return strconv.FormatInt(n, 10) }

// gnot formats ugnot as GNOT with up to 6 decimals.
func gnot(u int64) string {
	whole := u / 1_000_000
	frac := u % 1_000_000
	if frac == 0 {
		return i64toa(whole) + " GNOT"
	}
	f := strconv.FormatInt(frac+1_000_000, 10)[1:]
	f = strings.TrimRight(f, "0")
	return i64toa(whole) + "." + f + " GNOT"
}

func when(t time.Time) string { return t.UTC().Format("Jan 2, 15:04 UTC") }

// left describes time remaining until t, from now.
func left(now, t time.Time) string {
	d := t.Sub(now)
	if d <= 0 {
		return "ended"
	}
	h := int64(d.Hours())
	if h >= 48 {
		return i64toa(h/24) + " days left"
	}
	if h >= 1 {
		return i64toa(h) + "h left"
	}
	return i64toa(int64(d.Minutes())) + "m left"
}

func short(a address) string {
	s := a.String()
	if len(s) <= 14 {
		return s
	}
	return s[:8] + "…" + s[len(s)-4:]
}

// webPath turns gno.land/r/x into /r/x for gnoweb links.
func webPath(pkgPath string) string {
	if i := strings.Index(pkgPath, "/"); i >= 0 {
		return pkgPath[i:]
	}
	return pkgPath
}

func jstr(s string) string {
	var b strings.Builder
	b.WriteByte('"')
	for _, r := range s {
		switch r {
		case '"':
			b.WriteString(`\"`)
		case '\\':
			b.WriteString(`\\`)
		case '\n':
			b.WriteString(`\n`)
		case '\r':
			b.WriteString(`\r`)
		case '\t':
			b.WriteString(`\t`)
		default:
			if r < 0x20 {
				b.WriteString(`\u00`)
				const hex = "0123456789abcdef"
				b.WriteByte(hex[r>>4])
				b.WriteByte(hex[r&0xf])
			} else {
				b.WriteRune(r)
			}
		}
	}
	b.WriteByte('"')
	return b.String()
}