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

errors.gno

package gild

// Error messages. Each failure has its own message so callers, tests and the
// web app can tell them apart.
const (
	ErrUserCallOnly = "gild: post must be a direct user call"
	ErrReward       = "gild: send exactly one coin of " + Denom
	ErrRewardRange  = "gild: reward is outside the allowed range"
	ErrTitle        = "gild: title must be 3 to 120 characters"
	ErrDetails      = "gild: details are too long"
	ErrDone         = "gild: done text is too long"
	ErrCategory     = "gild: unknown category"
	ErrDeadline     = "gild: deadline must be 1 hour to 90 days from now"
	ErrNotFound     = "gild: task not found"
	ErrNotOpen      = "gild: task is not open"
	ErrOwnTask      = "gild: you cannot take your own task"
	ErrPastDeadline = "gild: deadline has passed"
	ErrNotDoer      = "gild: only the doer can do this"
	ErrNotPoster    = "gild: only the poster can do this"
	ErrNotTaken     = "gild: task is not taken"
	ErrNotInReview  = "gild: task is not in review"
	ErrURL          = "gild: work link must start with https:// and have no spaces"
	ErrChangesUsed  = "gild: changes were already asked once"
	ErrNote         = "gild: note must be 1 to 1000 characters"
	ErrTooEarly     = "gild: the review window has not ended"
	ErrDoerHasTime  = "gild: the doer still has time before the deadline"
	ErrCannotCancel = "gild: this task can no longer be cancelled"
	ErrMinDone      = "gild: required experience must be 0 to 100 paid tasks"
	ErrInvite       = "gild: invite must be a valid address"
	ErrInviteSelf   = "gild: you cannot offer a task to yourself"
	ErrInviteOnly   = "gild: this task was offered to someone else"
	ErrNeedRecord   = "gild: this task needs more paid Gild work on your record"
)

gild.gno

// Package gild is a paid task board.
//
// A poster locks a reward in this realm when posting a task. One doer takes
// the task and sends a link to the work. The poster approves and the realm
// pays the doer. Two rules protect both sides:
//
//   - If the poster stays silent for ReviewWindow after the work is sent,
//     the doer can claim the reward.
//   - If nobody takes the task, or the doer never sends work before the
//     deadline, the poster gets the reward back.
//
// Every payout is written to a public work record (see p/thesithunyein/rep),
// which other realms can read through Completed and Earned.
//
// v1 adds two things the record makes possible:
//
//   - Experience-gated tasks: a poster can require that the doer already
//     finished at least MinDone paid tasks on Gild.
//   - Direct hires: a poster can offer a task to one person only.
//
// The record counts work from both boards, so history from gild/v0 carries
// over without being copied.
package gild

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

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/seqid/v0"
	"gno.land/p/g1jw2yrfqnd4fp90qadw88pnjgpden4vgagjvpe6/rep/v0"
	legacy "gno.land/r/g1jw2yrfqnd4fp90qadw88pnjgpden4vgagjvpe6/gild/v0"
)

// Rules. They are constants so anyone can read them in the source.
const (
	Denom                  = "ugnot"
	MinReward        int64 = 1_000_000             // 1 GNOT
	MaxReward        int64 = 1_000_000_000_000_000 // 1 billion GNOT, a sanity cap
	ReviewWindow           = 7 * 24 * time.Hour    // poster's time to answer sent work
	ChangesExtension       = 3 * 24 * time.Hour    // minimum time a doer gets after changes are asked
	MinDeadline            = time.Hour
	MaxDeadline            = 90 * 24 * time.Hour

	MinTitle   = 3
	MaxTitle   = 120
	MaxDetails = 4000
	MaxDone    = 1000
	MaxURL     = 300
	MaxNote    = 1000
	MaxPage    = 50
	MaxMinDone = 100 // the highest experience a task can require
)

// Status is where a task is in its life.
type Status int

const (
	StatusOpen     Status = iota // reward locked, waiting for a doer
	StatusTaken                  // a doer is working on it
	StatusInReview               // work sent, waiting for the poster
	StatusPaid                   // reward paid to the doer
	StatusRefunded               // reward returned to the poster
)

func (s Status) String() string {
	switch s {
	case StatusOpen:
		return "open"
	case StatusTaken:
		return "taken"
	case StatusInReview:
		return "in_review"
	case StatusPaid:
		return "paid"
	case StatusRefunded:
		return "refunded"
	}
	return "unknown"
}

// Categories a task can have.
var categories = []string{"code", "docs", "design", "testing", "translation", "other"}

// Task is one posted piece of work.
type Task struct {
	ID       seqid.ID
	Title    string
	Details  string
	Done     string // what "done" looks like
	Category string
	Poster   address
	Doer     address
	Reward   int64 // in Denom
	Status   Status

	CreatedAt   time.Time
	Deadline    time.Time // a doer must send work before this
	TakenAt     time.Time
	SubmittedAt time.Time
	ClosedAt    time.Time

	MinDone int     // paid Gild tasks the doer must already have; 0 means anyone
	Invite  address // if set, only this address can take the task

	WorkURL      string
	ChangesAsked bool
	ChangesNote  string
	PaidBy       string // "approval" or "silence" once paid
}

var (
	tasks     avl.Tree // id key -> *Task, every task
	openTasks avl.Tree // id key -> *Task, only open tasks
	byPoster  avl.Tree // address -> *avl.Tree of id key -> *Task
	byDoer    avl.Tree // address -> *avl.Tree of id key -> *Task
	byInvite  avl.Tree // address -> *avl.Tree of id key -> *Task, direct offers
	nextID    seqid.ID
	book      = rep.NewBook(20)

	lockedTotal int64 // rewards currently held by this realm
	paidTotal   int64 // rewards paid to doers

	webPath string // this realm's gnoweb path, e.g. "/r/thesithunyein/gild/v1"
)

func init(cur realm) {
	webPath = strings.TrimPrefix(cur.PkgPath(), "gno.land")
}

// Post creates a task and locks the coins sent with the call as its reward.
// It must be called directly by a user (maketx call) with exactly one coin of
// Denom attached. deadline is a Unix time in seconds.
//
// minDone is how many paid Gild tasks a doer must already have (0 = anyone).
// invite is an address the task is offered to, or "" for an open task.
func Post(cur realm, title, details, done, category string, deadline int64, minDone int, invite string) int64 {
	prev := cur.Previous()
	if !prev.IsUserCall() {
		panic(ErrUserCallOnly)
	}
	reward := rewardFrom(unsafe.OriginSend())

	title = trimSpace(title)
	details = trimSpace(details)
	done = trimSpace(done)
	checkText(title, MinTitle, MaxTitle, ErrTitle)
	checkText(details, 0, MaxDetails, ErrDetails)
	checkText(done, 0, MaxDone, ErrDone)
	if !isCategory(category) {
		panic(ErrCategory)
	}

	if minDone < 0 || minDone > MaxMinDone {
		panic(ErrMinDone)
	}
	var inv address
	if invite = trimSpace(invite); invite != "" {
		inv = address(invite)
		if !inv.IsValid() {
			panic(ErrInvite)
		}
		if inv == prev.Address() {
			panic(ErrInviteSelf)
		}
	}

	now := time.Now()
	dl := time.Unix(deadline, 0)
	if dl.Before(now.Add(MinDeadline)) || dl.After(now.Add(MaxDeadline)) {
		panic(ErrDeadline)
	}

	t := &Task{
		ID:        nextID.Next(),
		Title:     title,
		Details:   details,
		Done:      done,
		Category:  category,
		Poster:    prev.Address(),
		Reward:    reward,
		Status:    StatusOpen,
		CreatedAt: now,
		Deadline:  dl,
		MinDone:   minDone,
		Invite:    inv,
	}
	key := t.ID.Binary()
	tasks.Set(key, t)
	openTasks.Set(key, t)
	index(&byPoster, t.Poster, key, t)
	if inv != "" {
		index(&byInvite, inv, key, t)
	}
	lockedTotal += reward
	return int64(t.ID)
}

// Take assigns an open task to the caller. The poster cannot take their own
// task, and nobody can take a task after its deadline. A direct offer can only
// be taken by the invited address, and a gated task only by someone whose
// record meets its MinDone.
func Take(cur realm, id int64) {
	caller := cur.Previous().Address()
	t := mustGet(id)
	if t.Status != StatusOpen {
		panic(ErrNotOpen)
	}
	if caller == t.Poster {
		panic(ErrOwnTask)
	}
	now := time.Now()
	if !now.Before(t.Deadline) {
		panic(ErrPastDeadline)
	}
	if t.Invite != "" && caller != t.Invite {
		panic(ErrInviteOnly)
	}
	if t.MinDone > 0 && !HasCompleted(caller, t.MinDone) {
		panic(ErrNeedRecord)
	}
	t.Doer = caller
	t.Status = StatusTaken
	t.TakenAt = now
	key := t.ID.Binary()
	openTasks.Remove(key)
	index(&byDoer, caller, key, t)
}

// Release gives a taken task back so someone else can take it. Only the doer
// can call it, and only before work is sent. Any change request is cleared,
// so the next doer starts fresh.
func Release(cur realm, id int64) {
	caller := cur.Previous().Address()
	t := mustGet(id)
	if caller != t.Doer {
		panic(ErrNotDoer)
	}
	if t.Status != StatusTaken {
		panic(ErrNotTaken)
	}
	key := t.ID.Binary()
	unindex(&byDoer, t.Doer, key)
	t.Doer = ""
	t.TakenAt = time.Time{}
	t.WorkURL = ""
	t.ChangesAsked = false
	t.ChangesNote = ""
	t.Status = StatusOpen
	openTasks.Set(key, t)
}

// Submit sends a link to the finished work. Only the doer can call it, and
// only while the task is taken.
func Submit(cur realm, id int64, workURL string) {
	caller := cur.Previous().Address()
	t := mustGet(id)
	if caller != t.Doer {
		panic(ErrNotDoer)
	}
	if t.Status != StatusTaken {
		panic(ErrNotTaken)
	}
	workURL = trimSpace(workURL)
	if !isWorkURL(workURL) {
		panic(ErrURL)
	}
	t.WorkURL = workURL
	t.SubmittedAt = time.Now()
	t.Status = StatusInReview
}

// Approve pays the doer. Only the poster can call it, and only after work
// was sent.
func Approve(cur realm, id int64) {
	caller := cur.Previous().Address()
	t := mustGet(id)
	if caller != t.Poster {
		panic(ErrNotPoster)
	}
	if t.Status != StatusInReview {
		panic(ErrNotInReview)
	}
	pay(t, cur, "approval")
}

// RequestChanges sends the task back to the doer once. The doer gets at least
// ChangesExtension from now before the poster can take the reward back.
func RequestChanges(cur realm, id int64, note string) {
	caller := cur.Previous().Address()
	t := mustGet(id)
	if caller != t.Poster {
		panic(ErrNotPoster)
	}
	if t.Status != StatusInReview {
		panic(ErrNotInReview)
	}
	if t.ChangesAsked {
		panic(ErrChangesUsed)
	}
	note = trimSpace(note)
	checkText(note, 1, MaxNote, ErrNote)

	t.ChangesAsked = true
	t.ChangesNote = note
	t.Status = StatusTaken
	t.SubmittedAt = time.Time{}
	if floor := time.Now().Add(ChangesExtension); t.Deadline.Before(floor) {
		t.Deadline = floor
	}
}

// ClaimAfterSilence pays the doer when the poster has not answered within
// ReviewWindow of the work being sent.
func ClaimAfterSilence(cur realm, id int64) {
	caller := cur.Previous().Address()
	t := mustGet(id)
	if caller != t.Doer {
		panic(ErrNotDoer)
	}
	if t.Status != StatusInReview {
		panic(ErrNotInReview)
	}
	if time.Now().Before(t.SubmittedAt.Add(ReviewWindow)) {
		panic(ErrTooEarly)
	}
	pay(t, cur, "silence")
}

// Cancel returns the reward to the poster. It works while the task is open,
// or when a doer took it but sent no work before the deadline. It never works
// once work has been sent, so a poster cannot cancel to avoid paying.
func Cancel(cur realm, id int64) {
	caller := cur.Previous().Address()
	t := mustGet(id)
	if caller != t.Poster {
		panic(ErrNotPoster)
	}
	switch t.Status {
	case StatusOpen:
		openTasks.Remove(t.ID.Binary())
	case StatusTaken:
		if time.Now().Before(t.Deadline) {
			panic(ErrDoerHasTime)
		}
	default:
		panic(ErrCannotCancel)
	}
	t.Status = StatusRefunded
	t.ClosedAt = time.Now()
	lockedTotal -= t.Reward
	send(t.Poster, t.Reward, cur)
}

// Completed returns how many tasks addr finished and was paid for on Gild,
// across both boards (v0 and v1). Other realms can call it to gate features
// by proven work.
func Completed(addr address) int { return legacy.Completed(addr) + book.Completed(addr) }

// Earned returns the total paid to addr on Gild across both boards, in Denom.
func Earned(addr address) int64 { return legacy.Earned(addr) + book.Earned(addr) }

// HasCompleted reports whether addr finished at least n tasks on Gild.
func HasCompleted(addr address, n int) bool { return n <= 0 || Completed(addr) >= n }

// pay marks the task paid, records it, then sends the reward. State changes
// come before the transfer.
func pay(t *Task, rlm realm, by string) {
	now := time.Now()
	t.Status = StatusPaid
	t.ClosedAt = now
	t.PaidBy = by
	lockedTotal -= t.Reward
	paidTotal += t.Reward
	book.Add(rep.Record{
		TaskID: idStr(t.ID),
		Title:  t.Title,
		Poster: t.Poster,
		Doer:   t.Doer,
		Amount: t.Reward,
		Denom:  Denom,
		At:     now,
	})
	send(t.Doer, t.Reward, rlm)
}

// send pays amount from this realm to addr. rlm must be the live realm handle.
func send(to address, amount int64, rlm realm) {
	b := banker.NewBanker(banker.BankerTypeRealmSend, rlm)
	b.SendCoins(rlm.Address(), to, chain.Coins{{Denom, amount}})
}

func rewardFrom(sent chain.Coins) int64 {
	if len(sent) != 1 || sent[0].Denom != Denom {
		panic(ErrReward)
	}
	amount := sent[0].Amount
	if amount < MinReward || amount > MaxReward {
		panic(ErrRewardRange)
	}
	return amount
}

// idStr is the public form of a task id, e.g. "12".
func idStr(id seqid.ID) string { return strconv.FormatInt(int64(id), 10) }

func mustGet(id int64) *Task {
	if id < 1 {
		panic(ErrNotFound)
	}
	v := tasks.Get(seqid.ID(id).Binary())
	if v == nil {
		panic(ErrNotFound)
	}
	return v.(*Task)
}

func index(tree *avl.Tree, addr address, key string, t *Task) {
	var sub *avl.Tree
	if v := tree.Get(addr.String()); v != nil {
		sub = v.(*avl.Tree)
	} else {
		sub = avl.NewTree()
		tree.Set(addr.String(), sub)
	}
	sub.Set(key, t)
}

func unindex(tree *avl.Tree, addr address, key string) {
	v := tree.Get(addr.String())
	if v == nil {
		return
	}
	sub := v.(*avl.Tree)
	sub.Remove(key)
	if sub.Size() == 0 {
		tree.Remove(addr.String())
	}
}

func isCategory(c string) bool {
	for _, k := range categories {
		if c == k {
			return true
		}
	}
	return false
}

gnomod.toml

module = "gno.land/r/g1jw2yrfqnd4fp90qadw88pnjgpden4vgagjvpe6/gild/v1"
gno = "0.9"

[addpkg]
  creator = "g1jw2yrfqnd4fp90qadw88pnjgpden4vgagjvpe6"
  height = 1504726
  max_deposit = "100000000ugnot"

read.gno

package gild

import (
	"strconv"
	"strings"
	"time"

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

// ---- JSON views for apps ----

// TaskJSON returns one task as JSON, or "null" if it does not exist.
func TaskJSON(id int64) string {
	if id < 1 {
		return "null"
	}
	v := tasks.Get(seqid.ID(id).Binary())
	if v == nil {
		return "null"
	}
	return taskJSON(v.(*Task))
}

// TasksJSON lists tasks newest first. filter is "open" or "all".
func TasksJSON(filter string, offset, limit int) string {
	switch filter {
	case "open":
		return pageJSON(&openTasks, offset, limit)
	case "all":
		return pageJSON(&tasks, offset, limit)
	}
	return `{"total":0,"items":[]}`
}

// PosterTasksJSON lists tasks posted by addr, newest first.
func PosterTasksJSON(addr address, offset, limit int) string {
	return pageJSON(sub(&byPoster, addr), offset, limit)
}

// DoerTasksJSON lists tasks taken by addr, newest first.
func DoerTasksJSON(addr address, offset, limit int) string {
	return pageJSON(sub(&byDoer, addr), offset, limit)
}

// InvitesJSON lists tasks offered directly to addr, newest first. It keeps
// every offer, so check each task's status.
func InvitesJSON(addr address, offset, limit int) string {
	return pageJSON(sub(&byInvite, addr), offset, limit)
}

// StatsJSON returns totals for this board (v1). Add gild/v0 StatsJSON for
// all-time numbers.
func StatsJSON() string {
	var b strings.Builder
	b.WriteString(`{"open":`)
	b.WriteString(strconv.Itoa(openTasks.Size()))
	b.WriteString(`,"tasks":`)
	b.WriteString(strconv.Itoa(tasks.Size()))
	b.WriteString(`,"locked":`)
	b.WriteString(strconv.FormatInt(lockedTotal, 10))
	b.WriteString(`,"paid":`)
	b.WriteString(strconv.FormatInt(paidTotal, 10))
	b.WriteString(`,"completed":`)
	b.WriteString(strconv.Itoa(book.Total()))
	b.WriteString(`,"builders":`)
	b.WriteString(strconv.Itoa(book.Size()))
	b.WriteString(`,"denom":"` + Denom + `"}`)
	return b.String()
}

// ProfileJSON returns the work record of addr. completed and earned count
// both boards; posted, spent and recent cover this board only.
func ProfileJSON(addr address) string {
	p := book.Profile(addr)
	var b strings.Builder
	b.WriteString(`{"address":`)
	b.WriteString(jsonStr(addr.String()))
	b.WriteString(`,"completed":`)
	b.WriteString(strconv.Itoa(Completed(addr)))
	b.WriteString(`,"earned":`)
	b.WriteString(strconv.FormatInt(Earned(addr), 10))
	b.WriteString(`,"posted":`)
	b.WriteString(strconv.Itoa(p.Posted))
	b.WriteString(`,"spent":`)
	b.WriteString(strconv.FormatInt(p.Spent, 10))
	b.WriteString(`,"recent":[`)
	for i, r := range p.Recent() {
		if i > 0 {
			b.WriteByte(',')
		}
		b.WriteString(`{"taskId":`)
		b.WriteString(jsonStr(r.TaskID))
		b.WriteString(`,"title":`)
		b.WriteString(jsonStr(r.Title))
		b.WriteString(`,"poster":`)
		b.WriteString(jsonStr(r.Poster.String()))
		b.WriteString(`,"doer":`)
		b.WriteString(jsonStr(r.Doer.String()))
		b.WriteString(`,"amount":`)
		b.WriteString(strconv.FormatInt(r.Amount, 10))
		b.WriteString(`,"at":`)
		b.WriteString(strconv.FormatInt(r.At.Unix(), 10))
		b.WriteByte('}')
	}
	b.WriteString("]}")
	return b.String()
}

func sub(tree *avl.Tree, addr address) *avl.Tree {
	if v := tree.Get(addr.String()); v != nil {
		return v.(*avl.Tree)
	}
	return avl.NewTree()
}

func clampPage(offset, limit int) (int, int) {
	if offset < 0 {
		offset = 0
	}
	if limit < 1 || limit > MaxPage {
		limit = MaxPage
	}
	return offset, limit
}

func pageJSON(tree *avl.Tree, offset, limit int) string {
	offset, limit = clampPage(offset, limit)
	var b strings.Builder
	b.WriteString(`{"total":`)
	b.WriteString(strconv.Itoa(tree.Size()))
	b.WriteString(`,"items":[`)
	first := true
	tree.ReverseIterateByOffset(offset, limit, func(_ string, v any) bool {
		if !first {
			b.WriteByte(',')
		}
		first = false
		b.WriteString(taskJSON(v.(*Task)))
		return false
	})
	b.WriteString("]}")
	return b.String()
}

func taskJSON(t *Task) string {
	var b strings.Builder
	b.WriteString(`{"id":`)
	b.WriteString(strconv.FormatInt(int64(t.ID), 10))
	b.WriteString(`,"title":`)
	b.WriteString(jsonStr(t.Title))
	b.WriteString(`,"details":`)
	b.WriteString(jsonStr(t.Details))
	b.WriteString(`,"done":`)
	b.WriteString(jsonStr(t.Done))
	b.WriteString(`,"category":`)
	b.WriteString(jsonStr(t.Category))
	b.WriteString(`,"poster":`)
	b.WriteString(jsonStr(t.Poster.String()))
	b.WriteString(`,"doer":`)
	b.WriteString(jsonStr(t.Doer.String()))
	b.WriteString(`,"reward":`)
	b.WriteString(strconv.FormatInt(t.Reward, 10))
	b.WriteString(`,"denom":"` + Denom + `","status":"`)
	b.WriteString(t.Status.String())
	b.WriteString(`","createdAt":`)
	b.WriteString(unix(t.CreatedAt))
	b.WriteString(`,"deadline":`)
	b.WriteString(unix(t.Deadline))
	b.WriteString(`,"takenAt":`)
	b.WriteString(unix(t.TakenAt))
	b.WriteString(`,"submittedAt":`)
	b.WriteString(unix(t.SubmittedAt))
	b.WriteString(`,"closedAt":`)
	b.WriteString(unix(t.ClosedAt))
	b.WriteString(`,"claimableAt":`)
	if t.Status == StatusInReview {
		b.WriteString(unix(t.SubmittedAt.Add(ReviewWindow)))
	} else {
		b.WriteString("0")
	}
	b.WriteString(`,"workUrl":`)
	b.WriteString(jsonStr(t.WorkURL))
	b.WriteString(`,"changesAsked":`)
	b.WriteString(strconv.FormatBool(t.ChangesAsked))
	b.WriteString(`,"changesNote":`)
	b.WriteString(jsonStr(t.ChangesNote))
	b.WriteString(`,"paidBy":`)
	b.WriteString(jsonStr(t.PaidBy))
	b.WriteString(`,"minDone":`)
	b.WriteString(strconv.Itoa(t.MinDone))
	b.WriteString(`,"invite":`)
	b.WriteString(jsonStr(t.Invite.String()))
	b.WriteByte('}')
	return b.String()
}

func unix(t time.Time) string {
	if t.IsZero() {
		return "0"
	}
	return strconv.FormatInt(t.Unix(), 10)
}

// jsonStr returns s as a JSON string literal. It also escapes <, > and & so
// the output is safe to place inside HTML.
func jsonStr(s string) string {
	const hex = "0123456789abcdef"
	var b strings.Builder
	b.WriteByte('"')
	for _, r := range s {
		switch {
		case r == '"':
			b.WriteString(`\"`)
		case r == '\\':
			b.WriteString(`\\`)
		case r == '\n':
			b.WriteString(`\n`)
		case r == '\t':
			b.WriteString(`\t`)
		case r < 0x20 || r == '<' || r == '>' || r == '&' || r == 0x2028 || r == 0x2029:
			b.WriteString(`\u`)
			b.WriteByte(hex[(r>>12)&0xf])
			b.WriteByte(hex[(r>>8)&0xf])
			b.WriteByte(hex[(r>>4)&0xf])
			b.WriteByte(hex[r&0xf])
		default:
			b.WriteRune(r)
		}
	}
	b.WriteByte('"')
	return b.String()
}

// mdText escapes characters that would turn user text into markdown links,
// images, headings or HTML.
func mdText(s string) string {
	r := strings.NewReplacer(
		`\`, `\\`, "[", `\[`, "]", `\]`, "(", `\(`, ")", `\)`,
		"<", "&lt;", ">", "&gt;", "`", "\\`", "*", `\*`, "_", `\_`, "#", `\#`, "!", `\!`,
		"|", `\|`,
	)
	return r.Replace(s)
}

// gnot formats an amount in ugnot as GNOT, e.g. 1500000 -> "1.5 GNOT".
func gnot(u int64) string {
	whole := u / 1_000_000
	frac := u % 1_000_000
	s := strconv.FormatInt(whole, 10)
	if frac != 0 {
		f := strconv.FormatInt(frac+1_000_000, 10)[1:]
		s += "." + strings.TrimRight(f, "0")
	}
	return s + " GNOT"
}

render.gno

package gild

import (
	"strconv"
	"strings"
	"time"

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

// AppURL is the web app. Every gnoweb page links to it, but nothing here
// depends on it: the realm works the same from gnokey or gnoweb.
const AppURL = "https://gild.sithunyein.com/app"

// Render serves the gnoweb pages:
//
//	""             the board: totals, open tasks, rules
//	"task/<id>"    one task
//	"u/<address>"  someone's work record
func Render(path string) string {
	switch {
	case path == "":
		return renderHome()
	case strings.HasPrefix(path, "task/"):
		id, err := strconv.ParseInt(strings.TrimPrefix(path, "task/"), 10, 64)
		if err != nil || id < 1 {
			return notFound()
		}
		v := tasks.Get(seqid.ID(id).Binary())
		if v == nil {
			return notFound()
		}
		return renderTask(v.(*Task))
	case strings.HasPrefix(path, "u/"):
		addr := address(strings.TrimPrefix(path, "u/"))
		if !addr.IsValid() {
			return notFound()
		}
		return renderProfile(addr)
	}
	return notFound()
}

func notFound() string {
	return "# Not found\n\n[Back to the board](" + webPath + ")\n"
}

func renderHome() string {
	var b strings.Builder
	b.WriteString("# Gild\n\n")
	b.WriteString("**Post work. Pay on proof.** The reward is locked in this realm when a task is posted, ")
	b.WriteString("and paid to the doer when the poster approves. Every payout adds to a public work record ")
	b.WriteString("that other realms can read.\n\n")
	b.WriteString("[Open the app](" + AppURL + ") · [Builders](" + siblingPath("builders/v2") + ") · ")
	b.WriteString("[Source](" + webPath + "$source) · [Earlier board (v0)](" + siblingPath("gild/v0") + ")\n\n")

	b.WriteString("| Open tasks | Locked | Paid to doers | Tasks completed |\n|---|---|---|---|\n")
	b.WriteString("| " + strconv.Itoa(openTasks.Size()) + " | " + gnot(lockedTotal) + " | " + gnot(paidTotal) + " | " + strconv.Itoa(book.Total()) + " |\n\n")

	b.WriteString("## Open tasks\n\n")
	if openTasks.Size() == 0 {
		b.WriteString("No open tasks right now. [Post one in the app](" + AppURL + "#/post).\n\n")
	} else {
		b.WriteString("| Task | Reward | Who can take it | Due |\n|---|---|---|---|\n")
		openTasks.ReverseIterateByOffset(0, 30, func(_ string, v any) bool {
			t := v.(*Task)
			b.WriteString("| [" + cell(t.Title) + "](" + webPath + ":task/" + idStr(t.ID) + ") | **" + gnot(t.Reward) + "** | " + whoCanTake(t) + " | " + t.Deadline.UTC().Format("Jan 2") + " |\n")
			return false
		})
		b.WriteString("\n")
	}

	b.WriteString("## How a task works\n\n")
	b.WriteString("1. **Post and lock.** The poster sends the reward with `Post`. It stays in this realm.\n")
	b.WriteString("2. **Take.** One doer takes it. Posters can require past paid work, or offer the task to one person.\n")
	b.WriteString("3. **Send work.** The doer sends a link with `Submit`. The poster can ask for changes once.\n")
	b.WriteString("4. **Get paid.** `Approve` pays the doer. If the poster is silent for 7 days, the doer can `ClaimAfterSilence`.\n\n")
	b.WriteString("Nobody took it, or no work by the deadline? The poster can `Cancel` for a full refund. ")
	b.WriteString("Once work is sent, the poster can no longer cancel. There is no admin key and no fee.\n\n")

	b.WriteString("## Use the work record in your realm\n\n")
	b.WriteString("```go\nimport gild \"gno.land" + webPath + "\"\n\n")
	b.WriteString("func Join(cur realm) {\n\tif !gild.HasCompleted(cur.Previous().Address(), 1) {\n\t\tpanic(\"finish a paid Gild task first\")\n\t}\n}\n```\n\n")
	b.WriteString("`Completed`, `Earned` and `HasCompleted` count paid work from both Gild boards. ")
	b.WriteString("[Builders](" + siblingPath("builders/v2") + ") uses them to accept only people with proven work.\n")
	return b.String()
}

func renderTask(t *Task) string {
	var b strings.Builder
	b.WriteString("# " + mdText(t.Title) + "\n\n")
	b.WriteString("[← Board](" + webPath + ") · [Open in the app](" + AppURL + "#/task/" + idStr(t.ID) + ")\n\n")
	b.WriteString("| | |\n|---|---|\n")
	b.WriteString("| Reward | **" + gnot(t.Reward) + "** |\n")
	b.WriteString("| Status | " + statusText(t.Status) + " |\n")
	b.WriteString("| Category | " + t.Category + " |\n")
	b.WriteString("| Who can take it | " + whoCanTake(t) + " |\n")
	b.WriteString("| Poster | " + who(t.Poster) + " |\n")
	if t.Doer != "" {
		b.WriteString("| Doer | " + who(t.Doer) + " |\n")
	}
	b.WriteString("| Deadline | " + t.Deadline.UTC().Format("Jan 2, 2006 15:04 MST") + " |\n")
	if t.Status == StatusInReview {
		b.WriteString("| Auto-pay from | " + t.SubmittedAt.Add(ReviewWindow).UTC().Format("Jan 2, 2006 15:04 MST") + " |\n")
	}
	if t.Status == StatusPaid {
		b.WriteString("| Paid by | " + t.PaidBy + " |\n")
	}
	b.WriteString("\n")
	if t.Details != "" {
		b.WriteString("## The task\n\n" + mdText(t.Details) + "\n\n")
	}
	if t.Done != "" {
		b.WriteString("## Done looks like\n\n" + mdText(t.Done) + "\n\n")
	}
	if t.WorkURL != "" {
		b.WriteString("## Work\n\n" + mdText(t.WorkURL) + "\n\n")
	}
	if t.ChangesNote != "" {
		b.WriteString("## Changes asked\n\n" + mdText(t.ChangesNote) + "\n\n")
	}
	if fn := nextStep(t); fn != "" {
		b.WriteString("## Next step\n\n" + fn + "\n")
	}
	return b.String()
}

// nextStep tells a gnoweb reader which function moves the task forward.
func nextStep(t *Task) string {
	act := func(fn string) string { return "[" + fn + "](" + webPath + "$help&func=" + fn + ")" }
	switch t.Status {
	case StatusOpen:
		if time.Now().Before(t.Deadline) {
			return "Call " + act("Take") + " with id " + idStr(t.ID) + ", or [take it in the app](" + AppURL + "#/task/" + idStr(t.ID) + ")."
		}
		return "The deadline passed. The poster can " + act("Cancel") + " for a refund."
	case StatusTaken:
		return "The doer sends work with " + act("Submit") + "."
	case StatusInReview:
		return "The poster can " + act("Approve") + " or " + act("RequestChanges") + ". After 7 days of silence the doer can " + act("ClaimAfterSilence") + "."
	}
	return ""
}

func renderProfile(addr address) string {
	p := book.Profile(addr)
	var b strings.Builder
	b.WriteString("# Work record\n\n`" + addr.String() + "`\n\n")
	b.WriteString("[← Board](" + webPath + ") · [Profile in the app](" + AppURL + "#/u/" + addr.String() + ")\n\n")
	b.WriteString("| Tasks done | Earned | Paid out (v1) |\n|---|---|---|\n")
	b.WriteString("| " + strconv.Itoa(Completed(addr)) + " | " + gnot(Earned(addr)) + " | " + strconv.Itoa(p.Posted) + " |\n\n")
	b.WriteString("Tasks done and earned include work on the [earlier board](" + siblingPath("gild/v0") + ":u/" + addr.String() + ").\n\n")
	recent := p.Recent()
	if len(recent) == 0 {
		return b.String()
	}
	b.WriteString("## Recent work on this board\n\n| Task | Paid | When |\n|---|---|---|\n")
	for _, r := range recent {
		b.WriteString("| [" + cell(r.Title) + "](" + webPath + ":task/" + r.TaskID + ") | " + gnot(r.Amount) + " | " + r.At.UTC().Format("Jan 2, 2006") + " |\n")
	}
	return b.String()
}

func whoCanTake(t *Task) string {
	switch {
	case t.Invite != "":
		return "Offered to " + who(t.Invite)
	case t.MinDone > 0:
		return strconv.Itoa(t.MinDone) + "+ paid tasks"
	}
	return "Anyone"
}

func statusText(s Status) string {
	switch s {
	case StatusOpen:
		return "Open"
	case StatusTaken:
		return "In progress"
	case StatusInReview:
		return "In review"
	case StatusPaid:
		return "Paid"
	case StatusRefunded:
		return "Refunded"
	}
	return "Unknown"
}

// who links an address to its work record, shortened to fit a table.
func who(a address) string {
	s := a.String()
	short := s
	if len(s) > 12 {
		short = s[:6] + "…" + s[len(s)-4:]
	}
	return "[" + short + "](" + webPath + ":u/" + s + ")"
}

// cell is mdText for a table cell: one line, no pipes.
func cell(s string) string {
	return mdText(strings.Join(strings.Fields(s), " "))
}

// siblingPath returns another realm in this namespace, e.g. "builders/v2".
func siblingPath(rel string) string {
	p := webPath
	if i := strings.Index(p, "/gild/"); i >= 0 {
		p = p[:i]
	}
	return p + "/" + rel
}

text.gno

package gild

import "strings"

func trimSpace(s string) string { return strings.TrimSpace(s) }

// checkText panics with msg unless s has between min and max characters and
// contains no control characters other than newline and tab.
func checkText(s string, min, max int, msg string) {
	n := 0
	for _, r := range s {
		if r < 0x20 && r != '\n' && r != '\t' {
			panic(msg)
		}
		if r == 0x7f {
			panic(msg)
		}
		n++
	}
	if n < min || n > max {
		panic(msg)
	}
}

// isWorkURL accepts https links with no spaces or control characters.
func isWorkURL(s string) bool {
	if len(s) > MaxURL || !strings.HasPrefix(s, "https://") || len(s) <= len("https://") {
		return false
	}
	for _, r := range s {
		if r <= 0x20 || r == 0x7f || r == '"' || r == '<' || r == '>' || r == '`' {
			return false
		}
	}
	return true
}