Playground
api.gno
package bounties
import (
"chain"
"net/url"
"strconv"
"strings"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounty/v0"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/jsonw/v0"
"gno.land/p/nt/avl/v0"
"gno.land/r/nt/grc20reg/v0"
)
const (
realmPath = "gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounties"
apiMaxLimit = 50
apiMaxScan = 2000
apiMaxToken = 200
)
// renderAPI serves JSON for the web app, under Render("api/..."):
//
// api/stats counts, escrow totals, council, paused
// api/bounties?status=&tag=&page=&limit= newest first; status "all" or empty for every bounty
// api/bounty/<id> a bounty with milestones, disputes and applications
// api/user/<address>?page=&limit= bounties an address is involved in, with roles
// api/tokens registered GRC20 tokens usable for funding
func renderAPI(route string, q url.Values) string {
parts := strings.Split(route, "/")
switch {
case route == "api/stats":
return apiStats()
case route == "api/bounties":
return apiList(q)
case len(parts) == 3 && parts[1] == "bounty":
id, err := strconv.ParseUint(parts[2], 10, 64)
if err != nil {
return apiError("invalid id")
}
bn := getBounty(id)
if bn == nil {
return apiError("not found")
}
return bountyJSON(bn, true)
case len(parts) == 3 && parts[1] == "user":
return apiUser(address(parts[2]), q)
case route == "api/tokens":
return apiTokens()
}
return apiError("unknown endpoint")
}
func apiStats() string {
var escrow []string
escrowed.Iterate("", "", func(k string, v any) bool {
if amt := v.(int64); amt > 0 {
escrow = append(escrow, jsonw.Obj(append([]string{"amount", jsonw.Int(amt)}, denomFields(k, grc20reg.Get(k) != nil)...)...))
}
return false
})
return jsonw.Obj(
"total", jsonw.Int(int64(bounties.Size())),
"open", jsonw.Int(int64(statusCount[bounty.StatusOpen])),
"active", jsonw.Int(int64(statusCount[bounty.StatusActive])),
"completed", jsonw.Int(int64(statusCount[bounty.StatusCompleted])),
"cancelled", jsonw.Int(int64(statusCount[bounty.StatusCancelled])),
"escrow", jsonw.Arr(escrow),
"council", jsonw.String(council.Owner().String()),
"paused", jsonw.Bool(paused),
"realmAddress", jsonw.String(chain.PackageAddress(realmPath).String()),
)
}
func apiList(q url.Values) string {
status := q.Get("status")
want, filtered := bounty.ParseStatus(status)
if status != "" && status != "all" && !filtered {
return apiError("unknown status")
}
tag := strings.ToLower(q.Get("tag"))
limit := limitOf(q)
skip := (pageOf(q) - 1) * limit
var items []string
more := false
scanned := 0
bounties.ReverseIterate("", "", func(_ string, v any) bool {
scanned++
if scanned > apiMaxScan {
more = true
return true
}
bn := v.(*bounty.Bounty)
if filtered && bn.Status != want {
return false
}
if tag != "" && !hasTag(bn, tag) {
return false
}
if skip > 0 {
skip--
return false
}
if len(items) == limit {
more = true
return true
}
items = append(items, bountyJSON(bn, false))
return false
})
return jsonw.Obj("items", jsonw.Arr(items), "more", jsonw.Bool(more))
}
func apiUser(addr address, q url.Values) string {
if !addr.IsValid() {
return apiError("invalid address")
}
limit := limitOf(q)
var items []string
more := false
if v := byUser.Get(addr.String()); v != nil {
ids := v.(*avl.Tree)
ids.ReverseIterateByOffset((pageOf(q)-1)*limit, limit, func(k string, _ any) bool {
if bv := bounties.Get(k); bv != nil {
bn := bv.(*bounty.Bounty)
items = append(items, jsonw.Obj("bounty", bountyJSON(bn, false), "roles", jsonw.Strings(roles(bn, addr))))
}
return false
})
more = ids.Size() > pageOf(q)*limit
}
return jsonw.Obj("items", jsonw.Arr(items), "more", jsonw.Bool(more))
}
func apiTokens() string {
var items []string
grc20reg.GetRegistry().Iterate("", "", func(k string, _ any) bool {
tok := grc20reg.Get(k)
if tok == nil {
return false
}
items = append(items, jsonw.Obj(
"key", jsonw.String(k),
"name", jsonw.String(tok.GetName()),
"symbol", jsonw.String(tok.GetSymbol()),
"decimals", jsonw.Int(int64(tok.GetDecimals())),
))
return len(items) >= apiMaxToken
})
return jsonw.Obj("items", jsonw.Arr(items))
}
func bountyJSON(bn *bounty.Bounty, full bool) string {
ms := make([]string, len(bn.Milestones))
for i, m := range bn.Milestones {
fields := []string{
"title", jsonw.String(m.Title),
"amount", jsonw.Int(m.Amount),
"status", jsonw.String(m.Status.String()),
}
if full {
dispute := jsonw.Null
if d := m.Dispute; d != nil {
dispute = jsonw.Obj(
"openedBy", jsonw.String(d.OpenedBy.String()),
"reason", jsonw.String(d.Reason),
"openedAt", jsonw.Time(d.OpenedAt),
"resolved", jsonw.Bool(d.Resolved),
"resolvedAt", jsonw.Time(d.ResolvedAt),
"workerBps", jsonw.Int(d.WorkerBps),
"ruling", jsonw.String(d.Ruling),
)
}
fields = append(fields,
"submission", jsonw.String(m.Submission),
"submittedAt", jsonw.Time(m.SubmittedAt),
"approvals", jsonw.Addresses(m.Approvals),
"feedback", jsonw.String(m.Feedback),
"worker", jsonw.String(m.Worker.String()),
"paidOut", jsonw.Int(m.PaidOut),
"refunded", jsonw.Int(m.Refunded),
"settledAt", jsonw.Time(m.SettleAt),
"dispute", dispute,
)
}
ms[i] = jsonw.Obj(fields...)
}
fields := []string{
"id", jsonw.Uint(bn.ID),
"title", jsonw.String(bn.Title),
"tags", jsonw.Strings(bn.Tags),
"status", jsonw.String(bn.Status.String()),
"poster", jsonw.String(bn.Poster.String()),
"assignee", jsonw.String(bn.Assignee.String()),
"total", jsonw.Int(bn.Total()),
"escrowed", jsonw.Int(bn.Escrowed()),
"paidOut", jsonw.Int(bn.PaidOut()),
"applications", jsonw.Int(int64(len(bn.Applications))),
"createdAt", jsonw.Time(bn.CreatedAt),
"milestones", jsonw.Arr(ms),
}
fields = append(fields, denomFields(bn.Denom, bn.IsGRC20)...)
if full {
var apps []string
for _, a := range bn.Applications {
apps = append(apps, jsonw.Obj(
"applicant", jsonw.String(a.Applicant.String()),
"pitch", jsonw.String(a.Pitch),
"at", jsonw.Time(a.At),
))
}
fields = append(fields,
"description", jsonw.String(bn.Description),
"link", jsonw.String(bn.Link),
"reviewers", jsonw.Addresses(bn.Reviewers),
"quorum", jsonw.Int(int64(bn.Quorum)),
"arbiter", jsonw.String(bn.Arbiter.String()),
"councilArbitrated", jsonw.Bool(councilArbitrated.Has(idKey(bn.ID))),
"council", jsonw.String(council.Owner().String()),
"workWindowDays", jsonw.Int(int64(bn.WorkWindow.Hours()/24)),
"assignedAt", jsonw.Time(bn.AssignedAt),
"closedAt", jsonw.Time(bn.ClosedAt),
"applicationList", jsonw.Arr(apps),
)
}
return jsonw.Obj(fields...)
}
// denomFields describes how to display amounts of denom.
func denomFields(denom string, isGRC20 bool) []string {
symbol, decimals := denom, 0
switch {
case isGRC20:
if tok := grc20reg.Get(denom); tok != nil {
symbol, decimals = tok.GetSymbol(), tok.GetDecimals()
}
case denom == "ugnot":
symbol, decimals = "GNOT", 6
}
return []string{
"denom", jsonw.String(denom),
"isGRC20", jsonw.Bool(isGRC20),
"symbol", jsonw.String(symbol),
"decimals", jsonw.Int(int64(decimals)),
}
}
func roles(bn *bounty.Bounty, addr address) []string {
var out []string
if bn.Poster == addr {
out = append(out, "poster")
}
if bn.Assignee == addr {
out = append(out, "assignee")
}
if bn.IsReviewer(addr) {
out = append(out, "reviewer")
}
if bn.Arbiter == addr {
out = append(out, "arbiter")
}
if bn.HasApplied(addr) && bn.Assignee != addr {
out = append(out, "applicant")
}
for _, m := range bn.Milestones {
if m.Worker == addr && bn.Assignee != addr {
out = append(out, "contributor")
break
}
}
return out
}
func limitOf(q url.Values) int {
n, err := strconv.Atoi(q.Get("limit"))
if err != nil || n < 1 {
return 20
}
if n > apiMaxLimit {
return apiMaxLimit
}
return n
}
func apiError(msg string) string {
return jsonw.Obj("error", jsonw.String(msg))
}
bounties.gno
// Package bounties is Guildhall's escrowed bounty board.
//
// Anyone can post a task, fund it with GNOT (or any native coin) or any token
// in the grc20 registry, and split it into milestones. Funds sit in this
// realm until the bounty's reviewers approve a milestone, at which point the
// milestone is paid to the contributor and a record of the work is written to
// gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation. Contested milestones go to an arbiter, who
// can pay the worker, refund the poster, or split the difference.
//
// The rules live in gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounty. This realm holds the funds,
// authenticates callers, moves coins, and renders the board.
package bounties
import (
"chain"
"chain/banker"
"chain/runtime/unsafe"
"strconv"
"strings"
"time"
"unicode/utf8"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounty/v0"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/ownable/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation"
"gno.land/r/nt/grc20reg/v0"
)
const maxWorkWindowDays = 365
var (
bounties avl.Tree // padded id -> *bounty.Bounty
lastID uint64
byUser avl.Tree // address -> *avl.Tree(padded id -> struct{})
// councilArbitrated holds the ids of bounties whose arbiter is "the
// council" rather than a fixed address, so they follow the council if
// it changes hands.
councilArbitrated avl.Tree
statusCount = map[bounty.Status]int{}
escrowed avl.Tree // denom key -> int64 currently held
council *ownable.Ownable
paused bool
)
// InitialCouncil owns this namespace and is the only key that can deploy
// here. It holds the council seat until TransferCouncil hands it on.
const InitialCouncil address = "g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm"
func init() {
council = ownable.NewWithAddress(InitialCouncil)
}
// ---------------------------------------------------------------------------
// Posting
// PostBounty posts a bounty funded with the native coins sent along with the
// call. milestones is "Title=amount;Title=amount" and must add up to exactly
// what was sent; leave it empty for a single milestone worth the whole
// amount. reviewers is a comma-separated address list (empty means the poster
// reviews alone) and quorum is how many of them must approve each milestone.
// An empty arbiter delegates disputes to the Guildhall council.
func PostBounty(cur realm, title, description, link, tags, reviewers string, quorum int, milestones, arbiter string, workWindowDays int) uint64 {
assertNotPaused()
if !cur.Previous().IsUserCall() {
panic("bounties: native bounties must be posted directly by a user (maketx call with -send)")
}
sent := unsafe.OriginSend()
if len(sent) != 1 || sent[0].Amount <= 0 {
panic("bounties: send exactly one coin denomination to fund the bounty")
}
coin := sent[0]
specs, err := bounty.ParseMilestones(milestones, coin.Amount)
if err != nil {
panic(err.Error())
}
b := newBounty(cur, coin.Denom, false, title, description, link, tags, reviewers, quorum, specs, arbiter, workWindowDays)
if b.Total() != coin.Amount {
panic(ufmt.Sprintf("bounties: milestones add up to %d but %d%s was sent", b.Total(), coin.Amount, coin.Denom))
}
return store(b)
}
// PostBountyGRC20 posts a bounty funded with a registered GRC20 token. The
// caller must first approve this realm's address for the milestone total on
// the token; this call pulls the funds into escrow.
func PostBountyGRC20(cur realm, tokenKey, title, description, link, tags, reviewers string, quorum int, milestones, arbiter string, workWindowDays int) uint64 {
assertNotPaused()
if grc20reg.Get(tokenKey) == nil {
panic("bounties: unknown token " + strconv.Quote(tokenKey))
}
if len(unsafe.OriginSend()) > 0 && cur.Previous().IsUserCall() {
panic("bounties: do not send native coins with a GRC20 bounty")
}
specs, err := bounty.ParseMilestones(milestones, 0)
if err != nil {
panic(err.Error())
}
b := newBounty(cur, tokenKey, true, title, description, link, tags, reviewers, quorum, specs, arbiter, workWindowDays)
grc20reg.TransferFrom(0, cur, tokenKey, b.Poster, cur.Address(), b.Total())
return store(b)
}
func newBounty(cur realm, denom string, isGRC20 bool, title, description, link, tags, reviewers string, quorum int, specs []bounty.MilestoneSpec, arbiter string, workWindowDays int) *bounty.Bounty {
if workWindowDays < 0 || workWindowDays > maxWorkWindowDays {
panic(ufmt.Sprintf("bounties: work window must be 0..%d days", maxWorkWindowDays))
}
arb := address(strings.TrimSpace(arbiter))
if arb == "" {
arb = council.Owner()
}
b, err := bounty.New(bounty.Params{
ID: lastID + 1,
Poster: cur.Previous().Address(),
Title: title,
Description: description,
Link: strings.TrimSpace(link),
Tags: strings.Split(tags, ","),
Denom: denom,
IsGRC20: isGRC20,
Reviewers: bounty.ParseAddresses(reviewers),
Quorum: quorum,
Arbiter: arb,
Milestones: specs,
WorkWindow: time.Duration(workWindowDays) * 24 * time.Hour,
Now: time.Now(),
})
if err != nil {
panic(err.Error())
}
if strings.TrimSpace(arbiter) == "" {
councilArbitrated.Set(idKey(b.ID), struct{}{})
}
return b
}
func store(b *bounty.Bounty) uint64 {
lastID = b.ID
bounties.Set(idKey(b.ID), b)
statusCount[b.Status]++
addEscrow(b, b.Total())
index(b.Poster, b.ID)
for _, r := range b.Reviewers {
index(r, b.ID)
}
index(b.Arbiter, b.ID)
emit("BountyPosted", b,
"poster", b.Poster.String(),
"denom", b.Denom,
"total", strconv.FormatInt(b.Total(), 10))
return b.ID
}
// ---------------------------------------------------------------------------
// Working on a bounty
// Apply asks the poster to be assigned to an open bounty.
func Apply(cur realm, id uint64, pitch string) {
b := mustGet(id)
caller := cur.Previous().Address()
check(b.Apply(caller, pitch, time.Now()))
index(caller, id)
emit("BountyApplied", b, "applicant", caller.String())
}
// Assign hands an open bounty to a contributor. Poster only.
func Assign(cur realm, id uint64, assignee address) {
b := mustGet(id)
before := b.Status
check(b.Assign(cur.Previous().Address(), assignee, time.Now()))
moved(b, before)
index(assignee, id)
emit("BountyAssigned", b, "assignee", assignee.String())
}
// Unassign returns an active bounty to the open pool. The assignee may step
// back at any time; the poster may reclaim it once the work window has
// passed. Milestones awaiting review or arbitration must be settled first.
func Unassign(cur realm, id uint64) {
b := mustGet(id)
before, prev := b.Status, b.Assignee
check(b.Unassign(cur.Previous().Address(), time.Now()))
moved(b, before)
emit("BountyUnassigned", b, "previous", prev.String())
}
// Submit hands milestone (1-based) in for review, pointing at the work.
func Submit(cur realm, id uint64, milestone int, link string) {
b := mustGet(id)
check(b.Submit(cur.Previous().Address(), milestone-1, link, time.Now()))
emit("MilestoneSubmitted", b, "milestone", strconv.Itoa(milestone), "link", link)
}
// Approve records a reviewer's approval of a submitted milestone. The
// approval that reaches the quorum releases the milestone's funds to the
// contributor and writes a reputation record.
func Approve(cur realm, id uint64, milestone int) {
b := mustGet(id)
caller := cur.Previous().Address()
before := b.Status
payouts, err := b.Approve(caller, milestone-1, time.Now())
check(err)
emit("MilestoneApproved", b, "milestone", strconv.Itoa(milestone), "reviewer", caller.String())
m, _ := b.Milestone(milestone - 1)
settle(0, cur, b, payouts, m.Approvals, false)
moved(b, before)
}
// RequestChanges sends a submitted milestone back with feedback.
func RequestChanges(cur realm, id uint64, milestone int, feedback string) {
b := mustGet(id)
check(b.RequestChanges(cur.Previous().Address(), milestone-1, feedback))
emit("MilestoneChangesRequested", b, "milestone", strconv.Itoa(milestone))
}
// OpenDispute escalates a submitted or rejected milestone to the arbiter.
// The poster or the contributor who submitted it may open one.
func OpenDispute(cur realm, id uint64, milestone int, reason string) {
b := mustGet(id)
caller := cur.Previous().Address()
check(b.OpenDispute(caller, milestone-1, reason, time.Now()))
emit("MilestoneDisputed", b, "milestone", strconv.Itoa(milestone), "by", caller.String())
}
// Resolve settles a disputed milestone. workerBps is the share, in basis
// points (0..10000), paid to the contributor; the rest is refunded to the
// poster. Arbiter only.
func Resolve(cur realm, id uint64, milestone int, workerBps int, ruling string) {
b := mustGet(id)
caller := cur.Previous().Address()
if councilArbitrated.Has(idKey(id)) {
// Council-arbitrated bounties follow the council's current owner.
b.Arbiter = council.Owner()
}
before := b.Status
payouts, err := b.Resolve(caller, milestone-1, int64(workerBps), ruling, time.Now())
check(err)
emit("DisputeResolved", b, "milestone", strconv.Itoa(milestone), "worker_bps", strconv.Itoa(workerBps))
settle(0, cur, b, payouts, []address{caller}, true)
moved(b, before)
}
// Cancel withdraws an open bounty and refunds every unpaid milestone to the
// poster. Active bounties must be unassigned first.
func Cancel(cur realm, id uint64) {
b := mustGet(id)
before := b.Status
payouts, err := b.Cancel(cur.Previous().Address(), time.Now())
check(err)
settle(0, cur, b, payouts, nil, false)
moved(b, before)
emit("BountyCancelled", b)
}
// ---------------------------------------------------------------------------
// Council
// Council returns the default arbiter and operator of the board.
func Council() address {
return council.Owner()
}
// TransferCouncil hands the council seat to a new address, typically an
// arbitration committee's multisig. Bounties posted with the council as
// arbiter follow. Only the current council can move the seat.
func TransferCouncil(cur realm, newCouncil address) {
if err := council.TransferOwnership(0, cur, newCouncil); err != nil {
panic(err.Error())
}
emitCouncil(newCouncil)
}
func emitCouncil(addr address) {
chain.Emit("BountiesCouncilChanged", "council", addr.String())
}
// SetPaused stops (or resumes) the posting of new bounties. Work on existing
// bounties, payouts and refunds are never paused.
func SetPaused(cur realm, p bool) {
council.AssertOwnedBy(cur.Previous().Address())
paused = p
chain.Emit("BountiesPaused", "paused", strconv.FormatBool(p))
}
// ---------------------------------------------------------------------------
// Queries
// Count returns the number of bounties ever posted.
func Count() int {
return bounties.Size()
}
// CountByStatus returns the number of bounties in status ("open", "active",
// "completed" or "cancelled").
func CountByStatus(status string) int {
s, ok := bounty.ParseStatus(status)
if !ok {
return 0
}
return statusCount[s]
}
// Escrowed returns what the board currently holds for denom (a native denom
// or a grc20reg key).
func Escrowed(denom string) int64 {
v := escrowed.Get(denom)
if v == nil {
return 0
}
return v.(int64)
}
// IsPaused reports whether posting is paused.
func IsPaused() bool {
return paused
}
// ---------------------------------------------------------------------------
// Internals
// settle executes payouts, crediting reputation for each payment to a worker.
func settle(_ int, rlm realm, b *bounty.Bounty, payouts []bounty.Payout, reviewers []address, arbitrated bool) {
for _, p := range payouts {
transfer(0, rlm, b, p.To, p.Amount)
addEscrow(b, -p.Amount)
m, _ := b.Milestone(p.Milestone)
emit("Payout", b,
"kind", string(p.Kind),
"to", p.To.String(),
"amount", strconv.FormatInt(p.Amount, 10),
"milestone", strconv.Itoa(p.Milestone+1))
if p.Kind != bounty.PayoutWork {
continue
}
share := int64(bounty.MaxBps)
if arbitrated && m.Amount > 0 {
share = p.Amount * bounty.MaxBps / m.Amount
}
reputation.AddRecord(cross(rlm),
p.To,
b.Poster,
reviewers,
share,
p.Amount,
b.Denom,
clip(b.Title+" — "+m.Title, 300),
m.Submission,
ufmt.Sprintf("%d/%d", b.ID, p.Milestone+1),
arbitrated,
)
}
}
func transfer(_ int, rlm realm, b *bounty.Bounty, to address, amount int64) {
if amount <= 0 {
return
}
if b.IsGRC20 {
grc20reg.Transfer(0, rlm, b.Denom, to, amount)
return
}
bk := banker.NewBanker(banker.BankerTypeRealmSend, rlm)
bk.SendCoins(rlm.Address(), to, chain.Coins{{Denom: b.Denom, Amount: amount}})
}
func mustGet(id uint64) *bounty.Bounty {
v := bounties.Get(idKey(id))
if v == nil {
panic("bounties: unknown bounty " + strconv.FormatUint(id, 10))
}
return v.(*bounty.Bounty)
}
func getBounty(id uint64) *bounty.Bounty {
v := bounties.Get(idKey(id))
if v == nil {
return nil
}
return v.(*bounty.Bounty)
}
func moved(b *bounty.Bounty, before bounty.Status) {
if b.Status == before {
return
}
statusCount[before]--
statusCount[b.Status]++
}
func addEscrow(b *bounty.Bounty, delta int64) {
cur := int64(0)
if v := escrowed.Get(b.Denom); v != nil {
cur = v.(int64)
}
escrowed.Set(b.Denom, cur+delta)
}
func index(addr address, id uint64) {
if addr == "" {
return
}
var t *avl.Tree
if v := byUser.Get(addr.String()); v != nil {
t = v.(*avl.Tree)
} else {
t = avl.NewTree()
byUser.Set(addr.String(), t)
}
t.Set(idKey(id), struct{}{})
}
func assertNotPaused() {
if paused {
panic("bounties: posting is paused by the council")
}
}
func check(err error) {
if err != nil {
panic(err.Error())
}
}
func emit(event string, b *bounty.Bounty, kv ...string) {
attrs := append([]string{"id", strconv.FormatUint(b.ID, 10), "status", b.Status.String()}, kv...)
chain.Emit(event, attrs...)
}
func idKey(id uint64) string {
s := strconv.FormatUint(id, 10)
for len(s) < 12 {
s = "0" + s
}
return s
}
func clip(s string, n int) string {
if len(s) <= n {
return s
}
for n > 0 && !utf8.RuneStart(s[n]) {
n--
}
return s[:n]
}
gnomod.toml
module = "gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounties" gno = "0.9" [addpkg] creator = "g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm" height = 232979 max_deposit = "100000000ugnot"
render.gno
package bounties
import (
"chain"
"net/url"
"strconv"
"strings"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounty/v0"
"gno.land/p/moul/txlink/v0"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/markdown/sanitize/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation"
"gno.land/r/nt/grc20reg/v0"
)
const (
realmURL = "/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounties"
repURL = "/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/reputation"
pageSize = 20
)
// Render serves the bounty board:
//
// "" the board (?status=open|active|completed|cancelled|all, ?tag=x, ?page=N)
// <id> a bounty with its milestones and next actions
// u/<address> bounties an address posted, works on, reviews or applied to
// post how to post a bounty
func Render(path string) string {
route, query := splitQuery(path)
parts := strings.Split(route, "/")
switch {
case parts[0] == "api":
return renderAPI(route, query)
case route == "":
return renderBoard(query)
case route == "post":
return renderPost()
case len(parts) == 2 && parts[0] == "u":
return renderUser(address(parts[1]), pageOf(query))
case len(parts) == 1:
id, err := strconv.ParseUint(parts[0], 10, 64)
if err != nil {
return notFound()
}
return renderBounty(id)
}
return notFound()
}
func renderBoard(q url.Values) string {
status := q.Get("status")
if status == "" {
status = "open"
}
tag := strings.ToLower(q.Get("tag"))
page := pageOf(q)
var b strings.Builder
b.WriteString("# Guildhall Bounties\n\n")
b.WriteString("Fund work, get it reviewed, pay on approval. Every payout becomes a public [reputation record](" + repURL + ").\n\n")
b.WriteString(ufmt.Sprintf("**%d** open · **%d** in progress · **%d** completed · **%s** in escrow\n\n",
statusCount[bounty.StatusOpen], statusCount[bounty.StatusActive], statusCount[bounty.StatusCompleted], escrowSummary()))
if paused {
b.WriteString("> Posting new bounties is paused by the council. Existing bounties are unaffected.\n\n")
} else {
b.WriteString("[+ Post a bounty](" + realmURL + ":post)\n\n")
}
var tabs []string
for _, s := range []string{"open", "active", "completed", "cancelled", "all"} {
label := s
if s == status {
label = "**" + s + "**"
}
link := realmURL + "?status=" + s
if tag != "" {
link += "&tag=" + url.QueryEscape(tag)
}
tabs = append(tabs, "["+label+"]("+link+")")
}
b.WriteString(strings.Join(tabs, " · "))
if tag != "" {
b.WriteString(" · tag: `" + sanitize.InlineText(tag) + "` ([clear](" + realmURL + "?status=" + url.QueryEscape(status) + "))")
}
b.WriteString("\n\n")
want, filtered := bounty.ParseStatus(status)
var matches []*bounty.Bounty
skip := (page - 1) * pageSize
more := false
bounties.ReverseIterate("", "", func(_ string, v any) bool {
bn := v.(*bounty.Bounty)
if filtered && bn.Status != want {
return false
}
if tag != "" && !hasTag(bn, tag) {
return false
}
if skip > 0 {
skip--
return false
}
if len(matches) == pageSize {
more = true
return true
}
matches = append(matches, bn)
return false
})
b.WriteString(bountyTable(matches))
var nav []string
if page > 1 {
nav = append(nav, "[← newer]("+boardLink(status, tag, page-1)+")")
}
if more {
nav = append(nav, "[older →]("+boardLink(status, tag, page+1)+")")
}
if len(nav) > 0 {
b.WriteString("\n" + strings.Join(nav, " · ") + "\n")
}
return b.String()
}
func renderBounty(id uint64) string {
bn := getBounty(id)
if bn == nil {
return notFound()
}
var b strings.Builder
b.WriteString(ufmt.Sprintf("# #%d %s\n\n", bn.ID, sanitize.InlineText(bn.Title)))
b.WriteString(ufmt.Sprintf("**%s** · %s · posted %s", strings.ToUpper(bn.Status.String()), formatAmount(bn, bn.Total()), bn.CreatedAt.UTC().Format("2006-01-02")))
if len(bn.Tags) > 0 {
var ts []string
for _, t := range bn.Tags {
ts = append(ts, "["+t+"]("+realmURL+"?status=all&tag="+url.QueryEscape(t)+")")
}
b.WriteString(" · " + strings.Join(ts, " "))
}
b.WriteString("\n\n")
if bn.Description != "" {
b.WriteString(sanitize.Block(bn.Description) + "\n\n")
}
if bn.Link != "" {
b.WriteString("Reference: " + linkOrText(bn.Link) + "\n\n")
}
b.WriteString("| | |\n|---|---|\n")
b.WriteString("| Posted by | " + person(bn.Poster) + " |\n")
if bn.Assignee != "" {
b.WriteString("| Assigned to | " + person(bn.Assignee) + " since " + bn.AssignedAt.UTC().Format("2006-01-02") + " |\n")
}
var revs []string
for _, r := range bn.Reviewers {
revs = append(revs, person(r))
}
b.WriteString(ufmt.Sprintf("| Reviewers (%d of %d must approve) | %s |\n", bn.Quorum, len(bn.Reviewers), strings.Join(revs, ", ")))
arb := person(bn.Arbiter)
if councilArbitrated.Has(idKey(bn.ID)) {
arb = "Guildhall council (" + person(council.Owner()) + ")"
}
b.WriteString("| Arbiter | " + arb + " |\n")
b.WriteString(ufmt.Sprintf("| Work window | %d days |\n", int(bn.WorkWindow.Hours()/24)))
b.WriteString("| Escrow | " + formatAmount(bn, bn.Escrowed()) + " held · " + formatAmount(bn, bn.PaidOut()) + " paid |\n\n")
b.WriteString("## Milestones\n\n")
b.WriteString("| # | Milestone | Reward | Status | Work | Approvals |\n|---:|---|---:|---|---|---|\n")
for i, m := range bn.Milestones {
work := "-"
if m.Submission != "" {
work = linkOrText(m.Submission)
}
b.WriteString(ufmt.Sprintf("| %d | %s | %s | %s | %s | %d/%d |\n",
i+1, sanitize.TableCell(m.Title), formatAmount(bn, m.Amount), milestoneStatus(m), work, len(m.Approvals), bn.Quorum))
}
b.WriteString("\n")
for i, m := range bn.Milestones {
if m.Feedback != "" && m.Status == bounty.MilestoneChangesRequested {
b.WriteString(ufmt.Sprintf("> **Milestone %d, changes requested:** %s\n\n", i+1, sanitize.InlineText(m.Feedback)))
}
if d := m.Dispute; d != nil {
b.WriteString(ufmt.Sprintf("> **Milestone %d, disputed by %s:** %s\n", i+1, person(d.OpenedBy), sanitize.InlineText(d.Reason)))
if d.Resolved {
ruling := ""
if d.Ruling != "" {
ruling = ": " + sanitize.InlineText(d.Ruling)
}
b.WriteString(ufmt.Sprintf(">\n> **Ruling:** %s to the worker%s\n", bps(d.WorkerBps), ruling))
}
b.WriteString("\n")
}
}
b.WriteString(renderActions(bn))
if bn.Status == bounty.StatusOpen && len(bn.Applications) > 0 {
b.WriteString("## Applications\n\n| Applicant | Reputation | Pitch | |\n|---|---:|---|---|\n")
for _, a := range bn.Applications {
assign := txlink.NewLink("Assign").AddArgs("id", idStr(bn), "assignee", a.Applicant.String()).URL()
b.WriteString(ufmt.Sprintf("| %s | %d | %s | [assign](%s) |\n",
person(a.Applicant), reputation.Score(a.Applicant), sanitize.TableCell(a.Pitch), assign))
}
b.WriteString("\n")
}
return b.String()
}
// renderActions lists the transactions that can move the bounty forward, as
// gnoweb transaction links. The chain enforces who may call them; the page
// just lists them all.
func renderActions(bn *bounty.Bounty) string {
var acts []string
id := idStr(bn)
add := func(label, fn string, args ...string) {
acts = append(acts, "["+label+"]("+txlink.NewLink(fn).AddArgs(append([]string{"id", id}, args...)...).URL()+")")
}
switch bn.Status {
case bounty.StatusOpen:
add("Apply", "Apply")
add("Assign (poster)", "Assign")
add("Cancel and refund (poster)", "Cancel")
case bounty.StatusActive:
for i, m := range bn.Milestones {
n := strconv.Itoa(i + 1)
switch m.Status {
case bounty.MilestonePending, bounty.MilestoneChangesRequested:
add("Submit milestone "+n+" (assignee)", "Submit", "milestone", n)
if m.Status == bounty.MilestoneChangesRequested {
add("Dispute milestone "+n, "OpenDispute", "milestone", n)
}
case bounty.MilestoneSubmitted:
add("Approve milestone "+n+" (reviewer)", "Approve", "milestone", n)
add("Request changes on "+n+" (reviewer)", "RequestChanges", "milestone", n)
add("Dispute milestone "+n, "OpenDispute", "milestone", n)
case bounty.MilestoneDisputed:
add("Resolve milestone "+n+" (arbiter)", "Resolve", "milestone", n)
}
}
add("Step back / reclaim", "Unassign")
}
if len(acts) == 0 {
return ""
}
return "## Actions\n\n" + strings.Join(acts, " · ") + "\n\n"
}
func renderUser(addr address, page int) string {
if !addr.IsValid() {
return notFound()
}
var b strings.Builder
b.WriteString("# Bounties for " + addr.String() + "\n\n")
b.WriteString(ufmt.Sprintf("Reputation: **%d** (%s) · [profile](%s:u/%s)\n\n",
reputation.Score(addr), reputation.Level(addr), repURL, addr.String()))
v := byUser.Get(addr.String())
if v == nil {
b.WriteString("_Not involved in any bounty yet._\n")
return b.String()
}
ids := v.(*avl.Tree)
var list []*bounty.Bounty
ids.ReverseIterateByOffset((page-1)*pageSize, pageSize, func(k string, _ any) bool {
if bv := bounties.Get(k); bv != nil {
list = append(list, bv.(*bounty.Bounty))
}
return false
})
b.WriteString("| # | Bounty | Role | Reward | Status |\n|---:|---|---|---:|---|\n")
for _, bn := range list {
b.WriteString(ufmt.Sprintf("| %d | [%s](%s:%d) | %s | %s | %s |\n",
bn.ID, sanitize.TableCell(bn.Title), realmURL, bn.ID, role(bn, addr), formatAmount(bn, bn.Total()), bn.Status.String()))
}
if ids.Size() > page*pageSize {
b.WriteString(ufmt.Sprintf("\n[older →](%s:u/%s?page=%d)\n", realmURL, addr.String(), page+1))
}
return b.String()
}
func renderPost() string {
native := txlink.NewLink("PostBounty").
AddArgs("title", "", "description", "", "link", "", "tags", "", "reviewers", "", "quorum", "1", "milestones", "", "arbiter", "", "workWindowDays", "30").
SetSend("1000000ugnot").URL()
grc := txlink.NewLink("PostBountyGRC20").
AddArgs("tokenKey", "", "title", "", "milestones", "", "quorum", "1", "workWindowDays", "30").URL()
var b strings.Builder
b.WriteString("# Post a bounty\n\n")
b.WriteString("## With GNOT\n\n")
b.WriteString("[Open the form](" + native + ") and set the amount to send to the bounty's total.\n\n")
b.WriteString("- **milestones**: `Title=amount;Title=amount` in the smallest unit (`ugnot`). They must add up to exactly what you send. Leave empty for a single milestone worth everything sent.\n")
b.WriteString("- **reviewers**: comma-separated addresses. Leave empty to review it yourself.\n")
b.WriteString("- **quorum**: how many reviewers must approve each milestone.\n")
b.WriteString("- **arbiter**: who settles disputes. Leave empty for the Guildhall council.\n")
b.WriteString("- **workWindowDays**: after this many days without progress you can take the bounty back from its assignee (default 30).\n\n")
b.WriteString("```sh\ngnokey maketx call -pkgpath gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounties -func PostBounty \\\n")
b.WriteString(" -args \"Port faucet to interrealm v2\" -args \"Rewrite r/faucet using cur realm\" \\\n")
b.WriteString(" -args \"https://github.com/gnolang/gno/issues/1234\" -args \"realm,good-first-issue\" \\\n")
b.WriteString(" -args \"g1reviewer1...,g1reviewer2...\" -args 2 \\\n")
b.WriteString(" -args \"Design=20000000;Implementation=80000000\" -args \"\" -args 30 \\\n")
b.WriteString(" -send 100000000ugnot -gas-fee 1000000ugnot -gas-wanted 20000000 -broadcast -chainid gnoland1 KEY\n```\n\n")
b.WriteString("## With a GRC20 token\n\n")
b.WriteString("1. Approve `" + chain.PackageAddress("gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/guildhall/bounties").String() + "` on the token for the bounty's total.\n")
b.WriteString("2. Call [PostBountyGRC20](" + grc + ") with the token's [grc20reg](/r/nt/grc20reg/v0) key. Milestone amounts are required.\n")
return b.String()
}
func bountyTable(list []*bounty.Bounty) string {
if len(list) == 0 {
return "_No bounties here yet._\n"
}
var b strings.Builder
b.WriteString("| # | Bounty | Reward | Progress | Status | Poster |\n|---:|---|---:|---|---|---|\n")
for _, bn := range list {
settled := 0
for _, m := range bn.Milestones {
if m.Status.Settled() {
settled++
}
}
b.WriteString(ufmt.Sprintf("| %d | [%s](%s:%d)%s | %s | %d/%d | %s | %s |\n",
bn.ID, sanitize.TableCell(bn.Title), realmURL, bn.ID, tagSuffix(bn), formatAmount(bn, bn.Total()),
settled, len(bn.Milestones), bn.Status.String(), person(bn.Poster)))
}
return b.String()
}
func milestoneStatus(m *bounty.Milestone) string {
switch m.Status {
case bounty.MilestonePaid:
return "✅ paid"
case bounty.MilestoneSplit:
return "⚖️ split"
case bounty.MilestoneRefunded:
return "↩️ refunded"
case bounty.MilestoneDisputed:
return "⚠️ disputed"
case bounty.MilestoneSubmitted:
return "🔍 in review"
case bounty.MilestoneChangesRequested:
return "✏️ changes requested"
}
return "⏳ pending"
}
func role(bn *bounty.Bounty, addr address) string {
if rs := roles(bn, addr); len(rs) > 0 {
return strings.Join(rs, ", ")
}
return "-"
}
func hasTag(bn *bounty.Bounty, tag string) bool {
for _, t := range bn.Tags {
if t == tag {
return true
}
}
return false
}
func tagSuffix(bn *bounty.Bounty) string {
if len(bn.Tags) == 0 {
return ""
}
return " `" + strings.Join(bn.Tags, "` `") + "`"
}
func person(addr address) string {
if addr == "" {
return "-"
}
s := addr.String()
short := s
if len(s) > 14 {
short = s[:8] + "…" + s[len(s)-4:]
}
return "[" + short + "](" + repURL + ":u/" + s + ")"
}
func linkOrText(s string) string {
if u := sanitize.URL(s); u != "" && (strings.HasPrefix(s, "https://") || strings.HasPrefix(s, "/")) {
return "[" + sanitize.LinkTitle(s) + "](" + u + ")"
}
return sanitize.InlineText(s)
}
func formatAmount(bn *bounty.Bounty, amount int64) string {
if bn.IsGRC20 {
if tok := grc20reg.Get(bn.Denom); tok != nil {
return decimal(amount, tok.GetDecimals()) + " " + sanitize.InlineText(tok.GetSymbol())
}
return strconv.FormatInt(amount, 10) + " " + sanitize.InlineText(bn.Denom)
}
if bn.Denom == "ugnot" {
return decimal(amount, 6) + " GNOT"
}
return strconv.FormatInt(amount, 10) + " " + sanitize.InlineText(bn.Denom)
}
func escrowSummary() string {
var parts []string
escrowed.Iterate("", "", func(k string, v any) bool {
amt := v.(int64)
if amt <= 0 {
return false
}
switch {
case k == "ugnot":
parts = append(parts, decimal(amt, 6)+" GNOT")
case grc20reg.Get(k) != nil:
tok := grc20reg.Get(k)
parts = append(parts, decimal(amt, tok.GetDecimals())+" "+sanitize.InlineText(tok.GetSymbol()))
default:
parts = append(parts, strconv.FormatInt(amt, 10)+" "+sanitize.InlineText(k))
}
return false
})
if len(parts) == 0 {
return "nothing"
}
return strings.Join(parts, " + ")
}
func decimal(amount int64, decimals int) string {
if decimals <= 0 {
return strconv.FormatInt(amount, 10)
}
s := strconv.FormatInt(amount, 10)
neg := strings.HasPrefix(s, "-")
s = strings.TrimPrefix(s, "-")
for len(s) <= decimals {
s = "0" + s
}
whole, frac := s[:len(s)-decimals], strings.TrimRight(s[len(s)-decimals:], "0")
if neg {
whole = "-" + whole
}
if frac == "" {
return whole
}
return whole + "." + frac
}
func bps(v int64) string {
return decimal(v, 2) + "%"
}
func idStr(bn *bounty.Bounty) string {
return strconv.FormatUint(bn.ID, 10)
}
func boardLink(status, tag string, page int) string {
l := realmURL + "?status=" + url.QueryEscape(status) + "&page=" + strconv.Itoa(page)
if tag != "" {
l += "&tag=" + url.QueryEscape(tag)
}
return l
}
func splitQuery(path string) (string, url.Values) {
route, raw := path, ""
if i := strings.Index(path, "?"); i >= 0 {
route, raw = path[:i], path[i+1:]
}
q, _ := url.ParseQuery(raw)
return strings.Trim(route, "/"), q
}
func pageOf(q url.Values) int {
p, err := strconv.Atoi(q.Get("page"))
if err != nil || p < 1 {
return 1
}
return p
}
func notFound() string {
return "# Not found\n\n[Back to the board](" + realmURL + ")\n"
}