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/r/g1ypczwgczq2rkmgxc2t898tpsv5n8ecq3gj9fsv/quillbounty"
gno = "0.9"

[addpkg]
  creator = "g1ypczwgczq2rkmgxc2t898tpsv5n8ecq3gj9fsv"
  height = 1563314
  max_deposit = "50000000ugnot"

quillbounty.gno

package quillbounty

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

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

var (
	bounties       *avl.Tree // padID(id) -> *Bounty
	builders       *avl.Tree // address.String() -> *BuilderProfile
	nextBountyID   uint64 = 1
	totalFunded    int64
	totalPaidOut   int64
	totalCompleted int
)

func init() {
	bounties = avl.NewTree()
	builders = avl.NewTree()
}

// CreateBounty creates a new ugnot-escrowed bounty on Gno.land.
// Caller must attach native ugnot via transaction send envelope.
// Security: enforces runtime.AssertOriginCall() + cur.Previous().IsUserCall()
// before inspecting unsafe.OriginSend() per Interrealm v2 payment guidelines.
func CreateBounty(
	cur realm,
	title string,
	category string,
	spec string,
	reviewerAddr string,
	durationBlocks int64,
) uint64 {
	runtime.AssertOriginCall()
	prev := cur.Previous()
	if !prev.IsUserCall() {
		panic("CreateBounty: direct EOA call required")
	}

	title = strings.TrimSpace(title)
	spec = strings.TrimSpace(spec)
	if len(title) < 3 || len(title) > MaxTitleLen {
		panic("CreateBounty: title must be 3..120 characters")
	}
	if len(spec) < 10 || len(spec) > MaxSpecLen {
		panic("CreateBounty: spec must be 10..4000 characters")
	}
	if durationBlocks < MinDurationBlocks || durationBlocks > MaxDurationBlocks {
		panic("CreateBounty: durationBlocks out of allowed range")
	}

	sent := unsafe.OriginSend()
	if len(sent) != 1 || sent[0].Denom != DenomUgnot || sent[0].Amount <= 0 {
		panic("CreateBounty: must send positive ugnot only")
	}
	amount := sent[0].Amount

	sponsor := prev.Address()
	reviewer := sponsor
	reviewerAddr = strings.TrimSpace(reviewerAddr)
	if reviewerAddr != "" {
		rev := address(reviewerAddr)
		if !rev.IsValid() {
			panic("CreateBounty: invalid reviewer address")
		}
		reviewer = rev
	}

	newTotalFunded, ok := overflow.Add64(totalFunded, amount)
	if !ok {
		panic("CreateBounty: totalFunded overflow")
	}

	height := runtime.ChainHeight()
	id := nextBountyID
	nextBountyID++

	b := &Bounty{
		ID:             id,
		Sponsor:        sponsor,
		Reviewer:       reviewer,
		Title:          title,
		Category:       normalizeCategory(category),
		Spec:           spec,
		TotalFunded:    amount,
		RemainingUgnot: amount,
		CreatedHeight:  height,
		DeadlineHeight: height + durationBlocks,
		Status:         StatusOpen,
		Submissions:    make([]*Submission, 0),
	}
	bounties.Set(padID(id), b)
	totalFunded = newTotalFunded

	chain.Emit(
		"BountyCreated",
		"bounty_id", strconv.FormatUint(id, 10),
		"sponsor", sponsor.String(),
		"reviewer", reviewer.String(),
		"category", b.Category,
		"amount_ugnot", strconv.FormatInt(amount, 10),
		"deadline_height", strconv.FormatInt(b.DeadlineHeight, 10),
	)
	return id
}

// TopUpBounty allows anyone to add additional ugnot funding to an open bounty.
func TopUpBounty(cur realm, bountyID uint64) {
	runtime.AssertOriginCall()
	prev := cur.Previous()
	if !prev.IsUserCall() {
		panic("TopUpBounty: direct EOA call required")
	}

	b := mustGetBounty(bountyID)
	if b.Status != StatusOpen {
		panic("TopUpBounty: bounty is not open")
	}
	if runtime.ChainHeight() >= b.DeadlineHeight {
		panic("TopUpBounty: bounty deadline already passed")
	}

	sent := unsafe.OriginSend()
	if len(sent) != 1 || sent[0].Denom != DenomUgnot || sent[0].Amount <= 0 {
		panic("TopUpBounty: must send positive ugnot only")
	}
	amount := sent[0].Amount

	newRem, ok1 := overflow.Add64(b.RemainingUgnot, amount)
	newTot, ok2 := overflow.Add64(b.TotalFunded, amount)
	newGlobal, ok3 := overflow.Add64(totalFunded, amount)
	if !ok1 || !ok2 || !ok3 {
		panic("TopUpBounty: arithmetic overflow")
	}

	b.RemainingUgnot = newRem
	b.TotalFunded = newTot
	totalFunded = newGlobal

	chain.Emit(
		"BountyToppedUp",
		"bounty_id", strconv.FormatUint(bountyID, 10),
		"funder", prev.Address().String(),
		"amount_ugnot", strconv.FormatInt(amount, 10),
		"remaining_ugnot", strconv.FormatInt(b.RemainingUgnot, 10),
	)
}

// SubmitWork submits verifiable proof-of-work (PR/repo/gnoweb link + commit hash) on-chain.
func SubmitWork(
	cur realm,
	bountyID uint64,
	proofURL string,
	commitHash string,
	summary string,
) uint64 {
	b := mustGetBounty(bountyID)
	if b.Status != StatusOpen {
		panic("SubmitWork: bounty is not open")
	}
	if runtime.ChainHeight() >= b.DeadlineHeight {
		panic("SubmitWork: bounty deadline has passed")
	}

	builder := cur.Previous().Address()
	if builder == b.Sponsor {
		panic("SubmitWork: sponsor cannot submit to own bounty")
	}

	proofURL = strings.TrimSpace(proofURL)
	commitHash = strings.TrimSpace(commitHash)
	summary = strings.TrimSpace(summary)
	if len(proofURL) < 8 || len(proofURL) > MaxURLLen ||
		(!strings.HasPrefix(proofURL, "https://") && !strings.HasPrefix(proofURL, "gno.land/")) {
		panic("SubmitWork: proofURL must start with https:// or gno.land/")
	}
	if len(summary) < 5 || len(summary) > MaxSummaryLen {
		panic("SubmitWork: summary must be 5..1000 characters")
	}

	subID := uint64(len(b.Submissions) + 1)
	sub := &Submission{
		ID:          subID,
		BountyID:    bountyID,
		Builder:     builder,
		ProofURL:    proofURL,
		CommitHash:  commitHash,
		Summary:     summary,
		Status:      SubPending,
		SubmittedAt: runtime.ChainHeight(),
	}
	b.Submissions = append(b.Submissions, sub)

	chain.Emit(
		"WorkSubmitted",
		"bounty_id", strconv.FormatUint(bountyID, 10),
		"submission_id", strconv.FormatUint(subID, 10),
		"builder", builder.String(),
		"proof_url", proofURL,
	)
	return subID
}

// RequestRevision records an on-chain review note asking the builder to refine their submission.
func RequestRevision(cur realm, bountyID uint64, submissionID uint64, feedback string) {
	b := mustGetBounty(bountyID)
	caller := cur.Previous().Address()
	if caller != b.Sponsor && caller != b.Reviewer {
		panic("RequestRevision: unauthorized reviewer")
	}
	if b.Status != StatusOpen {
		panic("RequestRevision: bounty is not open")
	}

	sub := mustGetSubmission(b, submissionID)
	if sub.Status == SubApproved {
		panic("RequestRevision: submission already approved")
	}
	feedback = strings.TrimSpace(feedback)
	if len(feedback) < 3 || len(feedback) > MaxSummaryLen {
		panic("RequestRevision: feedback must be 3..1000 characters")
	}

	sub.Status = SubNeedsRevision
	sub.ReviewNote = feedback
	sub.ReviewedAt = runtime.ChainHeight()

	chain.Emit(
		"RevisionRequested",
		"bounty_id", strconv.FormatUint(bountyID, 10),
		"submission_id", strconv.FormatUint(submissionID, 10),
		"reviewer", caller.String(),
	)
}

// ApproveSubmission approves a submission and atomically releases escrowed ugnot.
// Pass payoutUgnot == 0 to release the entire remaining bounty balance (100% single-winner payout),
// or pass 0 < payoutUgnot <= RemainingUgnot for multi-winner split payouts.
func ApproveSubmission(
	cur realm,
	bountyID uint64,
	submissionID uint64,
	payoutUgnot int64,
	reviewNote string,
) {
	b := mustGetBounty(bountyID)
	caller := cur.Previous().Address()
	if caller != b.Sponsor && caller != b.Reviewer {
		panic("ApproveSubmission: unauthorized reviewer")
	}
	if b.Status != StatusOpen {
		panic("ApproveSubmission: bounty is not open")
	}
	if b.RemainingUgnot <= 0 {
		panic("ApproveSubmission: no remaining escrow")
	}

	sub := mustGetSubmission(b, submissionID)
	if sub.Status == SubApproved {
		panic("ApproveSubmission: submission already approved")
	}

	payout := payoutUgnot
	if payout == 0 {
		payout = b.RemainingUgnot
	}
	if payout <= 0 || payout > b.RemainingUgnot {
		panic("ApproveSubmission: invalid payout amount")
	}

	newGlobalPaid, ok := overflow.Add64(totalPaidOut, payout)
	if !ok {
		panic("ApproveSubmission: totalPaidOut overflow")
	}

	// Effects first (Checks-Effects-Interactions)
	sub.Status = SubApproved
	sub.PayoutUgnot = payout
	sub.ReviewNote = strings.TrimSpace(reviewNote)
	sub.ReviewedAt = runtime.ChainHeight()

	b.RemainingUgnot -= payout
	if b.RemainingUgnot == 0 {
		b.Status = StatusCompleted
		totalCompleted++
	}
	totalPaidOut = newGlobalPaid
	recordBuilderReputation(sub.Builder, payout, bountyID)

	// Interaction last: release escrowed ugnot from realm vault to winning builder
	bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	bnk.SendCoins(cur.Address(), sub.Builder, chain.NewCoins(chain.NewCoin(DenomUgnot, payout)))

	chain.Emit(
		"SubmissionApproved",
		"bounty_id", strconv.FormatUint(bountyID, 10),
		"submission_id", strconv.FormatUint(submissionID, 10),
		"builder", sub.Builder.String(),
		"payout_ugnot", strconv.FormatInt(payout, 10),
		"remaining_ugnot", strconv.FormatInt(b.RemainingUgnot, 10),
	)
}

// RefundExpired returns remaining escrowed ugnot to the sponsor after deadlineHeight passes.
func RefundExpired(cur realm, bountyID uint64) int64 {
	b := mustGetBounty(bountyID)
	caller := cur.Previous().Address()
	if caller != b.Sponsor {
		panic("RefundExpired: only sponsor can reclaim expired funds")
	}
	if b.Status != StatusOpen {
		panic("RefundExpired: bounty is not open")
	}
	if runtime.ChainHeight() < b.DeadlineHeight {
		panic("RefundExpired: deadline height not reached yet")
	}
	if b.RemainingUgnot <= 0 {
		panic("RefundExpired: nothing to refund")
	}

	refundAmt := b.RemainingUgnot
	b.RemainingUgnot = 0
	b.Status = StatusExpired

	bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	bnk.SendCoins(cur.Address(), b.Sponsor, chain.NewCoins(chain.NewCoin(DenomUgnot, refundAmt)))

	chain.Emit(
		"BountyRefunded",
		"bounty_id", strconv.FormatUint(bountyID, 10),
		"sponsor", b.Sponsor.String(),
		"refund_ugnot", strconv.FormatInt(refundAmt, 10),
	)
	return refundAmt
}

// GetBounty returns a read-only copy of a bounty for cross-realm composability.
func GetBounty(bountyID uint64) *Bounty {
	raw := bounties.Get(padID(bountyID))
	if raw == nil {
		return nil
	}
	b := raw.(*Bounty)
	cp := *b
	cp.Submissions = make([]*Submission, len(b.Submissions))
	for i, s := range b.Submissions {
		sc := *s
		cp.Submissions[i] = &sc
	}
	return &cp
}

// GetBuilderProfile returns on-chain reputation stats for a builder address.
func GetBuilderProfile(addr address) *BuilderProfile {
	raw := builders.Get(addr.String())
	if raw == nil {
		return nil
	}
	p := raw.(*BuilderProfile)
	cp := *p
	return &cp
}

// Stats returns aggregate protocol metrics (totalBounties, totalCompleted, totalFundedUgnot, totalPaidOutUgnot).
func Stats() (int, int, int64, int64) {
	return bounties.Size(), totalCompleted, totalFunded, totalPaidOut
}

func mustGetBounty(bountyID uint64) *Bounty {
	raw := bounties.Get(padID(bountyID))
	if raw == nil {
		panic("bounty not found")
	}
	return raw.(*Bounty)
}

func mustGetSubmission(b *Bounty, submissionID uint64) *Submission {
	if submissionID == 0 || int(submissionID) > len(b.Submissions) {
		panic("submission not found")
	}
	return b.Submissions[submissionID-1]
}

func recordBuilderReputation(addr address, payout int64, bountyID uint64) {
	key := addr.String()
	var prof *BuilderProfile
	if raw := builders.Get(key); raw != nil {
		prof = raw.(*BuilderProfile)
	} else {
		prof = &BuilderProfile{Address: addr}
		builders.Set(key, prof)
	}
	prof.CompletedCount++
	newEarned, ok := overflow.Add64(prof.TotalEarnedUgnot, payout)
	if !ok {
		panic("builder earned overflow")
	}
	prof.TotalEarnedUgnot = newEarned
	prof.LastBountyID = bountyID
}

quillbounty_test.gno

package quillbounty

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

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

const testPkgPath = "gno.land/r/g1ypczwgczq2rkmgxc2t898tpsv5n8ecq3gj9fsv/quillbounty"

func resetState() {
	bounties = avl.NewTree()
	builders = avl.NewTree()
	nextBountyID = 1
	totalFunded = 0
	totalPaidOut = 0
	totalCompleted = 0
}

func TestFullLifecycle_CreateTopUpSubmitSplitPayout(cur realm, t *testing.T) {
	defer resetState()

	pkgAddr := chain.PackageAddress(testPkgPath)
	sponsor := testutils.TestAddress("sponsor")
	reviewer := testutils.TestAddress("reviewer")
	builderA := testutils.TestAddress("builderA")
	builderB := testutils.TestAddress("builderB")

	// Seed realm vault to mirror ugnot credited by tx send-envelope in production
	testing.IssueCoins(pkgAddr, chain.Coins{{Denom: DenomUgnot, Amount: 2_000_000}})

	// 1. Sponsor creates a 1.5 GNOT bounty with an independent reviewer
	testing.SetRealm(testing.NewUserRealm(sponsor))
	testing.SetOriginSend(chain.Coins{{Denom: DenomUgnot, Amount: 1_500_000}})
	bountyID := CreateBounty(
		cross(cur),
		"Build Gno MCP Indexer",
		"ai",
		"Deliver an MCP server querying Onyx realms with automated tests.",
		reviewer.String(),
		100,
	)
	uassert.Equal(t, uint64(1), bountyID)

	// 2. Another funder tops up +0.5 GNOT
	testing.SetRealm(testing.NewUserRealm(reviewer))
	testing.SetOriginSend(chain.Coins{{Denom: DenomUgnot, Amount: 500_000}})
	TopUpBounty(cross(cur), bountyID)

	b := GetBounty(bountyID)
	urequire.NotEqual(t, nil, b)
	uassert.Equal(t, int64(2_000_000), b.TotalFunded)
	uassert.Equal(t, int64(2_000_000), b.RemainingUgnot)

	// 3. Builder A & Builder B submit verifiable work
	testing.SetRealm(testing.NewUserRealm(builderA))
	subA := SubmitWork(cross(cur), bountyID, "https://github.com/minorCoder/quillbounty", "abc1234", "Delivered MCP bridge + tests")
	uassert.Equal(t, uint64(1), subA)

	testing.SetRealm(testing.NewUserRealm(builderB))
	subB := SubmitWork(cross(cur), bountyID, "gno.land/r/demo/helper", "def5678", "Added benchmark suite")
	uassert.Equal(t, uint64(2), subB)

	// 4. Reviewer requests revision on Builder B, then approves split payouts (1.2 GNOT + remaining 0.8 GNOT)
	testing.SetRealm(testing.NewUserRealm(reviewer))
	RequestRevision(cross(cur), bountyID, subB, "Please include edge-case assertions")
	uassert.Equal(t, string(SubNeedsRevision), string(GetBounty(bountyID).Submissions[1].Status))

	ApproveSubmission(cross(cur), bountyID, subA, 1_200_000, "Clean primary implementation")
	uassert.Equal(t, string(StatusOpen), string(GetBounty(bountyID).Status))
	uassert.Equal(t, int64(800_000), GetBounty(bountyID).RemainingUgnot)

	// payoutUgnot == 0 releases entire remaining balance (800_000 ugnot) and closes bounty
	ApproveSubmission(cross(cur), bountyID, subB, 0, "Great benchmark additions")

	bFinal := GetBounty(bountyID)
	uassert.Equal(t, string(StatusCompleted), string(bFinal.Status))
	uassert.Equal(t, int64(0), bFinal.RemainingUgnot)

	// Verify real on-chain balances received
	ro := banker.NewReadonlyBanker()
	uassert.Equal(t, int64(1_200_000), ro.GetCoin(builderA, DenomUgnot))
	uassert.Equal(t, int64(800_000), ro.GetCoin(builderB, DenomUgnot))

	// Verify Builder Reputation Ledger
	profA := GetBuilderProfile(builderA)
	urequire.NotEqual(t, nil, profA)
	uassert.Equal(t, 1, profA.CompletedCount)
	uassert.Equal(t, int64(1_200_000), profA.TotalEarnedUgnot)

	// Verify Render routes (Home, Detail, Builders, JSON API)
	home := Render("")
	uassert.True(t, strings.Contains(home, "QuillBounty"))
	uassert.True(t, strings.Contains(home, "Build Gno MCP Indexer"))

	detail := Render("bounty/1")
	uassert.True(t, strings.Contains(detail, "COMPLETED"))
	uassert.True(t, strings.Contains(detail, "abc1234"))

	board := Render("builders")
	uassert.True(t, strings.Contains(board, builderA.String()))

	apiJSON := Render("api/bounties")
	uassert.True(t, strings.Contains(apiJSON, `"protocol":"QuillBounty"`))
	uassert.True(t, strings.Contains(apiJSON, `"totalPaidOutUgnot":2000000`))

	detailJSON := Render("api/bounty/1")
	uassert.True(t, strings.Contains(detailJSON, `"submissions":[`))
}

func TestExpiryRefundSafetyControl(cur realm, t *testing.T) {
	defer resetState()

	pkgAddr := chain.PackageAddress(testPkgPath)
	sponsor := testutils.TestAddress("sponsor_exp")
	other := testutils.TestAddress("stranger")

	testing.IssueCoins(pkgAddr, chain.Coins{{Denom: DenomUgnot, Amount: 1_000_000}})
	testing.SetRealm(testing.NewUserRealm(sponsor))
	testing.SetOriginSend(chain.Coins{{Denom: DenomUgnot, Amount: 1_000_000}})
	id := CreateBounty(cross(cur), "Expired Task Test", "security", "Audit state transitions before launch.", "", 20)

	// Refund before deadline must panic
	uassert.AbortsWithMessage(t, cur, "RefundExpired: deadline height not reached yet", func(cur realm) {
		RefundExpired(cur, id)
	})

	// Advance chain past deadline
	testing.SkipHeights(25)

	// Non-sponsor cannot reclaim funds
	testing.SetRealm(testing.NewUserRealm(other))
	uassert.AbortsWithMessage(t, cur, "RefundExpired: only sponsor can reclaim expired funds", func(cur realm) {
		RefundExpired(cur, id)
	})

	// Sponsor reclaims full escrow safely
	testing.SetRealm(testing.NewUserRealm(sponsor))
	refunded := RefundExpired(cross(cur), id)
	uassert.Equal(t, int64(1_000_000), refunded)
	uassert.Equal(t, string(StatusExpired), string(GetBounty(id).Status))
	uassert.Equal(t, int64(1_000_000), banker.NewReadonlyBanker().GetCoin(sponsor, DenomUgnot))
}

func TestAuthorizationAndValidationGuards(cur realm, t *testing.T) {
	defer resetState()

	sponsor := testutils.TestAddress("sponsor_sec")
	attacker := testutils.TestAddress("attacker")
	builder := testutils.TestAddress("honest_builder")

	testing.SetRealm(testing.NewUserRealm(sponsor))
	testing.SetOriginSend(chain.Coins{{Denom: DenomUgnot, Amount: 500_000}})
	id := CreateBounty(cross(cur), "Security Guard Test", "security", "Verify caller identity and input validation.", "", 50)

	// Sponsor cannot self-submit
	uassert.AbortsWithMessage(t, cur, "SubmitWork: sponsor cannot submit to own bounty", func(cur realm) {
		SubmitWork(cur, id, "https://github.com/test/repo", "111", "self submit attempt")
	})

	// Invalid proof URL rejected
	testing.SetRealm(testing.NewUserRealm(builder))
	uassert.AbortsWithMessage(t, cur, "SubmitWork: proofURL must start with https:// or gno.land/", func(cur realm) {
		SubmitWork(cur, id, "javascript:alert(1)", "111", "bad url scheme")
	})

	subID := SubmitWork(cross(cur), id, "https://github.com/minorCoder/quillbounty", "999", "Valid PR submission")

	// Unauthorized attacker cannot approve payout
	testing.SetRealm(testing.NewUserRealm(attacker))
	uassert.AbortsWithMessage(t, cur, "ApproveSubmission: unauthorized reviewer", func(cur realm) {
		ApproveSubmission(cur, id, subID, 0, "steal funds")
	})
}

render.gno

package quillbounty

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

	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/mux/v0"
	"gno.land/p/nt/ufmt/v0"
)

var router *mux.Router

func init() {
	router = mux.NewRouter()
	router.HandleFunc("", renderHome)
	router.HandleFunc("bounty/{id}", renderBountyDetail)
	router.HandleFunc("builders", renderBuilders)
	router.HandleFunc("api/bounties", renderAPIBounties)
	router.HandleFunc("api/bounty/{id}", renderAPIBountyDetail)
	router.HandleFunc("api/builders", renderAPIBuilders)
}

// Render serves both interactive Markdown UI for gnoweb and machine-readable JSON
// endpoints under /api/* for AI agents and MCP clients via ABCI vm/qrender.
func Render(path string) string {
	return router.Render(path)
}

func realmVaultUgnot() int64 {
	// Derive current realm address deterministically from canonical package path
	realmAddr := chain.PackageAddress("gno.land/r/g1ypczwgczq2rkmgxc2t898tpsv5n8ecq3gj9fsv/quillbounty")
	bnk := banker.NewReadonlyBanker()
	return bnk.GetCoin(realmAddr, DenomUgnot)
}

func renderHome(res *mux.ResponseWriter, req *mux.Request) {
	catFilter := strings.ToLower(strings.TrimSpace(req.Query.Get("cat")))
	statusFilter := strings.ToLower(strings.TrimSpace(req.Query.Get("status")))

	var openCount int
	bounties.ReverseIterate("", "", func(_ string, v any) bool {
		b := v.(*Bounty)
		if b.Status == StatusOpen {
			openCount++
		}
		return false
	})

	var sb strings.Builder
	sb.WriteString("# QuillBounty — On-Chain Proof-of-Work Escrow\n\n")
	sb.WriteString("Trustless native `ugnot` bounty escrow, verifiable on-chain work proofs, split-payout reviews, and AI-agent JSON endpoints on **Gno.land**.\n\n")

	createLink := txlink.NewLink("CreateBounty").
		AddArgs("title", "Build Gno Realm Feature", "category", "dev", "spec", "Describe acceptance criteria and deliverables", "reviewerAddr", "", "durationBlocks", "50000").
		SetSend("1000000ugnot").
		URL()

	sb.WriteString(ufmt.Sprintf(
		"**Quick Actions:** [Create Bounty (+1 GNOT)](%s) | [Builder Leaderboard](?p=builders) | [JSON API](:api/bounties)\n\n",
		createLink,
	))

	// KPI strip
	sb.WriteString("| Metric | Live On-Chain Value |\n")
	sb.WriteString("| :--- | :--- |\n")
	sb.WriteString(ufmt.Sprintf("| **Open Bounties** | `%d` / `%d` total |\n", openCount, bounties.Size()))
	sb.WriteString(ufmt.Sprintf("| **Completed Bounties** | `%d` |\n", totalCompleted))
	sb.WriteString(ufmt.Sprintf("| **Total Funded** | `%s` (`%d ugnot`) |\n", formatGNOT(totalFunded), totalFunded))
	sb.WriteString(ufmt.Sprintf("| **Total Paid Out** | `%s` (`%d ugnot`) |\n", formatGNOT(totalPaidOut), totalPaidOut))
	sb.WriteString(ufmt.Sprintf("| **Live Vault Balance** | `%s` |\n", formatGNOT(realmVaultUgnot())))
	sb.WriteString(ufmt.Sprintf("| **Verified Builders** | `%d` | \n\n", builders.Size()))

	sb.WriteString("**Filter:** [All](:) · [Open](:?status=open) · [Dev](:?cat=dev) · [AI](:?cat=ai) · [Security](:?cat=security) · [Docs](:?cat=docs) · [Builders](:builders)\n\n")
	sb.WriteString("---\n\n")
	sb.WriteString("## Active & Recent Bounties\n\n")

	if bounties.Size() == 0 {
		sb.WriteString("_No bounties funded yet. Click **Create Bounty** above to fund the first on-chain escrow!_\n")
		res.Write(sb.String())
		return
	}

	sb.WriteString("| ID | Title | Category | Status | Escrow Remaining | Submissions | Deadline Block |\n")
	sb.WriteString("| :---: | :--- | :---: | :---: | :--- | :---: | :---: |\n")

	shown := 0
	bounties.ReverseIterate("", "", func(_ string, v any) bool {
		b := v.(*Bounty)
		if catFilter != "" && b.Category != catFilter {
			return false
		}
		if statusFilter != "" && string(b.Status) != statusFilter {
			return false
		}
		sb.WriteString(ufmt.Sprintf(
			"| #%d | [%s](:bounty/%d) | `%s` | **%s** | %s | %d | #%d |\n",
			b.ID, b.Title, b.ID, b.Category, strings.ToUpper(string(b.Status)),
			formatGNOT(b.RemainingUgnot), len(b.Submissions), b.DeadlineHeight,
		))
		shown++
		return false
	})

	if shown == 0 {
		sb.WriteString("| — | _No bounties match the active filter._ | — | — | — | — | — |\n")
	}

	sb.WriteString("\n---\n")
	sb.WriteString(ufmt.Sprintf("_Chain height: `#%d` · Machine-readable endpoints: `:api/bounties`, `:api/bounty/{id}`, `:api/builders`_\n", runtime.ChainHeight()))
	res.Write(sb.String())
}

func renderBountyDetail(res *mux.ResponseWriter, req *mux.Request) {
	idStr := req.GetVar("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		res.Write("# Invalid Bounty ID\n\n[Back to QuillBounty](:)\n")
		return
	}
	raw := bounties.Get(padID(id))
	if raw == nil {
		res.Write(ufmt.Sprintf("# Bounty #%d Not Found\n\n[Back to QuillBounty](:)\n", id))
		return
	}
	b := raw.(*Bounty)
	height := runtime.ChainHeight()
	blocksLeft := b.DeadlineHeight - height
	if blocksLeft < 0 {
		blocksLeft = 0
	}

	var sb strings.Builder
	sb.WriteString(ufmt.Sprintf("# Bounty #%d — %s\n\n", b.ID, b.Title))
	sb.WriteString("[← All Bounties](:) | [Builder Leaderboard](:builders) | ")
	sb.WriteString(ufmt.Sprintf("[JSON View](:api/bounty/%d)\n\n", b.ID))

	sb.WriteString("| Field | Value |\n")
	sb.WriteString("| :--- | :--- |\n")
	sb.WriteString(ufmt.Sprintf("| **Status** | `%s` |\n", strings.ToUpper(string(b.Status))))
	sb.WriteString(ufmt.Sprintf("| **Category** | `%s` |\n", b.Category))
	sb.WriteString(ufmt.Sprintf("| **Total Funded** | `%s` (`%d ugnot`) |\n", formatGNOT(b.TotalFunded), b.TotalFunded))
	sb.WriteString(ufmt.Sprintf("| **Remaining Escrow** | `%s` (`%d ugnot`) |\n", formatGNOT(b.RemainingUgnot), b.RemainingUgnot))
	sb.WriteString(ufmt.Sprintf("| **Sponsor** | `%s` |\n", b.Sponsor.String()))
	sb.WriteString(ufmt.Sprintf("| **Reviewer / Arbiter** | `%s` |\n", b.Reviewer.String()))
	sb.WriteString(ufmt.Sprintf("| **Deadline** | Block `#%d` (`%d` blocks remaining) |\n\n", b.DeadlineHeight, blocksLeft))

	sb.WriteString("## Specification\n\n")
	sb.WriteString(b.Spec + "\n\n")

	if b.Status == StatusOpen {
		submitLink := txlink.NewLink("SubmitWork").
			AddArgs("bountyID", strconv.FormatUint(b.ID, 10), "proofURL", "https://github.com/...", "commitHash", "", "summary", "Completed deliverable with tests").
			URL()
		topUpLink := txlink.NewLink("TopUpBounty").
			AddArgs("bountyID", strconv.FormatUint(b.ID, 10)).
			SetSend("500000ugnot").
			URL()
		refundLink := txlink.NewLink("RefundExpired").
			AddArgs("bountyID", strconv.FormatUint(b.ID, 10)).
			URL()

		sb.WriteString(ufmt.Sprintf(
			"**Actions:** [Submit Work](%s) | [Top Up +0.5 GNOT](%s) | [Refund Expired (Sponsor)](%s)\n\n",
			submitLink, topUpLink, refundLink,
		))
	}

	sb.WriteString(ufmt.Sprintf("## Proof-of-Work Submissions (%d)\n\n", len(b.Submissions)))
	if len(b.Submissions) == 0 {
		sb.WriteString("_No submissions yet._\n")
	} else {
		for _, s := range b.Submissions {
			sb.WriteString(ufmt.Sprintf("### Submission #%d — `%s`\n\n", s.ID, strings.ToUpper(string(s.Status))))
			sb.WriteString(ufmt.Sprintf("- **Builder:** `%s`\n", s.Builder.String()))
			sb.WriteString(ufmt.Sprintf("- **Proof URL:** %s\n", s.ProofURL))
			if s.CommitHash != "" {
				sb.WriteString(ufmt.Sprintf("- **Commit:** `%s`\n", s.CommitHash))
			}
			sb.WriteString(ufmt.Sprintf("- **Summary:** %s\n", s.Summary))
			if s.PayoutUgnot > 0 {
				sb.WriteString(ufmt.Sprintf("- **Paid Out:** `%s` (`%d ugnot`)\n", formatGNOT(s.PayoutUgnot), s.PayoutUgnot))
			}
			if s.ReviewNote != "" {
				sb.WriteString(ufmt.Sprintf("- **Review Note:** %s\n", s.ReviewNote))
			}
			if b.Status == StatusOpen && s.Status != SubApproved {
				approveLink := txlink.NewLink("ApproveSubmission").
					AddArgs("bountyID", strconv.FormatUint(b.ID, 10), "submissionID", strconv.FormatUint(s.ID, 10), "payoutUgnot", "0", "reviewNote", "Verified deliverable").
					URL()
				sb.WriteString(ufmt.Sprintf("- **Reviewer Action:** [Approve & Release Full Escrow](%s)\n", approveLink))
			}
			sb.WriteString("\n")
		}
	}

	res.Write(sb.String())
}

func renderBuilders(res *mux.ResponseWriter, _ *mux.Request) {
	list := sortedBuilders()
	var sb strings.Builder
	sb.WriteString("# QuillBounty — Verified Builder Leaderboard\n\n")
	sb.WriteString("[← All Bounties](:) | [JSON API](:api/builders)\n\n")

	if len(list) == 0 {
		sb.WriteString("_No payouts completed yet._\n")
		res.Write(sb.String())
		return
	}

	sb.WriteString("| Rank | Builder Address | Completed | Total Earned | Last Bounty |\n")
	sb.WriteString("| :---: | :--- | :---: | :--- | :---: |\n")
	for i, p := range list {
		sb.WriteString(ufmt.Sprintf(
			"| #%d | `%s` | %d | **%s** (`%d ugnot`) | [#%d](:bounty/%d) |\n",
			i+1, p.Address.String(), p.CompletedCount, formatGNOT(p.TotalEarnedUgnot), p.TotalEarnedUgnot, p.LastBountyID, p.LastBountyID,
		))
	}
	res.Write(sb.String())
}

func renderAPIBounties(res *mux.ResponseWriter, _ *mux.Request) {
	var sb strings.Builder
	sb.WriteString(`{"protocol":"QuillBounty","chainHeight":`)
	sb.WriteString(strconv.FormatInt(runtime.ChainHeight(), 10))
	sb.WriteString(`,"totalFundedUgnot":` + strconv.FormatInt(totalFunded, 10))
	sb.WriteString(`,"totalPaidOutUgnot":` + strconv.FormatInt(totalPaidOut, 10))
	sb.WriteString(`,"vaultUgnot":` + strconv.FormatInt(realmVaultUgnot(), 10))
	sb.WriteString(`,"bounties":[`)

	first := true
	bounties.ReverseIterate("", "", func(_ string, v any) bool {
		b := v.(*Bounty)
		if !first {
			sb.WriteByte(',')
		}
		first = false
		writeBountyJSON(&sb, b, false)
		return false
	})
	sb.WriteString("]}")
	res.Write(sb.String())
}

func renderAPIBountyDetail(res *mux.ResponseWriter, req *mux.Request) {
	id, err := strconv.ParseUint(req.GetVar("id"), 10, 64)
	if err != nil {
		res.Write(`{"error":"invalid_bounty_id"}`)
		return
	}
	raw := bounties.Get(padID(id))
	if raw == nil {
		res.Write(`{"error":"bounty_not_found"}`)
		return
	}
	var sb strings.Builder
	writeBountyJSON(&sb, raw.(*Bounty), true)
	res.Write(sb.String())
}

func renderAPIBuilders(res *mux.ResponseWriter, _ *mux.Request) {
	list := sortedBuilders()
	var sb strings.Builder
	sb.WriteString(`{"builders":[`)
	for i, p := range list {
		if i > 0 {
			sb.WriteByte(',')
		}
		sb.WriteString(ufmt.Sprintf(
			`{"address":"%s","completedCount":%d,"totalEarnedUgnot":%d,"lastBountyId":%d}`,
			escapeJSON(p.Address.String()), p.CompletedCount, p.TotalEarnedUgnot, p.LastBountyID,
		))
	}
	sb.WriteString("]}")
	res.Write(sb.String())
}

func writeBountyJSON(sb *strings.Builder, b *Bounty, includeSubmissions bool) {
	sb.WriteString(ufmt.Sprintf(
		`{"id":%d,"title":"%s","category":"%s","status":"%s","sponsor":"%s","reviewer":"%s","totalFundedUgnot":%d,"remainingUgnot":%d,"createdHeight":%d,"deadlineHeight":%d,"submissionCount":%d`,
		b.ID, escapeJSON(b.Title), escapeJSON(b.Category), string(b.Status),
		b.Sponsor.String(), b.Reviewer.String(), b.TotalFunded, b.RemainingUgnot,
		b.CreatedHeight, b.DeadlineHeight, len(b.Submissions),
	))
	if includeSubmissions {
		sb.WriteString(`,"spec":"` + escapeJSON(b.Spec) + `","submissions":[`)
		for i, s := range b.Submissions {
			if i > 0 {
				sb.WriteByte(',')
			}
			sb.WriteString(ufmt.Sprintf(
				`{"id":%d,"builder":"%s","proofUrl":"%s","commitHash":"%s","summary":"%s","status":"%s","payoutUgnot":%d,"reviewNote":"%s","submittedAt":%d,"reviewedAt":%d}`,
				s.ID, s.Builder.String(), escapeJSON(s.ProofURL), escapeJSON(s.CommitHash),
				escapeJSON(s.Summary), string(s.Status), s.PayoutUgnot, escapeJSON(s.ReviewNote),
				s.SubmittedAt, s.ReviewedAt,
			))
		}
		sb.WriteByte(']')
	}
	sb.WriteByte('}')
}

func sortedBuilders() []*BuilderProfile {
	list := make([]*BuilderProfile, 0, builders.Size())
	builders.Iterate("", "", func(_ string, v any) bool {
		list = append(list, v.(*BuilderProfile))
		return false
	})
	// Deterministic in-place sort by TotalEarnedUgnot desc, then CompletedCount desc
	for i := 1; i < len(list); i++ {
		cur := list[i]
		j := i - 1
		for j >= 0 && (list[j].TotalEarnedUgnot < cur.TotalEarnedUgnot ||
			(list[j].TotalEarnedUgnot == cur.TotalEarnedUgnot && list[j].CompletedCount < cur.CompletedCount)) {
			list[j+1] = list[j]
			j--
		}
		list[j+1] = cur
	}
	return list
}

types.gno

package quillbounty

import (
	"strconv"
	"strings"
)

const (
	DenomUgnot        = "ugnot"
	MinDurationBlocks = int64(10)
	MaxDurationBlocks = int64(5_000_000)
	MaxTitleLen       = 120
	MaxSpecLen        = 4000
	MaxSummaryLen     = 1000
	MaxURLLen         = 300
)

type BountyStatus string

const (
	StatusOpen      BountyStatus = "open"
	StatusCompleted BountyStatus = "completed"
	StatusExpired   BountyStatus = "expired"
)

type SubmissionStatus string

const (
	SubPending       SubmissionStatus = "pending"
	SubNeedsRevision SubmissionStatus = "needs_revision"
	SubApproved      SubmissionStatus = "approved"
)

type Submission struct {
	ID           uint64
	BountyID     uint64
	Builder      address
	ProofURL     string
	CommitHash   string
	Summary      string
	Status       SubmissionStatus
	ReviewNote   string
	PayoutUgnot  int64
	SubmittedAt  int64
	ReviewedAt   int64
}

type Bounty struct {
	ID             uint64
	Sponsor        address
	Reviewer       address
	Title          string
	Category       string
	Spec           string
	TotalFunded    int64
	RemainingUgnot int64
	CreatedHeight  int64
	DeadlineHeight int64
	Status         BountyStatus
	Submissions    []*Submission
}

type BuilderProfile struct {
	Address          address
	CompletedCount   int
	TotalEarnedUgnot int64
	LastBountyID     uint64
}

func padID(id uint64) string {
	s := strconv.FormatUint(id, 10)
	if len(s) >= 12 {
		return s
	}
	return strings.Repeat("0", 12-len(s)) + s
}

func normalizeCategory(cat string) string {
	c := strings.ToLower(strings.TrimSpace(cat))
	switch c {
	case "dev", "ai", "security", "docs", "design":
		return c
	default:
		return "dev"
	}
}

func formatGNOT(ugnot int64) string {
	if ugnot < 0 {
		return "-" + formatGNOT(-ugnot)
	}
	whole := ugnot / 1_000_000
	frac := ugnot % 1_000_000
	if frac == 0 {
		return strconv.FormatInt(whole, 10) + " GNOT"
	}
	f := strconv.FormatInt(frac, 10)
	f = strings.Repeat("0", 6-len(f)) + f
	f = strings.TrimRight(f, "0")
	return strconv.FormatInt(whole, 10) + "." + f + " GNOT"
}

func escapeJSON(s string) string {
	var b strings.Builder
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch c {
		case '"':
			b.WriteString(`\"`)
		case '\\':
			b.WriteString(`\\`)
		case '\n':
			b.WriteString(`\n`)
		case '\r':
			b.WriteString(`\r`)
		case '\t':
			b.WriteString(`\t`)
		default:
			if c < 0x20 {
				b.WriteString(" ")
			} else {
				b.WriteByte(c)
			}
		}
	}
	return b.String()
}

func shortAddr(a address) string {
	s := a.String()
	if len(s) <= 14 {
		return s
	}
	return s[:8] + "..." + s[len(s)-4:]
}