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

gnomod.toml

module = "gno.land/p/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthcore/v0"
gno = "0.9"

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

hearthcore_test.gno

package hearthcore

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func TestComputeSplitConservation(t *testing.T) {
	cases := []struct {
		escrow int64
		bps    uint64
		wantH  int64
		wantS  int64
	}{
		{1000000, 0, 0, 1000000},
		{1000000, 10000, 1000000, 0},
		{1000000, 5000, 500000, 500000},
		{1000000, 7500, 750000, 250000},
		{999999, 3333, 333299, 666700},
		{1, 5000, 0, 1},
		{0, 5000, 0, 0},
		{9000000000000000, 3333, 2999700000000000, 6000300000000000},
	}

	for _, tc := range cases {
		h, s := ComputeSplit(tc.escrow, tc.bps)
		uassert.Equal(t, tc.wantH, h)
		uassert.Equal(t, tc.wantS, s)
		uassert.Equal(t, tc.escrow, h+s)
	}
}

func TestFormatGNOT(t *testing.T) {
	uassert.Equal(t, "0.00 GNOT", FormatGNOT(0))
	uassert.Equal(t, "1.00 GNOT", FormatGNOT(1000000))
	uassert.Equal(t, "2.50 GNOT", FormatGNOT(2500000))
	uassert.Equal(t, "0.10 GNOT", FormatGNOT(100000))
	uassert.Equal(t, "0.123456 GNOT", FormatGNOT(123456))
	uassert.Equal(t, "42.05 GNOT", FormatGNOT(42050000))
}

func TestComputeTier(t *testing.T) {
	uassert.Equal(t, string(TierApprentice), string(ComputeTier(0, 0, 0, 0)))
	uassert.Equal(t, string(TierApprentice), string(ComputeTier(1, 5000000, 5, 1)))
	uassert.Equal(t, string(TierJourneyman), string(ComputeTier(2, 5000000, 9, 2)))
	uassert.Equal(t, string(TierJourneyman), string(ComputeTier(1, 10000000, 5, 1)))
	uassert.Equal(t, string(TierMaster), string(ComputeTier(5, 10000000, 23, 5)))
	uassert.Equal(t, string(TierMaster), string(ComputeTier(1, 100000000, 5, 1)))
	uassert.Equal(t, string(TierGuildmaster), string(ComputeTier(10, 50000000, 48, 10)))
	// Low rating blocks Guildmaster promotion.
	uassert.Equal(t, string(TierMaster), string(ComputeTier(10, 50000000, 30, 10)))
}

func TestFormatRating(t *testing.T) {
	uassert.Equal(t, "Unrated", FormatRating(0, 0))
	uassert.Equal(t, "5.0 / 5.0", FormatRating(15, 3))
	uassert.Equal(t, "4.7 / 5.0", FormatRating(14, 3))
}

func TestCategoryAndStatusHelpers(t *testing.T) {
	cat, ok := ParseCategory("  AGENT ")
	uassert.True(t, ok)
	uassert.Equal(t, string(CatAgent), string(cat))
	uassert.Equal(t, "AI Agent", cat.Label())
	uassert.Equal(t, "ai", cat.IconName())

	_, bad := ParseCategory("invalid")
	uassert.False(t, bad)

	uassert.True(t, StatusOpen.IsValid())
	uassert.False(t, Status("bogus").IsValid())
	uassert.Equal(t, 3, StatusSettled.StepIndex())
}

func TestValidationHelpers(t *testing.T) {
	uassert.Equal(t, "https://github.com/org/repo/pull/1", ValidateProofURL("  https://github.com/org/repo/pull/1  "))
	uassert.Equal(t, "ipfs://bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi", ValidateProofURL("ipfs://bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi"))
	uassert.Equal(t, DefaultDeadlineBlocks, ValidateDeadlineBlocks(0))
	uassert.Equal(t, int64(250), ValidateDeadlineBlocks(250))
	uassert.Equal(t, uint8(5), ValidateRating(5))
	uassert.Equal(t, `cost is \$50 and \$GNOT`, EscapeMath("cost is $50 and $GNOT"))
}

func TestJSONBuilder(t *testing.T) {
	obj := NewJSONObject().
		Str("title", "Build \"alpha\"\nrealm").
		Int64("escrow_ugnot", 2500000).
		Uint64("id", 7).
		Bool("active", true).
		Raw("tags", JoinJSONArray([]string{QuoteJSON("realm"), QuoteJSON("mcp")})).
		String()

	uassert.Equal(t, `{"title":"Build \"alpha\"\nrealm","escrow_ugnot":2500000,"id":7,"active":true,"tags":["realm","mcp"]}`, obj)
}

func TestSVGVisuals(t *testing.T) {
	hero := RenderHeroBannerSVG(3, 2, 1, 4, 12500000, 48000000)
	uassert.True(t, strings.HasPrefix(hero, "![HearthBounty Live On-Chain Escrow Dashboard](data:image/svg+xml;base64,"))

	step := RenderLifecycleSVG(StatusSubmitted, 3500000)
	uassert.True(t, strings.HasPrefix(step, "![Bounty Lifecycle Progress](data:image/svg+xml;base64,"))

	badge := RenderTierBadgeSVG("agent<script>", TierGuildmaster, 12, 600000000, true)
	uassert.True(t, strings.HasPrefix(badge, "![HearthBounty Reputation Badge](data:image/svg+xml;base64,"))
}

json.gno

package hearthcore

import (
	"strconv"
	"strings"
)

// JSONBuilder constructs deterministic, RFC-8259-compliant JSON objects without
// reflection or external dependencies so realms can expose structured queries
// to AI agents and MCP servers via vm/qeval.
type JSONBuilder struct {
	b     strings.Builder
	count int
}

// NewJSONObject starts a new JSON object builder.
func NewJSONObject() *JSONBuilder {
	jb := &JSONBuilder{}
	jb.b.WriteByte('{')
	return jb
}

func (jb *JSONBuilder) writeKey(key string) {
	if jb.count > 0 {
		jb.b.WriteByte(',')
	}
	jb.b.WriteString(QuoteJSON(key))
	jb.b.WriteByte(':')
	jb.count++
}

// Str appends a string field.
func (jb *JSONBuilder) Str(key, val string) *JSONBuilder {
	jb.writeKey(key)
	jb.b.WriteString(QuoteJSON(val))
	return jb
}

// Int64 appends a signed 64-bit integer field.
func (jb *JSONBuilder) Int64(key string, val int64) *JSONBuilder {
	jb.writeKey(key)
	jb.b.WriteString(strconv.FormatInt(val, 10))
	return jb
}

// Uint64 appends an unsigned 64-bit integer field.
func (jb *JSONBuilder) Uint64(key string, val uint64) *JSONBuilder {
	jb.writeKey(key)
	jb.b.WriteString(strconv.FormatUint(val, 10))
	return jb
}

// Bool appends a boolean field.
func (jb *JSONBuilder) Bool(key string, val bool) *JSONBuilder {
	jb.writeKey(key)
	if val {
		jb.b.WriteString("true")
	} else {
		jb.b.WriteString("false")
	}
	return jb
}

// Raw appends a pre-encoded JSON value (array or nested object).
func (jb *JSONBuilder) Raw(key, rawJSON string) *JSONBuilder {
	jb.writeKey(key)
	jb.b.WriteString(rawJSON)
	return jb
}

// String closes and returns the encoded JSON object.
func (jb *JSONBuilder) String() string {
	return jb.b.String() + "}"
}

// JoinJSONArray joins pre-encoded JSON elements into a JSON array.
func JoinJSONArray(items []string) string {
	if len(items) == 0 {
		return "[]"
	}
	var b strings.Builder
	b.WriteByte('[')
	for i, item := range items {
		if i > 0 {
			b.WriteByte(',')
		}
		b.WriteString(item)
	}
	b.WriteByte(']')
	return b.String()
}

// QuoteJSON encodes s as a valid RFC-8259 JSON string literal.
func QuoteJSON(s string) string {
	var b strings.Builder
	b.Grow(len(s) + 2)
	b.WriteByte('"')
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch c {
		case '"':
			b.WriteString(`\"`)
		case '\\':
			b.WriteString(`\\`)
		case '\b':
			b.WriteString(`\b`)
		case '\f':
			b.WriteString(`\f`)
		case '\n':
			b.WriteString(`\n`)
		case '\r':
			b.WriteString(`\r`)
		case '\t':
			b.WriteString(`\t`)
		default:
			if c < 0x20 {
				b.WriteString(`\u00`)
				b.WriteByte(hexDigit(c >> 4))
				b.WriteByte(hexDigit(c & 0x0f))
			} else {
				b.WriteByte(c)
			}
		}
	}
	b.WriteByte('"')
	return b.String()
}

func hexDigit(n byte) byte {
	if n < 10 {
		return '0' + n
	}
	return 'a' + (n - 10)
}

types.gno

// Package hearthcore provides deterministic escrow math, bounty lifecycle
// primitives, reputation tier calculation, RFC-8259 JSON encoding, and
// on-chain SVG visual builders for HearthBounty and any Gno.land realm that
// imports it.
package hearthcore

import (
	"strconv"
	"strings"
)

const (
	// Denom is the native settlement denomination on Gno.land.
	Denom = "ugnot"

	// UgnotPerGNOT is the number of micro-GNOT in 1 GNOT.
	UgnotPerGNOT int64 = 1000000

	// MinRewardUgnot enforces a 0.1 GNOT floor to discourage dust spam.
	MinRewardUgnot int64 = 100000

	// Deadline block bounds ensure deterministic block-height timeouts.
	MinDeadlineBlocks     int64 = 10
	MaxDeadlineBlocks     int64 = 2000000
	DefaultDeadlineBlocks int64 = 50000

	// MaxBps represents 100.00% in integer basis points.
	MaxBps uint64 = 10000

	// Text length limits keep storage deposits bounded and predictable.
	MaxTitleLen    = 120
	MaxSpecLen     = 4000
	MaxNoteLen     = 600
	MaxURLLen      = 300
	MaxDigestLen   = 128
	MaxHandleLen   = 40
	MaxBioLen      = 300
	MaxSkillsLen   = 200
	MaxEndpointLen = 240
)

// Status represents a bounty's lifecycle state.
type Status string

const (
	StatusOpen      Status = "open"
	StatusClaimed   Status = "claimed"
	StatusSubmitted Status = "submitted"
	StatusDisputed  Status = "disputed"
	StatusSettled   Status = "settled"
	StatusCancelled Status = "cancelled"
)

// IsValid reports whether s is a known lifecycle status.
func (s Status) IsValid() bool {
	switch s {
	case StatusOpen, StatusClaimed, StatusSubmitted, StatusDisputed, StatusSettled, StatusCancelled:
		return true
	default:
		return false
	}
}

// Label returns a concise display label for s.
func (s Status) Label() string {
	switch s {
	case StatusOpen:
		return "Open"
	case StatusClaimed:
		return "Claimed"
	case StatusSubmitted:
		return "Submitted"
	case StatusDisputed:
		return "Disputed"
	case StatusSettled:
		return "Settled"
	case StatusCancelled:
		return "Cancelled"
	default:
		return "Unknown"
	}
}

// IconName returns a verified gnoweb icon identifier for s.
func (s Status) IconName() string {
	switch s {
	case StatusOpen:
		return "flame"
	case StatusClaimed:
		return "clock"
	case StatusSubmitted:
		return "upload"
	case StatusDisputed:
		return "warning"
	case StatusSettled:
		return "check-circle"
	case StatusCancelled:
		return "trash"
	default:
		return "info"
	}
}

// StepIndex returns the 0-based progression index for active lifecycle steps.
func (s Status) StepIndex() int {
	switch s {
	case StatusOpen:
		return 0
	case StatusClaimed:
		return 1
	case StatusSubmitted:
		return 2
	case StatusSettled:
		return 3
	case StatusDisputed:
		return 2
	default:
		return -1
	}
}

// Category classifies the kind of engineering work a bounty requests.
type Category string

const (
	CatRealm Category = "realm"
	CatTool  Category = "tool"
	CatAudit Category = "audit"
	CatDocs  Category = "docs"
	CatAgent Category = "agent"
)

// AllCategories returns all supported categories in canonical order.
func AllCategories() []Category {
	return []Category{CatRealm, CatTool, CatAudit, CatDocs, CatAgent}
}

// ParseCategory normalizes and validates a category string.
func ParseCategory(raw string) (Category, bool) {
	c := Category(strings.ToLower(strings.TrimSpace(raw)))
	switch c {
	case CatRealm, CatTool, CatAudit, CatDocs, CatAgent:
		return c, true
	default:
		return "", false
	}
}

// Label returns a human-friendly title for c.
func (c Category) Label() string {
	switch c {
	case CatRealm:
		return "Realm"
	case CatTool:
		return "Tooling"
	case CatAudit:
		return "Security Audit"
	case CatDocs:
		return "Docs & Guides"
	case CatAgent:
		return "AI Agent"
	default:
		return "General"
	}
}

// IconName returns a verified gnoweb icon identifier for c.
func (c Category) IconName() string {
	switch c {
	case CatRealm:
		return "code"
	case CatTool:
		return "settings"
	case CatAudit:
		return "shield"
	case CatDocs:
		return "book"
	case CatAgent:
		return "ai"
	default:
		return "tag"
	}
}

// Tier represents a builder or agent's earned on-chain reputation rank.
type Tier string

const (
	TierApprentice  Tier = "Apprentice"
	TierJourneyman  Tier = "Journeyman"
	TierMaster      Tier = "Master"
	TierGuildmaster Tier = "Guildmaster"
)

// ComputeTier deterministically assigns a reputation tier using pure integer math.
func ComputeTier(settledCount uint64, earnedUgnot int64, ratingSum uint64, ratingCount uint64) Tier {
	highQuality := ratingCount == 0 || ratingSum*10 >= ratingCount*45
	if (settledCount >= 10 || earnedUgnot >= 500*UgnotPerGNOT) && highQuality {
		return TierGuildmaster
	}
	if settledCount >= 5 || earnedUgnot >= 100*UgnotPerGNOT {
		return TierMaster
	}
	if settledCount >= 2 || earnedUgnot >= 10*UgnotPerGNOT {
		return TierJourneyman
	}
	return TierApprentice
}

// TierColor returns a high-contrast hex accent color for SVG badges.
func (t Tier) Color() string {
	switch t {
	case TierGuildmaster:
		return "#f59e0b"
	case TierMaster:
		return "#a78bfa"
	case TierJourneyman:
		return "#38bdf8"
	default:
		return "#34d399"
	}
}

// ComputeSplit splits an escrowed ugnot balance between hunter and sponsor
// using integer basis points (0..10000). It guarantees exact conservation:
// hunterUgnot + sponsorRefundUgnot == escrowUgnot.
func ComputeSplit(escrowUgnot int64, hunterBps uint64) (hunterUgnot int64, sponsorRefundUgnot int64) {
	if escrowUgnot < 0 {
		panic("hearthcore: negative escrow amount")
	}
	if hunterBps > MaxBps {
		panic("hearthcore: hunterBps exceeds 10000")
	}
	if hunterBps == 0 {
		return 0, escrowUgnot
	}
	if hunterBps == MaxBps {
		return escrowUgnot, 0
	}
	// Divide first to prevent int64 multiplication overflow on large balances.
	q := escrowUgnot / int64(MaxBps)
	r := escrowUgnot % int64(MaxBps)
	hunterUgnot = q*int64(hunterBps) + (r*int64(hunterBps))/int64(MaxBps)
	sponsorRefundUgnot = escrowUgnot - hunterUgnot
	return hunterUgnot, sponsorRefundUgnot
}

// FormatGNOT formats micro-GNOT into a deterministic human-readable GNOT string
// without floating-point operations.
func FormatGNOT(ugnot int64) string {
	neg := false
	if ugnot < 0 {
		neg = true
		ugnot = -ugnot
	}
	whole := ugnot / UgnotPerGNOT
	frac := ugnot % UgnotPerGNOT

	prefix := ""
	if neg {
		prefix = "-"
	}
	if frac == 0 {
		return prefix + strconv.FormatInt(whole, 10) + ".00 GNOT"
	}

	fracStr := strconv.FormatInt(frac, 10)
	for len(fracStr) < 6 {
		fracStr = "0" + fracStr
	}
	// Keep at least 2 decimal digits, trimming trailing zeros beyond 2.
	trimmed := strings.TrimRight(fracStr, "0")
	if len(trimmed) < 2 {
		trimmed = fracStr[:2]
	}
	return prefix + strconv.FormatInt(whole, 10) + "." + trimmed + " GNOT"
}

// FormatRating formats an integer rating sum/count into "X.Y / 5.0" or "Unrated".
func FormatRating(sum uint64, count uint64) string {
	if count == 0 {
		return "Unrated"
	}
	tenths := (sum*10 + count/2) / count
	whole := tenths / 10
	rem := tenths % 10
	return strconv.FormatUint(whole, 10) + "." + strconv.FormatUint(rem, 10) + " / 5.0"
}

// ShortAddr shortens a bech32 Gno address for compact tables and badges.
func ShortAddr(addr address) string {
	s := string(addr)
	if len(s) <= 14 {
		return s
	}
	return s[:8] + "..." + s[len(s)-4:]
}

// EscapeMath neutralizes unescaped dollar signs after Markdown sanitization so
// gnoweb's math extension does not treat prices or user text as TeX formulas.
func EscapeMath(s string) string {
	return strings.ReplaceAll(s, "$", `\$`)
}

// NeutralizeGnoTags escapes any remaining <gno- or </gno- tag sequences
// (case-insensitive) as defense-in-depth on top of p/nt/markdown/sanitize/v0
// so user-authored text can never smuggle gnoweb UI directives.
func NeutralizeGnoTags(s string) string {
	lower := strings.ToLower(s)
	if !strings.Contains(lower, "<gno-") && !strings.Contains(lower, "</gno-") {
		return s
	}
	var b strings.Builder
	b.Grow(len(s) + 8)
	for i := 0; i < len(s); i++ {
		if s[i] == '<' {
			rem := lower[i:]
			if strings.HasPrefix(rem, "<gno-") || strings.HasPrefix(rem, "</gno-") {
				b.WriteString("&lt;")
				continue
			}
		}
		b.WriteByte(s[i])
	}
	return b.String()
}

// ValidateText verifies a required or optional text field within rune/byte bounds.
func ValidateText(field, value string, minLen, maxLen int) string {
	trimmed := strings.TrimSpace(value)
	if len(trimmed) < minLen {
		panic("hearthcore: " + field + " is too short")
	}
	if len(trimmed) > maxLen {
		panic("hearthcore: " + field + " exceeds maximum length")
	}
	return trimmed
}

// ValidateProofURL enforces safe http/https/ipfs proof links.
func ValidateProofURL(raw string) string {
	trimmed := ValidateText("proof URL", raw, 8, MaxURLLen)
	if !strings.HasPrefix(trimmed, "https://") &&
		!strings.HasPrefix(trimmed, "http://") &&
		!strings.HasPrefix(trimmed, "ipfs://") {
		panic("hearthcore: proof URL must start with https://, http://, or ipfs://")
	}
	if strings.ContainsAny(trimmed, " \t\r\n") {
		panic("hearthcore: proof URL must not contain whitespace")
	}
	return trimmed
}

// ValidateProofDigest verifies a non-empty hexadecimal or prefixed content digest.
func ValidateProofDigest(raw string) string {
	trimmed := ValidateText("proof digest", raw, 8, MaxDigestLen)
	if strings.ContainsAny(trimmed, " \t\r\n") {
		panic("hearthcore: proof digest must not contain whitespace")
	}
	return trimmed
}

// ValidateDeadlineBlocks checks that a bounty deadline window is within safe bounds.
func ValidateDeadlineBlocks(blocks int64) int64 {
	if blocks == 0 {
		return DefaultDeadlineBlocks
	}
	if blocks < MinDeadlineBlocks || blocks > MaxDeadlineBlocks {
		panic("hearthcore: deadlineBlocks out of allowed range")
	}
	return blocks
}

// ValidateRating checks that a settlement rating is in [1, 5].
func ValidateRating(rating uint8) uint8 {
	if rating < 1 || rating > 5 {
		panic("hearthcore: rating must be between 1 and 5")
	}
	return rating
}

visuals.gno

package hearthcore

import (
	"strconv"
	"strings"

	"gno.land/p/nt/svg/v0"
)

// EscapeXML escapes special XML characters before embedding dynamic text inside
// deterministic on-chain SVG documents.
func EscapeXML(s string) string {
	r := strings.NewReplacer(
		"&", "&amp;",
		"<", "&lt;",
		">", "&gt;",
		`"`, "&quot;",
		"'", "&#39;",
	)
	return r.Replace(s)
}

// RenderHeroBannerSVG builds a deterministic on-chain SVG hero banner and
// stacked bounty distribution chart for gnoweb using gno.land/p/nt/svg/v0.
func RenderHeroBannerSVG(openCount, claimedCount, submittedCount, settledCount int, totalEscrowUgnot, totalSettledUgnot int64) string {
	c := svg.NewCanvas(860, 210).WithViewBox(0, 0, 860, 210)
	c.AddStyle("text", "font-family: ui-sans-serif, system-ui, -apple-system, sans-serif;")

	// Deep slate tavern backdrop with subtle border frame.
	bg := svg.NewRectangle(0, 0, 860, 210, "#0f172a")
	bg.RX = 14
	bg.RY = 14
	bg.Attr.Stroke = "#334155"
	bg.Attr.StrokeWidth = "2"
	c.Append(bg)

	// Warm hearth accent bar on left edge.
	accent := svg.NewRectangle(0, 0, 10, 210, "#f59e0b")
	accent.RX = 5
	c.Append(accent)

	// Brand emblem circle + ember spark.
	emblem := svg.NewCircle(54, 56, 22, "#1e293b")
	emblem.Attr.Stroke = "#f59e0b"
	emblem.Attr.StrokeWidth = "2.5"
	c.Append(emblem)
	c.Append(svg.NewCircle(54, 56, 9, "#f59e0b"))
	c.Append(svg.NewCircle(54, 53, 4, "#fef3c7"))

	// Title and subtitle.
	title := svg.NewText(92, 52, "HEARTHBOUNTY", "#f8fafc")
	title.Attr.Style = "font-size:24px;font-weight:800;letter-spacing:1.4px;"
	c.Append(title)

	sub := svg.NewText(92, 74, "On-Chain Micro-Bounty Escrow &amp; AI Agent Guild", "#94a3b8")
	sub.Attr.Style = "font-size:13px;font-weight:500;"
	c.Append(sub)

	// Live metric pill cards on top right.
	drawMetricBox(c, 525, 22, 152, 62, "ESCROW LOCKED", EscapeXML(FormatGNOT(totalEscrowUgnot)), "#f59e0b")
	drawMetricBox(c, 690, 22, 152, 62, "SETTLED VOLUME", EscapeXML(FormatGNOT(totalSettledUgnot)), "#34d399")

	// Stacked status distribution bar.
	barX := 34
	barY := 118
	barW := 792
	barH := 24

	track := svg.NewRectangle(barX, barY, barW, barH, "#1e293b")
	track.RX = 6
	track.RY = 6
	c.Append(track)

	total := openCount + claimedCount + submittedCount + settledCount
	if total > 0 {
		wOpen := (barW * openCount) / total
		wClaimed := (barW * claimedCount) / total
		wSubmitted := (barW * submittedCount) / total
		wSettled := barW - wOpen - wClaimed - wSubmitted
		if settledCount == 0 {
			wSettled = 0
		}

		curX := barX
		if wOpen > 0 {
			r := svg.NewRectangle(curX, barY, wOpen, barH, "#f59e0b")
			r.RX = 4
			c.Append(r)
			curX += wOpen
		}
		if wClaimed > 0 {
			r := svg.NewRectangle(curX, barY, wClaimed, barH, "#38bdf8")
			c.Append(r)
			curX += wClaimed
		}
		if wSubmitted > 0 {
			r := svg.NewRectangle(curX, barY, wSubmitted, barH, "#a78bfa")
			c.Append(r)
			curX += wSubmitted
		}
		if wSettled > 0 {
			r := svg.NewRectangle(curX, barY, wSettled, barH, "#34d399")
			r.RX = 4
			c.Append(r)
		}
	}

	// Legend row.
	drawLegendDot(c, 38, 174, "#f59e0b", "Open: "+strconv.Itoa(openCount))
	drawLegendDot(c, 195, 174, "#38bdf8", "Claimed: "+strconv.Itoa(claimedCount))
	drawLegendDot(c, 375, 174, "#a78bfa", "Submitted: "+strconv.Itoa(submittedCount))
	drawLegendDot(c, 575, 174, "#34d399", "Settled: "+strconv.Itoa(settledCount))

	badge := svg.NewText(718, 178, "MCP + gnoweb v1.8", "#64748b")
	badge.Attr.Style = "font-size:11px;font-weight:600;"
	c.Append(badge)

	return c.Render("HearthBounty Live On-Chain Escrow Dashboard")
}

func drawMetricBox(c *svg.Canvas, x, y, w, h int, label, value, color string) {
	box := svg.NewRectangle(x, y, w, h, "#1e293b")
	box.RX = 8
	box.RY = 8
	box.Attr.Stroke = "#334155"
	box.Attr.StrokeWidth = "1.5"
	c.Append(box)

	lbl := svg.NewText(x+12, y+22, label, "#94a3b8")
	lbl.Attr.Style = "font-size:10px;font-weight:700;letter-spacing:0.8px;"
	c.Append(lbl)

	val := svg.NewText(x+12, y+47, value, color)
	val.Attr.Style = "font-size:16px;font-weight:800;"
	c.Append(val)
}

func drawLegendDot(c *svg.Canvas, x, y int, color, text string) {
	c.Append(svg.NewCircle(x, y-4, 6, color))
	t := svg.NewText(x+14, y, text, "#e2e8f0")
	t.Attr.Style = "font-size:13px;font-weight:600;"
	c.Append(t)
}

// RenderLifecycleSVG renders an on-chain 4-step bounty progression strip.
func RenderLifecycleSVG(status Status, rewardUgnot int64) string {
	c := svg.NewCanvas(820, 108).WithViewBox(0, 0, 820, 108)
	c.AddStyle("text", "font-family: ui-sans-serif, system-ui, -apple-system, sans-serif;")

	bg := svg.NewRectangle(0, 0, 820, 108, "#0f172a")
	bg.RX = 12
	bg.RY = 12
	bg.Attr.Stroke = "#334155"
	bg.Attr.StrokeWidth = "1.5"
	c.Append(bg)

	steps := []string{"1. OPEN", "2. CLAIMED", "3. SUBMITTED", "4. SETTLED"}
	activeIdx := status.StepIndex()

	// Connector rail.
	rail := svg.NewRectangle(72, 42, 480, 4, "#334155")
	rail.RX = 2
	c.Append(rail)

	for i, label := range steps {
		cx := 72 + i*160
		fill := "#1e293b"
		stroke := "#475569"
		textColor := "#94a3b8"

		if status == StatusCancelled {
			stroke = "#ef4444"
		} else if status == StatusDisputed && i == 2 {
			fill = "#f97316"
			stroke = "#fdba74"
			textColor = "#f8fafc"
		} else if activeIdx >= 0 && i < activeIdx {
			fill = "#10b981"
			stroke = "#34d399"
			textColor = "#e2e8f0"
		} else if activeIdx == i {
			fill = "#f59e0b"
			stroke = "#fde68a"
			textColor = "#f8fafc"
		}

		node := svg.NewCircle(cx, 44, 15, fill)
		node.Attr.Stroke = stroke
		node.Attr.StrokeWidth = "2.5"
		c.Append(node)

		numColor := "#0f172a"
		if activeIdx < i || status == StatusCancelled {
			numColor = "#cbd5e1"
		}
		num := svg.NewText(cx-4, 49, strconv.Itoa(i+1), numColor)
		num.Attr.Style = "font-size:13px;font-weight:800;"
		c.Append(num)

		lbl := svg.NewText(cx-34, 82, label, textColor)
		lbl.Attr.Style = "font-size:11px;font-weight:700;letter-spacing:0.6px;"
		c.Append(lbl)
	}

	// Reward badge on right side.
	pill := svg.NewRectangle(618, 22, 182, 64, "#1e293b")
	pill.RX = 10
	pill.RY = 10
	pill.Attr.Stroke = "#f59e0b"
	pill.Attr.StrokeWidth = "2"
	c.Append(pill)

	st := svg.NewText(634, 44, "ESCROW: "+EscapeXML(strings.ToUpper(status.Label())), "#94a3b8")
	st.Attr.Style = "font-size:10px;font-weight:700;letter-spacing:0.7px;"
	c.Append(st)

	rew := svg.NewText(634, 70, EscapeXML(FormatGNOT(rewardUgnot)), "#fbbf24")
	rew.Attr.Style = "font-size:17px;font-weight:800;"
	c.Append(rew)

	return c.Render("Bounty Lifecycle Progress")
}

// RenderTierBadgeSVG creates a compact builder/agent reputation shield card.
func RenderTierBadgeSVG(handle string, tier Tier, settledCount uint64, earnedUgnot int64, isAgent bool) string {
	c := svg.NewCanvas(520, 86).WithViewBox(0, 0, 520, 86)
	c.AddStyle("text", "font-family: ui-sans-serif, system-ui, -apple-system, sans-serif;")

	bg := svg.NewRectangle(0, 0, 520, 86, "#0f172a")
	bg.RX = 10
	bg.RY = 10
	bg.Attr.Stroke = tier.Color()
	bg.Attr.StrokeWidth = "2"
	c.Append(bg)

	// Left rank circle.
	rankDot := svg.NewCircle(42, 43, 22, "#1e293b")
	rankDot.Attr.Stroke = tier.Color()
	rankDot.Attr.StrokeWidth = "2.5"
	c.Append(rankDot)

	initial := "B"
	initX := 36
	if isAgent {
		initial = "AI"
		initX = 33
	}
	initTxt := svg.NewText(initX, 49, initial, tier.Color())
	initTxt.Attr.Style = "font-size:15px;font-weight:800;"
	c.Append(initTxt)

	nameTxt := svg.NewText(80, 36, EscapeXML(handle), "#f8fafc")
	nameTxt.Attr.Style = "font-size:17px;font-weight:800;"
	c.Append(nameTxt)

	role := "Builder"
	if isAgent {
		role = "Autonomous AI Agent"
	}
	meta := string(tier) + " · " + role + " · " + strconv.FormatUint(settledCount, 10) + " settled"
	metaTxt := svg.NewText(80, 59, EscapeXML(meta), "#94a3b8")
	metaTxt.Attr.Style = "font-size:12px;font-weight:600;"
	c.Append(metaTxt)

	earnedTxt := svg.NewText(370, 49, EscapeXML(FormatGNOT(earnedUgnot)), tier.Color())
	earnedTxt.Attr.Style = "font-size:16px;font-weight:800;"
	c.Append(earnedTxt)

	return c.Render("HearthBounty Reputation Badge")
}