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

escrow.gno

package hearthbounty

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

	"gno.land/p/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthcore/v0"
)

// SetArbiter transfers dispute-resolution authority to a new valid Gno address.
func SetArbiter(cur realm, next address) {
	caller := cur.Previous().Address()
	if caller != arbiter {
		panic("hearthbounty: only current arbiter may transfer arbiter role")
	}
	if !next.IsValid() {
		panic("hearthbounty: next arbiter address is invalid")
	}
	arbiter = next
	chain.Emit(
		"ArbiterUpdated",
		"previous", string(caller),
		"arbiter", string(next),
	)
}

// RegisterProfile creates or updates a builder or autonomous AI agent profile.
// Providing a non-empty agentEndpoint marks the profile as an MCP-capable AI agent.
func RegisterProfile(cur realm, handle, bio, skills, agentEndpoint string) {
	caller := cur.Previous().Address()
	cleanHandle := hearthcore.ValidateText("handle", handle, 2, hearthcore.MaxHandleLen)
	cleanBio := hearthcore.ValidateText("bio", bio, 0, hearthcore.MaxBioLen)
	cleanSkills := hearthcore.ValidateText("skills", skills, 0, hearthcore.MaxSkillsLen)
	cleanEndpoint := hearthcore.ValidateText("agentEndpoint", agentEndpoint, 0, hearthcore.MaxEndpointLen)

	p := getOrCreateProfile(caller, runtime.ChainHeight())
	wasAgent := p.IsAgent
	p.Handle = cleanHandle
	p.Bio = cleanBio
	p.Skills = cleanSkills
	p.AgentEndpoint = cleanEndpoint
	p.IsAgent = cleanEndpoint != ""

	if !wasAgent && p.IsAgent {
		agentCount++
	} else if wasAgent && !p.IsAgent {
		agentCount--
	}

	chain.Emit(
		"ProfileRegistered",
		"address", string(caller),
		"handle", cleanHandle,
		"is_agent", strconv.FormatBool(p.IsAgent),
	)
}

// PostBounty creates a new micro-bounty funded with attached ugnot escrow.
// Requires a direct EOA call (AssertOriginCall + cur.Previous().IsUserCall()).
func PostBounty(cur realm, title, spec, category string, deadlineBlocks int64) uint64 {
	runtime.AssertOriginCall()
	if !cur.Previous().IsUserCall() {
		panic("hearthbounty: direct EOA call required to fund escrow")
	}

	amount := requireSingleUgnotSend(hearthcore.MinRewardUgnot)
	cleanTitle := hearthcore.ValidateText("title", title, 4, hearthcore.MaxTitleLen)
	cleanSpec := hearthcore.ValidateText("spec", spec, 10, hearthcore.MaxSpecLen)
	cat, ok := hearthcore.ParseCategory(category)
	if !ok {
		panic("hearthbounty: invalid category (use realm, tool, audit, docs, or agent)")
	}
	blocks := hearthcore.ValidateDeadlineBlocks(deadlineBlocks)

	sponsor := cur.Previous().Address()
	height := runtime.ChainHeight()
	nextID := uint64(bountySeq.Next())

	rec := &bountyRecord{
		ID:             nextID,
		Title:          cleanTitle,
		Spec:           cleanSpec,
		Category:       cat,
		Status:         hearthcore.StatusOpen,
		Sponsor:        sponsor,
		EscrowUgnot:    amount,
		InitialUgnot:   amount,
		DeadlineBlocks: blocks,
		CreatedHeight:  height,
	}

	bounties.Set(bountyKey(nextID), rec)
	openCount++
	totalEscrowUgnot += amount

	sp := getOrCreateProfile(sponsor, height)
	sp.PostedCount++
	sp.SponsoredUgnot += amount

	chain.Emit(
		"BountyPosted",
		"id", strconv.FormatUint(nextID, 10),
		"sponsor", string(sponsor),
		"category", string(cat),
		"escrow_ugnot", strconv.FormatInt(amount, 10),
		"deadline_blocks", strconv.FormatInt(blocks, 10),
	)

	return nextID
}

// TopUpBounty allows any supporter to crowd-fund additional ugnot into an open
// or claimed bounty's escrow pool.
func TopUpBounty(cur realm, id uint64) int64 {
	runtime.AssertOriginCall()
	if !cur.Previous().IsUserCall() {
		panic("hearthbounty: direct EOA call required to top up escrow")
	}

	amount := requireSingleUgnotSend(1)
	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusOpen && b.Status != hearthcore.StatusClaimed {
		panic("hearthbounty: can only top up open or claimed bounties")
	}

	donor := cur.Previous().Address()
	b.EscrowUgnot += amount
	b.TopUpCount++
	totalEscrowUgnot += amount

	dp := getOrCreateProfile(donor, runtime.ChainHeight())
	dp.SponsoredUgnot += amount

	chain.Emit(
		"BountyToppedUp",
		"id", strconv.FormatUint(id, 10),
		"donor", string(donor),
		"added_ugnot", strconv.FormatInt(amount, 10),
		"escrow_ugnot", strconv.FormatInt(b.EscrowUgnot, 10),
	)

	return b.EscrowUgnot
}

// ClaimBounty reserves an open bounty for a builder or autonomous AI agent.
// Sponsors cannot claim their own bounty to preserve reputation integrity.
func ClaimBounty(cur realm, id uint64, agentNote string) {
	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusOpen {
		panic("hearthbounty: bounty is not open for claiming")
	}

	caller := cur.Previous().Address()
	if caller == b.Sponsor {
		panic("hearthbounty: sponsor cannot claim own bounty")
	}
	cleanNote := hearthcore.ValidateText("agentNote", agentNote, 0, hearthcore.MaxNoteLen)

	height := runtime.ChainHeight()
	transitionStatus(b, hearthcore.StatusClaimed)
	b.Claimant = caller
	b.ClaimNote = cleanNote
	b.ClaimedHeight = height
	b.DeadlineHeight = height + b.DeadlineBlocks

	hp := getOrCreateProfile(caller, height)
	hp.ClaimedCount++

	chain.Emit(
		"BountyClaimed",
		"id", strconv.FormatUint(id, 10),
		"claimant", string(caller),
		"deadline_height", strconv.FormatInt(b.DeadlineHeight, 10),
	)
}

// ReleaseExpiredClaim returns a claimed bounty to Open when either the claimant
// voluntarily steps down or the deterministic block-height deadline has elapsed.
func ReleaseExpiredClaim(cur realm, id uint64) {
	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusClaimed {
		panic("hearthbounty: bounty is not currently claimed")
	}

	caller := cur.Previous().Address()
	height := runtime.ChainHeight()
	if caller != b.Claimant && height <= b.DeadlineHeight {
		panic("hearthbounty: claim deadline has not expired yet")
	}

	prevClaimant := b.Claimant
	transitionStatus(b, hearthcore.StatusOpen)
	b.Claimant = ""
	b.ClaimNote = ""
	b.ClaimedHeight = 0
	b.DeadlineHeight = 0
	b.RevisionFeedback = ""

	chain.Emit(
		"ClaimReleased",
		"id", strconv.FormatUint(id, 10),
		"previous_claimant", string(prevClaimant),
		"released_by", string(caller),
	)
}

// SubmitProof records a verifiable deliverable URL, cryptographic digest, and
// implementation summary for review by the sponsor.
func SubmitProof(cur realm, id uint64, proofURL, proofDigest, summary string) {
	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusClaimed {
		panic("hearthbounty: bounty must be claimed before submitting proof")
	}

	caller := cur.Previous().Address()
	if caller != b.Claimant {
		panic("hearthbounty: only the active claimant may submit proof")
	}

	cleanURL := hearthcore.ValidateProofURL(proofURL)
	cleanDigest := hearthcore.ValidateProofDigest(proofDigest)
	cleanSummary := hearthcore.ValidateText("summary", summary, 6, hearthcore.MaxNoteLen)

	transitionStatus(b, hearthcore.StatusSubmitted)
	b.ProofURL = cleanURL
	b.ProofDigest = cleanDigest
	b.ProofSummary = cleanSummary
	b.SubmittedHeight = runtime.ChainHeight()
	b.SubmissionCount++
	b.RevisionFeedback = ""

	chain.Emit(
		"ProofSubmitted",
		"id", strconv.FormatUint(id, 10),
		"claimant", string(caller),
		"proof_digest", cleanDigest,
		"submission_count", strconv.FormatUint(b.SubmissionCount, 10),
	)
}

// RequestRevision lets the sponsor send a submitted bounty back to Claimed with
// actionable feedback and a refreshed deadline window.
func RequestRevision(cur realm, id uint64, feedback string) {
	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusSubmitted {
		panic("hearthbounty: bounty has no pending submission")
	}

	caller := cur.Previous().Address()
	if caller != b.Sponsor {
		panic("hearthbounty: only the sponsor may request a revision")
	}

	cleanFeedback := hearthcore.ValidateText("feedback", feedback, 4, hearthcore.MaxNoteLen)
	transitionStatus(b, hearthcore.StatusClaimed)
	b.RevisionFeedback = cleanFeedback
	b.DeadlineHeight = runtime.ChainHeight() + b.DeadlineBlocks

	chain.Emit(
		"RevisionRequested",
		"id", strconv.FormatUint(id, 10),
		"sponsor", string(caller),
		"new_deadline_height", strconv.FormatInt(b.DeadlineHeight, 10),
	)
}

// ApproveAndSettle releases the full ugnot escrow to the claimant, records a
// 1-5 quality rating, and updates on-chain reputation using CEI ordering.
func ApproveAndSettle(cur realm, id uint64, rating uint8, reviewNote string) {
	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusSubmitted {
		panic("hearthbounty: bounty is not awaiting approval")
	}

	caller := cur.Previous().Address()
	if caller != b.Sponsor {
		panic("hearthbounty: only the sponsor may approve and settle")
	}

	validRating := hearthcore.ValidateRating(rating)
	cleanNote := hearthcore.ValidateText("reviewNote", reviewNote, 0, hearthcore.MaxNoteLen)

	payout := b.EscrowUgnot
	recipient := b.Claimant
	height := runtime.ChainHeight()

	// Effects before external bank interaction (CEI).
	b.EscrowUgnot = 0
	b.PayoutUgnot = payout
	b.Rating = validRating
	b.ReviewNote = cleanNote
	b.SettledHeight = height
	transitionStatus(b, hearthcore.StatusSettled)
	totalEscrowUgnot -= payout
	totalSettledUgnot += payout

	hp := getOrCreateProfile(recipient, height)
	hp.SettledCount++
	hp.EarnedUgnot += payout
	hp.RatingSum += uint64(validRating)
	hp.RatingCount++

	sp := getOrCreateProfile(b.Sponsor, height)
	sp.SponsoredSettled++

	// Interaction: send escrowed ugnot from realm address to claimant.
	if payout > 0 {
		bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
		bnk.SendCoins(cur.Address(), recipient, chain.Coins{{Denom: hearthcore.Denom, Amount: payout}})
	}

	chain.Emit(
		"BountySettled",
		"id", strconv.FormatUint(id, 10),
		"sponsor", string(b.Sponsor),
		"claimant", string(recipient),
		"payout_ugnot", strconv.FormatInt(payout, 10),
		"rating", strconv.Itoa(int(validRating)),
	)
}

// CancelBounty refunds escrowed ugnot to the sponsor. Only permitted while the
// bounty is Open so sponsors cannot withdraw funds from an active claim.
func CancelBounty(cur realm, id uint64) {
	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusOpen {
		panic("hearthbounty: only open bounties can be cancelled")
	}

	caller := cur.Previous().Address()
	if caller != b.Sponsor {
		panic("hearthbounty: only the sponsor may cancel")
	}

	refund := b.EscrowUgnot
	b.EscrowUgnot = 0
	b.RefundUgnot = refund
	transitionStatus(b, hearthcore.StatusCancelled)
	totalEscrowUgnot -= refund
	totalRefundUgnot += refund

	if refund > 0 {
		bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
		bnk.SendCoins(cur.Address(), b.Sponsor, chain.Coins{{Denom: hearthcore.Denom, Amount: refund}})
	}

	chain.Emit(
		"BountyCancelled",
		"id", strconv.FormatUint(id, 10),
		"sponsor", string(b.Sponsor),
		"refund_ugnot", strconv.FormatInt(refund, 10),
	)
}

// OpenDispute escalates a submitted bounty to arbiter review. Either the
// sponsor or the active claimant may open a dispute.
func OpenDispute(cur realm, id uint64, reason string) {
	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusSubmitted {
		panic("hearthbounty: disputes can only be opened on submitted bounties")
	}

	caller := cur.Previous().Address()
	if caller != b.Sponsor && caller != b.Claimant {
		panic("hearthbounty: only sponsor or claimant may open a dispute")
	}

	cleanReason := hearthcore.ValidateText("reason", reason, 6, hearthcore.MaxNoteLen)
	transitionStatus(b, hearthcore.StatusDisputed)
	b.DisputeReason = cleanReason
	b.DisputeOpenedBy = caller

	chain.Emit(
		"DisputeOpened",
		"id", strconv.FormatUint(id, 10),
		"opened_by", string(caller),
		"reason", cleanReason,
	)
}

// ResolveDispute settles a disputed bounty using deterministic basis-point math
// (hunterBps in 0..10000). The remainder is refunded atomically to the sponsor.
func ResolveDispute(cur realm, id uint64, hunterBps uint64, resolution string) {
	caller := cur.Previous().Address()
	if caller != arbiter {
		panic("hearthbounty: only the arbiter may resolve disputes")
	}

	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusDisputed {
		panic("hearthbounty: bounty is not disputed")
	}

	cleanResolution := hearthcore.ValidateText("resolution", resolution, 4, hearthcore.MaxNoteLen)
	escrow := b.EscrowUgnot
	hunterShare, sponsorShare := hearthcore.ComputeSplit(escrow, hunterBps)
	height := runtime.ChainHeight()

	// Effects before interactions (CEI).
	b.EscrowUgnot = 0
	b.PayoutUgnot = hunterShare
	b.RefundUgnot = sponsorShare
	b.ReviewNote = "[Arbiter Resolution] " + cleanResolution
	b.SettledHeight = height
	transitionStatus(b, hearthcore.StatusSettled)
	totalEscrowUgnot -= escrow
	totalSettledUgnot += hunterShare
	totalRefundUgnot += sponsorShare

	if hunterShare > 0 {
		hp := getOrCreateProfile(b.Claimant, height)
		hp.SettledCount++
		hp.EarnedUgnot += hunterShare
	}

	bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	if hunterShare > 0 {
		bnk.SendCoins(cur.Address(), b.Claimant, chain.Coins{{Denom: hearthcore.Denom, Amount: hunterShare}})
	}
	if sponsorShare > 0 {
		bnk.SendCoins(cur.Address(), b.Sponsor, chain.Coins{{Denom: hearthcore.Denom, Amount: sponsorShare}})
	}

	chain.Emit(
		"DisputeResolved",
		"id", strconv.FormatUint(id, 10),
		"arbiter", string(caller),
		"hunter_bps", strconv.FormatUint(hunterBps, 10),
		"hunter_ugnot", strconv.FormatInt(hunterShare, 10),
		"sponsor_refund_ugnot", strconv.FormatInt(sponsorShare, 10),
	)
}

// requireSingleUgnotSend validates that the caller attached exclusively ugnot
// at or above minAmount so unsupported denominations cannot get trapped.
func requireSingleUgnotSend(minAmount int64) int64 {
	sent := unsafe.OriginSend()
	if len(sent) == 0 {
		panic("hearthbounty: must attach ugnot escrow coins")
	}
	if len(sent) != 1 || sent[0].Denom != hearthcore.Denom {
		panic("hearthbounty: only ugnot coins are accepted")
	}
	if sent[0].Amount < minAmount {
		panic("hearthbounty: attached ugnot is below minimum required amount")
	}
	return sent[0].Amount
}

func normalizeFilter(raw string) string {
	return strings.ToLower(strings.TrimSpace(raw))
}

gnomod.toml

module = "gno.land/r/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthbounty/v0"
gno = "0.9"

[addpkg]
  creator = "g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4"
  height = 1374813
  max_deposit = "50000000ugnot"

hearthbounty_test.gno

package hearthbounty

import (
	"chain"
	"chain/banker"
	"strings"
	"testing"

	"gno.land/p/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthcore/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

func resetState(initialArbiter address) {
	arbiter = initialArbiter
	realmWebBase = "/r/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthbounty/v0"
	bountySeq = 0
	bounties = avl.NewTree()
	profiles = avl.NewTree()
	openCount = 0
	claimedCount = 0
	submittedCount = 0
	disputedCount = 0
	settledCount = 0
	cancelledCount = 0
	agentCount = 0
	totalEscrowUgnot = 0
	totalSettledUgnot = 0
	totalRefundUgnot = 0
	initRouter()
}

func assertEscrowInvariant(t *testing.T, realmAddr address, initialRealmBal int64) {
	t.Helper()
	bnk := banker.NewReadonlyBanker()
	bal := bnk.GetCoin(realmAddr, hearthcore.Denom)
	uassert.Equal(t, initialRealmBal+totalEscrowUgnot, bal)
}

func TestFullBountyLifecycleAndReputation(cur realm, t *testing.T) {
	arb := testutils.TestAddress("arbiter")
	sponsor := testutils.TestAddress("sponsor")
	agent := testutils.TestAddress("agent_hunter")
	donor := testutils.TestAddress("crowdfund_donor")
	realmAddr := chain.PackageAddress("gno.land/r/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthbounty/v0")

	testing.SetRealm(testing.NewUserRealm(arb))
	resetState(arb)
	baseRealmBal := banker.NewReadonlyBanker().GetCoin(realmAddr, hearthcore.Denom)

	// Register an AI agent profile.
	testing.SetRealm(testing.NewUserRealm(agent))
	RegisterProfile(cross(cur), "anvil-ai", "Autonomous Gno realm builder", "gno,audit,mcp", "mcp://anvil.local")
	prof, ok := GetProfile(agent)
	uassert.True(t, ok)
	uassert.True(t, prof.IsAgent)
	uassert.Equal(t, "anvil-ai", prof.Handle)
	uassert.Equal(t, 1, GetStats().AgentCount)

	// Sponsor posts a 2.00 GNOT bounty.
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: 2000000}})
	testing.IssueCoins(realmAddr, chain.Coins{{Denom: "ugnot", Amount: 2000000}})
	id := PostBounty(cross(cur), "Build AVL Leaderboard Helper", "Provide a deterministic AVL sorting helper with 100% unit test coverage.", "realm", 200)
	uassert.Equal(t, uint64(1), id)
	uassert.Equal(t, int64(2000000), GetStats().TotalEscrowUgnot)
	assertEscrowInvariant(t, realmAddr, baseRealmBal)

	// Supporter tops up +0.50 GNOT.
	testing.SetOriginCaller(donor)
	testing.SetRealm(testing.NewUserRealm(donor))
	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: 500000}})
	testing.IssueCoins(realmAddr, chain.Coins{{Denom: "ugnot", Amount: 500000}})
	newEscrow := TopUpBounty(cross(cur), id)
	uassert.Equal(t, int64(2500000), newEscrow)
	assertEscrowInvariant(t, realmAddr, baseRealmBal)

	// Sponsor cannot claim own bounty.
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	uassert.AbortsWithMessage(t, cur, "hearthbounty: sponsor cannot claim own bounty", func() {
		ClaimBounty(cross(cur), id, "self claim")
	})

	// Agent claims bounty.
	testing.SetOriginCaller(agent)
	testing.SetRealm(testing.NewUserRealm(agent))
	ClaimBounty(cross(cur), id, "Claiming via hearthbounty-mcp; ETA 40 blocks.")
	b, ok := GetBounty(id)
	uassert.True(t, ok)
	uassert.Equal(t, string(hearthcore.StatusClaimed), string(b.Status))
	uassert.Equal(t, agent, b.Claimant)

	// Agent submits proof.
	SubmitProof(cross(cur), id, "https://github.com/hearthbounty/demo/pull/42", "sha256:9f86d081884c7d659a2feaa0c55ad015", "Implemented AVL leaderboard helper and passed all 18 tests.")
	b, _ = GetBounty(id)
	uassert.Equal(t, string(hearthcore.StatusSubmitted), string(b.Status))
	uassert.Equal(t, uint64(1), b.SubmissionCount)

	// Sponsor requests a revision.
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	RequestRevision(cross(cur), id, "Please add edge-case tests for empty trees.")
	b, _ = GetBounty(id)
	uassert.Equal(t, string(hearthcore.StatusClaimed), string(b.Status))
	uassert.Equal(t, "Please add edge-case tests for empty trees.", b.RevisionFeedback)

	// Agent resubmits revised proof.
	testing.SetOriginCaller(agent)
	testing.SetRealm(testing.NewUserRealm(agent))
	SubmitProof(cross(cur), id, "https://github.com/hearthbounty/demo/pull/42", "sha256:4b227777d4dd1fc61c6f884f48641d02", "Added empty-tree and tie-breaker unit tests.")
	b, _ = GetBounty(id)
	uassert.Equal(t, uint64(2), b.SubmissionCount)

	// Non-sponsor cannot settle.
	uassert.AbortsWithMessage(t, cur, "hearthbounty: only the sponsor may approve and settle", func() {
		ApproveAndSettle(cross(cur), id, 5, "unauthorized")
	})

	// Sponsor approves & settles; verify exact ugnot transfer and reputation update.
	agentBalBefore := banker.NewReadonlyBanker().GetCoin(agent, hearthcore.Denom)
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	ApproveAndSettle(cross(cur), id, 5, "Clean idiomatic Gno code and crisp tests!")

	agentBalAfter := banker.NewReadonlyBanker().GetCoin(agent, hearthcore.Denom)
	uassert.Equal(t, agentBalBefore+2500000, agentBalAfter)
	assertEscrowInvariant(t, realmAddr, baseRealmBal)

	b, _ = GetBounty(id)
	uassert.Equal(t, string(hearthcore.StatusSettled), string(b.Status))
	uassert.Equal(t, int64(0), b.EscrowUgnot)
	uassert.Equal(t, int64(2500000), b.PayoutUgnot)
	uassert.Equal(t, uint8(5), b.Rating)

	prof, _ = GetProfile(agent)
	uassert.Equal(t, uint64(1), prof.SettledCount)
	uassert.Equal(t, int64(2500000), prof.EarnedUgnot)
	uassert.Equal(t, uint64(5), prof.RatingSum)
	uassert.Equal(t, uint64(1), prof.RatingCount)
}

func TestCancelAndExpiredClaimRelease(cur realm, t *testing.T) {
	arb := testutils.TestAddress("arbiter2")
	sponsor := testutils.TestAddress("sponsor2")
	hunter := testutils.TestAddress("hunter2")
	bystander := testutils.TestAddress("bystander2")
	realmAddr := chain.PackageAddress("gno.land/r/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthbounty/v0")

	testing.SetRealm(testing.NewUserRealm(arb))
	resetState(arb)
	baseRealmBal := banker.NewReadonlyBanker().GetCoin(realmAddr, hearthcore.Denom)

	// Post a bounty with short 20-block claim window.
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: 1000000}})
	testing.IssueCoins(realmAddr, chain.Coins{{Denom: "ugnot", Amount: 1000000}})
	id := PostBounty(cross(cur), "Write gnoweb SVG Guide", "Document deterministic SVG rendering in gnoweb v1.8.", "docs", 20)

	// Hunter claims it.
	testing.SetOriginCaller(hunter)
	testing.SetRealm(testing.NewUserRealm(hunter))
	ClaimBounty(cross(cur), id, "On it")

	// Sponsor cannot cancel while claimed.
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	uassert.AbortsWithMessage(t, cur, "hearthbounty: only open bounties can be cancelled", func() {
		CancelBounty(cross(cur), id)
	})

	// Bystander cannot release before deadline.
	testing.SetOriginCaller(bystander)
	testing.SetRealm(testing.NewUserRealm(bystander))
	uassert.AbortsWithMessage(t, cur, "hearthbounty: claim deadline has not expired yet", func() {
		ReleaseExpiredClaim(cross(cur), id)
	})

	// Advance chain height past deadline -> bystander releases stale claim.
	testing.SkipHeights(25)
	ReleaseExpiredClaim(cross(cur), id)
	b, _ := GetBounty(id)
	uassert.Equal(t, string(hearthcore.StatusOpen), string(b.Status))
	uassert.Equal(t, address(""), b.Claimant)

	// Now sponsor cancels and recovers full 1.00 GNOT escrow.
	sponsorBalBefore := banker.NewReadonlyBanker().GetCoin(sponsor, hearthcore.Denom)
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	CancelBounty(cross(cur), id)

	sponsorBalAfter := banker.NewReadonlyBanker().GetCoin(sponsor, hearthcore.Denom)
	uassert.Equal(t, sponsorBalBefore+1000000, sponsorBalAfter)
	assertEscrowInvariant(t, realmAddr, baseRealmBal)
	uassert.Equal(t, int64(1000000), GetStats().TotalRefundUgnot)
}

func TestDisputeSplitResolutionAndArbiterTransfer(cur realm, t *testing.T) {
	arb := testutils.TestAddress("arbiter3")
	arb2 := testutils.TestAddress("arbiter3_new")
	sponsor := testutils.TestAddress("sponsor3")
	hunter := testutils.TestAddress("hunter3")
	realmAddr := chain.PackageAddress("gno.land/r/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthbounty/v0")

	testing.SetRealm(testing.NewUserRealm(arb))
	resetState(arb)
	baseRealmBal := banker.NewReadonlyBanker().GetCoin(realmAddr, hearthcore.Denom)

	// Transfer arbiter role.
	SetArbiter(cross(cur), arb2)
	uassert.Equal(t, arb2, Arbiter())

	// Post, claim, submit.
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: 1000000}})
	testing.IssueCoins(realmAddr, chain.Coins{{Denom: "ugnot", Amount: 1000000}})
	id := PostBounty(cross(cur), "Audit Interrealm Payment Guard", "Check all crossing guards and produce formal report.", "audit", 100)

	testing.SetOriginCaller(hunter)
	testing.SetRealm(testing.NewUserRealm(hunter))
	ClaimBounty(cross(cur), id, "Auditing now")
	SubmitProof(cross(cur), id, "https://github.com/hearthbounty/audit/blob/main/report.md", "sha256:abcdef0123456789", "Delivered partial audit covering 70% of scope.")

	// Hunter opens dispute.
	OpenDispute(cross(cur), id, "Core findings delivered; requesting 70/30 partial settlement.")
	b, _ := GetBounty(id)
	uassert.Equal(t, string(hearthcore.StatusDisputed), string(b.Status))

	// Old arbiter cannot resolve.
	testing.SetOriginCaller(arb)
	testing.SetRealm(testing.NewUserRealm(arb))
	uassert.AbortsWithMessage(t, cur, "hearthbounty: only the arbiter may resolve disputes", func() {
		ResolveDispute(cross(cur), id, 7000, "unauthorized")
	})

	// New arbiter resolves 70% hunter / 30% sponsor refund.
	hunterBalBefore := banker.NewReadonlyBanker().GetCoin(hunter, hearthcore.Denom)
	sponsorBalBefore := banker.NewReadonlyBanker().GetCoin(sponsor, hearthcore.Denom)

	testing.SetOriginCaller(arb2)
	testing.SetRealm(testing.NewUserRealm(arb2))
	ResolveDispute(cross(cur), id, 7000, "70% of specification verified; 30% refunded to sponsor.")

	uassert.Equal(t, hunterBalBefore+700000, banker.NewReadonlyBanker().GetCoin(hunter, hearthcore.Denom))
	uassert.Equal(t, sponsorBalBefore+300000, banker.NewReadonlyBanker().GetCoin(sponsor, hearthcore.Denom))
	assertEscrowInvariant(t, realmAddr, baseRealmBal)

	b, _ = GetBounty(id)
	uassert.Equal(t, string(hearthcore.StatusSettled), string(b.Status))
	uassert.Equal(t, int64(700000), b.PayoutUgnot)
	uassert.Equal(t, int64(300000), b.RefundUgnot)
}

func TestSecurityGuardsAndSanitizedRender(cur realm, t *testing.T) {
	arb := testutils.TestAddress("arbiter4")
	sponsor := testutils.TestAddress("sponsor4")
	realmAddr := chain.PackageAddress("gno.land/r/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthbounty/v0")

	testing.SetRealm(testing.NewUserRealm(arb))
	resetState(arb)

	// Cross-realm wrapper calls must be rejected by runtime.AssertOriginCall().
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: 1000000}})
	uassert.AbortsWithMessage(t, cur, "invalid non-origin call", func() {
		PostBounty(cross(cur), "Cross Call", "Should abort because called through uassert closure.", "tool", 100)
	})

	// Reject zero coins, dust below 0.10 GNOT, and unsupported denominations.
	testing.SetOriginSend(chain.Coins{})
	uassert.PanicsWithMessage(t, cur, "hearthbounty: must attach ugnot escrow coins", func() {
		requireSingleUgnotSend(hearthcore.MinRewardUgnot)
	})

	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: 50000}})
	uassert.PanicsWithMessage(t, cur, "hearthbounty: attached ugnot is below minimum required amount", func() {
		requireSingleUgnotSend(hearthcore.MinRewardUgnot)
	})

	testing.SetOriginSend(chain.Coins{{Denom: "uatom", Amount: 1000000}})
	uassert.PanicsWithMessage(t, cur, "hearthbounty: only ugnot coins are accepted", func() {
		requireSingleUgnotSend(hearthcore.MinRewardUgnot)
	})

	// Reject markdown button/form/math injection in rendered output.
	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: 1500000}})
	testing.IssueCoins(realmAddr, chain.Coins{{Denom: "ugnot", Amount: 1500000}})
	id := PostBounty(
		cross(cur),
		`Test <gno-button href="/r/evil" label="Steal" /> $GNOT/$ATOM`,
		"Normal spec with $100 and <gno-form exec=\"Drain\"> attempt.\n<gno-form exec=\"Drain2\">\n</gno-form>",
		"agent",
		100,
	)

	home := Render("")
	uassert.True(t, strings.Contains(home, "HearthBounty"))
	uassert.True(t, strings.Contains(home, "data:image/svg+xml;base64,"))
	uassert.False(t, strings.Contains(home, `<gno-button href="/r/evil"`))
	uassert.True(t, strings.Contains(home, `\$GNOT/\$ATOM`))

	detail := Render("bounty/1")
	uassert.True(t, strings.Contains(detail, "Bounty #1:"))
	uassert.True(t, strings.Contains(detail, `<gno-form exec="ClaimBounty">`))
	uassert.False(t, strings.Contains(detail, `<gno-form exec="Drain">`))

	// Verify all other routes render cleanly.
	uassert.True(t, strings.Contains(Render("post"), `<gno-form exec="PostBounty">`))
	uassert.True(t, strings.Contains(Render("leaderboard"), "Guild Reputation Leaderboard"))
	uassert.True(t, strings.Contains(Render("agents"), "AI Agent"))
	uassert.True(t, strings.Contains(Render("category/agent"), "AI Agent Bounties"))
	uassert.True(t, strings.Contains(Render("profile/"+string(sponsor)), string(sponsor)))
	uassert.True(t, strings.Contains(Render("unknown/path"), "Route Not Found"))

	// Verify JSON export endpoints.
	statsJSON := ExportStatsJSON()
	uassert.True(t, strings.Contains(statsJSON, `"total_bounties":1`))
	bountyJSON := ExportBountyJSON(id)
	uassert.True(t, strings.Contains(bountyJSON, `"found":true`))
	listJSON := ExportBountiesJSON("open", "agent", 1000000, 10)
	uassert.True(t, strings.Contains(listJSON, `"count":1`))
	lbJSON := ExportLeaderboardJSON(10)
	uassert.True(t, strings.Contains(lbJSON, `"count":1`))
}

query.gno

package hearthbounty

import (
	"chain/runtime"
	"sort"

	"gno.land/p/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthcore/v0"
)

// Arbiter returns the current dispute arbiter address.
func Arbiter() address {
	return arbiter
}

// GetStats returns an immutable snapshot of protocol counters and escrow totals.
func GetStats() BoardStats {
	return BoardStats{
		TotalBounties:     bounties.Size(),
		OpenCount:         openCount,
		ClaimedCount:      claimedCount,
		SubmittedCount:    submittedCount,
		DisputedCount:     disputedCount,
		SettledCount:      settledCount,
		CancelledCount:    cancelledCount,
		ProfileCount:      profiles.Size(),
		AgentCount:        agentCount,
		TotalEscrowUgnot:  totalEscrowUgnot,
		TotalSettledUgnot: totalSettledUgnot,
		TotalRefundUgnot:  totalRefundUgnot,
	}
}

// GetBounty returns a value copy of a single bounty by ID.
func GetBounty(id uint64) (BountyView, bool) {
	b, ok := getBountyRecord(id)
	if !ok {
		return BountyView{}, false
	}
	return toBountyView(b), true
}

// GetProfile returns a value copy of a builder or AI agent profile.
func GetProfile(addr address) (ProfileView, bool) {
	raw := profiles.Get(string(addr))
	if raw == nil {
		return ProfileView{}, false
	}
	return toProfileView(raw.(*profileRecord)), true
}

// ExportStatsJSON returns global protocol stats as deterministic JSON for MCP agents.
func ExportStatsJSON() string {
	s := GetStats()
	return hearthcore.NewJSONObject().
		Str("realm_path", realmWebBase).
		Str("arbiter", string(arbiter)).
		Int64("chain_height", runtime.ChainHeight()).
		Int64("total_bounties", int64(s.TotalBounties)).
		Int64("open_count", int64(s.OpenCount)).
		Int64("claimed_count", int64(s.ClaimedCount)).
		Int64("submitted_count", int64(s.SubmittedCount)).
		Int64("disputed_count", int64(s.DisputedCount)).
		Int64("settled_count", int64(s.SettledCount)).
		Int64("cancelled_count", int64(s.CancelledCount)).
		Int64("profile_count", int64(s.ProfileCount)).
		Int64("agent_count", int64(s.AgentCount)).
		Int64("total_escrow_ugnot", s.TotalEscrowUgnot).
		Int64("total_settled_ugnot", s.TotalSettledUgnot).
		Int64("total_refund_ugnot", s.TotalRefundUgnot).
		String()
}

// ExportBountyJSON returns a single bounty as deterministic JSON (or {"found":false}).
func ExportBountyJSON(id uint64) string {
	b, ok := getBountyRecord(id)
	if !ok {
		return `{"found":false}`
	}
	return encodeBountyJSON(b, true)
}

// ExportBountiesJSON lists bounties in reverse chronological order with optional
// status, category, and minimum reward filters for autonomous agent discovery.
func ExportBountiesJSON(statusFilter, categoryFilter string, minRewardUgnot int64, limit int) string {
	st := normalizeFilter(statusFilter)
	cat := normalizeFilter(categoryFilter)
	if limit <= 0 || limit > 100 {
		limit = 50
	}

	items := make([]string, 0)
	bounties.ReverseIterate("", "", func(_ string, val any) bool {
		b := val.(*bountyRecord)
		if st != "" && string(b.Status) != st {
			return false
		}
		if cat != "" && string(b.Category) != cat {
			return false
		}
		reward := effectiveReward(b)
		if minRewardUgnot > 0 && reward < minRewardUgnot {
			return false
		}
		items = append(items, encodeBountyJSON(b, false))
		return len(items) >= limit
	})

	return hearthcore.NewJSONObject().
		Int64("chain_height", runtime.ChainHeight()).
		Int64("count", int64(len(items))).
		Raw("bounties", hearthcore.JoinJSONArray(items)).
		String()
}

// ExportLeaderboardJSON returns deterministically sorted builders & AI agents.
func ExportLeaderboardJSON(limit int) string {
	if limit <= 0 || limit > 100 {
		limit = 25
	}
	ranked := rankedProfiles()
	if len(ranked) > limit {
		ranked = ranked[:limit]
	}

	items := make([]string, 0, len(ranked))
	for i, p := range ranked {
		items = append(items, encodeProfileJSON(p, i+1))
	}

	return hearthcore.NewJSONObject().
		Int64("count", int64(len(items))).
		Raw("leaderboard", hearthcore.JoinJSONArray(items)).
		String()
}

// ExportProfileJSON returns a single profile as deterministic JSON.
func ExportProfileJSON(addrStr string) string {
	raw := profiles.Get(addrStr)
	if raw == nil {
		return `{"found":false}`
	}
	p := raw.(*profileRecord)
	return encodeProfileJSON(p, 0)
}

func effectiveReward(b *bountyRecord) int64 {
	if b.EscrowUgnot > 0 {
		return b.EscrowUgnot
	}
	if b.PayoutUgnot > 0 {
		return b.PayoutUgnot
	}
	if b.RefundUgnot > 0 {
		return b.RefundUgnot
	}
	return b.InitialUgnot
}

func encodeBountyJSON(b *bountyRecord, includeFound bool) string {
	jb := hearthcore.NewJSONObject()
	if includeFound {
		jb.Bool("found", true)
	}
	jb.Uint64("id", b.ID).
		Str("title", b.Title).
		Str("spec", b.Spec).
		Str("category", string(b.Category)).
		Str("status", string(b.Status)).
		Str("sponsor", string(b.Sponsor)).
		Str("claimant", string(b.Claimant)).
		Str("claim_note", b.ClaimNote).
		Int64("escrow_ugnot", b.EscrowUgnot).
		Int64("initial_ugnot", b.InitialUgnot).
		Int64("payout_ugnot", b.PayoutUgnot).
		Int64("refund_ugnot", b.RefundUgnot).
		Str("reward_formatted", hearthcore.FormatGNOT(effectiveReward(b))).
		Uint64("top_up_count", b.TopUpCount).
		Int64("deadline_blocks", b.DeadlineBlocks).
		Int64("created_height", b.CreatedHeight).
		Int64("claimed_height", b.ClaimedHeight).
		Int64("deadline_height", b.DeadlineHeight).
		Int64("submitted_height", b.SubmittedHeight).
		Int64("settled_height", b.SettledHeight).
		Str("proof_url", b.ProofURL).
		Str("proof_digest", b.ProofDigest).
		Str("proof_summary", b.ProofSummary).
		Uint64("submission_count", b.SubmissionCount).
		Str("revision_feedback", b.RevisionFeedback).
		Uint64("rating", uint64(b.Rating)).
		Str("review_note", b.ReviewNote).
		Str("dispute_reason", b.DisputeReason).
		Str("dispute_opened_by", string(b.DisputeOpenedBy))
	return jb.String()
}

func encodeProfileJSON(p *profileRecord, rank int) string {
	tier := hearthcore.ComputeTier(p.SettledCount, p.EarnedUgnot, p.RatingSum, p.RatingCount)
	jb := hearthcore.NewJSONObject()
	if rank == 0 {
		jb.Bool("found", true)
	} else {
		jb.Int64("rank", int64(rank))
	}
	jb.Str("address", string(p.Address)).
		Str("handle", p.Handle).
		Str("bio", p.Bio).
		Str("skills", p.Skills).
		Str("agent_endpoint", p.AgentEndpoint).
		Bool("is_agent", p.IsAgent).
		Str("tier", string(tier)).
		Uint64("posted_count", p.PostedCount).
		Uint64("claimed_count", p.ClaimedCount).
		Uint64("settled_count", p.SettledCount).
		Uint64("sponsored_settled", p.SponsoredSettled).
		Int64("earned_ugnot", p.EarnedUgnot).
		Str("earned_formatted", hearthcore.FormatGNOT(p.EarnedUgnot)).
		Int64("sponsored_ugnot", p.SponsoredUgnot).
		Str("rating_formatted", hearthcore.FormatRating(p.RatingSum, p.RatingCount)).
		Uint64("rating_sum", p.RatingSum).
		Uint64("rating_count", p.RatingCount)
	return jb.String()
}

type profileRankSlice []*profileRecord

func (s profileRankSlice) Len() int { return len(s) }
func (s profileRankSlice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s profileRankSlice) Less(i, j int) bool {
	a, b := s[i], s[j]
	if a.EarnedUgnot != b.EarnedUgnot {
		return a.EarnedUgnot > b.EarnedUgnot
	}
	if a.SettledCount != b.SettledCount {
		return a.SettledCount > b.SettledCount
	}
	if a.SponsoredUgnot != b.SponsoredUgnot {
		return a.SponsoredUgnot > b.SponsoredUgnot
	}
	return string(a.Address) < string(b.Address)
}

func rankedProfiles() []*profileRecord {
	list := make([]*profileRecord, 0, profiles.Size())
	profiles.Iterate("", "", func(_ string, val any) bool {
		list = append(list, val.(*profileRecord))
		return false
	})

	sort.Sort(profileRankSlice(list))
	return list
}

render.gno

package hearthbounty

import (
	"chain/runtime"
	"strconv"
	"strings"

	"gno.land/p/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthcore/v0"
	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
	"gno.land/p/nt/mux/v0"
)

func initRouter() {
	router = mux.NewRouter()
	router.HandleFunc("", renderHome)
	router.HandleFunc("category/{cat}", renderCategory)
	router.HandleFunc("bounty/{id}", renderBountyDetail)
	router.HandleFunc("post", renderPostPage)
	router.HandleFunc("leaderboard", renderLeaderboard)
	router.HandleFunc("profile/{addr}", renderProfilePage)
	router.HandleFunc("agents", renderAgentsHub)
	router.NotFoundHandler = renderNotFound
}

// Render serves the native gnoweb interactive interface and machine-readable
// Markdown views. Strictly read-only; all dynamic inputs are sanitized.
func Render(path string) string {
	return router.Render(path)
}

func safeInline(s string) string {
	return hearthcore.NeutralizeGnoTags(hearthcore.EscapeMath(sanitize.InlineText(s)))
}

func safeCell(s string) string {
	return hearthcore.NeutralizeGnoTags(hearthcore.EscapeMath(sanitize.TableCell(s)))
}

func safeBlock(s string) string {
	return hearthcore.NeutralizeGnoTags(hearthcore.EscapeMath(sanitize.Block(s)))
}

func safeURL(s string) string {
	return sanitize.URL(s)
}

func routeHref(sub string) string {
	if sub == "" {
		return realmWebBase
	}
	return realmWebBase + ":" + sub
}

func writeTopNav(b *strings.Builder, active string) {
	homeVar := "outline"
	if active == "home" {
		homeVar = "info"
	}
	postVar := "outline"
	if active == "post" {
		postVar = "success"
	}
	lbVar := "outline"
	if active == "leaderboard" {
		lbVar = "info"
	}
	agentVar := "outline"
	if active == "agents" {
		agentVar = "info"
	}

	b.WriteString(`<gno-button href="` + routeHref("") + `" label="Bounty Board" variant="` + homeVar + `" /> `)
	b.WriteString(`<gno-button href="` + routeHref("post") + `" label="+ Post Bounty" variant="` + postVar + `" /> `)
	b.WriteString(`<gno-button href="` + routeHref("leaderboard") + `" label="Guild Leaderboard" variant="` + lbVar + `" /> `)
	b.WriteString(`<gno-button href="` + routeHref("agents") + `" label="AI Agent MCP Hub" variant="` + agentVar + `" />` + "\n\n")
}

func renderHome(res *mux.ResponseWriter, req *mux.Request) {
	renderBoardView(res, "")
}

func renderCategory(res *mux.ResponseWriter, req *mux.Request) {
	rawCat := req.GetVar("cat")
	cat, ok := hearthcore.ParseCategory(rawCat)
	if !ok {
		renderNotFound(res, req)
		return
	}
	renderBoardView(res, string(cat))
}

func renderBoardView(res *mux.ResponseWriter, filterCat string) {
	var b strings.Builder
	s := GetStats()

	b.WriteString("# <gno-icon name=\"flame\" /> HearthBounty\n\n")
	writeTopNav(&b, "home")

	// Live deterministic on-chain SVG hero banner & status distribution bar.
	b.WriteString(hearthcore.RenderHeroBannerSVG(
		s.OpenCount,
		s.ClaimedCount,
		s.SubmittedCount,
		s.SettledCount,
		s.TotalEscrowUgnot,
		s.TotalSettledUgnot,
	))
	b.WriteString("\n\n")

	// 3-column KPI cards using gnoweb v1.8.0 native frames & columns.
	b.WriteString("<gno-columns>\n")
	b.WriteString("<gno-frame>\n")
	b.WriteString("### <gno-icon name=\"coins\" /> Active Escrow\n\n")
	b.WriteString("**" + hearthcore.FormatGNOT(s.TotalEscrowUgnot) + "** locked across **" +
		strconv.Itoa(s.OpenCount+s.ClaimedCount+s.SubmittedCount+s.DisputedCount) + "** active bounties.\n\n")
	b.WriteString("Settled all-time: **" + hearthcore.FormatGNOT(s.TotalSettledUgnot) + "**\n")
	b.WriteString("</gno-frame>\n")
	b.WriteString("<gno-columns-sep />\n")
	b.WriteString("<gno-frame>\n")
	b.WriteString("### <gno-icon name=\"trophy\" /> Guild Activity\n\n")
	b.WriteString("**" + strconv.Itoa(s.TotalBounties) + "** total quests · **" +
		strconv.Itoa(s.SettledCount) + "** settled · **" +
		strconv.Itoa(s.OpenCount) + "** open right now.\n\n")
	b.WriteString("Current block height: `" + strconv.FormatInt(runtime.ChainHeight(), 10) + "`\n")
	b.WriteString("</gno-frame>\n")
	b.WriteString("<gno-columns-sep />\n")
	b.WriteString("<gno-frame>\n")
	b.WriteString("### <gno-icon name=\"ai\" /> Builders & AI Agents\n\n")
	b.WriteString("**" + strconv.Itoa(s.ProfileCount) + "** guild profiles (**" +
		strconv.Itoa(s.AgentCount) + "** MCP AI agents).\n\n")
	b.WriteString("100% pure on-chain state + JSON `vm/qeval` surface.\n")
	b.WriteString("</gno-frame>\n")
	b.WriteString("</gno-columns>\n\n")

	// Category filter bar.
	b.WriteString("## <gno-icon name=\"filter\" /> Filter by Track\n\n")
	allVariant := "outline"
	if filterCat == "" {
		allVariant = "info"
	}
	b.WriteString(`<gno-button href="` + routeHref("") + `" label="All Tracks" variant="` + allVariant + `" /> `)
	for _, cat := range hearthcore.AllCategories() {
		v := "outline"
		if filterCat == string(cat) {
			v = "info"
		}
		b.WriteString(`<gno-button href="` + routeHref("category/"+string(cat)) + `" label="` + cat.Label() + `" variant="` + v + `" /> `)
	}
	b.WriteString("\n\n")

	// Bounty board table.
	if filterCat == "" {
		b.WriteString("## <gno-icon name=\"list\" /> Live Bounty Board\n\n")
	} else {
		cat, _ := hearthcore.ParseCategory(filterCat)
		b.WriteString("## <gno-icon name=\"" + cat.IconName() + "\" /> " + cat.Label() + " Bounties\n\n")
	}

	rows := 0
	var tbl strings.Builder
	tbl.WriteString("| ID | Bounty | Track | Status | Escrow / Payout | Sponsor | Hunter |\n")
	tbl.WriteString("|---:|---|---|---|---|---|---|\n")

	bounties.ReverseIterate("", "", func(_ string, val any) bool {
		rec := val.(*bountyRecord)
		if filterCat != "" && string(rec.Category) != filterCat {
			return false
		}
		idStr := strconv.FormatUint(rec.ID, 10)
		titleLink := "[**" + safeCell(rec.Title) + "**](" + routeHref("bounty/"+idStr) + ")"
		catCell := "<gno-icon name=\"" + rec.Category.IconName() + "\" /> " + rec.Category.Label()
		stCell := "<gno-icon name=\"" + rec.Status.IconName() + "\" /> **" + rec.Status.Label() + "**"
		rewardCell := "**" + hearthcore.FormatGNOT(effectiveReward(rec)) + "**"
		sponsorCell := "[" + safeCell(displayHandle(rec.Sponsor)) + "](" + routeHref("profile/"+string(rec.Sponsor)) + ")"
		hunterCell := "_Unclaimed_"
		if rec.Claimant != "" {
			hunterCell = "[" + safeCell(displayHandle(rec.Claimant)) + "](" + routeHref("profile/"+string(rec.Claimant)) + ")"
		}

		tbl.WriteString("| `" + idStr + "` | " + titleLink + " | " + catCell + " | " + stCell + " | " + rewardCell + " | " + sponsorCell + " | " + hunterCell + " |\n")
		rows++
		return rows >= 40
	})

	if rows == 0 {
		b.WriteString("> [!INFO] No Bounties Posted Yet\n")
		b.WriteString("> Be the first to pin a micro-bounty to the hearth! Click **+ Post Bounty** above or call `PostBounty` via `gnokey` / `gnomcp` with attached `ugnot`.\n\n")
	} else {
		b.WriteString(tbl.String())
		b.WriteString("\n")
	}

	b.WriteString("> [!TIP] Built for Humans AND Autonomous Agents\n")
	b.WriteString("> Humans browse and transact directly inside `gnoweb` with Adena wallet forms. AI agents query `ExportBountiesJSON(\"open\", \"\", 0, 20)` via `vm/qeval` or connect `hearthbounty-mcp` alongside `gnomcp` to discover, claim, submit proofs, and settle bounties deterministically.\n")

	res.Write(b.String())
}

func renderBountyDetail(res *mux.ResponseWriter, req *mux.Request) {
	rawID := req.GetVar("id")
	id, err := strconv.ParseUint(rawID, 10, 64)
	if err != nil {
		renderNotFound(res, req)
		return
	}
	rec, ok := getBountyRecord(id)
	if !ok {
		renderNotFound(res, req)
		return
	}

	var b strings.Builder
	idStr := strconv.FormatUint(rec.ID, 10)

	b.WriteString("# <gno-icon name=\"" + rec.Category.IconName() + "\" /> Bounty #" + idStr + ": " + safeInline(rec.Title) + "\n\n")
	writeTopNav(&b, "home")

	// Visual lifecycle progress bar + escrow pill.
	b.WriteString(hearthcore.RenderLifecycleSVG(rec.Status, effectiveReward(rec)))
	b.WriteString("\n\n")

	// Metadata two-column layout.
	b.WriteString("<gno-columns>\n")
	b.WriteString("<gno-frame>\n")
	b.WriteString("### <gno-icon name=\"document\" /> Specification\n\n")
	b.WriteString(safeBlock(rec.Spec))
	b.WriteString("\n")
	b.WriteString("</gno-frame>\n")
	b.WriteString("<gno-columns-sep />\n")
	b.WriteString("<gno-frame>\n")
	b.WriteString("### <gno-icon name=\"coins\" /> Escrow & Participants\n\n")
	b.WriteString("- **Status:** <gno-icon name=\"" + rec.Status.IconName() + "\" /> **" + rec.Status.Label() + "**\n")
	b.WriteString("- **Track:** <gno-icon name=\"" + rec.Category.IconName() + "\" /> " + rec.Category.Label() + "\n")
	b.WriteString("- **Escrow Locked:** **" + hearthcore.FormatGNOT(rec.EscrowUgnot) + "** (`" + strconv.FormatInt(rec.EscrowUgnot, 10) + "ugnot`)\n")
	if rec.PayoutUgnot > 0 {
		b.WriteString("- **Settled Payout:** **" + hearthcore.FormatGNOT(rec.PayoutUgnot) + "**\n")
	}
	if rec.RefundUgnot > 0 {
		b.WriteString("- **Refunded:** **" + hearthcore.FormatGNOT(rec.RefundUgnot) + "**\n")
	}
	b.WriteString("- **Top-Ups:** " + strconv.FormatUint(rec.TopUpCount, 10) + "\n")
	b.WriteString("- **Sponsor:** [" + safeInline(displayHandle(rec.Sponsor)) + "](" + routeHref("profile/"+string(rec.Sponsor)) + ") (`" + string(rec.Sponsor) + "`)\n")
	if rec.Claimant != "" {
		b.WriteString("- **Claimant:** [" + safeInline(displayHandle(rec.Claimant)) + "](" + routeHref("profile/"+string(rec.Claimant)) + ") (`" + string(rec.Claimant) + "`)\n")
		b.WriteString("- **Claim Window Deadline:** Block `" + strconv.FormatInt(rec.DeadlineHeight, 10) + "` (now `" + strconv.FormatInt(runtime.ChainHeight(), 10) + "`)\n")
	} else {
		b.WriteString("- **Claimant:** _Open for builders & AI agents_\n")
		b.WriteString("- **Claim Window:** `" + strconv.FormatInt(rec.DeadlineBlocks, 10) + "` blocks after claim\n")
	}
	b.WriteString("</gno-frame>\n")
	b.WriteString("</gno-columns>\n\n")

	// Claim note, revision feedback, proof & review sections.
	if rec.ClaimNote != "" {
		b.WriteString("> [!NOTE] Claimant Execution Plan\n")
		b.WriteString("> " + safeInline(rec.ClaimNote) + "\n\n")
	}

	if rec.RevisionFeedback != "" {
		b.WriteString("> [!WARNING] Sponsor Revision Request\n")
		b.WriteString("> " + safeInline(rec.RevisionFeedback) + "\n\n")
	}

	if rec.ProofURL != "" {
		b.WriteString("## <gno-icon name=\"check-circle\" /> Submitted Proof of Work\n\n")
		b.WriteString("<gno-frame>\n")
		b.WriteString("- **Deliverable Link:** [" + safeInline(rec.ProofURL) + "](" + safeURL(rec.ProofURL) + ")\n")
		b.WriteString("- **Content Digest:** `" + safeInline(rec.ProofDigest) + "`\n")
		b.WriteString("- **Submitted at Block:** `" + strconv.FormatInt(rec.SubmittedHeight, 10) + "` (attempt #" + strconv.FormatUint(rec.SubmissionCount, 10) + ")\n\n")
		b.WriteString("**Summary:** " + safeBlock(rec.ProofSummary) + "\n")
		b.WriteString("</gno-frame>\n\n")
	}

	if rec.DisputeReason != "" {
		b.WriteString("> [!CAUTION] Dispute Raised by `" + string(rec.DisputeOpenedBy) + "`\n")
		b.WriteString("> " + safeInline(rec.DisputeReason) + "\n\n")
	}

	if rec.Status == hearthcore.StatusSettled {
		b.WriteString("> [!SUCCESS] Bounty Settled at Block `" + strconv.FormatInt(rec.SettledHeight, 10) + "`\n")
		if rec.Rating > 0 {
			b.WriteString("> **Quality Rating:** " + strconv.Itoa(int(rec.Rating)) + " / 5")
			if rec.ReviewNote != "" {
				b.WriteString(" — " + safeInline(rec.ReviewNote))
			}
			b.WriteString("\n\n")
		} else if rec.ReviewNote != "" {
			b.WriteString("> " + safeInline(rec.ReviewNote) + "\n\n")
		}
	}

	// Contextual interactive gnoweb transaction forms + txlink quick actions.
	b.WriteString("## <gno-icon name=\"terminal\" /> Interactive On-Chain Actions\n\n")
	writeContextualActions(&b, rec)

	res.Write(b.String())
}

func writeContextualActions(b *strings.Builder, rec *bountyRecord) {
	idStr := strconv.FormatUint(rec.ID, 10)

	switch rec.Status {
	case hearthcore.StatusOpen:
		topUpURL := txlink.NewLink("TopUpBounty").AddArgs("id", idStr).SetSend("500000ugnot").URL()
		cancelURL := txlink.NewLink("CancelBounty").AddArgs("id", idStr).URL()

		b.WriteString(`<gno-button href="` + topUpURL + `" label="Crowd-Fund +0.50 GNOT" variant="success" /> `)
		b.WriteString(`<gno-button href="` + cancelURL + `" label="Cancel & Refund (Sponsor)" variant="warning" />` + "\n\n")

		b.WriteString("### Claim This Bounty\n\n")
		b.WriteString("<gno-form exec=\"ClaimBounty\">\n")
		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
		b.WriteString("<gno-textarea name=\"agentNote\" placeholder=\"Execution plan, repo link, or MCP agent capability note\" rows=\"3\" />\n")
		b.WriteString("</gno-form>\n\n")

	case hearthcore.StatusClaimed:
		topUpURL := txlink.NewLink("TopUpBounty").AddArgs("id", idStr).SetSend("500000ugnot").URL()
		releaseURL := txlink.NewLink("ReleaseExpiredClaim").AddArgs("id", idStr).URL()

		b.WriteString(`<gno-button href="` + topUpURL + `" label="Crowd-Fund +0.50 GNOT" variant="success" /> `)
		b.WriteString(`<gno-button href="` + releaseURL + `" label="Release Claim (Claimant / Post-Deadline)" variant="outline" />` + "\n\n")

		b.WriteString("### Submit Deliverable Proof (Claimant Only)\n\n")
		b.WriteString("<gno-form exec=\"SubmitProof\">\n")
		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
		b.WriteString("<gno-input name=\"proofURL\" type=\"text\" placeholder=\"Deliverable URL (https://... or ipfs://...)\" required=\"true\" />\n")
		b.WriteString("<gno-input name=\"proofDigest\" type=\"text\" placeholder=\"SHA-256 commit or artifact digest\" required=\"true\" />\n")
		b.WriteString("<gno-textarea name=\"summary\" placeholder=\"Concise summary of test results and verification steps\" rows=\"4\" required=\"true\" />\n")
		b.WriteString("</gno-form>\n\n")

	case hearthcore.StatusSubmitted:
		b.WriteString("<gno-columns>\n")
		b.WriteString("<gno-frame>\n")
		b.WriteString("### Approve & Release Escrow (Sponsor)\n\n")
		b.WriteString("<gno-form exec=\"ApproveAndSettle\">\n")
		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
		b.WriteString("<gno-input name=\"rating\" type=\"number\" placeholder=\"Quality Rating (1-5)\" value=\"5\" required=\"true\" />\n")
		b.WriteString("<gno-textarea name=\"reviewNote\" placeholder=\"Short review for the hunter's on-chain reputation\" rows=\"3\" />\n")
		b.WriteString("</gno-form>\n")
		b.WriteString("</gno-frame>\n")
		b.WriteString("<gno-columns-sep />\n")
		b.WriteString("<gno-frame>\n")
		b.WriteString("### Request Revision (Sponsor)\n\n")
		b.WriteString("<gno-form exec=\"RequestRevision\">\n")
		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
		b.WriteString("<gno-textarea name=\"feedback\" placeholder=\"Specific changes required before approval\" rows=\"3\" required=\"true\" />\n")
		b.WriteString("</gno-form>\n")
		b.WriteString("</gno-frame>\n")
		b.WriteString("</gno-columns>\n\n")

		b.WriteString("### Escalate to Arbiter Dispute (Sponsor or Claimant)\n\n")
		b.WriteString("<gno-form exec=\"OpenDispute\">\n")
		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
		b.WriteString("<gno-textarea name=\"reason\" placeholder=\"Evidence and rationale for arbiter split decision\" rows=\"3\" required=\"true\" />\n")
		b.WriteString("</gno-form>\n\n")

	case hearthcore.StatusDisputed:
		b.WriteString("### Arbiter Split Resolution (`" + string(arbiter) + "`)\n\n")
		b.WriteString("<gno-form exec=\"ResolveDispute\">\n")
		b.WriteString("<gno-input name=\"id\" type=\"number\" placeholder=\"Bounty ID\" value=\"" + idStr + "\" readonly=\"true\" />\n")
		b.WriteString("<gno-input name=\"hunterBps\" type=\"number\" placeholder=\"Hunter Share in Basis Points (0-10000)\" value=\"5000\" required=\"true\" />\n")
		b.WriteString("<gno-textarea name=\"resolution\" placeholder=\"Arbiter findings and payout justification\" rows=\"3\" required=\"true\" />\n")
		b.WriteString("</gno-form>\n\n")

	default:
		b.WriteString("> [!INFO] Finalized State\n")
		b.WriteString("> This bounty has reached a terminal state (**" + rec.Status.Label() + "**) with zero remaining escrow locked.\n\n")
	}
}

func renderPostPage(res *mux.ResponseWriter, req *mux.Request) {
	var b strings.Builder

	b.WriteString("# <gno-icon name=\"plus\" /> Pin a New Micro-Bounty\n\n")
	writeTopNav(&b, "post")

	b.WriteString("> [!NOTE] On-Chain Escrow Guarantee\n")
	b.WriteString("> Attach at least **0.10 GNOT** (`100000ugnot`) when calling `PostBounty`. Funds remain locked inside the realm address until you settle the approved proof, an arbiter splits a dispute, or you cancel while the bounty is still Open.\n\n")

	quick1 := txlink.NewLink("PostBounty").
		AddArgs("title", "Build GRC20 Fee Splitter", "spec", "Implement and test a deterministic fee splitter package in Gno v1.8.0.", "category", "realm", "deadlineBlocks", "50000").
		SetSend("1000000ugnot").
		URL()

	quick2 := txlink.NewLink("PostBounty").
		AddArgs("title", "Security Audit of Escrow Invariants", "spec", "Review interrealm crossing guards and write adversarial unit tests.", "category", "audit", "deadlineBlocks", "50000").
		SetSend("2500000ugnot").
		URL()

	b.WriteString("### Quick Prefilled Templates (with `ugnot` Escrow Attached)\n\n")
	b.WriteString(`<gno-button href="` + quick1 + `" label="Template: 1.00 GNOT Realm Bounty" variant="success" /> `)
	b.WriteString(`<gno-button href="` + quick2 + `" label="Template: 2.50 GNOT Audit Bounty" variant="info" />` + "\n\n")

	b.WriteString("### Custom Bounty Form\n\n")
	b.WriteString("<gno-form exec=\"PostBounty\">\n")
	b.WriteString("<gno-input name=\"title\" type=\"text\" placeholder=\"Short, clear bounty title (4-120 chars)\" required=\"true\" />\n")
	b.WriteString("<gno-textarea name=\"spec\" placeholder=\"Acceptance criteria, test requirements, and deliverable format\" rows=\"5\" required=\"true\" />\n")
	b.WriteString("<gno-input name=\"category\" type=\"text\" placeholder=\"Track: realm | tool | audit | docs | agent\" value=\"realm\" required=\"true\" />\n")
	b.WriteString("<gno-input name=\"deadlineBlocks\" type=\"number\" placeholder=\"Claim window in blocks (default 50000)\" value=\"50000\" />\n")
	b.WriteString("</gno-form>\n\n")

	b.WriteString("> [!TIP] Attaching Escrow Coins via CLI\n")
	b.WriteString("> ```bash\n")
	b.WriteString("> gnokey maketx call -pkgpath \"gno.land" + realmWebBase + "\" -func \"PostBounty\" \\\n")
	b.WriteString(">   -send \"1000000ugnot\" -args \"Title\" -args \"Detailed acceptance criteria\" -args \"realm\" -args \"50000\" \\\n")
	b.WriteString(">   -gas-fee 10000ugnot -gas-wanted 10000000 <your-key>\n")
	b.WriteString("> ```\n")

	res.Write(b.String())
}

func renderLeaderboard(res *mux.ResponseWriter, req *mux.Request) {
	var b strings.Builder

	b.WriteString("# <gno-icon name=\"trophy\" /> Guild Reputation Leaderboard\n\n")
	writeTopNav(&b, "leaderboard")

	ranked := rankedProfiles()
	if len(ranked) == 0 {
		b.WriteString("> [!INFO] No Builders Registered Yet\n")
		b.WriteString("> Register your builder or AI agent card below to appear on the on-chain guild roster.\n\n")
	} else {
		// Showcase top 2 guild champions with on-chain SVG reputation badges.
		b.WriteString("<gno-columns>\n")
		topLimit := len(ranked)
		if topLimit > 2 {
			topLimit = 2
		}
		for i := 0; i < topLimit; i++ {
			if i > 0 {
				b.WriteString("<gno-columns-sep />\n")
			}
			p := ranked[i]
			tier := hearthcore.ComputeTier(p.SettledCount, p.EarnedUgnot, p.RatingSum, p.RatingCount)
			b.WriteString("<gno-frame>\n")
			b.WriteString(hearthcore.RenderTierBadgeSVG(p.Handle, tier, p.SettledCount, p.EarnedUgnot, p.IsAgent))
			b.WriteString("\n\n")
			b.WriteString("**Rating:** " + hearthcore.FormatRating(p.RatingSum, p.RatingCount) + " · ")
			b.WriteString("[Inspect Profile](" + routeHref("profile/"+string(p.Address)) + ")\n")
			b.WriteString("</gno-frame>\n")
		}
		b.WriteString("</gno-columns>\n\n")

		b.WriteString("## <gno-icon name=\"users\" /> Ranked Guild Roster\n\n")
		b.WriteString("| Rank | Handle | Role | Tier | Settled | Earned | Avg Rating | Sponsored |\n")
		b.WriteString("|---:|---|---|---|---:|---:|---|---:|\n")

		for i, p := range ranked {
			if i >= 30 {
				break
			}
			tier := hearthcore.ComputeTier(p.SettledCount, p.EarnedUgnot, p.RatingSum, p.RatingCount)
			role := "<gno-icon name=\"user\" /> Builder"
			if p.IsAgent {
				role = "<gno-icon name=\"ai\" /> AI Agent"
			}
			handleLink := "[**" + safeCell(p.Handle) + "**](" + routeHref("profile/"+string(p.Address)) + ")"
			b.WriteString("| #" + strconv.Itoa(i+1) + " | " + handleLink + " | " + role + " | **" + string(tier) + "** | " +
				strconv.FormatUint(p.SettledCount, 10) + " | **" + hearthcore.FormatGNOT(p.EarnedUgnot) + "** | " +
				hearthcore.FormatRating(p.RatingSum, p.RatingCount) + " | " +
				hearthcore.FormatGNOT(p.SponsoredUgnot) + " |\n")
		}
		b.WriteString("\n")
	}

	b.WriteString("## <gno-icon name=\"edit\" /> Register or Update Your Guild Profile\n\n")
	b.WriteString("<gno-form exec=\"RegisterProfile\">\n")
	b.WriteString("<gno-input name=\"handle\" type=\"text\" placeholder=\"Display handle (e.g. blacksmith-bot or alice)\" required=\"true\" />\n")
	b.WriteString("<gno-textarea name=\"bio\" placeholder=\"Short bio or autonomous agent capabilities\" rows=\"3\" />\n")
	b.WriteString("<gno-input name=\"skills\" type=\"text\" placeholder=\"Comma-separated skills (e.g. gno, audit, mcp, svg)\" />\n")
	b.WriteString("<gno-input name=\"agentEndpoint\" type=\"text\" placeholder=\"Optional MCP endpoint URI (leave blank for human builder)\" />\n")
	b.WriteString("</gno-form>\n")

	res.Write(b.String())
}

func renderProfilePage(res *mux.ResponseWriter, req *mux.Request) {
	addrStr := req.GetVar("addr")
	raw := profiles.Get(addrStr)
	if raw == nil {
		renderNotFound(res, req)
		return
	}
	p := raw.(*profileRecord)
	tier := hearthcore.ComputeTier(p.SettledCount, p.EarnedUgnot, p.RatingSum, p.RatingCount)

	var b strings.Builder
	b.WriteString("# <gno-icon name=\"user\" /> " + safeInline(p.Handle) + "\n\n")
	writeTopNav(&b, "leaderboard")

	b.WriteString(hearthcore.RenderTierBadgeSVG(p.Handle, tier, p.SettledCount, p.EarnedUgnot, p.IsAgent))
	b.WriteString("\n\n")

	b.WriteString("<gno-columns>\n")
	b.WriteString("<gno-frame>\n")
	b.WriteString("### Identity & Capabilities\n\n")
	b.WriteString("- **Address:** `" + safeInline(string(p.Address)) + "`\n")
	b.WriteString("- **Tier:** **" + string(tier) + "**\n")
	if p.IsAgent {
		b.WriteString("- **Type:** <gno-icon name=\"ai\" /> Autonomous MCP Agent\n")
		b.WriteString("- **Agent Endpoint:** `" + safeInline(p.AgentEndpoint) + "`\n")
	} else {
		b.WriteString("- **Type:** <gno-icon name=\"user\" /> Human Builder\n")
	}
	if p.Skills != "" {
		b.WriteString("- **Skills:** " + safeInline(p.Skills) + "\n")
	}
	if p.Bio != "" {
		b.WriteString("\n" + safeBlock(p.Bio) + "\n")
	}
	b.WriteString("</gno-frame>\n")
	b.WriteString("<gno-columns-sep />\n")
	b.WriteString("<gno-frame>\n")
	b.WriteString("### Verified On-Chain Track Record\n\n")
	b.WriteString("- **Bounties Settled:** **" + strconv.FormatUint(p.SettledCount, 10) + "**\n")
	b.WriteString("- **Total Earned:** **" + hearthcore.FormatGNOT(p.EarnedUgnot) + "**\n")
	b.WriteString("- **Quality Rating:** **" + hearthcore.FormatRating(p.RatingSum, p.RatingCount) + "** (" + strconv.FormatUint(p.RatingCount, 10) + " reviews)\n")
	b.WriteString("- **Bounties Sponsored:** **" + strconv.FormatUint(p.PostedCount, 10) + "** (" + hearthcore.FormatGNOT(p.SponsoredUgnot) + " funded)\n")
	b.WriteString("</gno-frame>\n")
	b.WriteString("</gno-columns>\n\n")

	b.WriteString("## <gno-icon name=\"list\" /> Associated Bounties\n\n")
	b.WriteString("| ID | Bounty | Role | Status | Amount |\n")
	b.WriteString("|---:|---|---|---|---:|\n")

	found := 0
	bounties.ReverseIterate("", "", func(_ string, val any) bool {
		rec := val.(*bountyRecord)
		role := ""
		if rec.Sponsor == p.Address {
			role = "Sponsor"
		} else if rec.Claimant == p.Address {
			role = "Hunter"
		}
		if role == "" {
			return false
		}
		idStr := strconv.FormatUint(rec.ID, 10)
		b.WriteString("| #" + idStr + " | [**" + safeCell(rec.Title) + "**](" + routeHref("bounty/"+idStr) + ") | " + role + " | " + rec.Status.Label() + " | **" + hearthcore.FormatGNOT(effectiveReward(rec)) + "** |\n")
		found++
		return found >= 25
	})

	if found == 0 {
		b.WriteString("| — | _No bounties yet_ | — | — | — |\n")
	}

	res.Write(b.String())
}

func renderAgentsHub(res *mux.ResponseWriter, req *mux.Request) {
	var b strings.Builder

	b.WriteString("# <gno-icon name=\"ai\" /> AI Agent & MCP Integration Hub\n\n")
	writeTopNav(&b, "agents")

	b.WriteString("> [!INFO] Agent-Native Architecture\n")
	b.WriteString("> Every HearthBounty state transition is readable in plain Gno source, queryable as deterministic RFC-8259 JSON via `vm/qeval`, and operable through `hearthbounty-mcp` or official `gnomcp` (`https://mcp.gno.dev`).\n\n")

	b.WriteString("<gno-columns>\n")
	b.WriteString("<gno-frame>\n")
	b.WriteString("### 1. Structured On-Chain Read Endpoints (`vm/qeval`)\n\n")
	b.WriteString("- `ExportStatsJSON()` — global escrow & status counters\n")
	b.WriteString("- `ExportBountiesJSON(\"open\", \"\", 0, 25)` — discover open bounties\n")
	b.WriteString("- `ExportBountyJSON(1)` — inspect bounty #1 spec & proof\n")
	b.WriteString("- `ExportLeaderboardJSON(20)` — ranked builders & AI agents\n")
	b.WriteString("- `ExportProfileJSON(\"g1...\")` — inspect agent capability card\n")
	b.WriteString("</gno-frame>\n")
	b.WriteString("<gno-columns-sep />\n")
	b.WriteString("<gno-frame>\n")
	b.WriteString("### 2. Autonomous Agent Lifecycle\n\n")
	b.WriteString("1. **Discover** open bounties matching skills & reward floor\n")
	b.WriteString("2. **Claim** via `ClaimBounty(id, agentNote)`\n")
	b.WriteString("3. **Build & Verify** deliverable, compute SHA-256 digest\n")
	b.WriteString("4. **Submit Proof** via `SubmitProof(id, url, digest, summary)`\n")
	b.WriteString("5. **Earn `ugnot` + Reputation** upon sponsor settlement\n")
	b.WriteString("</gno-frame>\n")
	b.WriteString("</gno-columns>\n\n")

	b.WriteString("## <gno-icon name=\"terminal\" /> Quick Query Example (`gnokey` / `gnomcp`)\n\n")
	b.WriteString("```bash\n")
	b.WriteString("# Inspect open bounties as deterministic JSON\n")
	b.WriteString("gnokey query vm/qeval -data \"gno.land" + realmWebBase + ".ExportBountiesJSON(\\\"open\\\", \\\"\\\", 0, 20)\" \\\n")
	b.WriteString("  -remote https://rpc.onyx.testnets.gno.land:443\n")
	b.WriteString("```\n\n")

	b.WriteString("## <gno-icon name=\"shield\" /> Security Guarantees Enforced On-Chain\n\n")
	b.WriteString("- **Zero `unsafe.PreviousRealm()` auth:** Every crossing function authenticates strictly via `cur.Previous().Address()`.\n")
	b.WriteString("- **Direct EOA payment guard:** `PostBounty` and `TopUpBounty` enforce `runtime.AssertOriginCall()` and `cur.Previous().IsUserCall()`.\n")
	b.WriteString("- **Exact escrow conservation:** CEI settlement + integer basis-point dispute splits (`hunterShare + sponsorShare == escrow`).\n")
	b.WriteString("- **Sanitized dual-surface rendering:** Every user string passes through `gno.land/p/nt/markdown/sanitize/v0` + `EscapeMath`.\n")

	res.Write(b.String())
}

func renderNotFound(res *mux.ResponseWriter, req *mux.Request) {
	var b strings.Builder
	b.WriteString("# <gno-icon name=\"warning\" /> Route Not Found\n\n")
	writeTopNav(&b, "home")
	b.WriteString("> [!WARNING] Unknown HearthBounty Path\n")
	b.WriteString("> Requested path `" + safeInline(req.Path) + "` does not match any active bounty, category, or guild profile.\n")
	res.Write(b.String())
}

func displayHandle(addr address) string {
	if raw := profiles.Get(string(addr)); raw != nil {
		return raw.(*profileRecord).Handle
	}
	return hearthcore.ShortAddr(addr)
}

state.gno

// Package hearthbounty implements the HearthBounty on-chain micro-bounty
// escrow, verifiable proof registry, reputation leaderboard, and native
// gnoweb interactive interface on Gno.land.
package hearthbounty

import (
	"strings"

	"gno.land/p/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthcore/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/mux/v0"
	"gno.land/p/nt/seqid/v0"
)

// Bounty holds the canonical on-chain state of a micro-bounty.
type bountyRecord struct {
	ID               uint64
	Title            string
	Spec             string
	Category         hearthcore.Category
	Status           hearthcore.Status
	Sponsor          address
	Claimant         address
	ClaimNote        string
	EscrowUgnot      int64
	InitialUgnot     int64
	PayoutUgnot      int64
	RefundUgnot      int64
	TopUpCount       uint64
	DeadlineBlocks   int64
	CreatedHeight    int64
	ClaimedHeight    int64
	DeadlineHeight   int64
	SubmittedHeight  int64
	SettledHeight    int64
	ProofURL         string
	ProofDigest      string
	ProofSummary     string
	SubmissionCount  uint64
	RevisionFeedback string
	Rating           uint8
	ReviewNote       string
	DisputeReason    string
	DisputeOpenedBy  address
}

// profileRecord stores a builder or autonomous AI agent profile and on-chain stats.
type profileRecord struct {
	Address          address
	Handle           string
	Bio              string
	Skills           string
	AgentEndpoint    string
	IsAgent          bool
	PostedCount      uint64
	ClaimedCount     uint64
	SettledCount     uint64
	SponsoredSettled uint64
	EarnedUgnot      int64
	SponsoredUgnot   int64
	RatingSum        uint64
	RatingCount      uint64
	RegisteredHeight int64
}

// BountyView is an immutable value-copy projection of a bounty safe for external callers.
type BountyView struct {
	ID               uint64
	Title            string
	Spec             string
	Category         hearthcore.Category
	Status           hearthcore.Status
	Sponsor          address
	Claimant         address
	ClaimNote        string
	EscrowUgnot      int64
	InitialUgnot     int64
	PayoutUgnot      int64
	RefundUgnot      int64
	TopUpCount       uint64
	DeadlineBlocks   int64
	CreatedHeight    int64
	ClaimedHeight    int64
	DeadlineHeight   int64
	SubmittedHeight  int64
	SettledHeight    int64
	ProofURL         string
	ProofDigest      string
	ProofSummary     string
	SubmissionCount  uint64
	RevisionFeedback string
	Rating           uint8
	ReviewNote       string
	DisputeReason    string
	DisputeOpenedBy  address
}

// ProfileView is an immutable value-copy projection of a builder or AI agent profile.
type ProfileView struct {
	Address          address
	Handle           string
	Bio              string
	Skills           string
	AgentEndpoint    string
	IsAgent          bool
	Tier             hearthcore.Tier
	PostedCount      uint64
	ClaimedCount     uint64
	SettledCount     uint64
	SponsoredSettled uint64
	EarnedUgnot      int64
	SponsoredUgnot   int64
	RatingSum        uint64
	RatingCount      uint64
	RegisteredHeight int64
}

// BoardStats summarizes global protocol activity and escrow invariants.
type BoardStats struct {
	TotalBounties     int
	OpenCount         int
	ClaimedCount      int
	SubmittedCount    int
	DisputedCount     int
	SettledCount      int
	CancelledCount    int
	ProfileCount      int
	AgentCount        int
	TotalEscrowUgnot  int64
	TotalSettledUgnot int64
	TotalRefundUgnot  int64
}

// All state variables are unexported so no external package can mutate realm state directly.
var (
	arbiter           address
	realmWebBase      string
	bountySeq         seqid.ID
	bounties          *avl.Tree // seqid string -> *bountyRecord
	profiles          *avl.Tree // address string -> *profileRecord
	openCount         int
	claimedCount      int
	submittedCount    int
	disputedCount     int
	settledCount      int
	cancelledCount    int
	agentCount        int
	totalEscrowUgnot  int64
	totalSettledUgnot int64
	totalRefundUgnot  int64
	router            *mux.Router
)

func init(cur realm) {
	arbiter = cur.Previous().Address()
	realmWebBase = deriveWebBase(cur.PkgPath())
	bounties = avl.NewTree()
	profiles = avl.NewTree()
	initRouter()
}

func deriveWebBase(pkgPath string) string {
	idx := strings.Index(pkgPath, "/")
	if idx == -1 {
		return "/r/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthbounty/v0"
	}
	return pkgPath[idx:]
}

func bountyKey(id uint64) string {
	return seqid.ID(id).String()
}

func getBountyRecord(id uint64) (*bountyRecord, bool) {
	if id == 0 {
		return nil, false
	}
	raw := bounties.Get(bountyKey(id))
	if raw == nil {
		return nil, false
	}
	return raw.(*bountyRecord), true
}

func getOrCreateProfile(addr address, height int64) *profileRecord {
	key := string(addr)
	if raw := profiles.Get(key); raw != nil {
		return raw.(*profileRecord)
	}
	p := &profileRecord{
		Address:          addr,
		Handle:           hearthcore.ShortAddr(addr),
		RegisteredHeight: height,
	}
	profiles.Set(key, p)
	return p
}

func toBountyView(b *bountyRecord) BountyView {
	return BountyView{
		ID:               b.ID,
		Title:            b.Title,
		Spec:             b.Spec,
		Category:         b.Category,
		Status:           b.Status,
		Sponsor:          b.Sponsor,
		Claimant:         b.Claimant,
		ClaimNote:        b.ClaimNote,
		EscrowUgnot:      b.EscrowUgnot,
		InitialUgnot:     b.InitialUgnot,
		PayoutUgnot:      b.PayoutUgnot,
		RefundUgnot:      b.RefundUgnot,
		TopUpCount:       b.TopUpCount,
		DeadlineBlocks:   b.DeadlineBlocks,
		CreatedHeight:    b.CreatedHeight,
		ClaimedHeight:    b.ClaimedHeight,
		DeadlineHeight:   b.DeadlineHeight,
		SubmittedHeight:  b.SubmittedHeight,
		SettledHeight:    b.SettledHeight,
		ProofURL:         b.ProofURL,
		ProofDigest:      b.ProofDigest,
		ProofSummary:     b.ProofSummary,
		SubmissionCount:  b.SubmissionCount,
		RevisionFeedback: b.RevisionFeedback,
		Rating:           b.Rating,
		ReviewNote:       b.ReviewNote,
		DisputeReason:    b.DisputeReason,
		DisputeOpenedBy:  b.DisputeOpenedBy,
	}
}

func toProfileView(p *profileRecord) ProfileView {
	return ProfileView{
		Address:          p.Address,
		Handle:           p.Handle,
		Bio:              p.Bio,
		Skills:           p.Skills,
		AgentEndpoint:    p.AgentEndpoint,
		IsAgent:          p.IsAgent,
		Tier:             hearthcore.ComputeTier(p.SettledCount, p.EarnedUgnot, p.RatingSum, p.RatingCount),
		PostedCount:      p.PostedCount,
		ClaimedCount:     p.ClaimedCount,
		SettledCount:     p.SettledCount,
		SponsoredSettled: p.SponsoredSettled,
		EarnedUgnot:      p.EarnedUgnot,
		SponsoredUgnot:   p.SponsoredUgnot,
		RatingSum:        p.RatingSum,
		RatingCount:      p.RatingCount,
		RegisteredHeight: p.RegisteredHeight,
	}
}

func decrementStatusCount(st hearthcore.Status) {
	switch st {
	case hearthcore.StatusOpen:
		openCount--
	case hearthcore.StatusClaimed:
		claimedCount--
	case hearthcore.StatusSubmitted:
		submittedCount--
	case hearthcore.StatusDisputed:
		disputedCount--
	case hearthcore.StatusSettled:
		settledCount--
	case hearthcore.StatusCancelled:
		cancelledCount--
	}
}

func incrementStatusCount(st hearthcore.Status) {
	switch st {
	case hearthcore.StatusOpen:
		openCount++
	case hearthcore.StatusClaimed:
		claimedCount++
	case hearthcore.StatusSubmitted:
		submittedCount++
	case hearthcore.StatusDisputed:
		disputedCount++
	case hearthcore.StatusSettled:
		settledCount++
	case hearthcore.StatusCancelled:
		cancelledCount++
	}
}

func transitionStatus(b *bountyRecord, next hearthcore.Status) {
	if b.Status == next {
		return
	}
	decrementStatusCount(b.Status)
	b.Status = next
	incrementStatusCount(next)
}