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/runtime"
	"strconv"
	"strings"

	"gno.land/p/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthcore/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/r/nt/grc20reg/v0"
)

type contributorRefund struct {
	addr   address
	amount int64
}

// ValidateEscrowToken verifies that a requested settlement token key matches
// the canonical 1:1 ugnot-backed wrapped GNOT key registered in grc20reg.
func ValidateEscrowToken(tokenKey string) {
	if strings.TrimSpace(tokenKey) != EscrowTokenKey {
		panic("hearthbounty: only 1:1 ugnot-backed wugnot escrow is accepted")
	}
}

func validateEscrowAmount(amount, minAmount int64) int64 {
	if amount < minAmount {
		panic("hearthbounty: escrow amount is below minimum required (100000 wugnot)")
	}
	if amount > MaxEscrowUgnot {
		panic("hearthbounty: escrow amount exceeds single-bounty safety ceiling")
	}
	return amount
}

// 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 pre-approved 1:1 ugnot-backed
// wugnot via gno.land/r/nt/grc20reg/v0.
// Requires a direct EOA call (AssertOriginCall + cur.Previous().IsUserCall()).
func PostBounty(cur realm, title, spec, category string, rewardUgnot int64, deadlineBlocks int64) uint64 {
	runtime.AssertOriginCall()
	if !cur.Previous().IsUserCall() {
		panic("hearthbounty: direct EOA call required to fund escrow")
	}

	amount := validateEscrowAmount(rewardUgnot, 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()
	// Pull pre-approved wugnot into realm custody before mutating bounty state.
	// Panics atomically if sponsor balance or allowance is insufficient.
	grc20reg.TransferFrom(0, cur, EscrowTokenKey, sponsor, cur.Address(), amount)

	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,
		SponsorFundedUgnot: amount,
		DonorShares:        avl.NewTree(),
		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_token", EscrowTokenKey,
		"escrow_ugnot", strconv.FormatInt(amount, 10),
		"deadline_blocks", strconv.FormatInt(blocks, 10),
	)

	return nextID
}

// TopUpBounty allows supporters or the sponsor to add pre-approved wugnot
// (>= 0.10 GNOT) into an Open or Claimed bounty. Per-contributor custody is
// tracked in an AVL donor ledger so cancellations and dispute splits refund
// each contributor directly instead of handing external coins to the sponsor.
func TopUpBounty(cur realm, id uint64, amountUgnot int64) int64 {
	runtime.AssertOriginCall()
	if !cur.Previous().IsUserCall() {
		panic("hearthbounty: direct EOA call required to top up escrow")
	}

	amount := validateEscrowAmount(amountUgnot, MinTopUpUgnot)
	donor := cur.Previous().Address()
	b := validateTopUpTarget(donor, id, amount)

	grc20reg.TransferFrom(0, cur, EscrowTokenKey, donor, cur.Address(), amount)

	if donor == b.Sponsor {
		b.SponsorFundedUgnot += amount
	} else {
		if b.DonorShares == nil {
			b.DonorShares = avl.NewTree()
		}
		key := string(donor)
		prev := int64(0)
		if raw := b.DonorShares.Get(key); raw != nil {
			prev = raw.(int64)
		}
		b.DonorShares.Set(key, prev+amount)
		b.ExternalTopUpUgnot += amount
	}

	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
}

func validateTopUpTarget(donor address, id uint64, amount int64) *bountyRecord {
	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")
	}
	if b.Claimant != "" && donor == b.Claimant {
		panic("hearthbounty: active claimant cannot top up own claimed bounty")
	}
	if b.EscrowUgnot+amount > MaxEscrowUgnot {
		panic("hearthbounty: escrow total exceeds single-bounty safety ceiling")
	}
	if donor != b.Sponsor && b.DonorShares != nil && !b.DonorShares.Has(string(donor)) && b.DonorShares.Size() >= MaxExternalDonors {
		panic("hearthbounty: external donor cap reached for this bounty")
	}
	return b
}

// ClaimBounty reserves an open bounty for a builder or autonomous AI agent.
// Sponsors and external escrow contributors cannot claim the bounty they funded.
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")
	}
	if b.DonorShares != nil && b.DonorShares.Has(string(caller)) {
		panic("hearthbounty: escrow contributor cannot claim own funded 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 ChainHeight() reaches DeadlineHeight.
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
	if raw := profiles.Get(string(prevClaimant)); raw != nil {
		p := raw.(*profileRecord)
		if p.ClaimedCount > 0 {
			p.ClaimedCount--
		}
	}

	transitionStatus(b, hearthcore.StatusOpen)
	b.Claimant = ""
	b.ClaimNote = ""
	b.ClaimedHeight = 0
	b.DeadlineHeight = 0
	b.SubmittedHeight = 0
	b.ReviewDeadlineHeight = 0
	b.ProofURL = ""
	b.ProofDigest = ""
	b.ProofSummary = ""
	b.RevisionFeedback = ""

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

// SubmitProof records an HTTPS deliverable URL, SHA-256 content digest, and
// implementation summary, opening a deterministic sponsor review window.
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 := ValidateProofURL(proofURL)
	cleanDigest := hearthcore.ValidateProofDigest(proofDigest)
	cleanSummary := hearthcore.ValidateText("summary", summary, 6, hearthcore.MaxNoteLen)
	height := runtime.ChainHeight()

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

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

// RequestRevision lets the sponsor send a submitted bounty back to Claimed with
// actionable feedback and a refreshed claim 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.ReviewDeadlineHeight = 0
	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 wugnot 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)
	settleFullToClaimant(cur, b, validRating, cleanNote, "BountySettled")
}

// ExpireSubmission is callable by anyone once ChainHeight() reaches
// ReviewDeadlineHeight without sponsor action. It settles 100% of the escrow
// to the claimant so sponsors cannot hold delivered work hostage forever.
func ExpireSubmission(cur realm, id uint64) {
	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusSubmitted {
		panic("hearthbounty: bounty has no pending submission")
	}
	if runtime.ChainHeight() < b.ReviewDeadlineHeight {
		panic("hearthbounty: submission review window has not expired yet")
	}

	settleFullToClaimant(cur, b, 0, "[Auto-Settled] Sponsor review window expired", "SubmissionExpiredSettled")
}

func settleFullToClaimant(cur realm, b *bountyRecord, rating uint8, reviewNote, eventName string) {
	payout := b.EscrowUgnot
	recipient := b.Claimant
	height := runtime.ChainHeight()

	// Effects before external token transfer (CEI).
	b.EscrowUgnot = 0
	b.SponsorFundedUgnot = 0
	b.ExternalTopUpUgnot = 0
	b.DonorShares = avl.NewTree()
	b.PayoutUgnot = payout
	b.Rating = rating
	b.ReviewNote = reviewNote
	b.SettledHeight = height
	transitionStatus(b, hearthcore.StatusSettled)
	totalEscrowUgnot -= payout
	totalSettledUgnot += payout

	hp := getOrCreateProfile(recipient, height)
	hp.SettledCount++
	hp.EarnedUgnot += payout
	if rating > 0 {
		hp.RatingSum += uint64(rating)
		hp.RatingCount++
	}

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

	if payout > 0 {
		grc20reg.Transfer(0, cur, EscrowTokenKey, recipient, payout)
	}

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

// CancelBounty cancels an Open bounty and refunds each contributor directly.
// Third-party top-up coins are returned strictly to their original donors,
// never to the sponsor, and refunded sponsorship credits are reversed.
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")
	}

	totalRefund := b.EscrowUgnot
	sponsorRefund := b.SponsorFundedUgnot
	externalRefundTotal := int64(0)
	donorRefunds := make([]contributorRefund, 0)
	if b.DonorShares != nil {
		b.DonorShares.Iterate("", "", func(key string, val any) bool {
			amt := val.(int64)
			if amt > 0 {
				donorRefunds = append(donorRefunds, contributorRefund{
					addr:   address(key),
					amount: amt,
				})
				externalRefundTotal += amt
			}
			return false
		})
	}
	if sponsorRefund+externalRefundTotal != totalRefund {
		panic("hearthbounty: internal escrow custody invariant mismatch")
	}

	// Effects before interactions (CEI).
	b.EscrowUgnot = 0
	b.SponsorFundedUgnot = 0
	b.ExternalTopUpUgnot = 0
	b.DonorShares = avl.NewTree()
	b.RefundUgnot = totalRefund
	transitionStatus(b, hearthcore.StatusCancelled)
	totalEscrowUgnot -= totalRefund
	totalRefundUgnot += totalRefund

	decrementSponsoredCredit(b.Sponsor, sponsorRefund)
	for _, dr := range donorRefunds {
		decrementSponsoredCredit(dr.addr, dr.amount)
	}

	if sponsorRefund > 0 {
		grc20reg.Transfer(0, cur, EscrowTokenKey, b.Sponsor, sponsorRefund)
	}
	for _, dr := range donorRefunds {
		grc20reg.Transfer(0, cur, EscrowTokenKey, dr.addr, dr.amount)
	}

	chain.Emit(
		"BountyCancelled",
		"id", strconv.FormatUint(id, 10),
		"sponsor", string(b.Sponsor),
		"sponsor_refund_ugnot", strconv.FormatInt(sponsorRefund, 10),
		"external_refund_ugnot", strconv.FormatInt(externalRefundTotal, 10),
		"refund_ugnot", strconv.FormatInt(totalRefund, 10),
	)
}

// OpenDispute escalates a submitted bounty to arbiter review and sets a
// deterministic dispute resolution timeout.
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)
	height := runtime.ChainHeight()
	transitionStatus(b, hearthcore.StatusDisputed)
	b.DisputeReason = cleanReason
	b.DisputeOpenedBy = caller
	b.DisputedHeight = height
	b.DisputeDeadlineHeight = height + b.DeadlineBlocks

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

// ResolveDispute settles a disputed bounty using deterministic basis-point math
// (hunterBps in 0..10000). The arbiter cannot resolve a bounty they are a party
// to, and any refunded portion is returned pro-rata to sponsor and external donors.
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")
	}
	if caller == b.Sponsor || caller == b.Claimant {
		panic("hearthbounty: arbiter cannot resolve a bounty they are party to")
	}

	cleanResolution := hearthcore.ValidateText("resolution", resolution, 4, hearthcore.MaxNoteLen)
	settleDisputeSplit(cur, b, hunterBps, "[Arbiter Resolution] "+cleanResolution, caller, "DisputeResolved")
}

// ExpireDispute is callable by anyone once ChainHeight() reaches
// DisputeDeadlineHeight without arbiter action. It splits escrow 50/50
// (5000 bps to claimant, 5000 bps pro-rata back to contributors) so lost or
// conflicted arbiter keys can never trap escrowed wugnot forever.
func ExpireDispute(cur realm, id uint64) {
	b, ok := getBountyRecord(id)
	if !ok {
		panic("hearthbounty: bounty not found")
	}
	if b.Status != hearthcore.StatusDisputed {
		panic("hearthbounty: bounty is not disputed")
	}
	if runtime.ChainHeight() < b.DisputeDeadlineHeight {
		panic("hearthbounty: dispute resolution window has not expired yet")
	}

	caller := cur.Previous().Address()
	settleDisputeSplit(cur, b, 5000, "[Timeout Split 50/50] Arbiter resolution window expired", caller, "DisputeExpiredSplit")
}

func settleDisputeSplit(cur realm, b *bountyRecord, hunterBps uint64, reviewNote string, resolver address, eventName string) {
	escrow := b.EscrowUgnot
	_, sponsorRefund := hearthcore.ComputeSplit(b.SponsorFundedUgnot, hunterBps)

	donorRefunds := make([]contributorRefund, 0)
	totalRefunds := sponsorRefund
	if b.DonorShares != nil {
		b.DonorShares.Iterate("", "", func(key string, val any) bool {
			amt := val.(int64)
			if amt > 0 {
				_, dRefund := hearthcore.ComputeSplit(amt, hunterBps)
				if dRefund > 0 {
					donorRefunds = append(donorRefunds, contributorRefund{
						addr:   address(key),
						amount: dRefund,
					})
					totalRefunds += dRefund
				}
			}
			return false
		})
	}
	hunterShare := escrow - totalRefunds
	height := runtime.ChainHeight()

	// Effects before interactions (CEI).
	b.EscrowUgnot = 0
	b.SponsorFundedUgnot = 0
	b.ExternalTopUpUgnot = 0
	b.DonorShares = avl.NewTree()
	b.PayoutUgnot = hunterShare
	b.RefundUgnot = totalRefunds
	b.ReviewNote = reviewNote
	b.SettledHeight = height
	transitionStatus(b, hearthcore.StatusSettled)
	totalEscrowUgnot -= escrow
	totalSettledUgnot += hunterShare
	totalRefundUgnot += totalRefunds

	if hunterShare > 0 {
		hp := getOrCreateProfile(b.Claimant, height)
		hp.SettledCount++
		hp.EarnedUgnot += hunterShare
	}
	decrementSponsoredCredit(b.Sponsor, sponsorRefund)
	for _, dr := range donorRefunds {
		decrementSponsoredCredit(dr.addr, dr.amount)
	}

	if hunterShare > 0 {
		grc20reg.Transfer(0, cur, EscrowTokenKey, b.Claimant, hunterShare)
	}
	if sponsorRefund > 0 {
		grc20reg.Transfer(0, cur, EscrowTokenKey, b.Sponsor, sponsorRefund)
	}
	for _, dr := range donorRefunds {
		grc20reg.Transfer(0, cur, EscrowTokenKey, dr.addr, dr.amount)
	}

	chain.Emit(
		eventName,
		"id", strconv.FormatUint(b.ID, 10),
		"resolver", string(resolver),
		"hunter_bps", strconv.FormatUint(hunterBps, 10),
		"hunter_ugnot", strconv.FormatInt(hunterShare, 10),
		"sponsor_refund_ugnot", strconv.FormatInt(sponsorRefund, 10),
		"total_refund_ugnot", strconv.FormatInt(totalRefunds, 10),
	)
}

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

gnomod.toml

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

[addpkg]
  creator = "g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4"
  height = 1378958
  max_deposit = "100000000ugnot"

hearthbounty_test.gno

package hearthbounty

import (
	"chain"
	"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"
	"gno.land/r/gnoland/wugnot"
)

const (
	testRealmPath = "gno.land/r/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthbounty/v1"
	wugnotPkgPath = "gno.land/r/gnoland/wugnot"
)

func resetState(initialArbiter address) {
	arbiter = initialArbiter
	realmAddress = chain.PackageAddress(testRealmPath)
	realmPkgPath = testRealmPath
	realmWebBase = "/r/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthbounty/v1"
	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 prepCoins(user address, amount int64) {
	wugnotAddr := chain.PackageAddress(wugnotPkgPath)
	testing.SetOriginCaller(user)
	testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: amount}})
	testing.IssueCoins(wugnotAddr, chain.Coins{{Denom: "ugnot", Amount: amount}})
}

func assertEscrowInvariant(t *testing.T, realmAddr address, initialRealmBal int64) {
	t.Helper()
	uassert.Equal(t, initialRealmBal+totalEscrowUgnot, EscrowBalance(realmAddr))
}

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(testRealmPath)

	testing.SetRealm(testing.NewUserRealm(arb))
	resetState(arb)
	baseRealmBal := EscrowBalance(realmAddr)

	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)

	testing.SetRealm(testing.NewUserRealm(sponsor))
	prepCoins(sponsor, 2000000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 2000000)
	uassert.Equal(t, int64(2000000), EscrowAllowance(sponsor))

	id := PostBounty(cross(cur), "Build AVL Leaderboard Helper", "Provide a deterministic AVL sorting helper with full unit test coverage.", "realm", 2000000, 200)
	uassert.Equal(t, uint64(1), id)
	uassert.Equal(t, int64(2000000), GetStats().TotalEscrowUgnot)
	assertEscrowInvariant(t, realmAddr, baseRealmBal)

	testing.SetRealm(testing.NewUserRealm(donor))
	prepCoins(donor, 500000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 500000)
	newEscrow := TopUpBounty(cross(cur), id, 500000)
	uassert.Equal(t, int64(2500000), newEscrow)
	uassert.Equal(t, int64(500000), GetDonorContribution(id, donor))
	assertEscrowInvariant(t, realmAddr, baseRealmBal)

	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")
	})

	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)

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

	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)

	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)

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

	agentBalBefore := EscrowBalance(agent)
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	ApproveAndSettle(cross(cur), id, 5, "Clean idiomatic Gno code and crisp tests.")

	agentBalAfter := EscrowBalance(agent)
	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)
}

// H-1 regression proof: CancelBounty must refund external top-ups strictly to
// their original donors and NEVER transfer third-party coins to the sponsor.
func TestCancelRefundsThirdPartyDonorsWithoutSponsorTheft(cur realm, t *testing.T) {
	arb := testutils.TestAddress("h1_arb")
	sponsor := testutils.TestAddress("h1_sponsor")
	donorA := testutils.TestAddress("h1_donor_a")
	donorB := testutils.TestAddress("h1_donor_b")
	realmAddr := chain.PackageAddress(testRealmPath)

	testing.SetRealm(testing.NewUserRealm(arb))
	resetState(arb)
	baseRealmBal := EscrowBalance(realmAddr)

	// Sponsor posts 0.50 GNOT.
	testing.SetRealm(testing.NewUserRealm(sponsor))
	prepCoins(sponsor, 500000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 500000)
	id := PostBounty(cross(cur), "Crowd-Funded Escrow Custody Test", "Verify third-party top-ups are returned to donors on cancel.", "audit", 500000, 100)

	// Donor A tops up 1.50 GNOT in two contributions; Donor B tops up 0.40 GNOT.
	testing.SetRealm(testing.NewUserRealm(donorA))
	prepCoins(donorA, 1500000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 1500000)
	TopUpBounty(cross(cur), id, 1000000)
	TopUpBounty(cross(cur), id, 500000)

	testing.SetRealm(testing.NewUserRealm(donorB))
	prepCoins(donorB, 400000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 400000)
	TopUpBounty(cross(cur), id, 400000)

	// External donor cannot claim the bounty they funded (blocks open->topup->claim wash).
	uassert.AbortsWithMessage(t, cur, "hearthbounty: escrow contributor cannot claim own funded bounty", func() {
		ClaimBounty(cross(cur), id, "wash attempt")
	})

	b, _ := GetBounty(id)
	uassert.Equal(t, int64(2400000), b.EscrowUgnot)
	uassert.Equal(t, int64(500000), b.SponsorFundedUgnot)
	uassert.Equal(t, int64(1900000), b.ExternalTopUpUgnot)
	uassert.Equal(t, 2, b.ExternalDonorCount)

	sponsorBefore := EscrowBalance(sponsor)
	donorABefore := EscrowBalance(donorA)
	donorBBefore := EscrowBalance(donorB)

	// Sponsor cancels -> sponsor receives ONLY their own 0.50 GNOT; donors receive exact refunds.
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	CancelBounty(cross(cur), id)

	uassert.Equal(t, sponsorBefore+500000, EscrowBalance(sponsor))
	uassert.Equal(t, donorABefore+1500000, EscrowBalance(donorA))
	uassert.Equal(t, donorBBefore+400000, EscrowBalance(donorB))
	assertEscrowInvariant(t, realmAddr, baseRealmBal)

	// Phantom SponsoredUgnot credit must be zeroed after full refund.
	spProf, _ := GetProfile(sponsor)
	dAProf, _ := GetProfile(donorA)
	dBProf, _ := GetProfile(donorB)
	uassert.Equal(t, int64(0), spProf.SponsoredUgnot)
	uassert.Equal(t, int64(0), dAProf.SponsoredUgnot)
	uassert.Equal(t, int64(0), dBProf.SponsoredUgnot)
}

// H-1 claimant wash proof: active claimant cannot top up their own claimed bounty.
func TestClaimantCannotWashTopUpIntoEarned(cur realm, t *testing.T) {
	arb := testutils.TestAddress("wash_arb")
	sponsor := testutils.TestAddress("wash_sponsor")
	hunter := testutils.TestAddress("wash_hunter")
	realmAddr := chain.PackageAddress(testRealmPath)

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

	testing.SetRealm(testing.NewUserRealm(sponsor))
	prepCoins(sponsor, 500000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 500000)
	id := PostBounty(cross(cur), "Wash Guard Check", "Verify active claimant cannot top up own claimed bounty.", "tool", 500000, 50)

	testing.SetOriginCaller(hunter)
	testing.SetRealm(testing.NewUserRealm(hunter))
	ClaimBounty(cross(cur), id, "Claiming")

	uassert.PanicsWithMessage(t, cur, "hearthbounty: active claimant cannot top up own claimed bounty", func() {
		validateTopUpTarget(hunter, id, 200000)
	})
	// Non-origin cross-realm TopUpBounty is also blocked by AssertOriginCall.
	uassert.AbortsWithMessage(t, cur, "invalid non-origin call", func() {
		TopUpBounty(cross(cur), id, 200000)
	})
}

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(testRealmPath)

	testing.SetRealm(testing.NewUserRealm(arb))
	resetState(arb)
	baseRealmBal := EscrowBalance(realmAddr)

	testing.SetRealm(testing.NewUserRealm(sponsor))
	prepCoins(sponsor, 1000000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 1000000)
	id := PostBounty(cross(cur), "Write gnoweb SVG Guide", "Document deterministic SVG rendering in gnoweb v1.8.", "docs", 1000000, 20)

	testing.SetOriginCaller(hunter)
	testing.SetRealm(testing.NewUserRealm(hunter))
	ClaimBounty(cross(cur), id, "On it")
	SubmitProof(cross(cur), id, "https://github.com/hearthbounty/docs/pull/1", "sha256:0123456789abcdef", "Initial draft submitted before revision.")

	// Sponsor requests revision -> back to Claimed with stale proof fields still set until release.
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	RequestRevision(cross(cur), id, "Needs cleaner examples.")

	uassert.AbortsWithMessage(t, cur, "hearthbounty: only open bounties can be cancelled", func() {
		CancelBounty(cross(cur), id)
	})

	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 exactly to DeadlineHeight (20 blocks) -> bystander can release on exact deadline block.
	testing.SkipHeights(20)
	ReleaseExpiredClaim(cross(cur), id)
	b, _ := GetBounty(id)
	uassert.Equal(t, string(hearthcore.StatusOpen), string(b.Status))
	uassert.Equal(t, address(""), b.Claimant)
	uassert.Equal(t, "", b.ProofURL)
	uassert.Equal(t, "", b.ProofDigest)
	uassert.Equal(t, "", b.ProofSummary)

	// ClaimedCount must be decremented on release so claim-and-release cannot inflate it.
	hp, _ := GetProfile(hunter)
	uassert.Equal(t, uint64(0), hp.ClaimedCount)

	sponsorBalBefore := EscrowBalance(sponsor)
	testing.SetOriginCaller(sponsor)
	testing.SetRealm(testing.NewUserRealm(sponsor))
	CancelBounty(cross(cur), id)

	uassert.Equal(t, sponsorBalBefore+1000000, EscrowBalance(sponsor))
	assertEscrowInvariant(t, realmAddr, baseRealmBal)
	uassert.Equal(t, int64(1000000), GetStats().TotalRefundUgnot)
}

// M-1 proof #1: ExpireSubmission prevents sponsors from holding delivered proofs hostage.
func TestSubmissionReviewTimeoutAutoSettle(cur realm, t *testing.T) {
	arb := testutils.TestAddress("m1_arb")
	sponsor := testutils.TestAddress("m1_sponsor")
	hunter := testutils.TestAddress("m1_hunter")
	bystander := testutils.TestAddress("m1_bystander")
	realmAddr := chain.PackageAddress(testRealmPath)

	testing.SetRealm(testing.NewUserRealm(arb))
	resetState(arb)
	baseRealmBal := EscrowBalance(realmAddr)

	testing.SetRealm(testing.NewUserRealm(sponsor))
	prepCoins(sponsor, 1200000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 1200000)
	id := PostBounty(cross(cur), "Review Timeout Test", "Verify ExpireSubmission settles 100% after review deadline.", "realm", 1200000, 30)

	testing.SetOriginCaller(hunter)
	testing.SetRealm(testing.NewUserRealm(hunter))
	ClaimBounty(cross(cur), id, "Working on review timeout test")
	SubmitProof(cross(cur), id, "https://github.com/hearthbounty/v1/pull/7", "sha256:fedcba9876543210", "Delivered complete solution and test suite.")

	// Cannot expire before ReviewDeadlineHeight.
	testing.SetOriginCaller(bystander)
	testing.SetRealm(testing.NewUserRealm(bystander))
	uassert.AbortsWithMessage(t, cur, "hearthbounty: submission review window has not expired yet", func() {
		ExpireSubmission(cross(cur), id)
	})

	// Advance to exact ReviewDeadlineHeight -> bystander triggers permissionless settlement.
	hunterBefore := EscrowBalance(hunter)
	testing.SkipHeights(30)
	ExpireSubmission(cross(cur), id)

	uassert.Equal(t, hunterBefore+1200000, EscrowBalance(hunter))
	assertEscrowInvariant(t, realmAddr, baseRealmBal)
	b, _ := GetBounty(id)
	uassert.Equal(t, string(hearthcore.StatusSettled), string(b.Status))
	uassert.Equal(t, int64(1200000), b.PayoutUgnot)
}

// M-1 proof #2 + H-1 pro-rata dispute proof:
// - Arbiter cannot resolve a bounty where arbiter == sponsor or arbiter == claimant.
// - Dispute split refunds third-party donors pro-rata instead of sending their refund to sponsor.
// - ExpireDispute triggers a permissionless 50/50 split if the arbiter stalls or is conflicted.
func TestDisputeSplitConflictGuardAndTimeoutFallback(cur realm, t *testing.T) {
	arb := testutils.TestAddress("arbiter3")
	arb2 := testutils.TestAddress("arbiter3_new")
	sponsor := testutils.TestAddress("sponsor3")
	donor := testutils.TestAddress("donor3")
	hunter := testutils.TestAddress("hunter3")
	bystander := testutils.TestAddress("bystander3")
	realmAddr := chain.PackageAddress(testRealmPath)

	testing.SetRealm(testing.NewUserRealm(arb))
	resetState(arb)
	baseRealmBal := EscrowBalance(realmAddr)

	SetArbiter(cross(cur), arb2)
	uassert.Equal(t, arb2, Arbiter())

	// Bounty 1: 1.00 GNOT sponsor + 0.50 GNOT donor -> 70/30 dispute split.
	testing.SetRealm(testing.NewUserRealm(sponsor))
	prepCoins(sponsor, 1000000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 1000000)
	id1 := PostBounty(cross(cur), "Audit Interrealm Payment Guard", "Check all crossing guards and produce formal report.", "audit", 1000000, 40)

	testing.SetRealm(testing.NewUserRealm(donor))
	prepCoins(donor, 500000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 500000)
	TopUpBounty(cross(cur), id1, 500000)

	testing.SetOriginCaller(hunter)
	testing.SetRealm(testing.NewUserRealm(hunter))
	ClaimBounty(cross(cur), id1, "Auditing now")
	SubmitProof(cross(cur), id1, "https://github.com/hearthbounty/audit/blob/main/report.md", "sha256:abcdef0123456789", "Delivered partial audit covering 70% of scope.")
	OpenDispute(cross(cur), id1, "Core findings delivered; requesting 70/30 partial settlement.")

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

	hunterBalBefore := EscrowBalance(hunter)
	sponsorBalBefore := EscrowBalance(sponsor)
	donorBalBefore := EscrowBalance(donor)

	testing.SetOriginCaller(arb2)
	testing.SetRealm(testing.NewUserRealm(arb2))
	ResolveDispute(cross(cur), id1, 7000, "70% of specification verified; 30% refunded pro-rata.")

	// 70% of 1.50 GNOT = 1.05 GNOT hunter; 30% of 1.00 GNOT = 0.30 GNOT sponsor; 30% of 0.50 GNOT = 0.15 GNOT donor.
	uassert.Equal(t, hunterBalBefore+1050000, EscrowBalance(hunter))
	uassert.Equal(t, sponsorBalBefore+300000, EscrowBalance(sponsor))
	uassert.Equal(t, donorBalBefore+150000, EscrowBalance(donor))
	assertEscrowInvariant(t, realmAddr, baseRealmBal)

	// Bounty 2: Arbiter IS the claimant -> conflicted arbiter blocked, ExpireDispute falls back to 50/50.
	testing.SetRealm(testing.NewUserRealm(sponsor))
	prepCoins(sponsor, 1000000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 1000000)
	id2 := PostBounty(cross(cur), "Conflicted Arbiter Test", "Verify conflicted arbiter cannot self-settle dispute.", "audit", 1000000, 25)

	testing.SetOriginCaller(arb2)
	testing.SetRealm(testing.NewUserRealm(arb2))
	ClaimBounty(cross(cur), id2, "Arbiter claiming as hunter")
	SubmitProof(cross(cur), id2, "https://github.com/hearthbounty/v1/pull/9", "sha256:1234567890abcdef", "Submitted by arbiter address.")
	OpenDispute(cross(cur), id2, "Testing conflict of interest block.")

	uassert.AbortsWithMessage(t, cur, "hearthbounty: arbiter cannot resolve a bounty they are party to", func() {
		ResolveDispute(cross(cur), id2, 10000, "self payout attempt")
	})

	testing.SetOriginCaller(bystander)
	testing.SetRealm(testing.NewUserRealm(bystander))
	uassert.AbortsWithMessage(t, cur, "hearthbounty: dispute resolution window has not expired yet", func() {
		ExpireDispute(cross(cur), id2)
	})

	arb2Before := EscrowBalance(arb2)
	sponsorBefore2 := EscrowBalance(sponsor)
	testing.SkipHeights(25)
	ExpireDispute(cross(cur), id2)

	uassert.Equal(t, arb2Before+500000, EscrowBalance(arb2))
	uassert.Equal(t, sponsorBefore2+500000, EscrowBalance(sponsor))
	assertEscrowInvariant(t, realmAddr, baseRealmBal)
}

// M-2 proof + security guards: Unicode U+0130 ('İ') must NEVER desync tag neutralization.
func TestUnicodeNeutralizeGnoTagsAndSecurityGuards(cur realm, t *testing.T) {
	arb := testutils.TestAddress("arbiter4")
	sponsor := testutils.TestAddress("sponsor4")
	realmAddr := chain.PackageAddress(testRealmPath)

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

	// Direct NeutralizeGnoTags Unicode expansion vectors.
	unicodePayload := "İ<gno-form exec=\"PostBounty\">\n</gno-form> İ<GNO-BUTTON href=\"/r/evil\" />"
	cleaned := NeutralizeGnoTags(unicodePayload)
	uassert.False(t, strings.Contains(cleaned, "<gno-form"))
	uassert.False(t, strings.Contains(cleaned, "</gno-form"))
	uassert.False(t, strings.Contains(cleaned, "<GNO-BUTTON"))

	// ValidateProofURL enforces https:// only (rejects ipfs:// and http://).
	uassert.Equal(t, "https://github.com/org/repo/pull/1", ValidateProofURL("  https://github.com/org/repo/pull/1  "))
	uassert.PanicsWithMessage(t, cur, "hearthbounty: proof URL must start with https://", func() {
		ValidateProofURL("ipfs://bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi")
	})
	uassert.PanicsWithMessage(t, cur, "hearthbounty: proof URL must start with https://", func() {
		ValidateProofURL("http://insecure.example.com/proof")
	})

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

	// Reject dust below 0.10 GNOT and non-wugnot token keys (such as uatom).
	uassert.PanicsWithMessage(t, cur, "hearthbounty: escrow amount is below minimum required (100000 wugnot)", func() {
		validateEscrowAmount(50000, hearthcore.MinRewardUgnot)
	})
	uassert.PanicsWithMessage(t, cur, "hearthbounty: only 1:1 ugnot-backed wugnot escrow is accepted", func() {
		ValidateEscrowToken("uatom")
	})
	ValidateEscrowToken(EscrowToken())

	// End-to-end Render() check with Turkish dotted İ + raw <gno-form> injection.
	testing.SetRealm(testing.NewUserRealm(sponsor))
	prepCoins(sponsor, 1500000)
	wugnot.Deposit(cross(cur))
	testing.SetOriginSend(chain.Coins{})
	wugnot.Approve(cross(cur), realmAddr, 1500000)
	id := PostBounty(
		cross(cur),
		`İ<gno-button href="/r/evil" label="Steal" /> $GNOT/$ATOM`,
		"İ<gno-form exec=\"PostBounty\">\n</gno-form>\nNormal spec with $100 and <gno-form exec=\"Drain\"> attempt.",
		"agent",
		1500000,
		100,
	)

	home := Render("")
	uassert.True(t, strings.Contains(home, "HearthBounty v1"))
	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="PostBounty">`))
	uassert.False(t, strings.Contains(detail, `<gno-form exec="Drain">`))

	// Verify pagination, auxiliary routes, and canonical realm_path + escrow_token in ExportStatsJSON.
	uassert.True(t, strings.Contains(Render("page/1"), "Bounty Board (Page 1)"))
	uassert.True(t, strings.Contains(Render("post"), `<gno-form exec="PostBounty">`))
	uassert.True(t, strings.Contains(Render("post"), `/r/gnoland/wugnot$help&func=Approve`))
	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"))

	statsJSON := ExportStatsJSON()
	uassert.True(t, strings.Contains(statsJSON, `"realm_path":"`+testRealmPath+`"`))
	uassert.True(t, strings.Contains(statsJSON, `"escrow_token":"`+EscrowTokenKey+`"`))
	uassert.True(t, strings.Contains(statsJSON, `"escrow_address":"`+string(realmAddr)+`"`))
	uassert.True(t, strings.Contains(statsJSON, `"total_bounties":1`))
	bountyJSON := ExportBountyJSON(id)
	uassert.True(t, strings.Contains(bountyJSON, `"found":true`))
	uassert.True(t, strings.Contains(bountyJSON, `"sponsor_funded_ugnot":1500000`))
	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"
	"gno.land/r/nt/grc20reg/v0"
)

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

// PkgPath returns the canonical Gno.land package path of this realm.
func PkgPath() string {
	return realmPkgPath
}

// EscrowToken returns the canonical grc20reg key used for 1:1 ugnot-backed escrow.
func EscrowToken() string {
	return EscrowTokenKey
}

// EscrowRealmAddress returns the derived realm address that holds escrowed wugnot.
func EscrowRealmAddress() address {
	return realmAddress
}

// EscrowBalance returns the current wugnot balance of addr from grc20reg.
func EscrowBalance(addr address) int64 {
	return grc20reg.MustGet(EscrowTokenKey).BalanceOf(addr)
}

// EscrowAllowance returns how much wugnot owner has approved this realm to pull.
func EscrowAllowance(owner address) int64 {
	return grc20reg.MustGet(EscrowTokenKey).Allowance(owner, realmAddress)
}

// 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
}

// GetDonorContribution returns the external top-up ugnot currently held in
// custody for donor on bounty id (0 if none or if donor is the sponsor).
func GetDonorContribution(id uint64, donor address) int64 {
	b, ok := getBountyRecord(id)
	if !ok || b.DonorShares == nil {
		return 0
	}
	if raw := b.DonorShares.Get(string(donor)); raw != nil {
		return raw.(int64)
	}
	return 0
}

// 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", realmPkgPath).
		Str("web_path", realmWebBase).
		Str("escrow_token", EscrowTokenKey).
		Str("escrow_address", string(realmAddress)).
		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 {
	donorCount := int64(0)
	if b.DonorShares != nil {
		donorCount = int64(b.DonorShares.Size())
	}
	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("sponsor_funded_ugnot", b.SponsorFundedUgnot).
		Int64("external_top_up_ugnot", b.ExternalTopUpUgnot).
		Int64("external_donor_count", donorCount).
		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("review_deadline_height", b.ReviewDeadlineHeight).
		Int64("disputed_height", b.DisputedHeight).
		Int64("dispute_deadline_height", b.DisputeDeadlineHeight).
		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"
	"net/url"
	"strconv"
	"strings"

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

func initRouter() {
	router = mux.NewRouter()
	router.HandleFunc("", renderHome)
	router.HandleFunc("page/{page}", renderHomePage)
	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 interface and machine-readable Markdown views.
// Strictly read-only; all dynamic inputs are sanitized via sanitize/v0, EscapeMath,
// and byte-indexed ASCII NeutralizeGnoTags.
func Render(path string) string {
	return router.Render(path)
}

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

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

func safeBlock(s string) string {
	return 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 txHref(base, fn string, kv ...string) string {
	if len(kv) == 0 {
		return base + "$help&func=" + fn
	}
	values := url.Values{}
	for i := 0; i+1 < len(kv); i += 2 {
		values.Add(kv[i], kv[i+1])
	}
	return base + "$help&func=" + fn + "&" + values.Encode()
}

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, "", 1)
}

func renderHomePage(res *mux.ResponseWriter, req *mux.Request) {
	p, err := strconv.Atoi(req.GetVar("page"))
	if err != nil || p < 1 {
		renderNotFound(res, req)
		return
	}
	renderBoardView(res, "", p)
}

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), 1)
}

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

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

	b.WriteString(hearthcore.RenderHeroBannerSVG(
		s.OpenCount,
		s.ClaimedCount,
		s.SubmittedCount,
		s.SettledCount,
		s.TotalEscrowUgnot,
		s.TotalSettledUgnot,
	))
	b.WriteString("\n\n")

	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("On-chain AVL state + JSON `vm/qeval` query surface.\n")
	b.WriteString("</gno-frame>\n")
	b.WriteString("</gno-columns>\n\n")

	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")

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

	skip := (page - 1) * BoardPageSize
	seen := 0
	rows := 0
	hasMore := false
	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
		}
		if seen < skip {
			seen++
			return false
		}
		if rows >= BoardPageSize {
			hasMore = true
			return true
		}
		seen++
		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 false
	})

	if rows == 0 {
		b.WriteString("> [!INFO] No Bounties on This View\n")
		b.WriteString("> Post a micro-bounty via **+ Post Bounty** above or call `PostBounty` via `gnokey` / `gnomcp` with attached `ugnot`.\n\n")
	} else {
		b.WriteString(tbl.String())
		b.WriteString("\n")
		if filterCat == "" && (page > 1 || hasMore) {
			if page > 1 {
				prevHref := routeHref("page/" + strconv.Itoa(page-1))
				if page == 2 {
					prevHref = routeHref("")
				}
				b.WriteString(`<gno-button href="` + prevHref + `" label="Previous Page" variant="outline" /> `)
			}
			if hasMore {
				b.WriteString(`<gno-button href="` + routeHref("page/"+strconv.Itoa(page+1)) + `" label="Next Page" variant="outline" />`)
			}
			b.WriteString("\n\n")
		}
	}

	b.WriteString("> [!TIP] Dual Interface: gnoweb + MCP\n")
	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")

	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)
	now := runtime.ChainHeight()

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

	b.WriteString(hearthcore.RenderLifecycleSVG(rec.Status, effectiveReward(rec)))
	b.WriteString("\n\n")

	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 & Custody\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.EscrowUgnot > 0 {
		b.WriteString("- **Custody Split:** Sponsor `" + hearthcore.FormatGNOT(rec.SponsorFundedUgnot) + "` · External Donors `" + hearthcore.FormatGNOT(rec.ExternalTopUpUgnot) + "`\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(now, 10) + "`)\n")
	} else {
		b.WriteString("- **Claimant:** _Open for builders & AI agents_\n")
		b.WriteString("- **Claim / Review Window:** `" + strconv.FormatInt(rec.DeadlineBlocks, 10) + "` blocks\n")
	}
	if rec.Status == hearthcore.StatusSubmitted && rec.ReviewDeadlineHeight > 0 {
		b.WriteString("- **Auto-Settle Review Timeout:** Block `" + strconv.FormatInt(rec.ReviewDeadlineHeight, 10) + "`\n")
	}
	if rec.Status == hearthcore.StatusDisputed && rec.DisputeDeadlineHeight > 0 {
		b.WriteString("- **50/50 Dispute Timeout:** Block `" + strconv.FormatInt(rec.DisputeDeadlineHeight, 10) + "`\n")
	}
	b.WriteString("</gno-frame>\n")
	b.WriteString("</gno-columns>\n\n")

	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")
		}
	}

	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:
		approveTopUpURL := txHref("/r/gnoland/wugnot", "Approve", "spender", string(realmAddress), "amount", "500000")
		topUpURL := txHref(realmWebBase, "TopUpBounty", "id", idStr, "amountUgnot", "500000")
		cancelURL := txHref(realmWebBase, "CancelBounty", "id", idStr)

		b.WriteString(`<gno-button href="` + approveTopUpURL + `" label="1. Approve 0.50 wugnot" variant="outline" /> `)
		b.WriteString(`<gno-button href="` + topUpURL + `" label="2. Crowd-Fund +0.50 GNOT" variant="success" /> `)
		b.WriteString(`<gno-button href="` + cancelURL + `" label="Cancel & Refund Contributors (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:
		approveTopUpURL := txHref("/r/gnoland/wugnot", "Approve", "spender", string(realmAddress), "amount", "500000")
		topUpURL := txHref(realmWebBase, "TopUpBounty", "id", idStr, "amountUgnot", "500000")
		releaseURL := txHref(realmWebBase, "ReleaseExpiredClaim", "id", idStr)

		b.WriteString(`<gno-button href="` + approveTopUpURL + `" label="1. Approve 0.50 wugnot" variant="outline" /> `)
		b.WriteString(`<gno-button href="` + topUpURL + `" label="2. Crowd-Fund +0.50 GNOT" variant="success" /> `)
		b.WriteString(`<gno-button href="` + releaseURL + `" label="Release Claim (Claimant / At 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 HTTPS URL (https://...)\" 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:
		expireURL := txHref(realmWebBase, "ExpireSubmission", "id", idStr)
		b.WriteString(`<gno-button href="` + expireURL + `" label="Expire Review & Auto-Settle (Post-Timeout)" variant="outline" />` + "\n\n")

		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:
		expireDisputeURL := txHref(realmWebBase, "ExpireDispute", "id", idStr)
		b.WriteString(`<gno-button href="` + expireDisputeURL + `" label="Expire Dispute (50/50 Fallback Post-Timeout)" variant="warning" />` + "\n\n")

		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] 1:1 `wugnot` On-Chain Escrow & Custody Guarantee\n")
	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")

	wrapURL := txHref("/r/gnoland/wugnot", "Deposit", ".send", "1000000ugnot")
	approveURL := txHref("/r/gnoland/wugnot", "Approve", "spender", string(realmAddress), "amount", "1000000")
	quick1 := txHref(realmWebBase, "PostBounty",
		"title", "Build GRC20 Fee Splitter",
		"spec", "Implement and test a deterministic fee splitter package in Gno v1.8.0.",
		"category", "realm",
		"rewardUgnot", "1000000",
		"deadlineBlocks", "50000",
	)
	quick2 := txHref(realmWebBase, "PostBounty",
		"title", "Security Audit of Escrow Invariants",
		"spec", "Review interrealm crossing guards and write adversarial unit tests.",
		"category", "audit",
		"rewardUgnot", "2500000",
		"deadlineBlocks", "50000",
	)

	b.WriteString("### Quick Prefilled Flow (Wrap -> Approve -> Post)\n\n")
	b.WriteString(`<gno-button href="` + wrapURL + `" label="1. Wrap 1.00 GNOT -> wugnot" variant="outline" /> `)
	b.WriteString(`<gno-button href="` + approveURL + `" label="2. Approve 1.00 wugnot" variant="outline" /> `)
	b.WriteString(`<gno-button href="` + quick1 + `" label="3. Post 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=\"rewardUgnot\" type=\"number\" placeholder=\"Escrow reward in wugnot (1000000 = 1.00 GNOT, min 100000)\" value=\"1000000\" required=\"true\" />\n")
	b.WriteString("<gno-input name=\"deadlineBlocks\" type=\"number\" placeholder=\"Claim & review window in blocks (default 50000)\" value=\"50000\" />\n")
	b.WriteString("</gno-form>\n\n")

	b.WriteString("> [!TIP] Funding 1:1 `wugnot` Escrow via CLI\n")
	b.WriteString("> ```bash\n")
	b.WriteString("> # 1) Wrap 1.00 GNOT into 1,000,000 wugnot\n")
	b.WriteString("> gnokey maketx call -pkgpath \"gno.land/r/gnoland/wugnot\" -func \"Deposit\" -send \"1000000ugnot\" -gas-fee 10000ugnot -gas-wanted 5000000 <your-key>\n")
	b.WriteString("> # 2) Approve HearthBounty v1 realm address as spender\n")
	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")
	b.WriteString("> # 3) Post bounty pulling 1,000,000 wugnot into custody\n")
	b.WriteString("> gnokey maketx call -pkgpath \"" + realmPkgPath + "\" -func \"PostBounty\" \\\n")
	b.WriteString(">   -args \"Title\" -args \"Detailed acceptance criteria\" -args \"realm\" -args \"1000000\" -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 {
		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) + " net 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-Accessible Query Surface\n")
	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")

	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, custody & 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, httpsURL, digest, summary)`\n")
	b.WriteString("5. **Settle** via `ApproveAndSettle` or permissionless `ExpireSubmission`\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 \"" + realmPkgPath + ".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("- **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")
	b.WriteString("- **Runtime-current auth:** Every crossing function authenticates `cur.Previous().Address()` cleanly on the live realm frame.\n")
	b.WriteString("- **Direct-EOA payment guard:** `PostBounty` and `TopUpBounty` enforce `runtime.AssertOriginCall()` and `cur.Previous().IsUserCall()`.\n")
	b.WriteString("- **Per-contributor top-up custody:** `CancelBounty` and dispute splits refund external donors directly; sponsors never receive third-party top-ups.\n")
	b.WriteString("- **Permissionless liveness timeouts:** `ReleaseExpiredClaim`, `ExpireSubmission`, and `ExpireDispute` (50/50 fallback) prevent frozen escrow. Arbiter cannot resolve bounties they are party to.\n")
	b.WriteString("- **Unicode-safe rendering:** Every user string passes `p/nt/markdown/sanitize/v0`, `EscapeMath`, and byte-indexed ASCII `NeutralizeGnoTags`.\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)
}

sanitize.gno

package hearthbounty

import "strings"

func asciiLowerByte(c byte) byte {
	if c >= 'A' && c <= 'Z' {
		return c + ('a' - 'A')
	}
	return c
}

func hasASCIIPrefixFold(s string, pos int, pattern string) bool {
	if pos+len(pattern) > len(s) {
		return false
	}
	for j := 0; j < len(pattern); j++ {
		if asciiLowerByte(s[pos+j]) != pattern[j] {
			return false
		}
	}
	return true
}

// NeutralizeGnoTags escapes any <gno- or </gno- tag sequences using direct
// byte-indexed ASCII case folding on the original string. Avoiding strings.ToLower
// prevents multi-byte Unicode case expansions (such as U+0130 'İ' -> "i\u0307")
// from shifting slice indices and letting raw <gno-*> tags pass through.
func NeutralizeGnoTags(s string) string {
	var b strings.Builder
	changed := false
	for i := 0; i < len(s); i++ {
		if s[i] == '<' && (hasASCIIPrefixFold(s, i, "<gno-") || hasASCIIPrefixFold(s, i, "</gno-")) {
			if !changed {
				b.Grow(len(s) + 8)
				b.WriteString(s[:i])
				changed = true
			}
			b.WriteString("&lt;")
			continue
		}
		if changed {
			b.WriteByte(s[i])
		}
	}
	if !changed {
		return s
	}
	return b.String()
}

// ValidateProofURL enforces HTTPS-only deliverable links with no whitespace so
// rendered proof links always survive p/nt/markdown/sanitize/v0 intact.
func ValidateProofURL(raw string) string {
	trimmed := strings.TrimSpace(raw)
	if len(trimmed) < 12 {
		panic("hearthbounty: proof URL is too short")
	}
	if len(trimmed) > 300 {
		panic("hearthbounty: proof URL exceeds maximum length")
	}
	if !strings.HasPrefix(trimmed, "https://") {
		panic("hearthbounty: proof URL must start with https://")
	}
	if strings.ContainsAny(trimmed, " \t\r\n") {
		panic("hearthbounty: proof URL must not contain whitespace")
	}
	return trimmed
}

state.gno

// Package hearthbounty implements the HearthBounty v1 micro-bounty escrow,
// per-contributor top-up custody, deterministic review/dispute timeouts,
// verifiable proof registry, reputation leaderboard, and gnoweb UI 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"
)

const (
	// EscrowTokenKey identifies the official 1:1 ugnot-backed wrapped GNOT
	// token registered in gno.land/r/nt/grc20reg/v0.
	EscrowTokenKey = "gno.land/r/gnoland/wugnot.wugnot"

	// MinTopUpUgnot matches the 0.10 GNOT floor so dust spam cannot grief donor ledgers.
	MinTopUpUgnot int64 = hearthcore.MinRewardUgnot

	// MaxEscrowUgnot caps a single bounty's escrow (1,000,000 GNOT) to prevent int64 overflow.
	MaxEscrowUgnot int64 = 1000000000000

	// MaxExternalDonors bounds deterministic donor iteration during cancel/dispute refunds.
	MaxExternalDonors = 20

	// BoardPageSize caps rendered rows per gnoweb page well below the 1 MiB ceiling.
	BoardPageSize = 20
)

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
	SponsorFundedUgnot    int64
	ExternalTopUpUgnot    int64
	DonorShares           *avl.Tree // non-sponsor address string -> int64 ugnot
	PayoutUgnot           int64
	RefundUgnot           int64
	TopUpCount            uint64
	DeadlineBlocks        int64
	CreatedHeight         int64
	ClaimedHeight         int64
	DeadlineHeight        int64
	SubmittedHeight       int64
	ReviewDeadlineHeight  int64
	DisputedHeight        int64
	DisputeDeadlineHeight int64
	SettledHeight         int64
	ProofURL              string
	ProofDigest           string
	ProofSummary          string
	SubmissionCount       uint64
	RevisionFeedback      string
	Rating                uint8
	ReviewNote            string
	DisputeReason         string
	DisputeOpenedBy       address
}

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
	SponsorFundedUgnot    int64
	ExternalTopUpUgnot    int64
	ExternalDonorCount    int
	PayoutUgnot           int64
	RefundUgnot           int64
	TopUpCount            uint64
	DeadlineBlocks        int64
	CreatedHeight         int64
	ClaimedHeight         int64
	DeadlineHeight        int64
	SubmittedHeight       int64
	ReviewDeadlineHeight  int64
	DisputedHeight        int64
	DisputeDeadlineHeight 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
	realmAddress      address
	realmPkgPath      string
	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) {
	realmAddress = cur.Address()
	realmPkgPath = cur.PkgPath()
	realmWebBase = deriveWebBase(realmPkgPath)
	if deployer := cur.Previous().Address(); deployer.IsValid() {
		arbiter = deployer
	}
	bounties = avl.NewTree()
	profiles = avl.NewTree()
	initRouter()
}

func deriveWebBase(pkgPath string) string {
	idx := strings.Index(pkgPath, "/")
	if idx == -1 {
		return "/r/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthbounty/v1"
	}
	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 {
	donorCount := 0
	if b.DonorShares != nil {
		donorCount = b.DonorShares.Size()
	}
	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,
		SponsorFundedUgnot:    b.SponsorFundedUgnot,
		ExternalTopUpUgnot:    b.ExternalTopUpUgnot,
		ExternalDonorCount:    donorCount,
		PayoutUgnot:           b.PayoutUgnot,
		RefundUgnot:           b.RefundUgnot,
		TopUpCount:            b.TopUpCount,
		DeadlineBlocks:        b.DeadlineBlocks,
		CreatedHeight:         b.CreatedHeight,
		ClaimedHeight:         b.ClaimedHeight,
		DeadlineHeight:        b.DeadlineHeight,
		SubmittedHeight:       b.SubmittedHeight,
		ReviewDeadlineHeight:  b.ReviewDeadlineHeight,
		DisputedHeight:        b.DisputedHeight,
		DisputeDeadlineHeight: b.DisputeDeadlineHeight,
		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)
}

func decrementSponsoredCredit(addr address, amount int64) {
	if amount <= 0 {
		return
	}
	if raw := profiles.Get(string(addr)); raw != nil {
		p := raw.(*profileRecord)
		if p.SponsoredUgnot >= amount {
			p.SponsoredUgnot -= amount
		} else {
			p.SponsoredUgnot = 0
		}
	}
}