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

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

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

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

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

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.
func Post(cur realm, title, details, done, category string, deadline int64) 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)
	}

	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,
	}
	key := t.ID.Binary()
	tasks.Set(key, t)
	openTasks.Set(key, t)
	index(&byPoster, t.Poster, 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.
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)
	}
	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.
// Other realms can call it to gate features by proven work.
func Completed(addr address) int { return book.Completed(addr) }

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

// HasCompleted reports whether addr finished at least n tasks on Gild.
func HasCompleted(addr address, n int) bool { return book.HasCompleted(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/v0"
gno = "0.9"

[addpkg]
  creator = "g1jw2yrfqnd4fp90qadw88pnjgpden4vgagjvpe6"
  height = 1350662
  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)
}

// StatsJSON returns board totals.
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.
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(p.Completed))
	b.WriteString(`,"earned":`)
	b.WriteString(strconv.FormatInt(p.Earned, 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.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()
}

// ---- gnoweb pages ----

// Render serves "" (open tasks), "task/<id>" and "u/<address>".
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 "# Not found"
		}
		v := tasks.Get(seqid.ID(id).Binary())
		if v == nil {
			return "# Not found"
		}
		return renderTask(v.(*Task))
	case strings.HasPrefix(path, "u/"):
		addr := address(strings.TrimPrefix(path, "u/"))
		if !addr.IsValid() {
			return "# Not found"
		}
		return renderProfile(addr)
	}
	return "# Not found"
}

func renderHome() string {
	var b strings.Builder
	b.WriteString("# Gild\n\nPost work. Pay on proof.\n\n")
	b.WriteString("**" + strconv.Itoa(openTasks.Size()) + "** open · **" + gnot(lockedTotal) + "** locked · **" + gnot(paidTotal) + "** paid\n\n")
	b.WriteString("## Open tasks\n\n")
	if openTasks.Size() == 0 {
		b.WriteString("No open tasks yet.\n")
		return b.String()
	}
	openTasks.ReverseIterateByOffset(0, 20, func(_ string, v any) bool {
		t := v.(*Task)
		b.WriteString("- [" + mdText(t.Title) + "](" + webPath + ":task/" + idStr(t.ID) + ") · **" + gnot(t.Reward) + "** · " + t.Category + " · due " + t.Deadline.UTC().Format("Jan 2, 2006") + "\n")
		return false
	})
	return b.String()
}

func renderTask(t *Task) string {
	var b strings.Builder
	b.WriteString("# " + mdText(t.Title) + "\n\n")
	b.WriteString("**" + gnot(t.Reward) + "** · " + t.Status.String() + " · " + t.Category + "\n\n")
	b.WriteString("Posted by [" + t.Poster.String() + "](" + webPath + ":u/" + t.Poster.String() + ")")
	if t.Doer != "" {
		b.WriteString(" · taken by [" + t.Doer.String() + "](" + webPath + ":u/" + t.Doer.String() + ")")
	}
	b.WriteString("\n\nDeadline: " + t.Deadline.UTC().Format("Jan 2, 2006 15:04 MST") + "\n\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.Status == StatusInReview {
		b.WriteString("The doer can claim the reward after " + t.SubmittedAt.Add(ReviewWindow).UTC().Format("Jan 2, 2006 15:04 MST") + " if the poster does not answer.\n")
	}
	return b.String()
}

func renderProfile(addr address) string {
	p := book.Profile(addr)
	var b strings.Builder
	b.WriteString("# " + addr.String() + "\n\n")
	b.WriteString("**" + strconv.Itoa(p.Completed) + "** tasks done · **" + gnot(p.Earned) + "** earned · **" + strconv.Itoa(p.Posted) + "** paid out\n\n")
	recent := p.Recent()
	if len(recent) == 0 {
		b.WriteString("No finished work yet.\n")
		return b.String()
	}
	b.WriteString("## Recent work\n\n")
	for _, r := range recent {
		b.WriteString("- [" + mdText(r.Title) + "](" + webPath + ":task/" + r.TaskID + ") · " + gnot(r.Amount) + " · " + r.At.UTC().Format("Jan 2, 2006") + "\n")
	}
	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"
}

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
}