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

31.14 Kb · 686 lines
  1package hearthbounty
  2
  3import (
  4	"chain/runtime"
  5	"net/url"
  6	"strconv"
  7	"strings"
  8
  9	"gno.land/p/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthcore/v0"
 10	"gno.land/p/nt/markdown/sanitize/v0"
 11	"gno.land/p/nt/mux/v0"
 12)
 13
 14func initRouter() {
 15	router = mux.NewRouter()
 16	router.HandleFunc("", renderHome)
 17	router.HandleFunc("page/{page}", renderHomePage)
 18	router.HandleFunc("category/{cat}", renderCategory)
 19	router.HandleFunc("bounty/{id}", renderBountyDetail)
 20	router.HandleFunc("post", renderPostPage)
 21	router.HandleFunc("leaderboard", renderLeaderboard)
 22	router.HandleFunc("profile/{addr}", renderProfilePage)
 23	router.HandleFunc("agents", renderAgentsHub)
 24	router.NotFoundHandler = renderNotFound
 25}
 26
 27// Render serves the native gnoweb interface and machine-readable Markdown views.
 28// Strictly read-only; all dynamic inputs are sanitized via sanitize/v0, EscapeMath,
 29// and byte-indexed ASCII NeutralizeGnoTags.
 30func Render(path string) string {
 31	return router.Render(path)
 32}
 33
 34func safeInline(s string) string {
 35	return NeutralizeGnoTags(hearthcore.EscapeMath(sanitize.InlineText(s)))
 36}
 37
 38func safeCell(s string) string {
 39	return NeutralizeGnoTags(hearthcore.EscapeMath(sanitize.TableCell(s)))
 40}
 41
 42func safeBlock(s string) string {
 43	return NeutralizeGnoTags(hearthcore.EscapeMath(sanitize.Block(s)))
 44}
 45
 46func safeURL(s string) string {
 47	return sanitize.URL(s)
 48}
 49
 50func routeHref(sub string) string {
 51	if sub == "" {
 52		return realmWebBase
 53	}
 54	return realmWebBase + ":" + sub
 55}
 56
 57func txHref(base, fn string, kv ...string) string {
 58	if len(kv) == 0 {
 59		return base + "$help&func=" + fn
 60	}
 61	values := url.Values{}
 62	for i := 0; i+1 < len(kv); i += 2 {
 63		values.Add(kv[i], kv[i+1])
 64	}
 65	return base + "$help&func=" + fn + "&" + values.Encode()
 66}
 67
 68func writeTopNav(b *strings.Builder, active string) {
 69	homeVar := "outline"
 70	if active == "home" {
 71		homeVar = "info"
 72	}
 73	postVar := "outline"
 74	if active == "post" {
 75		postVar = "success"
 76	}
 77	lbVar := "outline"
 78	if active == "leaderboard" {
 79		lbVar = "info"
 80	}
 81	agentVar := "outline"
 82	if active == "agents" {
 83		agentVar = "info"
 84	}
 85
 86	b.WriteString(`<gno-button href="` + routeHref("") + `" label="Bounty Board" variant="` + homeVar + `" /> `)
 87	b.WriteString(`<gno-button href="` + routeHref("post") + `" label="+ Post Bounty" variant="` + postVar + `" /> `)
 88	b.WriteString(`<gno-button href="` + routeHref("leaderboard") + `" label="Guild Leaderboard" variant="` + lbVar + `" /> `)
 89	b.WriteString(`<gno-button href="` + routeHref("agents") + `" label="AI Agent MCP Hub" variant="` + agentVar + `" />` + "\n\n")
 90}
 91
 92func renderHome(res *mux.ResponseWriter, req *mux.Request) {
 93	renderBoardView(res, "", 1)
 94}
 95
 96func renderHomePage(res *mux.ResponseWriter, req *mux.Request) {
 97	p, err := strconv.Atoi(req.GetVar("page"))
 98	if err != nil || p < 1 {
 99		renderNotFound(res, req)
100		return
101	}
102	renderBoardView(res, "", p)
103}
104
105func renderCategory(res *mux.ResponseWriter, req *mux.Request) {
106	rawCat := req.GetVar("cat")
107	cat, ok := hearthcore.ParseCategory(rawCat)
108	if !ok {
109		renderNotFound(res, req)
110		return
111	}
112	renderBoardView(res, string(cat), 1)
113}
114
115func renderBoardView(res *mux.ResponseWriter, filterCat string, page int) {
116	var b strings.Builder
117	s := GetStats()
118
119	b.WriteString("# <gno-icon name=\"flame\" /> HearthBounty v1\n\n")
120	writeTopNav(&b, "home")
121
122	b.WriteString(hearthcore.RenderHeroBannerSVG(
123		s.OpenCount,
124		s.ClaimedCount,
125		s.SubmittedCount,
126		s.SettledCount,
127		s.TotalEscrowUgnot,
128		s.TotalSettledUgnot,
129	))
130	b.WriteString("\n\n")
131
132	b.WriteString("<gno-columns>\n")
133	b.WriteString("<gno-frame>\n")
134	b.WriteString("### <gno-icon name=\"coins\" /> Active Escrow\n\n")
135	b.WriteString("**" + hearthcore.FormatGNOT(s.TotalEscrowUgnot) + "** locked across **" +
136		strconv.Itoa(s.OpenCount+s.ClaimedCount+s.SubmittedCount+s.DisputedCount) + "** active bounties.\n\n")
137	b.WriteString("Settled all-time: **" + hearthcore.FormatGNOT(s.TotalSettledUgnot) + "**\n")
138	b.WriteString("</gno-frame>\n")
139	b.WriteString("<gno-columns-sep />\n")
140	b.WriteString("<gno-frame>\n")
141	b.WriteString("### <gno-icon name=\"trophy\" /> Guild Activity\n\n")
142	b.WriteString("**" + strconv.Itoa(s.TotalBounties) + "** total quests · **" +
143		strconv.Itoa(s.SettledCount) + "** settled · **" +
144		strconv.Itoa(s.OpenCount) + "** open right now.\n\n")
145	b.WriteString("Current block height: `" + strconv.FormatInt(runtime.ChainHeight(), 10) + "`\n")
146	b.WriteString("</gno-frame>\n")
147	b.WriteString("<gno-columns-sep />\n")
148	b.WriteString("<gno-frame>\n")
149	b.WriteString("### <gno-icon name=\"ai\" /> Builders & AI Agents\n\n")
150	b.WriteString("**" + strconv.Itoa(s.ProfileCount) + "** guild profiles (**" +
151		strconv.Itoa(s.AgentCount) + "** MCP AI agents).\n\n")
152	b.WriteString("On-chain AVL state + JSON `vm/qeval` query surface.\n")
153	b.WriteString("</gno-frame>\n")
154	b.WriteString("</gno-columns>\n\n")
155
156	b.WriteString("## <gno-icon name=\"filter\" /> Filter by Track\n\n")
157	allVariant := "outline"
158	if filterCat == "" {
159		allVariant = "info"
160	}
161	b.WriteString(`<gno-button href="` + routeHref("") + `" label="All Tracks" variant="` + allVariant + `" /> `)
162	for _, cat := range hearthcore.AllCategories() {
163		v := "outline"
164		if filterCat == string(cat) {
165			v = "info"
166		}
167		b.WriteString(`<gno-button href="` + routeHref("category/"+string(cat)) + `" label="` + cat.Label() + `" variant="` + v + `" /> `)
168	}
169	b.WriteString("\n\n")
170
171	if filterCat == "" {
172		b.WriteString("## <gno-icon name=\"list\" /> Bounty Board (Page " + strconv.Itoa(page) + ")\n\n")
173	} else {
174		cat, _ := hearthcore.ParseCategory(filterCat)
175		b.WriteString("## <gno-icon name=\"" + cat.IconName() + "\" /> " + cat.Label() + " Bounties\n\n")
176	}
177
178	skip := (page - 1) * BoardPageSize
179	seen := 0
180	rows := 0
181	hasMore := false
182	var tbl strings.Builder
183	tbl.WriteString("| ID | Bounty | Track | Status | Escrow / Payout | Sponsor | Hunter |\n")
184	tbl.WriteString("|---:|---|---|---|---|---|---|\n")
185
186	bounties.ReverseIterate("", "", func(_ string, val any) bool {
187		rec := val.(*bountyRecord)
188		if filterCat != "" && string(rec.Category) != filterCat {
189			return false
190		}
191		if seen < skip {
192			seen++
193			return false
194		}
195		if rows >= BoardPageSize {
196			hasMore = true
197			return true
198		}
199		seen++
200		idStr := strconv.FormatUint(rec.ID, 10)
201		titleLink := "[**" + safeCell(rec.Title) + "**](" + routeHref("bounty/"+idStr) + ")"
202		catCell := "<gno-icon name=\"" + rec.Category.IconName() + "\" /> " + rec.Category.Label()
203		stCell := "<gno-icon name=\"" + rec.Status.IconName() + "\" /> **" + rec.Status.Label() + "**"
204		rewardCell := "**" + hearthcore.FormatGNOT(effectiveReward(rec)) + "**"
205		sponsorCell := "[" + safeCell(displayHandle(rec.Sponsor)) + "](" + routeHref("profile/"+string(rec.Sponsor)) + ")"
206		hunterCell := "_Unclaimed_"
207		if rec.Claimant != "" {
208			hunterCell = "[" + safeCell(displayHandle(rec.Claimant)) + "](" + routeHref("profile/"+string(rec.Claimant)) + ")"
209		}
210
211		tbl.WriteString("| `" + idStr + "` | " + titleLink + " | " + catCell + " | " + stCell + " | " + rewardCell + " | " + sponsorCell + " | " + hunterCell + " |\n")
212		rows++
213		return false
214	})
215
216	if rows == 0 {
217		b.WriteString("> [!INFO] No Bounties on This View\n")
218		b.WriteString("> Post a micro-bounty via **+ Post Bounty** above or call `PostBounty` via `gnokey` / `gnomcp` with attached `ugnot`.\n\n")
219	} else {
220		b.WriteString(tbl.String())
221		b.WriteString("\n")
222		if filterCat == "" && (page > 1 || hasMore) {
223			if page > 1 {
224				prevHref := routeHref("page/" + strconv.Itoa(page-1))
225				if page == 2 {
226					prevHref = routeHref("")
227				}
228				b.WriteString(`<gno-button href="` + prevHref + `" label="Previous Page" variant="outline" /> `)
229			}
230			if hasMore {
231				b.WriteString(`<gno-button href="` + routeHref("page/"+strconv.Itoa(page+1)) + `" label="Next Page" variant="outline" />`)
232			}
233			b.WriteString("\n\n")
234		}
235	}
236
237	b.WriteString("> [!TIP] Dual Interface: gnoweb + MCP\n")
238	b.WriteString("> Humans transact directly inside `gnoweb` with Adena wallet forms. Agents read `ExportBountiesJSON(\"open\", \"\", 0, 20)` via `vm/qeval` and prepare testnet transactions through `hearthbounty-mcp` alongside `gnomcp`.\n")
239
240	res.Write(b.String())
241}
242
243func renderBountyDetail(res *mux.ResponseWriter, req *mux.Request) {
244	rawID := req.GetVar("id")
245	id, err := strconv.ParseUint(rawID, 10, 64)
246	if err != nil {
247		renderNotFound(res, req)
248		return
249	}
250	rec, ok := getBountyRecord(id)
251	if !ok {
252		renderNotFound(res, req)
253		return
254	}
255
256	var b strings.Builder
257	idStr := strconv.FormatUint(rec.ID, 10)
258	now := runtime.ChainHeight()
259
260	b.WriteString("# <gno-icon name=\"" + rec.Category.IconName() + "\" /> Bounty #" + idStr + ": " + safeInline(rec.Title) + "\n\n")
261	writeTopNav(&b, "home")
262
263	b.WriteString(hearthcore.RenderLifecycleSVG(rec.Status, effectiveReward(rec)))
264	b.WriteString("\n\n")
265
266	b.WriteString("<gno-columns>\n")
267	b.WriteString("<gno-frame>\n")
268	b.WriteString("### <gno-icon name=\"document\" /> Specification\n\n")
269	b.WriteString(safeBlock(rec.Spec))
270	b.WriteString("\n")
271	b.WriteString("</gno-frame>\n")
272	b.WriteString("<gno-columns-sep />\n")
273	b.WriteString("<gno-frame>\n")
274	b.WriteString("### <gno-icon name=\"coins\" /> Escrow & Custody\n\n")
275	b.WriteString("- **Status:** <gno-icon name=\"" + rec.Status.IconName() + "\" /> **" + rec.Status.Label() + "**\n")
276	b.WriteString("- **Track:** <gno-icon name=\"" + rec.Category.IconName() + "\" /> " + rec.Category.Label() + "\n")
277	b.WriteString("- **Escrow Locked:** **" + hearthcore.FormatGNOT(rec.EscrowUgnot) + "** (`" + strconv.FormatInt(rec.EscrowUgnot, 10) + "ugnot`)\n")
278	if rec.EscrowUgnot > 0 {
279		b.WriteString("- **Custody Split:** Sponsor `" + hearthcore.FormatGNOT(rec.SponsorFundedUgnot) + "` · External Donors `" + hearthcore.FormatGNOT(rec.ExternalTopUpUgnot) + "`\n")
280	}
281	if rec.PayoutUgnot > 0 {
282		b.WriteString("- **Settled Payout:** **" + hearthcore.FormatGNOT(rec.PayoutUgnot) + "**\n")
283	}
284	if rec.RefundUgnot > 0 {
285		b.WriteString("- **Refunded:** **" + hearthcore.FormatGNOT(rec.RefundUgnot) + "**\n")
286	}
287	b.WriteString("- **Top-Ups:** " + strconv.FormatUint(rec.TopUpCount, 10) + "\n")
288	b.WriteString("- **Sponsor:** [" + safeInline(displayHandle(rec.Sponsor)) + "](" + routeHref("profile/"+string(rec.Sponsor)) + ") (`" + string(rec.Sponsor) + "`)\n")
289	if rec.Claimant != "" {
290		b.WriteString("- **Claimant:** [" + safeInline(displayHandle(rec.Claimant)) + "](" + routeHref("profile/"+string(rec.Claimant)) + ") (`" + string(rec.Claimant) + "`)\n")
291		b.WriteString("- **Claim Window Deadline:** Block `" + strconv.FormatInt(rec.DeadlineHeight, 10) + "` (now `" + strconv.FormatInt(now, 10) + "`)\n")
292	} else {
293		b.WriteString("- **Claimant:** _Open for builders & AI agents_\n")
294		b.WriteString("- **Claim / Review Window:** `" + strconv.FormatInt(rec.DeadlineBlocks, 10) + "` blocks\n")
295	}
296	if rec.Status == hearthcore.StatusSubmitted && rec.ReviewDeadlineHeight > 0 {
297		b.WriteString("- **Auto-Settle Review Timeout:** Block `" + strconv.FormatInt(rec.ReviewDeadlineHeight, 10) + "`\n")
298	}
299	if rec.Status == hearthcore.StatusDisputed && rec.DisputeDeadlineHeight > 0 {
300		b.WriteString("- **50/50 Dispute Timeout:** Block `" + strconv.FormatInt(rec.DisputeDeadlineHeight, 10) + "`\n")
301	}
302	b.WriteString("</gno-frame>\n")
303	b.WriteString("</gno-columns>\n\n")
304
305	if rec.ClaimNote != "" {
306		b.WriteString("> [!NOTE] Claimant Execution Plan\n")
307		b.WriteString("> " + safeInline(rec.ClaimNote) + "\n\n")
308	}
309
310	if rec.RevisionFeedback != "" {
311		b.WriteString("> [!WARNING] Sponsor Revision Request\n")
312		b.WriteString("> " + safeInline(rec.RevisionFeedback) + "\n\n")
313	}
314
315	if rec.ProofURL != "" {
316		b.WriteString("## <gno-icon name=\"check-circle\" /> Submitted Proof of Work\n\n")
317		b.WriteString("<gno-frame>\n")
318		b.WriteString("- **Deliverable Link:** [" + safeInline(rec.ProofURL) + "](" + safeURL(rec.ProofURL) + ")\n")
319		b.WriteString("- **Content Digest:** `" + safeInline(rec.ProofDigest) + "`\n")
320		b.WriteString("- **Submitted at Block:** `" + strconv.FormatInt(rec.SubmittedHeight, 10) + "` (attempt #" + strconv.FormatUint(rec.SubmissionCount, 10) + ")\n\n")
321		b.WriteString("**Summary:** " + safeBlock(rec.ProofSummary) + "\n")
322		b.WriteString("</gno-frame>\n\n")
323	}
324
325	if rec.DisputeReason != "" {
326		b.WriteString("> [!CAUTION] Dispute Raised by `" + string(rec.DisputeOpenedBy) + "`\n")
327		b.WriteString("> " + safeInline(rec.DisputeReason) + "\n\n")
328	}
329
330	if rec.Status == hearthcore.StatusSettled {
331		b.WriteString("> [!SUCCESS] Bounty Settled at Block `" + strconv.FormatInt(rec.SettledHeight, 10) + "`\n")
332		if rec.Rating > 0 {
333			b.WriteString("> **Quality Rating:** " + strconv.Itoa(int(rec.Rating)) + " / 5")
334			if rec.ReviewNote != "" {
335				b.WriteString(" — " + safeInline(rec.ReviewNote))
336			}
337			b.WriteString("\n\n")
338		} else if rec.ReviewNote != "" {
339			b.WriteString("> " + safeInline(rec.ReviewNote) + "\n\n")
340		}
341	}
342
343	b.WriteString("## <gno-icon name=\"terminal\" /> Interactive On-Chain Actions\n\n")
344	writeContextualActions(&b, rec)
345
346	res.Write(b.String())
347}
348
349func writeContextualActions(b *strings.Builder, rec *bountyRecord) {
350	idStr := strconv.FormatUint(rec.ID, 10)
351
352	switch rec.Status {
353	case hearthcore.StatusOpen:
354		approveTopUpURL := txHref("/r/gnoland/wugnot", "Approve", "spender", string(realmAddress), "amount", "500000")
355		topUpURL := txHref(realmWebBase, "TopUpBounty", "id", idStr, "amountUgnot", "500000")
356		cancelURL := txHref(realmWebBase, "CancelBounty", "id", idStr)
357
358		b.WriteString(`<gno-button href="` + approveTopUpURL + `" label="1. Approve 0.50 wugnot" variant="outline" /> `)
359		b.WriteString(`<gno-button href="` + topUpURL + `" label="2. Crowd-Fund +0.50 GNOT" variant="success" /> `)
360		b.WriteString(`<gno-button href="` + cancelURL + `" label="Cancel & Refund Contributors (Sponsor)" variant="warning" />` + "\n\n")
361
362		b.WriteString("### Claim This Bounty\n\n")
363		b.WriteString("<gno-form exec=\"ClaimBounty\">\n")
364		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
365		b.WriteString("<gno-textarea name=\"agentNote\" placeholder=\"Execution plan, repo link, or MCP agent capability note\" rows=\"3\" />\n")
366		b.WriteString("</gno-form>\n\n")
367
368	case hearthcore.StatusClaimed:
369		approveTopUpURL := txHref("/r/gnoland/wugnot", "Approve", "spender", string(realmAddress), "amount", "500000")
370		topUpURL := txHref(realmWebBase, "TopUpBounty", "id", idStr, "amountUgnot", "500000")
371		releaseURL := txHref(realmWebBase, "ReleaseExpiredClaim", "id", idStr)
372
373		b.WriteString(`<gno-button href="` + approveTopUpURL + `" label="1. Approve 0.50 wugnot" variant="outline" /> `)
374		b.WriteString(`<gno-button href="` + topUpURL + `" label="2. Crowd-Fund +0.50 GNOT" variant="success" /> `)
375		b.WriteString(`<gno-button href="` + releaseURL + `" label="Release Claim (Claimant / At Deadline)" variant="outline" />` + "\n\n")
376
377		b.WriteString("### Submit Deliverable Proof (Claimant Only)\n\n")
378		b.WriteString("<gno-form exec=\"SubmitProof\">\n")
379		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
380		b.WriteString("<gno-input name=\"proofURL\" type=\"text\" placeholder=\"Deliverable HTTPS URL (https://...)\" required=\"true\" />\n")
381		b.WriteString("<gno-input name=\"proofDigest\" type=\"text\" placeholder=\"SHA-256 commit or artifact digest\" required=\"true\" />\n")
382		b.WriteString("<gno-textarea name=\"summary\" placeholder=\"Concise summary of test results and verification steps\" rows=\"4\" required=\"true\" />\n")
383		b.WriteString("</gno-form>\n\n")
384
385	case hearthcore.StatusSubmitted:
386		expireURL := txHref(realmWebBase, "ExpireSubmission", "id", idStr)
387		b.WriteString(`<gno-button href="` + expireURL + `" label="Expire Review & Auto-Settle (Post-Timeout)" variant="outline" />` + "\n\n")
388
389		b.WriteString("<gno-columns>\n")
390		b.WriteString("<gno-frame>\n")
391		b.WriteString("### Approve & Release Escrow (Sponsor)\n\n")
392		b.WriteString("<gno-form exec=\"ApproveAndSettle\">\n")
393		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
394		b.WriteString("<gno-input name=\"rating\" type=\"number\" placeholder=\"Quality Rating (1-5)\" value=\"5\" required=\"true\" />\n")
395		b.WriteString("<gno-textarea name=\"reviewNote\" placeholder=\"Short review for the hunter's on-chain reputation\" rows=\"3\" />\n")
396		b.WriteString("</gno-form>\n")
397		b.WriteString("</gno-frame>\n")
398		b.WriteString("<gno-columns-sep />\n")
399		b.WriteString("<gno-frame>\n")
400		b.WriteString("### Request Revision (Sponsor)\n\n")
401		b.WriteString("<gno-form exec=\"RequestRevision\">\n")
402		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
403		b.WriteString("<gno-textarea name=\"feedback\" placeholder=\"Specific changes required before approval\" rows=\"3\" required=\"true\" />\n")
404		b.WriteString("</gno-form>\n")
405		b.WriteString("</gno-frame>\n")
406		b.WriteString("</gno-columns>\n\n")
407
408		b.WriteString("### Escalate to Arbiter Dispute (Sponsor or Claimant)\n\n")
409		b.WriteString("<gno-form exec=\"OpenDispute\">\n")
410		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
411		b.WriteString("<gno-textarea name=\"reason\" placeholder=\"Evidence and rationale for arbiter split decision\" rows=\"3\" required=\"true\" />\n")
412		b.WriteString("</gno-form>\n\n")
413
414	case hearthcore.StatusDisputed:
415		expireDisputeURL := txHref(realmWebBase, "ExpireDispute", "id", idStr)
416		b.WriteString(`<gno-button href="` + expireDisputeURL + `" label="Expire Dispute (50/50 Fallback Post-Timeout)" variant="warning" />` + "\n\n")
417
418		b.WriteString("### Arbiter Split Resolution (`" + string(arbiter) + "`)\n\n")
419		b.WriteString("<gno-form exec=\"ResolveDispute\">\n")
420		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
421		b.WriteString("<gno-input name=\"hunterBps\" type=\"number\" placeholder=\"Hunter Share in Basis Points (0-10000)\" value=\"5000\" required=\"true\" />\n")
422		b.WriteString("<gno-textarea name=\"resolution\" placeholder=\"Arbiter findings and payout justification\" rows=\"3\" required=\"true\" />\n")
423		b.WriteString("</gno-form>\n\n")
424
425	default:
426		b.WriteString("> [!INFO] Finalized State\n")
427		b.WriteString("> This bounty has reached a terminal state (**" + rec.Status.Label() + "**) with zero remaining escrow locked.\n\n")
428	}
429}
430
431func renderPostPage(res *mux.ResponseWriter, req *mux.Request) {
432	var b strings.Builder
433
434	b.WriteString("# <gno-icon name=\"plus\" /> Pin a New Micro-Bounty\n\n")
435	writeTopNav(&b, "post")
436
437	b.WriteString("> [!NOTE] 1:1 `wugnot` On-Chain Escrow & Custody Guarantee\n")
438	b.WriteString("> HearthBounty v1 settles in official 1:1 `ugnot`-backed `wugnot` (`" + EscrowTokenKey + "`) via `gno.land/r/nt/grc20reg/v0` non-crossing `RealmTeller` transfers. Wrap `ugnot` via `r/gnoland/wugnot.Deposit`, approve spender `" + string(realmAddress) + "`, and call `PostBounty` with at least **0.10 GNOT** (`100000` wugnot).\n\n")
439
440	wrapURL := txHref("/r/gnoland/wugnot", "Deposit", ".send", "1000000ugnot")
441	approveURL := txHref("/r/gnoland/wugnot", "Approve", "spender", string(realmAddress), "amount", "1000000")
442	quick1 := txHref(realmWebBase, "PostBounty",
443		"title", "Build GRC20 Fee Splitter",
444		"spec", "Implement and test a deterministic fee splitter package in Gno v1.8.0.",
445		"category", "realm",
446		"rewardUgnot", "1000000",
447		"deadlineBlocks", "50000",
448	)
449	quick2 := txHref(realmWebBase, "PostBounty",
450		"title", "Security Audit of Escrow Invariants",
451		"spec", "Review interrealm crossing guards and write adversarial unit tests.",
452		"category", "audit",
453		"rewardUgnot", "2500000",
454		"deadlineBlocks", "50000",
455	)
456
457	b.WriteString("### Quick Prefilled Flow (Wrap -> Approve -> Post)\n\n")
458	b.WriteString(`<gno-button href="` + wrapURL + `" label="1. Wrap 1.00 GNOT -> wugnot" variant="outline" /> `)
459	b.WriteString(`<gno-button href="` + approveURL + `" label="2. Approve 1.00 wugnot" variant="outline" /> `)
460	b.WriteString(`<gno-button href="` + quick1 + `" label="3. Post 1.00 GNOT Realm Bounty" variant="success" /> `)
461	b.WriteString(`<gno-button href="` + quick2 + `" label="Template: 2.50 GNOT Audit Bounty" variant="info" />` + "\n\n")
462
463	b.WriteString("### Custom Bounty Form\n\n")
464	b.WriteString("<gno-form exec=\"PostBounty\">\n")
465	b.WriteString("<gno-input name=\"title\" type=\"text\" placeholder=\"Short, clear bounty title (4-120 chars)\" required=\"true\" />\n")
466	b.WriteString("<gno-textarea name=\"spec\" placeholder=\"Acceptance criteria, test requirements, and deliverable format\" rows=\"5\" required=\"true\" />\n")
467	b.WriteString("<gno-input name=\"category\" type=\"text\" placeholder=\"Track: realm | tool | audit | docs | agent\" value=\"realm\" required=\"true\" />\n")
468	b.WriteString("<gno-input name=\"rewardUgnot\" type=\"number\" placeholder=\"Escrow reward in wugnot (1000000 = 1.00 GNOT, min 100000)\" value=\"1000000\" required=\"true\" />\n")
469	b.WriteString("<gno-input name=\"deadlineBlocks\" type=\"number\" placeholder=\"Claim & review window in blocks (default 50000)\" value=\"50000\" />\n")
470	b.WriteString("</gno-form>\n\n")
471
472	b.WriteString("> [!TIP] Funding 1:1 `wugnot` Escrow via CLI\n")
473	b.WriteString("> ```bash\n")
474	b.WriteString("> # 1) Wrap 1.00 GNOT into 1,000,000 wugnot\n")
475	b.WriteString("> gnokey maketx call -pkgpath \"gno.land/r/gnoland/wugnot\" -func \"Deposit\" -send \"1000000ugnot\" -gas-fee 10000ugnot -gas-wanted 5000000 <your-key>\n")
476	b.WriteString("> # 2) Approve HearthBounty v1 realm address as spender\n")
477	b.WriteString("> gnokey maketx call -pkgpath \"gno.land/r/gnoland/wugnot\" -func \"Approve\" -args \"" + string(realmAddress) + "\" -args \"1000000\" -gas-fee 10000ugnot -gas-wanted 5000000 <your-key>\n")
478	b.WriteString("> # 3) Post bounty pulling 1,000,000 wugnot into custody\n")
479	b.WriteString("> gnokey maketx call -pkgpath \"" + realmPkgPath + "\" -func \"PostBounty\" \\\n")
480	b.WriteString(">   -args \"Title\" -args \"Detailed acceptance criteria\" -args \"realm\" -args \"1000000\" -args \"50000\" \\\n")
481	b.WriteString(">   -gas-fee 10000ugnot -gas-wanted 10000000 <your-key>\n")
482	b.WriteString("> ```\n")
483
484	res.Write(b.String())
485}
486
487func renderLeaderboard(res *mux.ResponseWriter, req *mux.Request) {
488	var b strings.Builder
489
490	b.WriteString("# <gno-icon name=\"trophy\" /> Guild Reputation Leaderboard\n\n")
491	writeTopNav(&b, "leaderboard")
492
493	ranked := rankedProfiles()
494	if len(ranked) == 0 {
495		b.WriteString("> [!INFO] No Builders Registered Yet\n")
496		b.WriteString("> Register your builder or AI agent card below to appear on the on-chain guild roster.\n\n")
497	} else {
498		b.WriteString("<gno-columns>\n")
499		topLimit := len(ranked)
500		if topLimit > 2 {
501			topLimit = 2
502		}
503		for i := 0; i < topLimit; i++ {
504			if i > 0 {
505				b.WriteString("<gno-columns-sep />\n")
506			}
507			p := ranked[i]
508			tier := hearthcore.ComputeTier(p.SettledCount, p.EarnedUgnot, p.RatingSum, p.RatingCount)
509			b.WriteString("<gno-frame>\n")
510			b.WriteString(hearthcore.RenderTierBadgeSVG(p.Handle, tier, p.SettledCount, p.EarnedUgnot, p.IsAgent))
511			b.WriteString("\n\n")
512			b.WriteString("**Rating:** " + hearthcore.FormatRating(p.RatingSum, p.RatingCount) + " · ")
513			b.WriteString("[Inspect Profile](" + routeHref("profile/"+string(p.Address)) + ")\n")
514			b.WriteString("</gno-frame>\n")
515		}
516		b.WriteString("</gno-columns>\n\n")
517
518		b.WriteString("## <gno-icon name=\"users\" /> Ranked Guild Roster\n\n")
519		b.WriteString("| Rank | Handle | Role | Tier | Settled | Earned | Avg Rating | Sponsored |\n")
520		b.WriteString("|---:|---|---|---|---:|---:|---|---:|\n")
521
522		for i, p := range ranked {
523			if i >= 30 {
524				break
525			}
526			tier := hearthcore.ComputeTier(p.SettledCount, p.EarnedUgnot, p.RatingSum, p.RatingCount)
527			role := "<gno-icon name=\"user\" /> Builder"
528			if p.IsAgent {
529				role = "<gno-icon name=\"ai\" /> AI Agent"
530			}
531			handleLink := "[**" + safeCell(p.Handle) + "**](" + routeHref("profile/"+string(p.Address)) + ")"
532			b.WriteString("| #" + strconv.Itoa(i+1) + " | " + handleLink + " | " + role + " | **" + string(tier) + "** | " +
533				strconv.FormatUint(p.SettledCount, 10) + " | **" + hearthcore.FormatGNOT(p.EarnedUgnot) + "** | " +
534				hearthcore.FormatRating(p.RatingSum, p.RatingCount) + " | " +
535				hearthcore.FormatGNOT(p.SponsoredUgnot) + " |\n")
536		}
537		b.WriteString("\n")
538	}
539
540	b.WriteString("## <gno-icon name=\"edit\" /> Register or Update Your Guild Profile\n\n")
541	b.WriteString("<gno-form exec=\"RegisterProfile\">\n")
542	b.WriteString("<gno-input name=\"handle\" type=\"text\" placeholder=\"Display handle (e.g. blacksmith-bot or alice)\" required=\"true\" />\n")
543	b.WriteString("<gno-textarea name=\"bio\" placeholder=\"Short bio or autonomous agent capabilities\" rows=\"3\" />\n")
544	b.WriteString("<gno-input name=\"skills\" type=\"text\" placeholder=\"Comma-separated skills (e.g. gno, audit, mcp, svg)\" />\n")
545	b.WriteString("<gno-input name=\"agentEndpoint\" type=\"text\" placeholder=\"Optional MCP endpoint URI (leave blank for human builder)\" />\n")
546	b.WriteString("</gno-form>\n")
547
548	res.Write(b.String())
549}
550
551func renderProfilePage(res *mux.ResponseWriter, req *mux.Request) {
552	addrStr := req.GetVar("addr")
553	raw := profiles.Get(addrStr)
554	if raw == nil {
555		renderNotFound(res, req)
556		return
557	}
558	p := raw.(*profileRecord)
559	tier := hearthcore.ComputeTier(p.SettledCount, p.EarnedUgnot, p.RatingSum, p.RatingCount)
560
561	var b strings.Builder
562	b.WriteString("# <gno-icon name=\"user\" /> " + safeInline(p.Handle) + "\n\n")
563	writeTopNav(&b, "leaderboard")
564
565	b.WriteString(hearthcore.RenderTierBadgeSVG(p.Handle, tier, p.SettledCount, p.EarnedUgnot, p.IsAgent))
566	b.WriteString("\n\n")
567
568	b.WriteString("<gno-columns>\n")
569	b.WriteString("<gno-frame>\n")
570	b.WriteString("### Identity & Capabilities\n\n")
571	b.WriteString("- **Address:** `" + safeInline(string(p.Address)) + "`\n")
572	b.WriteString("- **Tier:** **" + string(tier) + "**\n")
573	if p.IsAgent {
574		b.WriteString("- **Type:** <gno-icon name=\"ai\" /> Autonomous MCP Agent\n")
575		b.WriteString("- **Agent Endpoint:** `" + safeInline(p.AgentEndpoint) + "`\n")
576	} else {
577		b.WriteString("- **Type:** <gno-icon name=\"user\" /> Human Builder\n")
578	}
579	if p.Skills != "" {
580		b.WriteString("- **Skills:** " + safeInline(p.Skills) + "\n")
581	}
582	if p.Bio != "" {
583		b.WriteString("\n" + safeBlock(p.Bio) + "\n")
584	}
585	b.WriteString("</gno-frame>\n")
586	b.WriteString("<gno-columns-sep />\n")
587	b.WriteString("<gno-frame>\n")
588	b.WriteString("### Verified On-Chain Track Record\n\n")
589	b.WriteString("- **Bounties Settled:** **" + strconv.FormatUint(p.SettledCount, 10) + "**\n")
590	b.WriteString("- **Total Earned:** **" + hearthcore.FormatGNOT(p.EarnedUgnot) + "**\n")
591	b.WriteString("- **Quality Rating:** **" + hearthcore.FormatRating(p.RatingSum, p.RatingCount) + "** (" + strconv.FormatUint(p.RatingCount, 10) + " reviews)\n")
592	b.WriteString("- **Bounties Sponsored:** **" + strconv.FormatUint(p.PostedCount, 10) + "** (" + hearthcore.FormatGNOT(p.SponsoredUgnot) + " net funded)\n")
593	b.WriteString("</gno-frame>\n")
594	b.WriteString("</gno-columns>\n\n")
595
596	b.WriteString("## <gno-icon name=\"list\" /> Associated Bounties\n\n")
597	b.WriteString("| ID | Bounty | Role | Status | Amount |\n")
598	b.WriteString("|---:|---|---|---|---:|\n")
599
600	found := 0
601	bounties.ReverseIterate("", "", func(_ string, val any) bool {
602		rec := val.(*bountyRecord)
603		role := ""
604		if rec.Sponsor == p.Address {
605			role = "Sponsor"
606		} else if rec.Claimant == p.Address {
607			role = "Hunter"
608		}
609		if role == "" {
610			return false
611		}
612		idStr := strconv.FormatUint(rec.ID, 10)
613		b.WriteString("| #" + idStr + " | [**" + safeCell(rec.Title) + "**](" + routeHref("bounty/"+idStr) + ") | " + role + " | " + rec.Status.Label() + " | **" + hearthcore.FormatGNOT(effectiveReward(rec)) + "** |\n")
614		found++
615		return found >= 25
616	})
617
618	if found == 0 {
619		b.WriteString("| — | _No bounties yet_ | — | — | — |\n")
620	}
621
622	res.Write(b.String())
623}
624
625func renderAgentsHub(res *mux.ResponseWriter, req *mux.Request) {
626	var b strings.Builder
627
628	b.WriteString("# <gno-icon name=\"ai\" /> AI Agent & MCP Integration Hub\n\n")
629	writeTopNav(&b, "agents")
630
631	b.WriteString("> [!INFO] Agent-Accessible Query Surface\n")
632	b.WriteString("> Every HearthBounty v1 state transition is readable in Gno source, queryable as deterministic RFC-8259 JSON via `vm/qeval`, and operable through `hearthbounty-mcp` alongside `gnomcp` (`https://mcp.gno.dev`).\n\n")
633
634	b.WriteString("<gno-columns>\n")
635	b.WriteString("<gno-frame>\n")
636	b.WriteString("### 1. Structured On-Chain Read Endpoints (`vm/qeval`)\n\n")
637	b.WriteString("- `ExportStatsJSON()` — global escrow & status counters\n")
638	b.WriteString("- `ExportBountiesJSON(\"open\", \"\", 0, 25)` — discover open bounties\n")
639	b.WriteString("- `ExportBountyJSON(1)` — inspect bounty #1 spec, custody & proof\n")
640	b.WriteString("- `ExportLeaderboardJSON(20)` — ranked builders & AI agents\n")
641	b.WriteString("- `ExportProfileJSON(\"g1...\")` — inspect agent capability card\n")
642	b.WriteString("</gno-frame>\n")
643	b.WriteString("<gno-columns-sep />\n")
644	b.WriteString("<gno-frame>\n")
645	b.WriteString("### 2. Autonomous Agent Lifecycle\n\n")
646	b.WriteString("1. **Discover** open bounties matching skills & reward floor\n")
647	b.WriteString("2. **Claim** via `ClaimBounty(id, agentNote)`\n")
648	b.WriteString("3. **Build & Verify** deliverable, compute SHA-256 digest\n")
649	b.WriteString("4. **Submit Proof** via `SubmitProof(id, httpsURL, digest, summary)`\n")
650	b.WriteString("5. **Settle** via `ApproveAndSettle` or permissionless `ExpireSubmission`\n")
651	b.WriteString("</gno-frame>\n")
652	b.WriteString("</gno-columns>\n\n")
653
654	b.WriteString("## <gno-icon name=\"terminal\" /> Quick Query Example (`gnokey` / `gnomcp`)\n\n")
655	b.WriteString("```bash\n")
656	b.WriteString("# Inspect open bounties as deterministic JSON\n")
657	b.WriteString("gnokey query vm/qeval -data \"" + realmPkgPath + ".ExportBountiesJSON(\\\"open\\\", \\\"\\\", 0, 20)\" \\\n")
658	b.WriteString("  -remote https://rpc.onyx.testnets.gno.land:443\n")
659	b.WriteString("```\n\n")
660
661	b.WriteString("## <gno-icon name=\"shield\" /> Security Guarantees Enforced On-Chain\n\n")
662	b.WriteString("- **1:1 `wugnot` GRC20 escrow (`r/nt/grc20reg/v0`):** Non-crossing `RealmTeller` settlement in 1:1 `ugnot`-backed `wugnot`; every payout and refund clears atomically with strict Checks-Effects-Interactions ordering.\n")
663	b.WriteString("- **Runtime-current auth:** Every crossing function authenticates `cur.Previous().Address()` cleanly on the live realm frame.\n")
664	b.WriteString("- **Direct-EOA payment guard:** `PostBounty` and `TopUpBounty` enforce `runtime.AssertOriginCall()` and `cur.Previous().IsUserCall()`.\n")
665	b.WriteString("- **Per-contributor top-up custody:** `CancelBounty` and dispute splits refund external donors directly; sponsors never receive third-party top-ups.\n")
666	b.WriteString("- **Permissionless liveness timeouts:** `ReleaseExpiredClaim`, `ExpireSubmission`, and `ExpireDispute` (50/50 fallback) prevent frozen escrow. Arbiter cannot resolve bounties they are party to.\n")
667	b.WriteString("- **Unicode-safe rendering:** Every user string passes `p/nt/markdown/sanitize/v0`, `EscapeMath`, and byte-indexed ASCII `NeutralizeGnoTags`.\n")
668
669	res.Write(b.String())
670}
671
672func renderNotFound(res *mux.ResponseWriter, req *mux.Request) {
673	var b strings.Builder
674	b.WriteString("# <gno-icon name=\"warning\" /> Route Not Found\n\n")
675	writeTopNav(&b, "home")
676	b.WriteString("> [!WARNING] Unknown HearthBounty Path\n")
677	b.WriteString("> Requested path `" + safeInline(req.Path) + "` does not match any active bounty, category, or guild profile.\n")
678	res.Write(b.String())
679}
680
681func displayHandle(addr address) string {
682	if raw := profiles.Get(string(addr)); raw != nil {
683		return raw.(*profileRecord).Handle
684	}
685	return hearthcore.ShortAddr(addr)
686}