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

26.02 Kb · 670 lines
  1package questmaster
  2
  3import (
  4	"chain/runtime"
  5	"chain/runtime/unsafe"
  6	"net/url"
  7	"strconv"
  8	"strings"
  9
 10	"gno.land/p/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/escrow"
 11	"gno.land/p/moul/txlink/v0"
 12	"gno.land/p/nt/avl/v0"
 13)
 14
 15// Pages (gnoweb shows Render's Markdown):
 16//
 17//	""                 home: intro, totals, open quests, how it works
 18//	"quest/<id>"       one quest and what can happen next
 19//	"poster/<address>" quests posted by an address
 20//	"builder/<address>" quests an address has worked on (history)
 21//	"paid"             finished, paid quests
 22//	"help"             how to use every function, with gnokey commands
 23//
 24// List pages take "?page=N" (PageSize per page). Render never panics: any
 25// unknown path, bad id or bad address gives a "not found" page.
 26
 27// PageSize is the number of quests per list page.
 28const PageSize = 20
 29
 30// maxPage bounds ?page= so offsets stay small.
 31const maxPage = 1_000_000
 32
 33// SourceRepo is where the source code is published, shown in the footer of
 34// every page.
 35const SourceRepo = "https://github.com/elangrr/questmaster"
 36
 37// Render returns the gnoweb page for path, with the footer.
 38func Render(path string) string {
 39	return renderPage(path) + footer()
 40}
 41
 42// footer ends every page: attribution and where the source is.
 43func footer() string {
 44	src := "source: " + SourceRepo
 45	if strings.HasPrefix(SourceRepo, "https://") {
 46		src = "[source](" + SourceRepo + ")"
 47	}
 48	return "\n---\n\nBuilt on [gno.land](https://gno.land) · " + src + "\n"
 49}
 50
 51func renderPage(path string) string {
 52	p, query := splitQuery(path)
 53	page := pageArg(query)
 54	switch {
 55	case p == "":
 56		return renderHome(page)
 57	case p == "help":
 58		return renderHelp()
 59	case p == "paid":
 60		return renderPaid(page)
 61	case strings.HasPrefix(p, "quest/"):
 62		id, ok := parseID(strings.TrimPrefix(p, "quest/"))
 63		if !ok {
 64			return renderNotFound("There is no quest with that number.")
 65		}
 66		return renderQuest(id)
 67	case strings.HasPrefix(p, "poster/"):
 68		addr, ok := parseAddress(strings.TrimPrefix(p, "poster/"))
 69		if !ok {
 70			return renderNotFound("That is not a valid address.")
 71		}
 72		return renderUser(addr, true, page)
 73	case strings.HasPrefix(p, "builder/"):
 74		addr, ok := parseAddress(strings.TrimPrefix(p, "builder/"))
 75		if !ok {
 76			return renderNotFound("That is not a valid address.")
 77		}
 78		return renderUser(addr, false, page)
 79	}
 80	return renderNotFound("This page does not exist.")
 81}
 82
 83// ---------------------------------------------------------------------------
 84// Pages
 85
 86func renderHome(page int) string {
 87	var b strings.Builder
 88	t := GetTotals()
 89	b.WriteString("# QuestMaster\n\n")
 90	b.WriteString("A bounty board for small tasks, paid in GNOT. A poster describes a task and locks the reward in this realm. " +
 91		"A builder takes the task, does the work and sends a link to it. When the poster approves, the realm pays the builder. " +
 92		"If the poster never answers, the builder can collect the reward after the review window. Nobody else, not even the authors, can move the locked GNOT.\n\n")
 93
 94	b.WriteString("_Runs on the Onyx test network with test GNOT._\n\n")
 95	b.WriteString("**Post a quest:** " + postLinks() + " · [How it works](#how-it-works) · [Help and commands](" + pageURL("help") + ") · [Paid quests](" + pageURL("paid") + ")\n\n")
 96
 97	b.WriteString("## Board\n\n")
 98	b.WriteString("| Open quests | GNOT locked | GNOT paid out | Quests paid |\n")
 99	b.WriteString("|---|---|---|---|\n")
100	b.WriteString("| " + strconv.Itoa(t.OpenQuests) + " | " + gnotStr(t.Locked) + " | " + gnotStr(t.Paid) + " | " + strconv.Itoa(t.PaidQuests) + " |\n\n")
101
102	b.WriteString("## Open quests\n\n")
103	ids, nav := pageOf(&openIDs, page, "")
104	if openIDs.Size() == 0 {
105		b.WriteString("No open quests right now. [Post the first one](" + postLink() + ").\n\n")
106	} else if len(ids) == 0 {
107		b.WriteString("This page is empty. [Back to the first page](" + pageURL("") + ")\n\n")
108	} else {
109		b.WriteString("| # | Quest | Reward | Work window | Rejected |\n")
110		b.WriteString("|---|---|---|---|---|\n")
111		for _, id := range ids {
112			q := mustGet(id)
113			b.WriteString("| " + idStr(id) + " | " + questLink(q) + " | " + gnotStr(q.Reward()) + " GNOT | " +
114				blocksStr(q.WorkBlocks()) + " (" + approx(q.WorkBlocks()) + ") | " + strconv.Itoa(q.RejectCount()) + " |\n")
115		}
116		b.WriteString("\n" + nav)
117	}
118
119	b.WriteString("## How it works\n\n")
120	b.WriteString("1. **Post.** The poster writes a title, details and a work window, and sends the reward (at least 1 GNOT) with the call. The GNOT is locked here.\n")
121	b.WriteString("2. **Claim.** Anyone except the poster takes the quest. Only one builder works on a quest at a time.\n")
122	b.WriteString("3. **Submit.** The builder sends a link to the work (it must start with `https://`) before the work window ends.\n")
123	b.WriteString("4. **Review.** The poster approves (the builder is paid at once) or rejects with a reason (the quest opens again, and the reject count goes up for everyone to see).\n")
124	b.WriteString("5. **Paid.** The reward goes to the builder.\n\n")
125	b.WriteString("A poster can cancel an open quest and get the reward back at once. Anyone can claim an open quest; once a builder has it, the poster can **close** the quest instead: the builder keeps their turn, and if it ends without approval the reward goes back to the poster.\n\n")
126	b.WriteString(reviewWarning())
127	b.WriteString("Two deadlines keep things moving:\n\n")
128	b.WriteString("- **Work window** (set by the poster, " + blocksStr(escrow.MinWorkBlocks) + " to " + blocksStr(escrow.MaxWorkBlocks) +
129		" blocks): if the builder has not submitted by then, anyone can release the quest so someone else can take it.\n")
130	b.WriteString("- **Review window** (" + blocksStr(escrow.ReviewBlocks) + " blocks, " + approx(escrow.ReviewBlocks) +
131		"): if the poster has not approved or rejected by then, the builder can claim the reward.\n\n")
132	b.WriteString(timeNote())
133	return b.String()
134}
135
136func renderQuest(id uint64) string {
137	v := quests.Get(questKey(id))
138	if v == nil {
139		return renderNotFound("There is no quest with that number.")
140	}
141	q := v.(*escrow.Quest)
142	h := runtime.ChainHeight()
143	var b strings.Builder
144
145	b.WriteString("# Quest " + idStr(id) + ": " + esc(q.Title()) + "\n\n")
146	b.WriteString("[Board](" + pageURL("") + ") · [Help](" + pageURL("help") + ")\n\n")
147
148	b.WriteString("| | |\n|---|---|\n")
149	b.WriteString("| State | **" + questState(q) + "** |\n")
150	b.WriteString("| Reward | " + gnotStr(q.Reward()) + " GNOT |\n")
151	b.WriteString("| Poster | " + userLink(q.Poster(), true) + " |\n")
152	if q.Builder() != "" {
153		b.WriteString("| Builder | " + userLink(q.Builder(), false) + " |\n")
154	}
155	b.WriteString("| Work window | " + blocksStr(q.WorkBlocks()) + " blocks (" + approx(q.WorkBlocks()) + ") |\n")
156	b.WriteString("| Posted at block | " + blocksStr(q.CreatedAt()) + " |\n")
157	switch q.State() {
158	case escrow.Claimed:
159		b.WriteString("| Claimed at block | " + blocksStr(q.ClaimedAt()) + " |\n")
160		b.WriteString("| Work deadline | block " + blocksStr(q.WorkDeadline()) + " (" + left(q.WorkDeadline(), h) + ") |\n")
161	case escrow.Submitted:
162		b.WriteString("| Submitted at block | " + blocksStr(q.SubmittedAt()) + " |\n")
163		b.WriteString("| Review deadline | block " + blocksStr(q.ReviewDeadline()) + " (" + left(q.ReviewDeadline(), h) + ") |\n")
164	}
165	if q.WorkLink() != "" {
166		b.WriteString("| Work | " + linkOrText(q.WorkLink()) + " |\n")
167	}
168	b.WriteString("| Times rejected | " + strconv.Itoa(q.RejectCount()) + " |\n")
169	b.WriteString("| Current block | " + blocksStr(h) + " |\n\n")
170	if q.Closing() {
171		b.WriteString("> [!NOTE]\n> **Closing**: the reward returns to the poster when the current builder's turn ends, unless the work is approved.\n\n")
172	}
173
174	b.WriteString("## Details\n\n")
175	if strings.TrimSpace(q.Details()) == "" {
176		b.WriteString("_No details given._\n\n")
177	} else {
178		b.WriteString(escBlock(q.Details()) + "\n")
179	}
180
181	if q.RejectCount() > 0 {
182		b.WriteString("## Last reject reason\n\n")
183		b.WriteString(escBlock(q.LastRejectReason()) + "\n")
184	}
185
186	b.WriteString("## What can happen next\n\n")
187	b.WriteString(nextSteps(q, h))
188	b.WriteString(timeNote())
189	return b.String()
190}
191
192// step is one possible move on a quest page.
193type step struct{ text, fn string }
194
195func closeStep() step {
196	return step{"**Close quest**: the poster stops the quest. No coins move now; the builder keeps their turn, and if it ends without approval the reward goes back to the poster. It cannot be undone.", "CancelQuest"}
197}
198
199// reviewWarning is shown to posters on the home and help pages.
200func reviewWarning() string {
201	return "> [!WARNING]\n> **Posters: check your quest.** If you do not approve or reject a submission within the review window (" +
202		approx(escrow.ReviewBlocks) + "), the builder is paid automatically.\n\n"
203}
204
205// questState is the state as shown in tables and on the quest page.
206func questState(q *escrow.Quest) string {
207	if q.Closing() && !q.State().IsFinal() {
208		return stateText(q.State()) + ", closing"
209	}
210	return stateText(q.State())
211}
212
213// nextSteps lists the moves valid in q's state, who may make each, and a
214// transaction link and gnokey command for each.
215func nextSteps(q *escrow.Quest, h int64) string {
216	id := idStr(q.ID())
217	var b strings.Builder
218	var steps []step
219	switch q.State() {
220	case escrow.Open:
221		steps = []step{
222			{"**Claim**: anyone except the poster can take this quest and start working.", "ClaimQuest"},
223			{"**Cancel**: the poster can close the quest and get the " + gnotStr(q.Reward()) + " GNOT back.", "CancelQuest"},
224		}
225	case escrow.Claimed:
226		if h <= q.WorkDeadline() {
227			steps = append(steps, step{"**Submit work**: the builder sends a link to the work (starting with `https://`), until block " + blocksStr(q.WorkDeadline()) + ".", "SubmitWork"})
228		}
229		if q.Closing() {
230			steps = append(steps, step{"**Unclaim**: the builder gives the quest back. It is closing, so it ends and the reward goes back to the poster.", "UnclaimQuest"})
231		} else {
232			steps = append(steps, step{"**Unclaim**: the builder gives the quest back so others can take it.", "UnclaimQuest"})
233			steps = append(steps, closeStep())
234		}
235		if q.CanRelease(h) {
236			if q.Closing() {
237				steps = append(steps, step{"**Release**: the work deadline has passed without a submission, so anyone can end the quest; the reward goes back to the poster.", "ReleaseQuest"})
238			} else {
239				steps = append(steps, step{"**Release**: the work deadline has passed without a submission, so anyone can reopen the quest.", "ReleaseQuest"})
240			}
241		} else if q.Closing() {
242			b.WriteString("If nothing is submitted by block " + blocksStr(q.WorkDeadline()) + ", anyone can end the quest from block " + blocksStr(q.WorkDeadline()+1) + " and the reward goes back to the poster.\n\n")
243		} else {
244			b.WriteString("If nothing is submitted by block " + blocksStr(q.WorkDeadline()) + ", anyone can release the quest from block " + blocksStr(q.WorkDeadline()+1) + ".\n\n")
245		}
246	case escrow.Submitted:
247		steps = append(steps, step{"**Approve**: the poster accepts the work and the builder is paid " + gnotStr(q.Reward()) + " GNOT.", "ApproveWork"})
248		if h <= q.ReviewDeadline() {
249			if q.Closing() {
250				steps = append(steps, step{"**Reject**: the poster refuses the work with a reason, until block " + blocksStr(q.ReviewDeadline()) + ". The quest is closing, so it ends and the reward goes back to the poster.", "RejectWork"})
251			} else {
252				steps = append(steps, step{"**Reject**: the poster refuses the work with a reason, until block " + blocksStr(q.ReviewDeadline()) + ". The quest opens again.", "RejectWork"})
253			}
254		}
255		if !q.Closing() {
256			steps = append(steps, closeStep())
257		}
258		if q.CanClaimPayout(h) {
259			steps = append(steps, step{"**Claim payout**: the poster did not answer in time, so the builder can take the reward.", "ClaimPayout"})
260		} else {
261			b.WriteString("If the poster does not answer by block " + blocksStr(q.ReviewDeadline()) + ", the builder can claim the reward from block " + blocksStr(q.ReviewDeadline()+1) + ".\n\n")
262		}
263	case escrow.Paid:
264		return "Nothing: this quest is finished and the builder was paid " + gnotStr(q.Reward()) + " GNOT.\n\n"
265	case escrow.Cancelled:
266		return "Nothing: this quest was cancelled and the reward went back to the poster.\n\n"
267	}
268	for _, s := range steps {
269		b.WriteString("- " + s.text + " [Open in gnoweb](" + txLink(s.fn).AddArgs("id", id).URL() + ")\n")
270	}
271	b.WriteString("\nWith gnokey on Onyx (replace `KEY` with your key name):\n\n```\n")
272	for _, s := range steps {
273		b.WriteString(gnokeyCall(s.fn, id, extraArg(s.fn), "") + "\n")
274	}
275	b.WriteString("```\n\n")
276	return b.String()
277}
278
279func extraArg(fn string) string {
280	switch fn {
281	case "SubmitWork":
282		return "https://link-to-your-work"
283	case "RejectWork":
284		return "What is missing"
285	}
286	return ""
287}
288
289func renderUser(addr address, asPoster bool, page int) string {
290	var b strings.Builder
291	idx, other, title, what := &byBuilder, "poster", "Builder ", "Quests this address has claimed, with their current state. A quest stays here after the builder gives it up or is rejected."
292	if asPoster {
293		idx, other, title, what = &byPoster, "builder", "Poster ", "Quests posted by this address, with their current state."
294	}
295	b.WriteString("# " + title + shortAddr(addr) + "\n\n")
296	b.WriteString("[Board](" + pageURL("") + ") · [Same address as " + other + "](" + pageURL(other+"/"+addr.String()) + ")\n\n")
297	b.WriteString("Address: `" + addr.String() + "`\n\n" + what + "\n\n")
298
299	var ids []uint64
300	var nav string
301	base := "builder/" + addr.String()
302	if asPoster {
303		base = "poster/" + addr.String()
304	}
305	if v := idx.Get(addr.String()); v != nil {
306		ids, nav = pageOf(v.(*avl.Tree), page, base)
307	}
308	if len(ids) == 0 {
309		if page > 1 {
310			b.WriteString("This page is empty. [Back to the first page](" + pageURL(base) + ")\n")
311			return b.String()
312		}
313		b.WriteString("No quests yet.\n")
314		return b.String()
315	}
316	b.WriteString("| # | Quest | Reward | State | " + capital(other) + " |\n|---|---|---|---|---|\n")
317	for _, id := range ids {
318		q := mustGet(id)
319		who := q.Builder()
320		if !asPoster {
321			who = q.Poster()
322		}
323		whoText := "-"
324		if who != "" {
325			whoText = userLink(who, !asPoster)
326		}
327		b.WriteString("| " + idStr(id) + " | " + questLink(q) + " | " + gnotStr(q.Reward()) + " GNOT | " + questState(q) + " | " + whoText + " |\n")
328	}
329	b.WriteString("\n" + nav)
330	return b.String()
331}
332
333func renderPaid(page int) string {
334	var b strings.Builder
335	b.WriteString("# Paid quests\n\n")
336	b.WriteString("[Board](" + pageURL("") + ")\n\n")
337	b.WriteString("Every quest below was paid by this realm to its builder: " + plural(paidIDs.Size(), "quest") + ", " + gnotStr(totalPaid) + " GNOT in total.\n\n")
338	ids, nav := pageOf(&paidIDs, page, "paid")
339	if paidIDs.Size() == 0 {
340		b.WriteString("No quest has been paid yet.\n")
341		return b.String()
342	}
343	if len(ids) == 0 {
344		b.WriteString("This page is empty. [Back to the first page](" + pageURL("paid") + ")\n")
345		return b.String()
346	}
347	b.WriteString("| # | Quest | Reward | Builder | Times rejected |\n|---|---|---|---|---|\n")
348	for _, id := range ids {
349		q := mustGet(id)
350		b.WriteString("| " + idStr(id) + " | " + questLink(q) + " | " + gnotStr(q.Reward()) + " GNOT | " + userLink(q.Builder(), false) + " | " + strconv.Itoa(q.RejectCount()) + " |\n")
351	}
352	b.WriteString("\n" + nav)
353	return b.String()
354}
355
356func renderHelp() string {
357	var b strings.Builder
358	b.WriteString("# How to use QuestMaster\n\n")
359	b.WriteString("[Board](" + pageURL("") + ")\n\n")
360	b.WriteString("> [!NOTE]\n> QuestMaster runs on the **Onyx test network** (`onyx-1`) and uses **test GNOT** from the faucet, not real money.\n\n")
361	b.WriteString("Every action is a transaction on this realm. Use either:\n\n")
362	b.WriteString("- **gnoweb**: the action links on each quest page open a form for the function, with the quest number filled in. Sign it with a browser wallet such as Adena, or copy the gnokey command the form shows.\n")
363	b.WriteString("- **gnokey**: the commands below, already set for Onyx. Replace `KEY` with your key name and `ID` with the quest number.\n\n")
364	b.WriteString("Only direct calls from a wallet are accepted (not calls from other realms or `maketx run` scripts). Only `PostQuest` takes coins; every other call must send none.\n\n")
365
366	b.WriteString(reviewWarning())
367	b.WriteString("## Post a quest\n\n")
368	b.WriteString("Send the reward with the call: exactly one coin, in `ugnot`, at least " + gnotStr(MinReward) + " GNOT (1 GNOT = 1000000 ugnot). " +
369		"Arguments: title (up to " + strconv.Itoa(escrow.MaxTitleLen) + " characters, one line), details (up to " + strconv.Itoa(escrow.MaxDetailsLen) +
370		" characters), work window in blocks (" + blocksStr(escrow.MinWorkBlocks) + " to " + blocksStr(escrow.MaxWorkBlocks) + "). " +
371		"Anyone except you can claim your quest while it is open; once it is claimed, closing it (below) stops new claims. " +
372		"Posting also stores the quest on chain. The chain charges a storage deposit for that, paid by the poster on top of the reward: " +
373		"about 0.65 to 0.8 GNOT for a new quest at 100 ugnot per byte, the price on Onyx (measured on a local node). It is held by the chain, not by this realm, and is not part of the escrow; when a later call makes the stored data smaller, the chain returns that share to whoever made the call.\n\n")
374	b.WriteString("With gnoweb, pick a reward: " + postLinks() + ". The form shows the amount and asks you to confirm adding the coins. " +
375		"For another amount, change `.send=` in the link's address or use gnokey.\n\n")
376	b.WriteString("```\n" + gnokeyCall("PostQuest", "", "", "5000000ugnot") + "\n```\n\n")
377
378	sections := []struct{ title, text, fn, arg string }{
379		{"Claim a quest", "Anyone except the poster. The work window starts now.", "ClaimQuest", ""},
380		{"Submit work", "The builder only, until the work deadline. The link must start with `https://`.", "SubmitWork", "https://link-to-your-work"},
381		{"Approve work", "The poster only. The builder is paid at once.", "ApproveWork", ""},
382		{"Reject work", "The poster only, until the review deadline. The quest opens again (or, if you closed it, ends with a refund to you); the reason and the reject count are public.", "RejectWork", "What is missing"},
383		{"Cancel or close a quest", "The poster only. An open quest is cancelled at once and the reward is refunded. A claimed or submitted quest is closed instead: no coins move now, the builder keeps their turn, and the reward goes back to you when that turn ends without approval (the builder unclaims, the work deadline passes and anyone releases it, or you reject the work). Nobody can claim it again. Closing cannot be undone.", "CancelQuest", ""},
384		{"Unclaim a quest", "The builder only, before submitting. The quest opens again (or, if the poster closed it, ends with a refund to the poster).", "UnclaimQuest", ""},
385		{"Release a quest", "Anyone, once the work deadline has passed without a submission. The quest opens again (or, if the poster closed it, ends with a refund to the poster).", "ReleaseQuest", ""},
386		{"Claim a timeout payout", "The builder only, once the review deadline has passed without an answer from the poster.", "ClaimPayout", ""},
387	}
388	for _, s := range sections {
389		b.WriteString("## " + s.title + "\n\n" + s.text + "\n\n```\n" + gnokeyCall(s.fn, "ID", s.arg, "") + "\n```\n\n")
390	}
391
392	b.WriteString("## Reading the board\n\n")
393	b.WriteString("- `" + pageURL("quest/ID") + "`: one quest\n")
394	b.WriteString("- `" + pageURL("poster/ADDRESS") + "` and `" + pageURL("builder/ADDRESS") + "`: one address's quests\n")
395	b.WriteString("- `" + pageURL("paid") + "`: paid quests\n")
396	b.WriteString("- Lists take `?page=2` and so on, " + strconv.Itoa(PageSize) + " quests per page.\n\n")
397	b.WriteString(timeNote())
398	return b.String()
399}
400
401func renderNotFound(reason string) string {
402	return "# Not found\n\n" + reason + "\n\n[Go to the QuestMaster board](" + pageURL("") + ") · [Help](" + pageURL("help") + ")\n"
403}
404
405// ---------------------------------------------------------------------------
406// Pieces
407
408func questLink(q *escrow.Quest) string {
409	return "[" + escCell(q.Title()) + "](" + pageURL("quest/"+idStr(q.ID())) + ")"
410}
411
412// userLink links an address (always a valid bech32 address from storage or
413// a validated path) to its poster or builder page.
414func userLink(a address, asPoster bool) string {
415	page := "builder/"
416	if asPoster {
417		page = "poster/"
418	}
419	return "[" + shortAddr(a) + "](" + pageURL(page+a.String()) + ")"
420}
421
422func shortAddr(a address) string {
423	s := a.String()
424	if len(s) <= 14 {
425		return s
426	}
427	return s[:8] + "…" + s[len(s)-4:]
428}
429
430func stateText(s escrow.State) string {
431	switch s {
432	case escrow.Open:
433		return "Open"
434	case escrow.Claimed:
435		return "Claimed (work in progress)"
436	case escrow.Submitted:
437		return "Submitted (waiting for review)"
438	case escrow.Paid:
439		return "Paid"
440	case escrow.Cancelled:
441		return "Cancelled (refunded)"
442	}
443	return "Unknown"
444}
445
446// realmPkgPath is this realm's package path, captured once when the realm is
447// added. (unsafe.CurrentRealm() inside Render depends on the caller's frame,
448// so it is not used there.)
449var realmPkgPath string
450
451func init() {
452	realmPkgPath = unsafe.CurrentRealm().PkgPath()
453}
454
455// realmPath is this realm's web path, e.g. "/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/questmaster".
456func realmPath() string {
457	return strings.TrimPrefix(realmPkgPath, runtime.ChainDomain())
458}
459
460// txLink builds a gnoweb transaction link for fn on this realm.
461func txLink(fn string) *txlink.TxBuilder {
462	return txlink.Realm(realmPkgPath).NewLink(fn)
463}
464
465// pageURL links to one of this realm's pages.
466func pageURL(p string) string {
467	if p == "" {
468		return realmPath()
469	}
470	return realmPath() + ":" + p
471}
472
473func postLink() string { return postLinkFor(MinReward) }
474
475func postLinkFor(ugnot int64) string {
476	return txLink("PostQuest").SetSend(strconv.FormatInt(ugnot, 10) + "ugnot").URL()
477}
478
479// postLinks offers PostQuest forms with a few prefilled rewards.
480func postLinks() string {
481	var links []string
482	for _, n := range []int64{1, 5, 10} {
483		links = append(links, "["+strconv.FormatInt(n, 10)+" GNOT]("+postLinkFor(n*1_000_000)+")")
484	}
485	return strings.Join(links, " · ")
486}
487
488// gnokeyCall builds a copy-paste gnokey command. Only realm-chosen text goes
489// into it (function names, numbers, fixed example values).
490func gnokeyCall(fn, id, arg, send string) string {
491	cmd := "gnokey maketx call -pkgpath \"" + realmPkgPath + "\" -func \"" + fn + "\""
492	if fn == "PostQuest" {
493		cmd += " -args \"Fix a typo in the docs\" -args \"Details of the task\" -args \"20000\""
494	}
495	if id != "" {
496		cmd += " -args \"" + id + "\""
497	}
498	if arg != "" {
499		cmd += " -args \"" + arg + "\""
500	}
501	if send != "" {
502		cmd += " -send \"" + send + "\""
503	}
504	return cmd + " -gas-fee 100000ugnot -gas-wanted 10000000 -broadcast -chainid " + chainID + " -remote " + chainRPC + " KEY"
505}
506
507// QuestMaster runs on the Onyx test network only; every example command
508// targets it.
509const (
510	chainID  = "onyx-1"
511	chainRPC = "https://rpc.onyx.testnets.gno.land:443"
512)
513
514// pageOf returns the ids for page (newest first) and prev/next links.
515func pageOf(t *avl.Tree, pageNum int, base string) ([]uint64, string) {
516	total := t.Size()
517	offset := (pageNum - 1) * PageSize
518	if offset >= total {
519		return nil, ""
520	}
521	ids := page(t, offset, PageSize)
522	var nav []string
523	if pageNum > 1 {
524		nav = append(nav, "[← Newer]("+pageURL(base)+"?page="+strconv.Itoa(pageNum-1)+")")
525	}
526	if offset+PageSize < total {
527		nav = append(nav, "[Older →]("+pageURL(base)+"?page="+strconv.Itoa(pageNum+1)+")")
528	}
529	if len(nav) == 0 {
530		return ids, ""
531	}
532	last := (total + PageSize - 1) / PageSize
533	return ids, "Page " + strconv.Itoa(pageNum) + " of " + strconv.Itoa(last) + " · " + strings.Join(nav, " · ") + "\n\n"
534}
535
536// ---------------------------------------------------------------------------
537// Parsing (never panics)
538
539func splitQuery(path string) (string, url.Values) {
540	i := strings.IndexByte(path, '?')
541	if i < 0 {
542		return path, url.Values{}
543	}
544	q, err := url.ParseQuery(path[i+1:])
545	if err != nil {
546		q = url.Values{}
547	}
548	return path[:i], q
549}
550
551func pageArg(q url.Values) int {
552	n, err := strconv.Atoi(q.Get("page"))
553	if err != nil || n < 1 {
554		return 1
555	}
556	if n > maxPage {
557		return maxPage
558	}
559	return n
560}
561
562func parseID(s string) (uint64, bool) {
563	if s == "" || len(s) > 20 {
564		return 0, false
565	}
566	for _, c := range s {
567		if c < '0' || c > '9' {
568			return 0, false
569		}
570	}
571	id, err := strconv.ParseUint(s, 10, 64)
572	if err != nil || id == 0 || !quests.Has(questKey(id)) {
573		return 0, false
574	}
575	return id, true
576}
577
578func parseAddress(s string) (address, bool) {
579	if len(s) > 100 {
580		return "", false
581	}
582	a := address(s)
583	if !a.IsValid() {
584		return "", false
585	}
586	return a, true
587}
588
589// ---------------------------------------------------------------------------
590// Numbers
591
592// gnot formats ugnot as GNOT with up to 6 decimals, without floats.
593func gnotStr(ugnot int64) string {
594	neg := ""
595	if ugnot < 0 {
596		neg = "-"
597		ugnot = -ugnot
598	}
599	whole := strconv.FormatInt(ugnot/1_000_000, 10)
600	frac := ugnot % 1_000_000
601	if frac == 0 {
602		return neg + whole
603	}
604	f := strconv.FormatInt(frac, 10)
605	for len(f) < 6 {
606		f = "0" + f
607	}
608	return neg + whole + "." + strings.TrimRight(f, "0")
609}
610
611// blocksStr formats a block count or height with thousands separators.
612func blocksStr(n int64) string {
613	s := strconv.FormatInt(n, 10)
614	if n < 0 {
615		return s
616	}
617	for i := len(s) - 3; i > 0; i -= 3 {
618		s = s[:i] + "," + s[i:]
619	}
620	return s
621}
622
623// approx turns a number of blocks into "about N days/hours/minutes", at
624// ApproxBlockMillis per block.
625func approx(blocks int64) string {
626	if blocks <= 0 {
627		return "now"
628	}
629	secs := blocks * ApproxBlockMillis / 1000
630	switch {
631	case secs >= 2*86400:
632		return "about " + strconv.FormatInt((secs+43200)/86400, 10) + " days"
633	case secs >= 2*3600:
634		return "about " + strconv.FormatInt((secs+1800)/3600, 10) + " hours"
635	case secs >= 120:
636		return "about " + strconv.FormatInt((secs+30)/60, 10) + " minutes"
637	}
638	return "about a minute"
639}
640
641// left describes the time to a deadline block from height h.
642func left(deadline, h int64) string {
643	if h > deadline {
644		return "passed"
645	}
646	return approx(deadline-h+1) + " left"
647}
648
649// ApproxBlockMillis is the block time used for the approximate times on the
650// pages (measured about 3.4 to 3.5 s on Onyx and mainnet in Nov 2026).
651const ApproxBlockMillis = 3500
652
653func timeNote() string {
654	return "_Times are approximate, at about 3.5 seconds per block; deadlines are exact block heights._\n"
655}
656
657func capital(s string) string {
658	if s == "" {
659		return s
660	}
661	return strings.ToUpper(s[:1]) + s[1:]
662}
663
664// plural returns "1 quest" or "N quests".
665func plural(n int, word string) string {
666	if n == 1 {
667		return "1 " + word
668	}
669	return strconv.Itoa(n) + " " + word + "s"
670}