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.

render.gno

10.25 Kb · 335 lines
  1package guildhall
  2
  3import (
  4	"strconv"
  5	"strings"
  6
  7	"chain/runtime"
  8
  9	"gno.land/p/nt/markdown/sanitize/v0"
 10	"gno.land/p/nt/mux/v0"
 11	"gno.land/p/nt/ufmt/v0"
 12	"gno.land/p/nym-ololade001/guild/v0"
 13)
 14
 15const (
 16	realmPath = "gno.land/r/nym-ololade001/guildhall/v1"
 17	realmURL  = "/r/nym-ololade001/guildhall/v1"
 18	rpcURL    = "https://rpc.onyx.testnets.gno.land:443"
 19	chainID   = "onyx-1"
 20)
 21
 22var router = mux.NewRouter()
 23
 24func init() {
 25	router.HandleFunc("", boardHandler)
 26	router.HandleFunc("q/{id}", questHandler)
 27	router.HandleFunc("u/{addr}", profileHandler)
 28	router.HandleFunc("about", aboutHandler)
 29	router.SetNotFoundHandler(notFoundHandler)
 30}
 31
 32// Render serves the board through gnoweb; there is no other UI.
 33func Render(path string) string {
 34	return router.Render(path)
 35}
 36
 37func boardHandler(res *mux.ResponseWriter, req *mux.Request) {
 38	h := runtime.ChainHeight()
 39	var open, live []*guild.Quest
 40	active.Iterate("", "", func(_ string, value any) bool {
 41		q, ok := value.(*guild.Quest)
 42		if !ok || q == nil {
 43			return false
 44		}
 45		switch q.StatusAt(h) {
 46		case guild.Open:
 47			open = append(open, q)
 48		case guild.Claimed, guild.Submitted:
 49			live = append(live, q)
 50		}
 51		return false
 52	})
 53	sortByRewardDesc(open)
 54
 55	var b strings.Builder
 56	b.WriteString("# Guildhall\n\n")
 57	b.WriteString("Post a quest, lock the GNOT, and the realm pays whoever does the work, human or agent.\n\n")
 58	b.WriteString(ufmt.Sprintf("**Board:** %d open quests · %s in escrow · %s paid out\n\n",
 59		len(open), formatGNOT(escrowTotal), formatGNOT(paidTotal)))
 60
 61	b.WriteString("## Open quests\n\n")
 62	if len(open) == 0 {
 63		b.WriteString("No open quests yet.\n\n")
 64	} else {
 65		b.WriteString("| Quest | Reward | Lease | Deadline |\n")
 66		b.WriteString("|---|---|---|---|\n")
 67		for _, q := range open {
 68			b.WriteString(ufmt.Sprintf("| %s | %s | %d blocks | %d |\n",
 69				questLink(q.ID, sanitize.TableCell(q.Title)), formatGNOT(q.Reward), q.LeaseBlocks, q.Deadline))
 70		}
 71		b.WriteString("\n")
 72	}
 73
 74	if len(live) > 0 {
 75		b.WriteString("## In progress\n\n")
 76		for _, q := range live {
 77			who := userLink(q.Worker)
 78			if q.Status == guild.Claimed {
 79				b.WriteString(ufmt.Sprintf("- %s — claimed by %s, lease ends at block %d\n",
 80					questLink(q.ID, sanitize.InlineText(q.Title)), who, q.LeaseEnd))
 81			} else {
 82				b.WriteString(ufmt.Sprintf("- %s — submitted by %s, review ends at block %d\n",
 83					questLink(q.ID, sanitize.InlineText(q.Title)), who, q.ReviewEnd()))
 84			}
 85		}
 86		b.WriteString("\n")
 87	}
 88	b.WriteString(ufmt.Sprintf("[About Guildhall](%s:about)\n", realmURL))
 89	res.Write(b.String())
 90}
 91
 92func questHandler(res *mux.ResponseWriter, req *mux.Request) {
 93	idStr := req.GetVar("id")
 94	id, err := strconv.ParseUint(idStr, 10, 64)
 95	if err != nil {
 96		notFoundHandler(res, req)
 97		return
 98	}
 99	q, ok := quests.Get(questKey(id)).(*guild.Quest)
100	if !ok || q == nil {
101		notFoundHandler(res, req)
102		return
103	}
104	h := runtime.ChainHeight()
105	st := q.StatusAt(h)
106
107	var b strings.Builder
108	b.WriteString(ufmt.Sprintf("# %s\n\n", sanitize.InlineText(q.Title)))
109	b.WriteString(ufmt.Sprintf("- **Status:** %s\n", st.String()))
110	b.WriteString(ufmt.Sprintf("- **Reward:** %s\n", formatGNOT(q.Reward)))
111	b.WriteString(ufmt.Sprintf("- **Poster:** %s\n", userLink(q.Poster)))
112	if q.Worker.IsValid() {
113		b.WriteString(ufmt.Sprintf("- **Worker:** %s\n", userLink(q.Worker)))
114	}
115	b.WriteString(ufmt.Sprintf("- **Lease:** %d blocks", q.LeaseBlocks))
116	if q.Status == guild.Claimed {
117		if left := q.LeaseEnd - h; left > 0 {
118			b.WriteString(ufmt.Sprintf(", ends at block %d (%d left)", q.LeaseEnd, left))
119		} else {
120			b.WriteString(ufmt.Sprintf(", expired at block %d", q.LeaseEnd))
121		}
122	}
123	b.WriteString("\n")
124	b.WriteString(ufmt.Sprintf("- **Review window:** %d blocks", q.ReviewBlocks))
125	if q.Status == guild.Submitted {
126		if left := q.ReviewEnd() - h; left >= 0 {
127			b.WriteString(ufmt.Sprintf(", ends at block %d (%d left)", q.ReviewEnd(), left))
128		} else {
129			b.WriteString(ufmt.Sprintf(", closed at block %d", q.ReviewEnd()))
130		}
131	}
132	b.WriteString("\n")
133	b.WriteString(ufmt.Sprintf("- **Deadline:** block %d\n", q.Deadline))
134	if q.AutoPaid {
135		b.WriteString("- **Paid:** automatically, after the poster's silence\n")
136	}
137	if q.ProofURL != "" {
138		if u := sanitize.URL(q.ProofURL); u != "" {
139			b.WriteString(ufmt.Sprintf("- **Proof:** [%s](%s)\n", sanitize.InlineText(q.ProofURL), u))
140		} else {
141			b.WriteString(ufmt.Sprintf("- **Proof:** %s\n", sanitize.InlineText(q.ProofURL)))
142		}
143	}
144	if q.Note != "" {
145		b.WriteString(ufmt.Sprintf("- **Note:** %s\n", sanitize.InlineText(q.Note)))
146	}
147
148	if q.Spec != "" {
149		b.WriteString("\n## Spec\n")
150		// HTMLEscape neutralizes inline raw HTML (Block only guards
151		// line-leading hazards); Block then strips block-level injection.
152		b.WriteString(sanitize.Block(sanitize.HTMLEscape(q.Spec)))
153		b.WriteString("\n")
154	}
155
156	b.WriteString("\n## History\n\n")
157	for _, e := range q.History {
158		line := ufmt.Sprintf("- block %d — `%s` %s", e.Height, e.Actor.String(), e.Action)
159		if e.Detail != "" {
160			line += " — " + sanitize.InlineText(e.Detail)
161		}
162		b.WriteString(line + "\n")
163	}
164
165	cmds := questCommands(q, st, h)
166	if len(cmds) > 0 {
167		b.WriteString("\n## Commands\n\n")
168		b.WriteString("Replace `<key>` with your gnokey name:\n\n")
169		b.WriteString("```sh\n")
170		for _, c := range cmds {
171			b.WriteString(c + "\n")
172		}
173		b.WriteString("```\n")
174	}
175	b.WriteString(ufmt.Sprintf("\n[Back to the board](%s)\n", realmURL))
176	res.Write(b.String())
177}
178
179func profileHandler(res *mux.ResponseWriter, req *mux.Request) {
180	addrStr := req.GetVar("addr")
181	a := address(addrStr)
182	if !a.IsValid() {
183		notFoundHandler(res, req)
184		return
185	}
186	var b strings.Builder
187	b.WriteString(ufmt.Sprintf("# `%s`\n\n", a.String()))
188	p := findProfile(a)
189	if p == nil {
190		b.WriteString("No Guildhall activity for this address yet.\n")
191		res.Write(b.String())
192		return
193	}
194	b.WriteString(ufmt.Sprintf("- **Quests posted:** %d\n", p.Posted))
195	b.WriteString(ufmt.Sprintf("- **Quests paid:** %d (%d accepted, %d auto-accepted)\n",
196		p.Paid, p.Accepted, p.AutoAccepted))
197	b.WriteString(ufmt.Sprintf("- **GNOT earned:** %s\n", formatGNOT(p.Earned)))
198	b.WriteString(ufmt.Sprintf("- **GNOT spent:** %s\n", formatGNOT(p.Spent)))
199	writeIDList(&b, "Recently posted", p.PostedIDs)
200	writeIDList(&b, "Recently paid", p.PaidIDs)
201	b.WriteString(ufmt.Sprintf("\n[Back to the board](%s)\n", realmURL))
202	res.Write(b.String())
203}
204
205func writeIDList(b *strings.Builder, label string, ids []uint64) {
206	if len(ids) == 0 {
207		return
208	}
209	b.WriteString(ufmt.Sprintf("\n## %s\n\n", label))
210	start := len(ids) - 20
211	if start < 0 {
212		start = 0
213	}
214	for i := len(ids) - 1; i >= start; i-- {
215		b.WriteString("- " + questLink(ids[i], ufmt.Sprintf("quest %d", ids[i])) + "\n")
216	}
217}
218
219func aboutHandler(res *mux.ResponseWriter, req *mux.Request) {
220	res.Write(`# About Guildhall
221
222Guildhall is a bounty board on gno.land. Post a quest, lock the GNOT, and
223the realm pays whoever does the work, human or agent.
224
225## How it works
226
2271. A poster calls ` + "`Post`" + ` with the reward attached. The realm escrows it.
2282. A worker calls ` + "`Claim`" + ` and gets a lease of ` + "`LeaseBlocks`" + ` blocks.
2293. The worker calls ` + "`Submit`" + ` with a proof link before the lease ends.
2304. The poster calls ` + "`Accept`" + ` to pay, or ` + "`Reject`" + ` inside the
231   review window to send the quest back to the board.
2325. If the poster says nothing for ` + "`ReviewBlocks`" + ` blocks, the worker
233   calls ` + "`ClaimPayout`" + ` and silence counts as acceptance.
234
235## The rules
236
237- A claim lasts LeaseBlocks; once it lapses anyone may claim again.
238- While a submission is pending the quest cannot be refunded or cancelled.
239- After Deadline the poster may Refund an open or stale-claimed quest.
240- Cancel works while the quest is open and returns the escrow at once.
241- The poster can never claim their own quest.
242
243## State machine
244
245` + "`open → claimed → submitted → paid`" + `
246
247- ` + "`submitted → open`" + ` (rejected inside the review window)
248- ` + "`claimed → open`" + ` (lease expired; shows as open again)
249- ` + "`open → refunded`" + ` (poster, after the deadline)
250- ` + "`open → cancelled`" + ` (poster, any time before a live claim)
251
252## Import the state machine
253
254` + "```" + `
255import "gno.land/p/nym-ololade001/guild/v0"
256` + "```" + `
257
258[Back to the board](` + realmURL + `)
259`)
260}
261
262func notFoundHandler(res *mux.ResponseWriter, req *mux.Request) {
263	res.Write("# Not found\n\nNothing lives at this path. [Back to the board](" + realmURL + ")\n")
264}
265
266// questCommands lists the gnokey calls that make sense right now.
267func questCommands(q *guild.Quest, st guild.Status, h int64) []string {
268	id := ufmt.Sprintf("%d", q.ID)
269	call := func(fn string, extra ...string) string {
270		s := "gnokey maketx call -pkgpath " + realmPath + " -func " + fn + " -args " + id
271		for _, a := range extra {
272			s += " -args " + a
273		}
274		return s + " -gas-fee 1000000ugnot -gas-wanted 50000000" +
275			" -chainid " + chainID + " -remote " + rpcURL + " <key>"
276	}
277	var cmds []string
278	switch st {
279	case guild.Open:
280		if h < q.Deadline {
281			cmds = append(cmds, call("Claim"))
282		}
283		if h >= q.Deadline {
284			cmds = append(cmds, call("Refund"))
285		}
286		cmds = append(cmds, call("Cancel"))
287	case guild.Claimed:
288		cmds = append(cmds, call("Submit", `"<proofURL>"`, `"<note>"`))
289	case guild.Submitted:
290		if h <= q.ReviewEnd() {
291			cmds = append(cmds, call("Accept"), call("Reject", `"<reason>"`))
292		} else {
293			cmds = append(cmds, call("Accept"), call("ClaimPayout"))
294		}
295	}
296	return cmds
297}
298
299// questLink renders an absolute link to a quest page.
300func questLink(id uint64, text string) string {
301	return ufmt.Sprintf("[%s](%s:q/%d)", text, realmURL, id)
302}
303
304// userLink renders an absolute link to a profile page.
305func userLink(a address) string {
306	return ufmt.Sprintf("[%s](%s:u/%s)", a.String(), realmURL, a.String())
307}
308
309// sortByRewardDesc orders quests by reward, highest first, then by id.
310func sortByRewardDesc(qs []*guild.Quest) {
311	for i := 1; i < len(qs); i++ {
312		for j := i; j > 0; j-- {
313			a, b := qs[j-1], qs[j]
314			if a.Reward > b.Reward || (a.Reward == b.Reward && a.ID < b.ID) {
315				break
316			}
317			qs[j-1], qs[j] = qs[j], qs[j-1]
318		}
319	}
320}
321
322// formatGNOT renders ugnot as GNOT with up to six decimals, trimmed.
323func formatGNOT(amt int64) string {
324	whole := amt / 1000000
325	frac := amt % 1000000
326	if frac == 0 {
327		return ufmt.Sprintf("%d GNOT", whole)
328	}
329	fs := strconv.FormatInt(frac, 10)
330	for len(fs) < 6 {
331		fs = "0" + fs
332	}
333	fs = strings.TrimRight(fs, "0")
334	return ufmt.Sprintf("%d.%s GNOT", whole, fs)
335}