Playground
escape.gno
package questmaster
import (
"strings"
"gno.land/p/nt/markdown/sanitize/v0"
)
// Escaping. Every piece of user text that reaches a page (titles, details,
// reject reasons, work links) goes through one of the helpers below, which
// wrap p/nt/markdown/sanitize/v0 (the sanitizer that gnoweb's own markdown
// tests are written against) plus the gnoweb-specific steps described below.
//
// Nothing a user types can produce a heading, list, table cell break, new
// table row, link, image, HTML tag, mention link or math:
// - esc: single-line slots (headings, link text). Folds line breaks to
// spaces and backslash-escapes Markdown punctuation and `<`, `&`.
// - escCell: table cells. As esc, plus `|` and tabs.
// - escBlock: multi-line text (details, reasons). A blockquote that keeps
// line breaks; every line is escaped like a table cell.
// - linkOrText: the work link. Clickable only when it passes sanitize.URL
// (http/https only; ( ) < > ` | and other unsafe bytes percent-encoded)
// and nothing unsafe is left in the target; otherwise plain text. Its
// visible text is always the escaped URL itself, never user-chosen text.
//
// gnoweb adds two extensions the sanitizer does not know about, so every
// helper also runs gnowebSafe on its output:
// - "@name" and " g1…" (an address after a space) become profile links.
// "@" becomes "\@" (a Markdown escape that renders as "@"), the space
// before "g1" becomes the entity " ", and a "g1" at the very start of
// the text becomes "g1", because the realm itself often puts a space
// right before user text ("# Quest 1: ", "| ", "> ").
// - "$…$" and "$$…$$" become math. Every "$" becomes "\$".
// Each renders as the plain character in gnoweb; checked in the real renderer
// by scripts/local-flow.sh.
func esc(s string) string { return gnowebSafe(sanitize.InlineText(s)) }
func escCell(s string) string { return gnowebSafe(sanitize.TableCell(s)) }
// escBlock shows multi-line user text as a blockquote that keeps its line
// breaks but nothing else: every line is escaped like a table cell (so no
// link, image, HTML, `|` table or line-leading marker survives), a leading
// "=" is escaped (no setext heading), and lines end with a hard break.
func escBlock(s string) string {
s = sanitize.NormalizeBreaks(sanitize.StripBidiAndZeroWidth(s))
s = strings.ReplaceAll(s, "\u2028", "\n")
s = strings.ReplaceAll(s, "\u2029", "\n")
s = strings.ReplaceAll(s, "\u0085", "\n")
var b strings.Builder
blank := true // suppress leading and repeated blank lines
for _, line := range strings.Split(s, "\n") {
line = strings.TrimSpace(line)
if line == "" {
if !blank {
b.WriteString(">\n")
}
blank = true
continue
}
line = escCell(line)
if strings.HasPrefix(line, "=") {
line = "\\" + line
}
b.WriteString("> " + line + " \n")
blank = false
}
out := strings.TrimSuffix(b.String(), ">\n")
if out == "" {
return ""
}
return "\n" + out + "\n"
}
// gnowebSafe applies the gnoweb-specific steps described above.
func gnowebSafe(s string) string {
s = strings.ReplaceAll(s, "@", `\@`)
s = strings.ReplaceAll(s, "$", `\$`)
s = strings.ReplaceAll(s, " g1", " g1")
if strings.HasPrefix(s, "g1") {
s = "g1" + s[2:]
}
return s
}
// linkOrText shows a work link. The escrow already guarantees it starts
// with https:// and has no spaces or control characters.
func linkOrText(link string) string {
text := escCell(link)
u := sanitize.URL(link)
if u == "" || strings.ContainsAny(u, "()<>[]| \"'`") {
return text
}
return "[" + text + "](" + u + ")"
}
gnomod.toml
module = "gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/questmaster" gno = "0.9" [addpkg] creator = "g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8" height = 1347486 max_deposit = "30000000ugnot"
questmaster.gno
// Package questmaster is a GNOT bounty board. A poster locks GNOT on a quest,
// a builder takes it and submits a link to the work, and the poster approves
// (paying the builder) or rejects (reopening the quest). If the poster stays
// silent past the review window (about 7 days), the builder can claim the
// payout. A poster can cancel an open quest for a refund, or close a claimed
// or submitted one: the builder keeps their turn, and if it ends without
// approval the reward goes back to the poster.
//
// The rules live in the pure package p/escrow. This realm stores quests,
// holds the coins and moves them only as an escrow move tells it to.
//
// Callers (v1): every state-changing function accepts only a direct user call
// (`gnokey maketx call`, i.e. cur.Previous().IsUserCall()). Calls from other
// realms and from `maketx run` scripts are refused. This is what makes the
// unsafe.OriginSend() checks sound: for a direct user call, the coins sent with
// the call are guaranteed to have landed in this realm. Realm or DAO callers
// may be supported in a later version.
//
// There is no admin, owner, pause, upgrade or sweep function. Nobody can move
// escrowed coins except through the quest moves below.
//
// Coins sent straight to the realm address with a bank send (not through
// PostQuest) are not tracked by any quest and cannot be moved by anyone, so
// they are lost. On chain the guarantee is therefore: realm balance >= the
// locked total, with equality when nobody sends coins outside PostQuest. The
// pages and GetTotals use only the tracked numbers, never the balance.
//
// Nothing here hands out a pointer to stored state: read functions return
// plain values (QuestView, Totals, []uint64, strings).
package questmaster
import (
"chain"
"chain/banker"
"chain/runtime"
"chain/runtime/unsafe"
"strconv"
"gno.land/p/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/escrow"
"gno.land/p/nt/avl/v0"
)
const (
// Denom is the only coin a quest reward can be paid in.
Denom = "ugnot"
// MinReward is the smallest reward a quest can lock: 1 GNOT.
MinReward int64 = 1_000_000
// MaxPageSize caps how many ids one list call returns.
MaxPageSize = 50
)
// Panic messages for the realm's own checks. Escrow rule violations panic
// with the escrow error's text (prefix "escrow: ").
const (
ErrNotUserCall = "questmaster: only direct user calls (gnokey maketx call) are accepted"
ErrNoCoins = "questmaster: send the reward in ugnot with the call"
ErrSeveralCoins = "questmaster: send exactly one coin (ugnot)"
ErrWrongDenom = "questmaster: the reward must be in ugnot"
ErrRewardTooLow = "questmaster: the reward is below the minimum of 1 GNOT (1000000ugnot)"
ErrCoinsNotTaken = "questmaster: this function does not take coins; send none"
ErrUnknownQuest = "questmaster: unknown quest id"
)
var (
quests avl.Tree // questKey(id) -> *escrow.Quest
byPoster avl.Tree // poster address -> *avl.Tree of questKey(id) -> true
byBuilder avl.Tree // builder address -> *avl.Tree of questKey(id) -> true
openIDs avl.Tree // questKey(id) -> true, quests in state Open
paidIDs avl.Tree // questKey(id) -> true, quests in state Paid
lastID uint64
totalPosted int64 // ugnot ever locked by PostQuest
totalLocked int64 // ugnot held for quests that are Open, Claimed or Submitted
totalPaid int64 // ugnot paid to builders
totalRefunded int64 // ugnot refunded to posters
)
// ---------------------------------------------------------------------------
// State-changing functions
// PostQuest creates a quest. Send the reward with the call as exactly one coin
// of ugnot, at least MinReward. workBlocks is the builder's work window in
// blocks (escrow.MinWorkBlocks to escrow.MaxWorkBlocks). Returns the new id.
func PostQuest(cur realm, title, details string, workBlocks int64) uint64 {
poster := requireUserCall(cur)
reward := requireReward()
id := lastID + 1
q, err := escrow.NewQuest(id, poster, title, details, reward, workBlocks, runtime.ChainHeight())
if err != nil {
panic(err.Error())
}
lastID = id
key := questKey(id)
quests.Set(key, q)
addToIndex(&byPoster, poster, key)
openIDs.Set(key, true)
totalPosted += reward
totalLocked += reward
chain.Emit("QuestPosted", "id", idStr(id), "actor", poster.String(), "amount", amountStr(reward))
return id
}
// ClaimQuest takes an Open quest. The poster cannot claim their own quest.
func ClaimQuest(cur realm, id uint64) {
actor := requireUserCall(cur)
requireNoCoins()
q := mustGet(id)
check(q.Claim(actor, runtime.ChainHeight()))
key := questKey(id)
openIDs.Remove(key)
addToIndex(&byBuilder, actor, key)
chain.Emit("QuestClaimed", "id", idStr(id), "actor", actor.String())
}
// UnclaimQuest lets the builder give a Claimed quest back. It opens again, or,
// if the poster closed it, ends with a refund to the poster.
func UnclaimQuest(cur realm, id uint64) {
actor := requireUserCall(cur)
requireNoCoins()
q := mustGet(id)
p, err := q.Unclaim(actor, runtime.ChainHeight())
check(err)
chain.Emit("QuestUnclaimed", "id", idStr(id), "actor", actor.String())
endTurn(id, p, actor, "unclaimed", cur)
}
// ReleaseQuest ends the builder's turn on a Claimed quest whose work deadline
// has passed. Anyone may call it. The quest opens again, or, if the poster
// closed it, ends with a refund to the poster.
func ReleaseQuest(cur realm, id uint64) {
actor := requireUserCall(cur)
requireNoCoins()
q := mustGet(id)
p, err := q.Release(actor, runtime.ChainHeight())
check(err)
chain.Emit("QuestReleased", "id", idStr(id), "actor", actor.String())
endTurn(id, p, actor, "released", cur)
}
// SubmitWork sends the link to the work (must start with https://). Only the
// builder, up to and including the work deadline block.
func SubmitWork(cur realm, id uint64, link string) {
actor := requireUserCall(cur)
requireNoCoins()
q := mustGet(id)
check(q.Submit(actor, link, runtime.ChainHeight()))
chain.Emit("WorkSubmitted", "id", idStr(id), "actor", actor.String())
}
// ApproveWork accepts the submitted work and pays the reward to the builder.
// Only the poster.
func ApproveWork(cur realm, id uint64) {
actor := requireUserCall(cur)
requireNoCoins()
q := mustGet(id)
p, err := q.Approve(actor, runtime.ChainHeight())
check(err)
settlePaid(id, p)
chain.Emit("QuestPaid", "id", idStr(id), "actor", actor.String(), "to", p.To.String(), "amount", amountStr(p.Amount), "how", "approved")
send(p, cur)
}
// RejectWork refuses the submitted work with a reason. Its public reject count
// goes up. The quest opens again, or, if the poster closed it, ends with a
// refund to the poster. Only the poster, up to and including the review
// deadline block.
func RejectWork(cur realm, id uint64, reason string) {
actor := requireUserCall(cur)
requireNoCoins()
q := mustGet(id)
builder := q.Builder()
p, err := q.Reject(actor, reason, runtime.ChainHeight())
check(err)
chain.Emit("WorkRejected", "id", idStr(id), "actor", actor.String(), "builder", builder.String())
endTurn(id, p, actor, "rejected", cur)
}
// CancelQuest is the poster's way out. Only the poster.
// - Open quest: it ends at once and the reward is refunded.
// - Claimed or Submitted quest: it is marked as closing and no coins move.
// The builder keeps their turn (submit, approval, timeout payout); when
// the turn ends without approval (unclaim, release after the work
// deadline, or reject), the quest ends and the reward goes back to the
// poster instead of the quest opening again.
func CancelQuest(cur realm, id uint64) {
actor := requireUserCall(cur)
requireNoCoins()
q := mustGet(id)
p, err := q.Cancel(actor, runtime.ChainHeight())
check(err)
if !p.Due() {
chain.Emit("QuestClosing", "id", idStr(id), "actor", actor.String())
return
}
openIDs.Remove(questKey(id))
settleRefund(id, p, actor, "open", cur)
}
// endTurn finishes Unclaim, Release and Reject: the quest opens again, or a
// closing quest ends with the refund p.
func endTurn(id uint64, p escrow.Payout, actor address, how string, rlm realm) {
if !p.Due() {
openIDs.Set(questKey(id), true)
return
}
settleRefund(id, p, actor, how, rlm)
}
// settleRefund updates totals, emits QuestCancelled and sends the refund
// last. The quest is already Cancelled (final) when it is called.
func settleRefund(id uint64, p escrow.Payout, actor address, how string, rlm realm) {
if p.Kind != escrow.RefundPoster {
panic("questmaster: internal error: unexpected payout kind")
}
totalLocked -= p.Amount
totalRefunded += p.Amount
chain.Emit("QuestCancelled", "id", idStr(id), "actor", actor.String(), "to", p.To.String(), "amount", amountStr(p.Amount), "how", how)
send(p, rlm)
}
// ClaimPayout pays the builder when the poster has not answered within the
// review window. Only the builder, from the block after the review deadline.
func ClaimPayout(cur realm, id uint64) {
actor := requireUserCall(cur)
requireNoCoins()
q := mustGet(id)
p, err := q.ClaimPayout(actor, runtime.ChainHeight())
check(err)
settlePaid(id, p)
chain.Emit("QuestPaid", "id", idStr(id), "actor", actor.String(), "to", p.To.String(), "amount", amountStr(p.Amount), "how", "timeout")
send(p, cur)
}
// ---------------------------------------------------------------------------
// Read functions. All return plain values.
// QuestView is a read-only copy of one quest at the current block.
type QuestView struct {
ID uint64
Poster address
Title string
Details string
Reward int64 // ugnot
State escrow.State
Builder address
WorkLink string
WorkBlocks int64
CreatedAt int64
ClaimedAt int64
SubmittedAt int64
WorkDeadline int64 // last block to submit; 0 unless Claimed or Submitted
ReviewDeadline int64 // last block to reject; 0 unless Submitted
RejectCount int
LastRejectReason string
Closing bool // the poster closed it; the reward returns when the builder's turn ends without approval
CanRelease bool // ReleaseQuest would succeed now
CanClaimPayout bool // the builder could call ClaimPayout now
}
// GetQuest returns a copy of quest id. It panics on an unknown id.
func GetQuest(id uint64) QuestView {
q := mustGet(id)
h := runtime.ChainHeight()
return QuestView{
ID: q.ID(),
Poster: q.Poster(),
Title: q.Title(),
Details: q.Details(),
Reward: q.Reward(),
State: q.State(),
Builder: q.Builder(),
WorkLink: q.WorkLink(),
WorkBlocks: q.WorkBlocks(),
CreatedAt: q.CreatedAt(),
ClaimedAt: q.ClaimedAt(),
SubmittedAt: q.SubmittedAt(),
WorkDeadline: q.WorkDeadline(),
ReviewDeadline: q.ReviewDeadline(),
RejectCount: q.RejectCount(),
LastRejectReason: q.LastRejectReason(),
Closing: q.Closing(),
CanRelease: q.CanRelease(h),
CanClaimPayout: q.CanClaimPayout(h),
}
}
// Totals are the board-wide running sums, in ugnot.
type Totals struct {
Quests uint64 // quests ever posted
OpenQuests int // quests in state Open
Posted int64 // ugnot ever locked
Locked int64 // ugnot held now for Open, Claimed and Submitted quests
Paid int64 // ugnot paid to builders
Refunded int64 // ugnot refunded to posters
PaidQuests int // quests in state Paid
}
// GetTotals returns the running totals. Posted == Locked + Paid + Refunded.
func GetTotals() Totals {
return Totals{
Quests: lastID,
OpenQuests: openIDs.Size(),
Posted: totalPosted,
Locked: totalLocked,
Paid: totalPaid,
Refunded: totalRefunded,
PaidQuests: paidIDs.Size(),
}
}
// OpenQuestIDs lists ids of Open quests, newest first. offset skips that many;
// at most MaxPageSize ids are returned whatever limit is.
func OpenQuestIDs(offset, limit int) []uint64 {
return page(&openIDs, offset, limit)
}
// PaidQuestIDs lists ids of Paid quests, newest first (by quest id).
func PaidQuestIDs(offset, limit int) []uint64 {
return page(&paidIDs, offset, limit)
}
// AllQuestIDs lists ids of all quests, newest first.
func AllQuestIDs(offset, limit int) []uint64 {
return page(&quests, offset, limit)
}
// QuestIDsByPoster lists ids of quests posted by addr, newest first.
func QuestIDsByPoster(addr address, offset, limit int) []uint64 {
return indexPage(&byPoster, addr, offset, limit)
}
// QuestIDsByBuilder lists ids of quests addr has ever claimed, newest first.
// It is a history: a quest stays listed after the builder unclaims it, is
// released or is rejected, even if someone else builds it later. Use
// GetQuest(id).Builder for the current builder.
func QuestIDsByBuilder(addr address, offset, limit int) []uint64 {
return indexPage(&byBuilder, addr, offset, limit)
}
// CountByPoster returns how many quests addr has posted.
func CountByPoster(addr address) int { return indexSize(&byPoster, addr) }
// CountByBuilder returns how many quests addr has ever claimed.
func CountByBuilder(addr address) int { return indexSize(&byBuilder, addr) }
// ---------------------------------------------------------------------------
// Internal helpers
// requireUserCall refuses anything but a direct user call and returns the
// caller's address. See the package doc for why.
func requireUserCall(cur realm) address {
prev := cur.Previous()
if !prev.IsUserCall() {
panic(ErrNotUserCall)
}
return prev.Address()
}
// requireReward checks the coins sent with PostQuest (rules 1 and 2) and
// returns the amount. Valid only together with requireUserCall.
func requireReward() int64 {
sent := unsafe.OriginSend()
if len(sent) == 0 {
panic(ErrNoCoins)
}
if len(sent) > 1 {
panic(ErrSeveralCoins)
}
if sent[0].Denom != Denom {
panic(ErrWrongDenom)
}
if sent[0].Amount < MinReward {
panic(ErrRewardTooLow)
}
return sent[0].Amount
}
// requireNoCoins refuses coins sent to a function that does not take any
// (rule 3), so nothing gets stuck in the realm.
func requireNoCoins() {
if len(unsafe.OriginSend()) != 0 {
panic(ErrCoinsNotTaken)
}
}
func mustGet(id uint64) *escrow.Quest {
v := quests.Get(questKey(id))
if v == nil {
panic(ErrUnknownQuest)
}
return v.(*escrow.Quest)
}
func check(err error) {
if err != nil {
panic(err.Error())
}
}
// settlePaid updates storage and totals for a PayBuilder payout.
func settlePaid(id uint64, p escrow.Payout) {
if p.Kind != escrow.PayBuilder {
panic("questmaster: internal error: unexpected payout kind")
}
paidIDs.Set(questKey(id), true)
totalLocked -= p.Amount
totalPaid += p.Amount
}
// send moves exactly p.Amount ugnot from this realm to p.To. It is called last,
// after every state change (rule 4), and never sends the realm's balance
// (rule 5).
func send(p escrow.Payout, rlm realm) {
if p.Amount <= 0 || !p.To.IsValid() {
panic("questmaster: internal error: invalid payout")
}
b := banker.NewBanker(banker.BankerTypeRealmSend, rlm)
b.SendCoins(rlm.Address(), p.To, chain.Coins{{Denom: Denom, Amount: p.Amount}})
}
// questKey zero-pads id so the avl order is numeric order.
func questKey(id uint64) string {
s := strconv.FormatUint(id, 10)
for len(s) < 20 {
s = "0" + s
}
return s
}
func idStr(id uint64) string { return strconv.FormatUint(id, 10) }
func amountStr(ugnot int64) string { return strconv.FormatInt(ugnot, 10) }
func addToIndex(idx *avl.Tree, addr address, key string) {
var ids *avl.Tree
if v := idx.Get(addr.String()); v != nil {
ids = v.(*avl.Tree)
} else {
ids = avl.NewTree()
idx.Set(addr.String(), ids)
}
ids.Set(key, true)
}
func indexSize(idx *avl.Tree, addr address) int {
v := idx.Get(addr.String())
if v == nil {
return 0
}
return v.(*avl.Tree).Size()
}
func indexPage(idx *avl.Tree, addr address, offset, limit int) []uint64 {
v := idx.Get(addr.String())
if v == nil {
return []uint64{}
}
return page(v.(*avl.Tree), offset, limit)
}
// page returns up to min(limit, MaxPageSize) ids from t, newest first.
func page(t *avl.Tree, offset, limit int) []uint64 {
if offset < 0 {
offset = 0
}
if limit <= 0 || limit > MaxPageSize {
limit = MaxPageSize
}
ids := []uint64{}
t.ReverseIterateByOffset(offset, limit, func(key string, _ any) bool {
id, err := strconv.ParseUint(key, 10, 64)
if err != nil {
panic("questmaster: internal error: bad key")
}
ids = append(ids, id)
return false
})
return ids
}
questmaster_test.gno
package questmaster
import (
"chain"
"chain/banker"
"chain/runtime"
"strings"
"testing"
"gno.land/p/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/escrow"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// Test notes
//
// Coins: in `gno test`, testing.SetOriginSend only sets what
// unsafe.OriginSend() reports; it does not move coins. On chain, a MsgCall
// with -send credits the realm before the call runs. post() below does the
// same by issuing the reward to the realm address just before PostQuest.
// Failing posts get no coins issued, matching a reverted transaction.
//
// Reverts: the test harness does NOT roll back realm state when a call
// panics (checked: a test-only crossing function that changed a variable and
// then panicked left the change in place). On chain the whole transaction
// reverts. So the tests below snapshot all quests, totals and the realm
// balance before every failing call and check they are identical after it.
// This passes because every check (caller, coins, escrow rule) runs before
// the first write.
var (
alice = testutils.TestAddress("qb_alice")
bob = testutils.TestAddress("qb_bob")
carol = testutils.TestAddress("qb_carol")
dave = testutils.TestAddress("qb_dave")
realmAddr = chain.PackageAddress("gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/questmaster")
)
const (
gnot = int64(1_000_000)
link = "https://github.com/example/repo/pull/1"
)
func ugnot(n int64) chain.Coins { return chain.Coins{{Denom: "ugnot", Amount: n}} }
func bal(addr address) int64 {
return banker.NewReadonlyBanker().GetCoin(addr, "ugnot")
}
// resetState gives each test an empty board. The test harness keeps realm
// variables between tests but resets bank balances, so every test starts
// from scratch to keep the balance invariants exact.
func resetState() {
quests = avl.Tree{}
byPoster = avl.Tree{}
byBuilder = avl.Tree{}
openIDs = avl.Tree{}
paidIDs = avl.Tree{}
lastID = 0
totalPosted, totalLocked, totalPaid, totalRefunded = 0, 0, 0, 0
}
// testing.SetRealm changes the realm of the frame that calls it, so it is
// called inline in each crossing function (test or helper) right before the
// cross(cur) call it is meant for, not from a shared helper.
// post posts a quest from u with reward ugnot, simulating the MsgCall deposit.
func post(cur realm, u address, reward int64, title string) uint64 {
return postD(cur, u, reward, title, "details")
}
// postD is post with chosen details.
func postD(cur realm, u address, reward int64, title, details string) uint64 {
testing.SetRealm(testing.NewUserRealm(u))
testing.SetOriginSend(nil)
testing.SetOriginSend(ugnot(reward))
testing.IssueCoins(realmAddr, ugnot(reward))
id := PostQuest(cross(cur), title, details, 2_000)
testing.SetOriginSend(nil)
return id
}
// claimed / submitted set up a quest from alice taken by bob.
func claimed(cur realm, reward int64) uint64 {
id := post(cur, alice, reward, "claimed quest")
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
ClaimQuest(cross(cur), id)
return id
}
func submitted(cur realm, reward int64) uint64 {
id := claimed(cur, reward)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
SubmitWork(cross(cur), id, link)
return id
}
// snapshot is everything a failed call must leave unchanged.
type snapshot struct {
totals Totals
quests []QuestView
realm int64
open string
paid string
}
func takeSnapshot() snapshot {
s := snapshot{totals: GetTotals(), realm: bal(realmAddr)}
for id := uint64(1); id <= s.totals.Quests; id++ {
s.quests = append(s.quests, GetQuest(id))
}
s.open = idsString(allPages(OpenQuestIDs))
s.paid = idsString(allPages(PaidQuestIDs))
return s
}
func sameSnapshot(t *testing.T, a, b snapshot, what string) {
t.Helper()
if a.totals != b.totals {
t.Fatalf("%s: totals changed: %v -> %v", what, a.totals, b.totals)
}
if a.realm != b.realm {
t.Fatalf("%s: realm balance changed: %d -> %d", what, a.realm, b.realm)
}
if len(a.quests) != len(b.quests) {
t.Fatalf("%s: quest count changed", what)
}
for i := range a.quests {
if a.quests[i] != b.quests[i] {
t.Fatalf("%s: quest %d changed", what, i+1)
}
}
if a.open != b.open || a.paid != b.paid {
t.Fatalf("%s: open/paid lists changed", what)
}
}
// fails asserts fn aborts with a message containing substr and changes nothing.
func fails(t *testing.T, rlm realm, substr string, fn func(), what string) {
t.Helper()
before := takeSnapshot()
uassert.AbortsContains(t, rlm, substr, fn, what)
sameSnapshot(t, before, takeSnapshot(), what)
}
func allPages(list func(offset, limit int) []uint64) []uint64 {
var out []uint64
for off := 0; ; off += MaxPageSize {
p := list(off, MaxPageSize)
out = append(out, p...)
if len(p) < MaxPageSize {
return out
}
}
}
func idsString(ids []uint64) string {
var sb strings.Builder
for _, id := range ids {
sb.WriteString(idStr(id))
sb.WriteString(",")
}
return sb.String()
}
// checkInvariants: rule 12 and the totals identities.
func checkInvariants(t *testing.T, what string) {
t.Helper()
tot := GetTotals()
var held int64
open, paid := 0, 0
for id := uint64(1); id <= tot.Quests; id++ {
q := GetQuest(id)
if !q.State.IsFinal() {
held += q.Reward
}
if q.State == escrow.Open {
open++
}
if q.State == escrow.Paid {
paid++
}
}
if b := bal(realmAddr); b != held || held != tot.Locked {
t.Fatalf("%s: realm balance %d, sum of held rewards %d, locked total %d", what, b, held, tot.Locked)
}
if tot.Posted != tot.Locked+tot.Paid+tot.Refunded {
t.Fatalf("%s: posted %d != locked %d + paid %d + refunded %d", what, tot.Posted, tot.Locked, tot.Paid, tot.Refunded)
}
if tot.OpenQuests != open || tot.PaidQuests != paid {
t.Fatalf("%s: open %d/%d paid %d/%d", what, tot.OpenQuests, open, tot.PaidQuests, paid)
}
}
// ---------------------------------------------------------------------------
// Plan section 10, case 1: happy path with balances.
func TestHappyPath(cur realm, t *testing.T) {
resetState()
before := GetTotals()
id := post(cur, alice, 5*gnot, "Write a tutorial")
q := GetQuest(id)
uassert.Equal(t, escrow.Open.String(), q.State.String())
uassert.Equal(t, alice.String(), q.Poster.String())
uassert.Equal(t, 5*gnot, q.Reward)
uassert.Equal(t, runtime.ChainHeight(), q.CreatedAt)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
ClaimQuest(cross(cur), id)
uassert.Equal(t, escrow.Claimed.String(), GetQuest(id).State.String())
uassert.Equal(t, bob.String(), GetQuest(id).Builder.String())
SubmitWork(cross(cur), id, link)
uassert.Equal(t, escrow.Submitted.String(), GetQuest(id).State.String())
uassert.Equal(t, link, GetQuest(id).WorkLink)
bobBefore, realmBefore := bal(bob), bal(realmAddr)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
ApproveWork(cross(cur), id)
uassert.Equal(t, bobBefore+5*gnot, bal(bob), "builder gets exactly the reward")
uassert.Equal(t, realmBefore-5*gnot, bal(realmAddr), "realm pays exactly the reward")
uassert.Equal(t, escrow.Paid.String(), GetQuest(id).State.String())
after := GetTotals()
uassert.Equal(t, before.Posted+5*gnot, after.Posted)
uassert.Equal(t, before.Paid+5*gnot, after.Paid)
uassert.Equal(t, before.Locked, after.Locked)
uassert.Equal(t, before.PaidQuests+1, after.PaidQuests)
checkInvariants(t, "happy path")
}
// Case 2: cancel an open quest refunds the poster.
func TestCancelRefund(cur realm, t *testing.T) {
resetState()
id := post(cur, alice, 3*gnot, "To be cancelled")
before := GetTotals()
aliceBefore, realmBefore := bal(alice), bal(realmAddr)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
CancelQuest(cross(cur), id)
uassert.Equal(t, aliceBefore+3*gnot, bal(alice))
uassert.Equal(t, realmBefore-3*gnot, bal(realmAddr))
uassert.Equal(t, escrow.Cancelled.String(), GetQuest(id).State.String())
after := GetTotals()
uassert.Equal(t, before.Refunded+3*gnot, after.Refunded)
uassert.Equal(t, before.Locked-3*gnot, after.Locked)
uassert.Equal(t, before.OpenQuests-1, after.OpenQuests)
checkInvariants(t, "cancel")
}
// Case 3: reject reopens, clears the builder, counts; builder history kept.
func TestReject(cur realm, t *testing.T) {
resetState()
id := submitted(cur, 2*gnot)
realmBefore := bal(realmAddr)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
RejectWork(cross(cur), id, "Tests are missing")
q := GetQuest(id)
uassert.Equal(t, escrow.Open.String(), q.State.String())
uassert.Equal(t, address("").String(), q.Builder.String())
uassert.Equal(t, "", q.WorkLink)
uassert.Equal(t, 1, q.RejectCount)
uassert.Equal(t, "Tests are missing", q.LastRejectReason)
uassert.Equal(t, realmBefore, bal(realmAddr), "no coins move on reject")
uassert.True(t, containsID(allPages(OpenQuestIDs), id), "back in the open list")
uassert.True(t, containsID(QuestIDsByBuilder(bob, 0, MaxPageSize), id), "builder history kept")
// a second builder can take it; both stay in their own history
testing.SetRealm(testing.NewUserRealm(carol))
testing.SetOriginSend(nil)
ClaimQuest(cross(cur), id)
uassert.True(t, containsID(QuestIDsByBuilder(carol, 0, MaxPageSize), id))
uassert.True(t, containsID(QuestIDsByBuilder(bob, 0, MaxPageSize), id))
uassert.Equal(t, carol.String(), GetQuest(id).Builder.String())
checkInvariants(t, "reject")
}
// Case 4: ClaimPayout fails up to and including the review deadline, pays after.
func TestClaimPayoutTimeout(cur realm, t *testing.T) {
resetState()
id := submitted(cur, 4*gnot)
q := GetQuest(id)
uassert.Equal(t, q.SubmittedAt+escrow.ReviewBlocks, q.ReviewDeadline)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
fails(t, cur, "review deadline has not passed", func() { ClaimPayout(cross(cur), id) }, "payout right after submit")
testing.SkipHeights(q.ReviewDeadline - runtime.ChainHeight() - 1) // deadline - 1
fails(t, cur, "review deadline has not passed", func() { ClaimPayout(cross(cur), id) }, "payout at deadline-1")
testing.SkipHeights(1) // exactly at the deadline
uassert.Equal(t, q.ReviewDeadline, runtime.ChainHeight())
uassert.False(t, GetQuest(id).CanClaimPayout)
fails(t, cur, "review deadline has not passed", func() { ClaimPayout(cross(cur), id) }, "payout at deadline")
testing.SkipHeights(1) // deadline + 1
uassert.True(t, GetQuest(id).CanClaimPayout)
bobBefore, realmBefore := bal(bob), bal(realmAddr)
ClaimPayout(cross(cur), id)
uassert.Equal(t, bobBefore+4*gnot, bal(bob))
uassert.Equal(t, realmBefore-4*gnot, bal(realmAddr))
uassert.Equal(t, escrow.Paid.String(), GetQuest(id).State.String())
checkInvariants(t, "timeout payout")
}
// Reject is allowed at the review deadline and refused one block after.
func TestRejectAfterReviewDeadline(cur realm, t *testing.T) {
resetState()
id := submitted(cur, gnot)
d := GetQuest(id).ReviewDeadline
testing.SkipHeights(d - runtime.ChainHeight() + 1)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
fails(t, cur, "review deadline has passed", func() { RejectWork(cross(cur), id, "late") }, "late reject")
// approving late still works and pays the builder
bobBefore := bal(bob)
ApproveWork(cross(cur), id)
uassert.Equal(t, bobBefore+gnot, bal(bob))
}
// Case 5: ReleaseQuest fails up to and including the work deadline, works after.
func TestReleaseDeadline(cur realm, t *testing.T) {
resetState()
id := claimed(cur, gnot)
q := GetQuest(id)
uassert.Equal(t, q.ClaimedAt+2_000, q.WorkDeadline)
testing.SetRealm(testing.NewUserRealm(dave))
testing.SetOriginSend(nil)
fails(t, cur, "work deadline has not passed", func() { ReleaseQuest(cross(cur), id) }, "release right after claim")
testing.SkipHeights(q.WorkDeadline - runtime.ChainHeight())
uassert.Equal(t, q.WorkDeadline, runtime.ChainHeight())
fails(t, cur, "work deadline has not passed", func() { ReleaseQuest(cross(cur), id) }, "release at deadline")
// the builder may still submit at the deadline block; check on a copy quest instead
testing.SkipHeights(1)
uassert.True(t, GetQuest(id).CanRelease)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
fails(t, cur, "work deadline has passed", func() { SubmitWork(cross(cur), id, link) }, "submit after deadline")
testing.SetRealm(testing.NewUserRealm(dave))
testing.SetOriginSend(nil)
ReleaseQuest(cross(cur), id)
uassert.Equal(t, escrow.Open.String(), GetQuest(id).State.String())
uassert.Equal(t, address("").String(), GetQuest(id).Builder.String())
uassert.True(t, containsID(allPages(OpenQuestIDs), id))
checkInvariants(t, "release")
}
// Unclaim by the builder reopens the quest.
func TestUnclaim(cur realm, t *testing.T) {
resetState()
id := claimed(cur, gnot)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
UnclaimQuest(cross(cur), id)
uassert.Equal(t, escrow.Open.String(), GetQuest(id).State.String())
uassert.True(t, containsID(allPages(OpenQuestIDs), id))
uassert.True(t, containsID(QuestIDsByBuilder(bob, 0, MaxPageSize), id), "history kept after unclaim")
checkInvariants(t, "unclaim")
}
// Case 6: a stranger cannot approve, reject, cancel, submit, unclaim or claim payout.
func TestStranger(cur realm, t *testing.T) {
resetState()
open := post(cur, alice, gnot, "open")
cl := claimed(cur, gnot)
sub := submitted(cur, gnot)
testing.SetRealm(testing.NewUserRealm(carol))
testing.SetOriginSend(nil)
fails(t, cur, "only the poster", func() { CancelQuest(cross(cur), open) }, "stranger cancel")
fails(t, cur, "only the builder", func() { SubmitWork(cross(cur), cl, link) }, "stranger submit")
fails(t, cur, "only the builder", func() { UnclaimQuest(cross(cur), cl) }, "stranger unclaim")
fails(t, cur, "only the poster", func() { ApproveWork(cross(cur), sub) }, "stranger approve")
fails(t, cur, "only the poster", func() { RejectWork(cross(cur), sub, "no") }, "stranger reject")
testing.SkipHeights(escrow.ReviewBlocks + 1)
fails(t, cur, "only the builder", func() { ClaimPayout(cross(cur), sub) }, "stranger claim payout")
// roles do not cross either
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
fails(t, cur, "only the poster", func() { ApproveWork(cross(cur), sub) }, "builder approve")
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
fails(t, cur, "only the builder", func() { ClaimPayout(cross(cur), sub) }, "poster claim payout")
fails(t, cur, "only the builder", func() { SubmitWork(cross(cur), cl, link) }, "poster submit")
}
// Case 7: the poster cannot claim their own quest.
func TestPosterCannotClaim(cur realm, t *testing.T) {
resetState()
id := post(cur, alice, gnot, "mine")
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
fails(t, cur, "cannot claim their own quest", func() { ClaimQuest(cross(cur), id) }, "poster claim")
}
// Case 8: post with a wrong coin, several coins, no coins or too small a reward.
func TestPostCoins(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
cases := []struct {
name string
sent chain.Coins
want string
}{
{"no coins", nil, ErrNoCoins},
{"wrong denom", chain.Coins{{Denom: "uatom", Amount: 5 * gnot}}, ErrWrongDenom},
{"two coins", chain.Coins{{Denom: "ugnot", Amount: 5 * gnot}, {Denom: "uatom", Amount: 1}}, ErrSeveralCoins},
{"two ugnot entries", chain.Coins{{Denom: "ugnot", Amount: gnot}, {Denom: "ugnot", Amount: gnot}}, ErrSeveralCoins},
{"below minimum", ugnot(MinReward - 1), ErrRewardTooLow},
{"zero", ugnot(0), ErrRewardTooLow},
}
for _, c := range cases {
testing.SetOriginSend(c.sent)
fails(t, cur, c.want, func() { PostQuest(cross(cur), "title", "", 2_000) }, c.name)
}
testing.SetOriginSend(nil)
// exactly the minimum works, and the stored reward is the amount sent
id := post(cur, alice, MinReward, "minimum")
uassert.Equal(t, MinReward, GetQuest(id).Reward)
checkInvariants(t, "post coins")
}
// Rule 3: every function that does not take money refuses coins, even when the
// call would otherwise succeed.
func TestNoCoinsOnOtherCalls(cur realm, t *testing.T) {
resetState()
open := post(cur, alice, gnot, "open")
cl := claimed(cur, gnot)
sub := submitted(cur, gnot)
one := ugnot(1)
type call struct {
who address
name string
fn func()
}
calls := []call{
{bob, "ClaimQuest", func() { ClaimQuest(cross(cur), open) }},
{alice, "CancelQuest", func() { CancelQuest(cross(cur), open) }},
{bob, "SubmitWork", func() { SubmitWork(cross(cur), cl, link) }},
{bob, "UnclaimQuest", func() { UnclaimQuest(cross(cur), cl) }},
{alice, "ApproveWork", func() { ApproveWork(cross(cur), sub) }},
{alice, "RejectWork", func() { RejectWork(cross(cur), sub, "no") }},
}
for _, c := range calls {
testing.SetRealm(testing.NewUserRealm(c.who))
testing.SetOriginSend(nil)
testing.SetOriginSend(one)
fails(t, cur, ErrCoinsNotTaken, c.fn, c.name+" with coins")
}
// the two time-gated moves, past their deadlines
testing.SkipHeights(escrow.ReviewBlocks + 2_001)
testing.SetRealm(testing.NewUserRealm(dave))
testing.SetOriginSend(nil)
testing.SetOriginSend(one)
fails(t, cur, ErrCoinsNotTaken, func() { ReleaseQuest(cross(cur), cl) }, "ReleaseQuest with coins")
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
testing.SetOriginSend(one)
fails(t, cur, ErrCoinsNotTaken, func() { ClaimPayout(cross(cur), sub) }, "ClaimPayout with coins")
testing.SetOriginSend(nil)
// without coins the same calls succeed
ClaimPayout(cross(cur), sub)
testing.SetRealm(testing.NewUserRealm(dave))
testing.SetOriginSend(nil)
ReleaseQuest(cross(cur), cl)
checkInvariants(t, "no coins")
}
// Case 9: a payout cannot happen twice.
func TestNoDoublePayout(cur realm, t *testing.T) {
resetState()
// approve twice, then approve -> claim payout
a := submitted(cur, gnot)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
ApproveWork(cross(cur), a)
fails(t, cur, "not allowed in the quest's current state", func() { ApproveWork(cross(cur), a) }, "approve twice")
testing.SkipHeights(escrow.ReviewBlocks + 1)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
fails(t, cur, "not allowed in the quest's current state", func() { ClaimPayout(cross(cur), a) }, "approve then claim payout")
// claim payout twice, then claim payout -> approve
b := submitted(cur, gnot)
testing.SkipHeights(escrow.ReviewBlocks + 1)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
ClaimPayout(cross(cur), b)
fails(t, cur, "not allowed in the quest's current state", func() { ClaimPayout(cross(cur), b) }, "claim payout twice")
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
fails(t, cur, "not allowed in the quest's current state", func() { ApproveWork(cross(cur), b) }, "claim payout then approve")
// cancel twice
c := post(cur, alice, gnot, "cancel twice")
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
CancelQuest(cross(cur), c)
fails(t, cur, "not allowed in the quest's current state", func() { CancelQuest(cross(cur), c) }, "cancel twice")
checkInvariants(t, "double payout")
}
// Case 10: cancel after Claimed (or Submitted) fails.
// Case 10: cancelling a Claimed or Submitted quest refunds nothing: it only
// marks the quest as closing.
func TestCancelAfterClaimOnlyCloses(cur realm, t *testing.T) {
resetState()
cl := claimed(cur, gnot)
sub := submitted(cur, gnot)
before := takeSnapshot()
aliceBefore := bal(alice)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
CancelQuest(cross(cur), cl)
CancelQuest(cross(cur), sub)
after := takeSnapshot()
uassert.Equal(t, before.realm, after.realm, "no coins move on close")
uassert.Equal(t, aliceBefore, bal(alice))
uassert.True(t, before.totals == after.totals, "totals unchanged on close")
uassert.True(t, GetQuest(cl).Closing)
uassert.True(t, GetQuest(sub).Closing)
uassert.Equal(t, escrow.Claimed.String(), GetQuest(cl).State.String())
fails(t, cur, "already closing", func() { CancelQuest(cross(cur), cl) }, "close twice")
testing.SetRealm(testing.NewUserRealm(carol))
testing.SetOriginSend(nil)
fails(t, cur, "only the poster", func() { CancelQuest(cross(cur), sub) }, "stranger close")
checkInvariants(t, "close")
}
// The squatting attack from the security review: a squatter claims, the
// poster closes, the squatter holds until the work deadline; then anyone can
// end it, the poster is refunded exactly once and nobody can claim again.
func TestCloseStopsSquatting(cur realm, t *testing.T) {
resetState()
eve := testutils.TestAddress("qb_eve")
mal := testutils.TestAddress("qb_mal")
id := post(cur, alice, 5*gnot, "real task")
testing.SetRealm(testing.NewUserRealm(eve))
testing.SetOriginSend(nil)
ClaimQuest(cross(cur), id)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
CancelQuest(cross(cur), id)
uassert.False(t, containsID(allPages(OpenQuestIDs), id), "closing quest is not open")
checkInvariants(t, "closed")
d := GetQuest(id).WorkDeadline
testing.SkipHeights(d - runtime.ChainHeight())
testing.SetRealm(testing.NewUserRealm(mal))
testing.SetOriginSend(nil)
fails(t, cur, "work deadline has not passed", func() { ReleaseQuest(cross(cur), id) }, "release at the deadline")
testing.SkipHeights(1)
aliceBefore, malBefore, realmBefore := bal(alice), bal(mal), bal(realmAddr)
totBefore := GetTotals()
ReleaseQuest(cross(cur), id)
uassert.Equal(t, aliceBefore+5*gnot, bal(alice), "poster refunded once")
uassert.Equal(t, malBefore, bal(mal), "the caller gets nothing")
uassert.Equal(t, realmBefore-5*gnot, bal(realmAddr))
uassert.Equal(t, escrow.Cancelled.String(), GetQuest(id).State.String())
uassert.Equal(t, totBefore.Refunded+5*gnot, GetTotals().Refunded)
uassert.Equal(t, totBefore.OpenQuests, GetTotals().OpenQuests)
uassert.False(t, containsID(allPages(OpenQuestIDs), id))
fails(t, cur, "not allowed in the quest's current state", func() { ClaimQuest(cross(cur), id) }, "re-claim after close")
fails(t, cur, "not allowed in the quest's current state", func() { ReleaseQuest(cross(cur), id) }, "release twice")
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
fails(t, cur, "not allowed in the quest's current state", func() { CancelQuest(cross(cur), id) }, "cancel after refund")
checkInvariants(t, "squat released")
}
func TestCloseThenUnclaim(cur realm, t *testing.T) {
resetState()
id := claimed(cur, 3*gnot)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
CancelQuest(cross(cur), id)
aliceBefore := bal(alice)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
UnclaimQuest(cross(cur), id)
uassert.Equal(t, aliceBefore+3*gnot, bal(alice))
uassert.Equal(t, escrow.Cancelled.String(), GetQuest(id).State.String())
uassert.False(t, containsID(allPages(OpenQuestIDs), id))
checkInvariants(t, "close then unclaim")
}
func TestCloseThenReject(cur realm, t *testing.T) {
resetState()
id := submitted(cur, 4*gnot)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
CancelQuest(cross(cur), id)
aliceBefore, bobBefore := bal(alice), bal(bob)
RejectWork(cross(cur), id, "not what I asked")
uassert.Equal(t, aliceBefore+4*gnot, bal(alice))
uassert.Equal(t, bobBefore, bal(bob))
q := GetQuest(id)
uassert.Equal(t, escrow.Cancelled.String(), q.State.String())
uassert.Equal(t, 1, q.RejectCount)
uassert.False(t, containsID(allPages(OpenQuestIDs), id))
checkInvariants(t, "close then reject")
}
// While closing, the builder keeps every right.
func TestCloseStillPaysBuilder(cur realm, t *testing.T) {
resetState()
a := claimed(cur, 2*gnot)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
CancelQuest(cross(cur), a)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
SubmitWork(cross(cur), a, link)
bobBefore := bal(bob)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
ApproveWork(cross(cur), a)
uassert.Equal(t, bobBefore+2*gnot, bal(bob), "approve while closing pays the builder")
b := submitted(cur, 3*gnot)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
CancelQuest(cross(cur), b)
testing.SkipHeights(escrow.ReviewBlocks + 1)
bobBefore = bal(bob)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
ClaimPayout(cross(cur), b)
uassert.Equal(t, bobBefore+3*gnot, bal(bob), "timeout payout while closing pays the builder")
checkInvariants(t, "close still pays")
}
// The timeout rule, documented: a builder who submits anything is paid after
// the review window if the poster does nothing; a reject at the last block of
// the window prevents it.
func TestJunkSubmissionTimeout(cur realm, t *testing.T) {
resetState()
id := claimed(cur, 5*gnot)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
SubmitWork(cross(cur), id, "https://x")
testing.SkipHeights(GetQuest(id).ReviewDeadline - runtime.ChainHeight() + 1)
bobBefore := bal(bob)
ClaimPayout(cross(cur), id)
uassert.Equal(t, bobBefore+5*gnot, bal(bob), "silent poster: builder paid")
id2 := claimed(cur, 5*gnot)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
SubmitWork(cross(cur), id2, "https://x")
testing.SkipHeights(GetQuest(id2).ReviewDeadline - runtime.ChainHeight())
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
RejectWork(cross(cur), id2, "junk")
testing.SkipHeights(1)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
fails(t, cur, "not allowed in the quest's current state", func() { ClaimPayout(cross(cur), id2) }, "payout after reject")
checkInvariants(t, "junk timeout")
}
// Case 11: text over the limits and bad links fail at realm level.
func TestTextLimits(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
bad := []struct{ title, details, want string }{
{"", "", "title is empty"},
{strings.Repeat("a", escrow.MaxTitleLen+1), "", "title is too long"},
{"two\nlines", "", "control characters"},
{"ok", strings.Repeat("d", escrow.MaxDetailsLen+1), "details are too long"},
}
for _, c := range bad {
testing.SetOriginSend(ugnot(gnot))
fails(t, cur, c.want, func() { PostQuest(cross(cur), c.title, c.details, 2_000) }, "post: "+c.want)
}
testing.SetOriginSend(ugnot(gnot))
fails(t, cur, "work window is below", func() { PostQuest(cross(cur), "t", "", escrow.MinWorkBlocks-1) }, "work window low")
fails(t, cur, "work window is above", func() { PostQuest(cross(cur), "t", "", escrow.MaxWorkBlocks+1) }, "work window high")
testing.SetOriginSend(nil)
cl := claimed(cur, gnot)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
for _, l := range []string{"http://example.com", "example.com", "https://", "https://a b", "https://" + strings.Repeat("a", escrow.MaxLinkLen)} {
fails(t, cur, "escrow: work link", func() { SubmitWork(cross(cur), cl, l) }, "link "+l)
}
SubmitWork(cross(cur), cl, link)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
fails(t, cur, "reject reason is too long", func() { RejectWork(cross(cur), cl, strings.Repeat("r", escrow.MaxReasonLen+1)) }, "long reason")
fails(t, cur, "reject reason is empty", func() { RejectWork(cross(cur), cl, "") }, "empty reason")
}
// Non-user callers (other realms, maketx run scripts) are refused everywhere.
func TestCodeRealmRefused(cur realm, t *testing.T) {
resetState()
open := post(cur, alice, gnot, "open")
cl := claimed(cur, gnot)
sub := submitted(cur, gnot)
callers := []runtime.Realm{
testing.NewCodeRealm("gno.land/r/evil/proxy"),
// a `gnokey maketx run` script runs as an ephemeral realm
runtime.NewRealm(alice, "gno.land/e/"+alice.String()+"/run"),
}
for _, c := range callers {
testing.SetRealm(c)
testing.SetOriginSend(ugnot(gnot))
fails(t, cur, ErrNotUserCall, func() { PostQuest(cross(cur), "t", "", 2_000) }, "PostQuest")
testing.SetOriginSend(nil)
fails(t, cur, ErrNotUserCall, func() { ClaimQuest(cross(cur), open) }, "ClaimQuest")
fails(t, cur, ErrNotUserCall, func() { CancelQuest(cross(cur), open) }, "CancelQuest")
fails(t, cur, ErrNotUserCall, func() { SubmitWork(cross(cur), cl, link) }, "SubmitWork")
fails(t, cur, ErrNotUserCall, func() { UnclaimQuest(cross(cur), cl) }, "UnclaimQuest")
fails(t, cur, ErrNotUserCall, func() { ReleaseQuest(cross(cur), cl) }, "ReleaseQuest")
fails(t, cur, ErrNotUserCall, func() { ApproveWork(cross(cur), sub) }, "ApproveWork")
fails(t, cur, ErrNotUserCall, func() { RejectWork(cross(cur), sub, "no") }, "RejectWork")
fails(t, cur, ErrNotUserCall, func() { ClaimPayout(cross(cur), sub) }, "ClaimPayout")
}
}
// An unknown quest id panics cleanly on every function that takes an id.
func TestUnknownID(cur realm, t *testing.T) {
resetState()
missing := GetTotals().Quests + 1000
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
fails(t, cur, ErrUnknownQuest, func() { ClaimQuest(cross(cur), missing) }, "ClaimQuest")
fails(t, cur, ErrUnknownQuest, func() { UnclaimQuest(cross(cur), missing) }, "UnclaimQuest")
fails(t, cur, ErrUnknownQuest, func() { ReleaseQuest(cross(cur), missing) }, "ReleaseQuest")
fails(t, cur, ErrUnknownQuest, func() { SubmitWork(cross(cur), missing, link) }, "SubmitWork")
fails(t, cur, ErrUnknownQuest, func() { ApproveWork(cross(cur), missing) }, "ApproveWork")
fails(t, cur, ErrUnknownQuest, func() { RejectWork(cross(cur), missing, "no") }, "RejectWork")
fails(t, cur, ErrUnknownQuest, func() { CancelQuest(cross(cur), missing) }, "CancelQuest")
fails(t, cur, ErrUnknownQuest, func() { ClaimPayout(cross(cur), missing) }, "ClaimPayout")
uassert.PanicsContains(t, cur, ErrUnknownQuest, func() { GetQuest(missing) }, "GetQuest")
uassert.PanicsContains(t, cur, ErrUnknownQuest, func() { GetQuest(0) }, "GetQuest(0)")
}
// Read functions return copies: changing a returned value or slice does not
// change stored state. The exported API (see questmaster.gno) has no function
// or variable that returns *escrow.Quest or an avl tree; package variables
// are all unexported.
func TestNoPointerLeak(cur realm, t *testing.T) {
resetState()
id := post(cur, alice, gnot, "original title")
v := GetQuest(id)
v.Title = "changed"
v.Reward = 1
v.State = escrow.Paid
uassert.Equal(t, "original title", GetQuest(id).Title)
uassert.Equal(t, gnot, GetQuest(id).Reward)
uassert.Equal(t, escrow.Open.String(), GetQuest(id).State.String())
ids := QuestIDsByPoster(alice, 0, 1)
ids[0] = 999999
uassert.Equal(t, id, QuestIDsByPoster(alice, 0, 1)[0])
tot := GetTotals()
tot.Locked = 0
uassert.NotEqual(t, int64(0), GetTotals().Locked)
}
// Lists: newest first, offset, and a hard cap of MaxPageSize per call.
func TestLists(cur realm, t *testing.T) {
resetState()
var mine []uint64
for i := 0; i < MaxPageSize+5; i++ {
mine = append(mine, post(cur, dave, gnot, "bulk"))
}
first := QuestIDsByPoster(dave, 0, 1000)
uassert.Equal(t, MaxPageSize, len(first), "capped")
uassert.Equal(t, mine[len(mine)-1], first[0], "newest first")
second := QuestIDsByPoster(dave, MaxPageSize, 1000)
uassert.Equal(t, 5, len(second))
uassert.Equal(t, mine[0], second[4], "oldest last")
uassert.Equal(t, 3, len(QuestIDsByPoster(dave, 0, 3)))
uassert.Equal(t, MaxPageSize, len(QuestIDsByPoster(dave, -5, 0)), "bad offset/limit fall back to defaults")
uassert.Equal(t, 0, len(QuestIDsByPoster(dave, 10_000, 10)))
uassert.Equal(t, MaxPageSize+5, CountByPoster(dave))
uassert.Equal(t, 0, len(QuestIDsByBuilder(testutils.TestAddress("nobody"), 0, 10)))
uassert.Equal(t, 0, CountByBuilder(testutils.TestAddress("nobody")))
uassert.Equal(t, MaxPageSize, len(AllQuestIDs(0, 0)))
uassert.Equal(t, GetTotals().Quests, AllQuestIDs(0, 1)[0])
// tidy up so later tests see fewer open quests
testing.SetRealm(testing.NewUserRealm(dave))
testing.SetOriginSend(nil)
for _, id := range mine {
CancelQuest(cross(cur), id)
}
checkInvariants(t, "lists")
}
// Case 12: a long mixed run over many quests and users. After every step the
// realm balance equals the sum of rewards still held, equals the locked
// total, and posted == locked + paid + refunded. Coins are conserved across
// users and the realm.
func TestMixedRunInvariant(cur realm, t *testing.T) {
resetState()
users := []address{alice, bob, carol, dave}
start := int64(0)
for _, u := range users {
start += bal(u)
}
start += bal(realmAddr)
issued := int64(0)
seed := uint64(42)
rnd := func(n int) int {
seed = seed*6364136223846793005 + 1442695040888963407
return int((seed >> 33) % uint64(n))
}
var ids []uint64
done := map[string]int{}
for step := 0; step < 300; step++ {
var id uint64
var active []uint64
for _, x := range ids {
if !GetQuest(x).State.IsFinal() {
active = append(active, x)
}
}
if len(active) > 0 && rnd(8) != 0 {
id = active[rnd(len(active))] // mostly quests still in play
} else if len(ids) > 0 {
id = ids[rnd(len(ids))] // sometimes a finished one (must fail)
}
action := rnd(10)
if len(active) < 3 || action == 0 {
reward := gnot + int64(rnd(5))*250_000
ids = append(ids, post(cur, users[rnd(len(users))], reward, "mixed"))
issued += reward
done["post"]++
checkInvariants(t, "mixed post")
continue
}
q := GetQuest(id)
// pick a legal actor most of the time, a random one otherwise
poster, builder := q.Poster, q.Builder
pick := func(want address) address {
if rnd(8) == 0 || want == "" {
return users[rnd(len(users))]
}
return want
}
var name string
var fn func()
switch q.State {
case escrow.Open:
if rnd(4) == 0 {
testing.SetRealm(testing.NewUserRealm(pick(poster)))
testing.SetOriginSend(nil)
name, fn = "cancel", func() { CancelQuest(cross(cur), id) }
} else {
testing.SetRealm(testing.NewUserRealm(users[rnd(len(users))]))
testing.SetOriginSend(nil)
name, fn = "claim", func() { ClaimQuest(cross(cur), id) }
}
case escrow.Claimed:
switch rnd(5) {
case 4:
testing.SetRealm(testing.NewUserRealm(pick(poster)))
testing.SetOriginSend(nil)
name, fn = "close", func() { CancelQuest(cross(cur), id) }
case 0:
testing.SetRealm(testing.NewUserRealm(pick(builder)))
testing.SetOriginSend(nil)
name, fn = "unclaim", func() { UnclaimQuest(cross(cur), id) }
case 1:
testing.SkipHeights(q.WorkDeadline - runtime.ChainHeight() + 1)
testing.SetRealm(testing.NewUserRealm(users[rnd(len(users))]))
testing.SetOriginSend(nil)
name, fn = "release", func() { ReleaseQuest(cross(cur), id) }
default:
testing.SetRealm(testing.NewUserRealm(pick(builder)))
testing.SetOriginSend(nil)
name, fn = "submit", func() { SubmitWork(cross(cur), id, link) }
}
case escrow.Submitted:
switch k := rnd(5); {
case k == 4:
testing.SetRealm(testing.NewUserRealm(pick(poster)))
testing.SetOriginSend(nil)
name, fn = "close", func() { CancelQuest(cross(cur), id) }
case k == 0 || (k < 3 && runtime.ChainHeight() > q.ReviewDeadline):
testing.SetRealm(testing.NewUserRealm(pick(poster)))
testing.SetOriginSend(nil)
name, fn = "approve", func() { ApproveWork(cross(cur), id) }
case k < 3:
testing.SetRealm(testing.NewUserRealm(pick(poster)))
testing.SetOriginSend(nil)
name, fn = "reject", func() { RejectWork(cross(cur), id, "again") }
default:
testing.SkipHeights(q.ReviewDeadline - runtime.ChainHeight() + 1)
testing.SetRealm(testing.NewUserRealm(pick(builder)))
testing.SetOriginSend(nil)
name, fn = "timeout", func() { ClaimPayout(cross(cur), id) }
}
default:
testing.SetRealm(testing.NewUserRealm(pick(poster)))
testing.SetOriginSend(nil)
name, fn = "final-cancel", func() { CancelQuest(cross(cur), id) }
}
before := takeSnapshot()
r := revive(fn)
if r != nil {
sameSnapshot(t, before, takeSnapshot(), "failed "+name)
done["failed"]++
} else {
done[name]++
if q.Closing && (name == "unclaim" || name == "release" || name == "reject") {
done["closed-refund"]++
}
}
checkInvariants(t, name)
total := bal(realmAddr)
for _, u := range users {
total += bal(u)
}
if total != start+issued {
t.Fatalf("step %d %s: coins not conserved: %d != %d", step, name, total, start+issued)
}
}
for _, k := range []string{"post", "claim", "cancel", "unclaim", "release", "submit", "approve", "reject", "timeout", "failed", "close", "closed-refund"} {
if done[k] == 0 {
t.Errorf("mixed run never did %q: %v", k, done)
}
}
println("mixed run moves:", done)
}
func containsID(ids []uint64, id uint64) bool {
for _, x := range ids {
if x == id {
return true
}
}
return false
}
render.gno
package questmaster
import (
"chain/runtime"
"chain/runtime/unsafe"
"net/url"
"strconv"
"strings"
"gno.land/p/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/escrow"
"gno.land/p/moul/txlink/v0"
"gno.land/p/nt/avl/v0"
)
// Pages (gnoweb shows Render's Markdown):
//
// "" home: intro, totals, open quests, how it works
// "quest/<id>" one quest and what can happen next
// "poster/<address>" quests posted by an address
// "builder/<address>" quests an address has worked on (history)
// "paid" finished, paid quests
// "help" how to use every function, with gnokey commands
//
// List pages take "?page=N" (PageSize per page). Render never panics: any
// unknown path, bad id or bad address gives a "not found" page.
// PageSize is the number of quests per list page.
const PageSize = 20
// maxPage bounds ?page= so offsets stay small.
const maxPage = 1_000_000
// SourceRepo is where the source code is published, shown in the footer of
// every page.
const SourceRepo = "https://github.com/elangrr/questmaster"
// Render returns the gnoweb page for path, with the footer.
func Render(path string) string {
return renderPage(path) + footer()
}
// footer ends every page: attribution and where the source is.
func footer() string {
src := "source: " + SourceRepo
if strings.HasPrefix(SourceRepo, "https://") {
src = "[source](" + SourceRepo + ")"
}
return "\n---\n\nBuilt on [gno.land](https://gno.land) · " + src + "\n"
}
func renderPage(path string) string {
p, query := splitQuery(path)
page := pageArg(query)
switch {
case p == "":
return renderHome(page)
case p == "help":
return renderHelp()
case p == "paid":
return renderPaid(page)
case strings.HasPrefix(p, "quest/"):
id, ok := parseID(strings.TrimPrefix(p, "quest/"))
if !ok {
return renderNotFound("There is no quest with that number.")
}
return renderQuest(id)
case strings.HasPrefix(p, "poster/"):
addr, ok := parseAddress(strings.TrimPrefix(p, "poster/"))
if !ok {
return renderNotFound("That is not a valid address.")
}
return renderUser(addr, true, page)
case strings.HasPrefix(p, "builder/"):
addr, ok := parseAddress(strings.TrimPrefix(p, "builder/"))
if !ok {
return renderNotFound("That is not a valid address.")
}
return renderUser(addr, false, page)
}
return renderNotFound("This page does not exist.")
}
// ---------------------------------------------------------------------------
// Pages
func renderHome(page int) string {
var b strings.Builder
t := GetTotals()
b.WriteString("# QuestMaster\n\n")
b.WriteString("A bounty board for small tasks, paid in GNOT. A poster describes a task and locks the reward in this realm. " +
"A builder takes the task, does the work and sends a link to it. When the poster approves, the realm pays the builder. " +
"If the poster never answers, the builder can collect the reward after the review window. Nobody else, not even the authors, can move the locked GNOT.\n\n")
b.WriteString("_Runs on the Onyx test network with test GNOT._\n\n")
b.WriteString("**Post a quest:** " + postLinks() + " · [How it works](#how-it-works) · [Help and commands](" + pageURL("help") + ") · [Paid quests](" + pageURL("paid") + ")\n\n")
b.WriteString("## Board\n\n")
b.WriteString("| Open quests | GNOT locked | GNOT paid out | Quests paid |\n")
b.WriteString("|---|---|---|---|\n")
b.WriteString("| " + strconv.Itoa(t.OpenQuests) + " | " + gnotStr(t.Locked) + " | " + gnotStr(t.Paid) + " | " + strconv.Itoa(t.PaidQuests) + " |\n\n")
b.WriteString("## Open quests\n\n")
ids, nav := pageOf(&openIDs, page, "")
if openIDs.Size() == 0 {
b.WriteString("No open quests right now. [Post the first one](" + postLink() + ").\n\n")
} else if len(ids) == 0 {
b.WriteString("This page is empty. [Back to the first page](" + pageURL("") + ")\n\n")
} else {
b.WriteString("| # | Quest | Reward | Work window | Rejected |\n")
b.WriteString("|---|---|---|---|---|\n")
for _, id := range ids {
q := mustGet(id)
b.WriteString("| " + idStr(id) + " | " + questLink(q) + " | " + gnotStr(q.Reward()) + " GNOT | " +
blocksStr(q.WorkBlocks()) + " (" + approx(q.WorkBlocks()) + ") | " + strconv.Itoa(q.RejectCount()) + " |\n")
}
b.WriteString("\n" + nav)
}
b.WriteString("## How it works\n\n")
b.WriteString("1. **Post.** The poster writes a title, details and a work window, and sends the reward (at least 1 GNOT) with the call. The GNOT is locked here.\n")
b.WriteString("2. **Claim.** Anyone except the poster takes the quest. Only one builder works on a quest at a time.\n")
b.WriteString("3. **Submit.** The builder sends a link to the work (it must start with `https://`) before the work window ends.\n")
b.WriteString("4. **Review.** The poster approves (the builder is paid at once) or rejects with a reason (the quest opens again, and the reject count goes up for everyone to see).\n")
b.WriteString("5. **Paid.** The reward goes to the builder.\n\n")
b.WriteString("A poster can cancel an open quest and get the reward back at once. Anyone can claim an open quest; once a builder has it, the poster can **close** the quest instead: the builder keeps their turn, and if it ends without approval the reward goes back to the poster.\n\n")
b.WriteString(reviewWarning())
b.WriteString("Two deadlines keep things moving:\n\n")
b.WriteString("- **Work window** (set by the poster, " + blocksStr(escrow.MinWorkBlocks) + " to " + blocksStr(escrow.MaxWorkBlocks) +
" blocks): if the builder has not submitted by then, anyone can release the quest so someone else can take it.\n")
b.WriteString("- **Review window** (" + blocksStr(escrow.ReviewBlocks) + " blocks, " + approx(escrow.ReviewBlocks) +
"): if the poster has not approved or rejected by then, the builder can claim the reward.\n\n")
b.WriteString(timeNote())
return b.String()
}
func renderQuest(id uint64) string {
v := quests.Get(questKey(id))
if v == nil {
return renderNotFound("There is no quest with that number.")
}
q := v.(*escrow.Quest)
h := runtime.ChainHeight()
var b strings.Builder
b.WriteString("# Quest " + idStr(id) + ": " + esc(q.Title()) + "\n\n")
b.WriteString("[Board](" + pageURL("") + ") · [Help](" + pageURL("help") + ")\n\n")
b.WriteString("| | |\n|---|---|\n")
b.WriteString("| State | **" + questState(q) + "** |\n")
b.WriteString("| Reward | " + gnotStr(q.Reward()) + " GNOT |\n")
b.WriteString("| Poster | " + userLink(q.Poster(), true) + " |\n")
if q.Builder() != "" {
b.WriteString("| Builder | " + userLink(q.Builder(), false) + " |\n")
}
b.WriteString("| Work window | " + blocksStr(q.WorkBlocks()) + " blocks (" + approx(q.WorkBlocks()) + ") |\n")
b.WriteString("| Posted at block | " + blocksStr(q.CreatedAt()) + " |\n")
switch q.State() {
case escrow.Claimed:
b.WriteString("| Claimed at block | " + blocksStr(q.ClaimedAt()) + " |\n")
b.WriteString("| Work deadline | block " + blocksStr(q.WorkDeadline()) + " (" + left(q.WorkDeadline(), h) + ") |\n")
case escrow.Submitted:
b.WriteString("| Submitted at block | " + blocksStr(q.SubmittedAt()) + " |\n")
b.WriteString("| Review deadline | block " + blocksStr(q.ReviewDeadline()) + " (" + left(q.ReviewDeadline(), h) + ") |\n")
}
if q.WorkLink() != "" {
b.WriteString("| Work | " + linkOrText(q.WorkLink()) + " |\n")
}
b.WriteString("| Times rejected | " + strconv.Itoa(q.RejectCount()) + " |\n")
b.WriteString("| Current block | " + blocksStr(h) + " |\n\n")
if q.Closing() {
b.WriteString("> [!NOTE]\n> **Closing**: the reward returns to the poster when the current builder's turn ends, unless the work is approved.\n\n")
}
b.WriteString("## Details\n\n")
if strings.TrimSpace(q.Details()) == "" {
b.WriteString("_No details given._\n\n")
} else {
b.WriteString(escBlock(q.Details()) + "\n")
}
if q.RejectCount() > 0 {
b.WriteString("## Last reject reason\n\n")
b.WriteString(escBlock(q.LastRejectReason()) + "\n")
}
b.WriteString("## What can happen next\n\n")
b.WriteString(nextSteps(q, h))
b.WriteString(timeNote())
return b.String()
}
// step is one possible move on a quest page.
type step struct{ text, fn string }
func closeStep() step {
return step{"**Close quest**: the poster stops the quest. No coins move now; the builder keeps their turn, and if it ends without approval the reward goes back to the poster. It cannot be undone.", "CancelQuest"}
}
// reviewWarning is shown to posters on the home and help pages.
func reviewWarning() string {
return "> [!WARNING]\n> **Posters: check your quest.** If you do not approve or reject a submission within the review window (" +
approx(escrow.ReviewBlocks) + "), the builder is paid automatically.\n\n"
}
// questState is the state as shown in tables and on the quest page.
func questState(q *escrow.Quest) string {
if q.Closing() && !q.State().IsFinal() {
return stateText(q.State()) + ", closing"
}
return stateText(q.State())
}
// nextSteps lists the moves valid in q's state, who may make each, and a
// transaction link and gnokey command for each.
func nextSteps(q *escrow.Quest, h int64) string {
id := idStr(q.ID())
var b strings.Builder
var steps []step
switch q.State() {
case escrow.Open:
steps = []step{
{"**Claim**: anyone except the poster can take this quest and start working.", "ClaimQuest"},
{"**Cancel**: the poster can close the quest and get the " + gnotStr(q.Reward()) + " GNOT back.", "CancelQuest"},
}
case escrow.Claimed:
if h <= q.WorkDeadline() {
steps = append(steps, step{"**Submit work**: the builder sends a link to the work (starting with `https://`), until block " + blocksStr(q.WorkDeadline()) + ".", "SubmitWork"})
}
if q.Closing() {
steps = append(steps, step{"**Unclaim**: the builder gives the quest back. It is closing, so it ends and the reward goes back to the poster.", "UnclaimQuest"})
} else {
steps = append(steps, step{"**Unclaim**: the builder gives the quest back so others can take it.", "UnclaimQuest"})
steps = append(steps, closeStep())
}
if q.CanRelease(h) {
if q.Closing() {
steps = append(steps, step{"**Release**: the work deadline has passed without a submission, so anyone can end the quest; the reward goes back to the poster.", "ReleaseQuest"})
} else {
steps = append(steps, step{"**Release**: the work deadline has passed without a submission, so anyone can reopen the quest.", "ReleaseQuest"})
}
} else if q.Closing() {
b.WriteString("If nothing is submitted by block " + blocksStr(q.WorkDeadline()) + ", anyone can end the quest from block " + blocksStr(q.WorkDeadline()+1) + " and the reward goes back to the poster.\n\n")
} else {
b.WriteString("If nothing is submitted by block " + blocksStr(q.WorkDeadline()) + ", anyone can release the quest from block " + blocksStr(q.WorkDeadline()+1) + ".\n\n")
}
case escrow.Submitted:
steps = append(steps, step{"**Approve**: the poster accepts the work and the builder is paid " + gnotStr(q.Reward()) + " GNOT.", "ApproveWork"})
if h <= q.ReviewDeadline() {
if q.Closing() {
steps = append(steps, step{"**Reject**: the poster refuses the work with a reason, until block " + blocksStr(q.ReviewDeadline()) + ". The quest is closing, so it ends and the reward goes back to the poster.", "RejectWork"})
} else {
steps = append(steps, step{"**Reject**: the poster refuses the work with a reason, until block " + blocksStr(q.ReviewDeadline()) + ". The quest opens again.", "RejectWork"})
}
}
if !q.Closing() {
steps = append(steps, closeStep())
}
if q.CanClaimPayout(h) {
steps = append(steps, step{"**Claim payout**: the poster did not answer in time, so the builder can take the reward.", "ClaimPayout"})
} else {
b.WriteString("If the poster does not answer by block " + blocksStr(q.ReviewDeadline()) + ", the builder can claim the reward from block " + blocksStr(q.ReviewDeadline()+1) + ".\n\n")
}
case escrow.Paid:
return "Nothing: this quest is finished and the builder was paid " + gnotStr(q.Reward()) + " GNOT.\n\n"
case escrow.Cancelled:
return "Nothing: this quest was cancelled and the reward went back to the poster.\n\n"
}
for _, s := range steps {
b.WriteString("- " + s.text + " [Open in gnoweb](" + txLink(s.fn).AddArgs("id", id).URL() + ")\n")
}
b.WriteString("\nWith gnokey on Onyx (replace `KEY` with your key name):\n\n```\n")
for _, s := range steps {
b.WriteString(gnokeyCall(s.fn, id, extraArg(s.fn), "") + "\n")
}
b.WriteString("```\n\n")
return b.String()
}
func extraArg(fn string) string {
switch fn {
case "SubmitWork":
return "https://link-to-your-work"
case "RejectWork":
return "What is missing"
}
return ""
}
func renderUser(addr address, asPoster bool, page int) string {
var b strings.Builder
idx, other, title, what := &byBuilder, "poster", "Builder ", "Quests this address has claimed, with their current state. A quest stays here after the builder gives it up or is rejected."
if asPoster {
idx, other, title, what = &byPoster, "builder", "Poster ", "Quests posted by this address, with their current state."
}
b.WriteString("# " + title + shortAddr(addr) + "\n\n")
b.WriteString("[Board](" + pageURL("") + ") · [Same address as " + other + "](" + pageURL(other+"/"+addr.String()) + ")\n\n")
b.WriteString("Address: `" + addr.String() + "`\n\n" + what + "\n\n")
var ids []uint64
var nav string
base := "builder/" + addr.String()
if asPoster {
base = "poster/" + addr.String()
}
if v := idx.Get(addr.String()); v != nil {
ids, nav = pageOf(v.(*avl.Tree), page, base)
}
if len(ids) == 0 {
if page > 1 {
b.WriteString("This page is empty. [Back to the first page](" + pageURL(base) + ")\n")
return b.String()
}
b.WriteString("No quests yet.\n")
return b.String()
}
b.WriteString("| # | Quest | Reward | State | " + capital(other) + " |\n|---|---|---|---|---|\n")
for _, id := range ids {
q := mustGet(id)
who := q.Builder()
if !asPoster {
who = q.Poster()
}
whoText := "-"
if who != "" {
whoText = userLink(who, !asPoster)
}
b.WriteString("| " + idStr(id) + " | " + questLink(q) + " | " + gnotStr(q.Reward()) + " GNOT | " + questState(q) + " | " + whoText + " |\n")
}
b.WriteString("\n" + nav)
return b.String()
}
func renderPaid(page int) string {
var b strings.Builder
b.WriteString("# Paid quests\n\n")
b.WriteString("[Board](" + pageURL("") + ")\n\n")
b.WriteString("Every quest below was paid by this realm to its builder: " + plural(paidIDs.Size(), "quest") + ", " + gnotStr(totalPaid) + " GNOT in total.\n\n")
ids, nav := pageOf(&paidIDs, page, "paid")
if paidIDs.Size() == 0 {
b.WriteString("No quest has been paid yet.\n")
return b.String()
}
if len(ids) == 0 {
b.WriteString("This page is empty. [Back to the first page](" + pageURL("paid") + ")\n")
return b.String()
}
b.WriteString("| # | Quest | Reward | Builder | Times rejected |\n|---|---|---|---|---|\n")
for _, id := range ids {
q := mustGet(id)
b.WriteString("| " + idStr(id) + " | " + questLink(q) + " | " + gnotStr(q.Reward()) + " GNOT | " + userLink(q.Builder(), false) + " | " + strconv.Itoa(q.RejectCount()) + " |\n")
}
b.WriteString("\n" + nav)
return b.String()
}
func renderHelp() string {
var b strings.Builder
b.WriteString("# How to use QuestMaster\n\n")
b.WriteString("[Board](" + pageURL("") + ")\n\n")
b.WriteString("> [!NOTE]\n> QuestMaster runs on the **Onyx test network** (`onyx-1`) and uses **test GNOT** from the faucet, not real money.\n\n")
b.WriteString("Every action is a transaction on this realm. Use either:\n\n")
b.WriteString("- **gnoweb**: the action links on each quest page open a form for the function, with the quest number filled in. Sign it with a browser wallet such as Adena, or copy the gnokey command the form shows.\n")
b.WriteString("- **gnokey**: the commands below, already set for Onyx. Replace `KEY` with your key name and `ID` with the quest number.\n\n")
b.WriteString("Only direct calls from a wallet are accepted (not calls from other realms or `maketx run` scripts). Only `PostQuest` takes coins; every other call must send none.\n\n")
b.WriteString(reviewWarning())
b.WriteString("## Post a quest\n\n")
b.WriteString("Send the reward with the call: exactly one coin, in `ugnot`, at least " + gnotStr(MinReward) + " GNOT (1 GNOT = 1000000 ugnot). " +
"Arguments: title (up to " + strconv.Itoa(escrow.MaxTitleLen) + " characters, one line), details (up to " + strconv.Itoa(escrow.MaxDetailsLen) +
" characters), work window in blocks (" + blocksStr(escrow.MinWorkBlocks) + " to " + blocksStr(escrow.MaxWorkBlocks) + "). " +
"Anyone except you can claim your quest while it is open; once it is claimed, closing it (below) stops new claims. " +
"Posting also stores the quest on chain. The chain charges a storage deposit for that, paid by the poster on top of the reward: " +
"about 0.65 to 0.8 GNOT for a new quest at 100 ugnot per byte, the price on Onyx (measured on a local node). It is held by the chain, not by this realm, and is not part of the escrow; when a later call makes the stored data smaller, the chain returns that share to whoever made the call.\n\n")
b.WriteString("With gnoweb, pick a reward: " + postLinks() + ". The form shows the amount and asks you to confirm adding the coins. " +
"For another amount, change `.send=` in the link's address or use gnokey.\n\n")
b.WriteString("```\n" + gnokeyCall("PostQuest", "", "", "5000000ugnot") + "\n```\n\n")
sections := []struct{ title, text, fn, arg string }{
{"Claim a quest", "Anyone except the poster. The work window starts now.", "ClaimQuest", ""},
{"Submit work", "The builder only, until the work deadline. The link must start with `https://`.", "SubmitWork", "https://link-to-your-work"},
{"Approve work", "The poster only. The builder is paid at once.", "ApproveWork", ""},
{"Reject work", "The poster only, until the review deadline. The quest opens again (or, if you closed it, ends with a refund to you); the reason and the reject count are public.", "RejectWork", "What is missing"},
{"Cancel or close a quest", "The poster only. An open quest is cancelled at once and the reward is refunded. A claimed or submitted quest is closed instead: no coins move now, the builder keeps their turn, and the reward goes back to you when that turn ends without approval (the builder unclaims, the work deadline passes and anyone releases it, or you reject the work). Nobody can claim it again. Closing cannot be undone.", "CancelQuest", ""},
{"Unclaim a quest", "The builder only, before submitting. The quest opens again (or, if the poster closed it, ends with a refund to the poster).", "UnclaimQuest", ""},
{"Release a quest", "Anyone, once the work deadline has passed without a submission. The quest opens again (or, if the poster closed it, ends with a refund to the poster).", "ReleaseQuest", ""},
{"Claim a timeout payout", "The builder only, once the review deadline has passed without an answer from the poster.", "ClaimPayout", ""},
}
for _, s := range sections {
b.WriteString("## " + s.title + "\n\n" + s.text + "\n\n```\n" + gnokeyCall(s.fn, "ID", s.arg, "") + "\n```\n\n")
}
b.WriteString("## Reading the board\n\n")
b.WriteString("- `" + pageURL("quest/ID") + "`: one quest\n")
b.WriteString("- `" + pageURL("poster/ADDRESS") + "` and `" + pageURL("builder/ADDRESS") + "`: one address's quests\n")
b.WriteString("- `" + pageURL("paid") + "`: paid quests\n")
b.WriteString("- Lists take `?page=2` and so on, " + strconv.Itoa(PageSize) + " quests per page.\n\n")
b.WriteString(timeNote())
return b.String()
}
func renderNotFound(reason string) string {
return "# Not found\n\n" + reason + "\n\n[Go to the QuestMaster board](" + pageURL("") + ") · [Help](" + pageURL("help") + ")\n"
}
// ---------------------------------------------------------------------------
// Pieces
func questLink(q *escrow.Quest) string {
return "[" + escCell(q.Title()) + "](" + pageURL("quest/"+idStr(q.ID())) + ")"
}
// userLink links an address (always a valid bech32 address from storage or
// a validated path) to its poster or builder page.
func userLink(a address, asPoster bool) string {
page := "builder/"
if asPoster {
page = "poster/"
}
return "[" + shortAddr(a) + "](" + pageURL(page+a.String()) + ")"
}
func shortAddr(a address) string {
s := a.String()
if len(s) <= 14 {
return s
}
return s[:8] + "…" + s[len(s)-4:]
}
func stateText(s escrow.State) string {
switch s {
case escrow.Open:
return "Open"
case escrow.Claimed:
return "Claimed (work in progress)"
case escrow.Submitted:
return "Submitted (waiting for review)"
case escrow.Paid:
return "Paid"
case escrow.Cancelled:
return "Cancelled (refunded)"
}
return "Unknown"
}
// realmPkgPath is this realm's package path, captured once when the realm is
// added. (unsafe.CurrentRealm() inside Render depends on the caller's frame,
// so it is not used there.)
var realmPkgPath string
func init() {
realmPkgPath = unsafe.CurrentRealm().PkgPath()
}
// realmPath is this realm's web path, e.g. "/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/questmaster".
func realmPath() string {
return strings.TrimPrefix(realmPkgPath, runtime.ChainDomain())
}
// txLink builds a gnoweb transaction link for fn on this realm.
func txLink(fn string) *txlink.TxBuilder {
return txlink.Realm(realmPkgPath).NewLink(fn)
}
// pageURL links to one of this realm's pages.
func pageURL(p string) string {
if p == "" {
return realmPath()
}
return realmPath() + ":" + p
}
func postLink() string { return postLinkFor(MinReward) }
func postLinkFor(ugnot int64) string {
return txLink("PostQuest").SetSend(strconv.FormatInt(ugnot, 10) + "ugnot").URL()
}
// postLinks offers PostQuest forms with a few prefilled rewards.
func postLinks() string {
var links []string
for _, n := range []int64{1, 5, 10} {
links = append(links, "["+strconv.FormatInt(n, 10)+" GNOT]("+postLinkFor(n*1_000_000)+")")
}
return strings.Join(links, " · ")
}
// gnokeyCall builds a copy-paste gnokey command. Only realm-chosen text goes
// into it (function names, numbers, fixed example values).
func gnokeyCall(fn, id, arg, send string) string {
cmd := "gnokey maketx call -pkgpath \"" + realmPkgPath + "\" -func \"" + fn + "\""
if fn == "PostQuest" {
cmd += " -args \"Fix a typo in the docs\" -args \"Details of the task\" -args \"20000\""
}
if id != "" {
cmd += " -args \"" + id + "\""
}
if arg != "" {
cmd += " -args \"" + arg + "\""
}
if send != "" {
cmd += " -send \"" + send + "\""
}
return cmd + " -gas-fee 100000ugnot -gas-wanted 10000000 -broadcast -chainid " + chainID + " -remote " + chainRPC + " KEY"
}
// QuestMaster runs on the Onyx test network only; every example command
// targets it.
const (
chainID = "onyx-1"
chainRPC = "https://rpc.onyx.testnets.gno.land:443"
)
// pageOf returns the ids for page (newest first) and prev/next links.
func pageOf(t *avl.Tree, pageNum int, base string) ([]uint64, string) {
total := t.Size()
offset := (pageNum - 1) * PageSize
if offset >= total {
return nil, ""
}
ids := page(t, offset, PageSize)
var nav []string
if pageNum > 1 {
nav = append(nav, "[← Newer]("+pageURL(base)+"?page="+strconv.Itoa(pageNum-1)+")")
}
if offset+PageSize < total {
nav = append(nav, "[Older →]("+pageURL(base)+"?page="+strconv.Itoa(pageNum+1)+")")
}
if len(nav) == 0 {
return ids, ""
}
last := (total + PageSize - 1) / PageSize
return ids, "Page " + strconv.Itoa(pageNum) + " of " + strconv.Itoa(last) + " · " + strings.Join(nav, " · ") + "\n\n"
}
// ---------------------------------------------------------------------------
// Parsing (never panics)
func splitQuery(path string) (string, url.Values) {
i := strings.IndexByte(path, '?')
if i < 0 {
return path, url.Values{}
}
q, err := url.ParseQuery(path[i+1:])
if err != nil {
q = url.Values{}
}
return path[:i], q
}
func pageArg(q url.Values) int {
n, err := strconv.Atoi(q.Get("page"))
if err != nil || n < 1 {
return 1
}
if n > maxPage {
return maxPage
}
return n
}
func parseID(s string) (uint64, bool) {
if s == "" || len(s) > 20 {
return 0, false
}
for _, c := range s {
if c < '0' || c > '9' {
return 0, false
}
}
id, err := strconv.ParseUint(s, 10, 64)
if err != nil || id == 0 || !quests.Has(questKey(id)) {
return 0, false
}
return id, true
}
func parseAddress(s string) (address, bool) {
if len(s) > 100 {
return "", false
}
a := address(s)
if !a.IsValid() {
return "", false
}
return a, true
}
// ---------------------------------------------------------------------------
// Numbers
// gnot formats ugnot as GNOT with up to 6 decimals, without floats.
func gnotStr(ugnot int64) string {
neg := ""
if ugnot < 0 {
neg = "-"
ugnot = -ugnot
}
whole := strconv.FormatInt(ugnot/1_000_000, 10)
frac := ugnot % 1_000_000
if frac == 0 {
return neg + whole
}
f := strconv.FormatInt(frac, 10)
for len(f) < 6 {
f = "0" + f
}
return neg + whole + "." + strings.TrimRight(f, "0")
}
// blocksStr formats a block count or height with thousands separators.
func blocksStr(n int64) string {
s := strconv.FormatInt(n, 10)
if n < 0 {
return s
}
for i := len(s) - 3; i > 0; i -= 3 {
s = s[:i] + "," + s[i:]
}
return s
}
// approx turns a number of blocks into "about N days/hours/minutes", at
// ApproxBlockMillis per block.
func approx(blocks int64) string {
if blocks <= 0 {
return "now"
}
secs := blocks * ApproxBlockMillis / 1000
switch {
case secs >= 2*86400:
return "about " + strconv.FormatInt((secs+43200)/86400, 10) + " days"
case secs >= 2*3600:
return "about " + strconv.FormatInt((secs+1800)/3600, 10) + " hours"
case secs >= 120:
return "about " + strconv.FormatInt((secs+30)/60, 10) + " minutes"
}
return "about a minute"
}
// left describes the time to a deadline block from height h.
func left(deadline, h int64) string {
if h > deadline {
return "passed"
}
return approx(deadline-h+1) + " left"
}
// ApproxBlockMillis is the block time used for the approximate times on the
// pages (measured about 3.4 to 3.5 s on Onyx and mainnet in Nov 2026).
const ApproxBlockMillis = 3500
func timeNote() string {
return "_Times are approximate, at about 3.5 seconds per block; deadlines are exact block heights._\n"
}
func capital(s string) string {
if s == "" {
return s
}
return strings.ToUpper(s[:1]) + s[1:]
}
// plural returns "1 quest" or "N quests".
func plural(n int, word string) string {
if n == 1 {
return "1 " + word
}
return strconv.Itoa(n) + " " + word + "s"
}
render_test.gno
package questmaster
import (
"chain/runtime"
"strings"
"testing"
"gno.land/p/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/escrow"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
const base = "/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/questmaster"
func has(t *testing.T, page, want, what string) {
t.Helper()
if !strings.Contains(page, want) {
t.Fatalf("%s: page does not contain %q\n--- page ---\n%s", what, want, page)
}
}
func hasNot(t *testing.T, page, bad, what string) {
t.Helper()
if strings.Contains(page, bad) {
t.Fatalf("%s: page must not contain %q\n--- page ---\n%s", what, bad, page)
}
}
// renders calls Render and fails the test (instead of crashing) on a panic.
func renders(t *testing.T, path string) string {
t.Helper()
var out string
if r := revive(func() { out = Render(path) }); r != nil {
t.Fatalf("Render(%q) panicked: %v", path, r)
}
return out
}
var allPaths = []string{
"", "?page=2", "help", "paid", "paid?page=2",
"quest/1", "quest/2", "quest/3", "quest/4", "quest/5", "quest/6",
"poster/" + alice.String(), "builder/" + bob.String(), "poster/" + bob.String() + "?page=2",
}
func TestRenderEmptyBoard(cur realm, t *testing.T) {
resetState()
for _, p := range allPaths {
renders(t, p)
}
home := renders(t, "")
has(t, home, "# QuestMaster", "home title")
has(t, home, "| 0 | 0 | 0 | 0 |", "empty totals")
has(t, home, "No open quests right now.", "empty list")
has(t, home, "[Post the first one]("+base+"$help&func=PostQuest&.send=1000000ugnot)", "post link with send")
has(t, renders(t, "paid"), "No quest has been paid yet.", "empty paid")
has(t, renders(t, "poster/"+alice.String()), "No quests yet.", "empty poster")
has(t, renders(t, "quest/1"), "# Not found", "no quest 1 yet")
}
// board builds a board with quests in every state and more than one page of
// open quests. Known numbers:
//
// 1 Paid (approved, 2 GNOT) 2 Paid (timeout, 3 GNOT)
// 3 Cancelled (1.5 GNOT) 4 Claimed by bob
// 5 Submitted by bob 6 Open after one reject
// 7..31 Open (25 quests, 1 GNOT each)
func board(cur realm) {
resetState()
a := submitted(cur, 2*gnot)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
ApproveWork(cross(cur), a)
b := submitted(cur, 3*gnot)
testing.SkipHeights(escrow.ReviewBlocks + 1)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
ClaimPayout(cross(cur), b)
c := post(cur, alice, 1_500_000, "Cancelled quest")
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
CancelQuest(cross(cur), c)
claimed(cur, 4*gnot)
submitted(cur, 5*gnot)
f := submitted(cur, 6*gnot)
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
RejectWork(cross(cur), f, "Please add tests")
for i := 0; i < 25; i++ {
post(cur, carol, gnot, "Small task")
}
}
func TestRenderFullBoard(cur realm, t *testing.T) {
board(cur)
for _, p := range allPaths {
renders(t, p)
}
home := renders(t, "")
// open: 6 + 25 = 26; locked: 4+5+6+25 = 40; paid 2+3 = 5; 2 quests paid
has(t, home, "| 26 | 40 | 5 | 2 |", "totals")
uassert.Equal(t, PageSize, strings.Count(home, "](/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/questmaster:quest/"), "first page holds PageSize quests")
has(t, home, "| 31 | [Small task]("+base+":quest/31) | 1 GNOT | 2,000 (about 117 minutes) | 0 |", "newest first")
has(t, home, "Page 1 of 2 · [Older →]("+base+"?page=2)", "next link")
hasNot(t, home, "Newer", "no prev link on page 1")
p2 := renders(t, "?page=2")
uassert.Equal(t, 6, strings.Count(p2, "](/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/questmaster:quest/"), "second page")
has(t, p2, "| 6 | [claimed quest]("+base+":quest/6) | 6 GNOT | 2,000 (about 117 minutes) | 1 |", "rejected quest shows count")
has(t, p2, "Page 2 of 2 · [← Newer]("+base+"?page=1)", "prev link")
has(t, renders(t, "?page=3"), "This page is empty.", "past the end")
paid := renders(t, "paid")
has(t, paid, "2 quests, 5 GNOT in total", "paid summary")
has(t, paid, "| 2 | [claimed quest]("+base+":quest/2) | 3 GNOT | "+userLink(bob, false)+" | 0 |", "paid row")
poster := renders(t, "poster/"+alice.String())
has(t, poster, "| 3 | [Cancelled quest]("+base+":quest/3) | 1.5 GNOT | Cancelled (refunded) | - |", "cancelled row")
has(t, poster, "| 4 | [claimed quest]("+base+":quest/4) | 4 GNOT | Claimed (work in progress) |", "claimed row")
builder := renders(t, "builder/"+bob.String())
// builder history keeps quest 6 although bob was rejected
has(t, builder, "| 6 | [claimed quest]("+base+":quest/6) | 6 GNOT | Open |", "history row")
has(t, builder, "| 1 | [claimed quest]("+base+":quest/1) | 2 GNOT | Paid |", "paid in history")
has(t, renders(t, "poster/"+carol.String()+"?page=2"), "Page 2 of 2", "poster page 2")
}
func TestRenderQuestStates(cur realm, t *testing.T) {
board(cur)
open := renders(t, "quest/7")
has(t, open, "| State | **Open** |", "open state")
has(t, open, "**Claim**", "claim step")
has(t, open, "[Open in gnoweb]("+base+"$help&func=ClaimQuest&id=7)", "claim link")
has(t, open, "[Open in gnoweb]("+base+"$help&func=CancelQuest&id=7)", "cancel link")
has(t, open, `-pkgpath "gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/questmaster" -func "ClaimQuest" -args "7"`, "gnokey claim")
has(t, open, "-chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 KEY", "onyx pinned")
hasNot(t, open, "ApproveWork", "no approve when open")
claimedPage := renders(t, "quest/4")
has(t, claimedPage, "| State | **Claimed (work in progress)** |", "claimed state")
has(t, claimedPage, "func=SubmitWork&id=4", "submit link")
has(t, claimedPage, "func=UnclaimQuest&id=4", "unclaim link")
hasNot(t, claimedPage, "func=ReleaseQuest", "no release before deadline")
has(t, claimedPage, "anyone can release the quest from block", "release explained")
has(t, claimedPage, "| Work deadline | block ", "work deadline row")
has(t, claimedPage, " left) |", "time left")
sub := renders(t, "quest/5")
has(t, sub, "| State | **Submitted (waiting for review)** |", "submitted")
has(t, sub, "func=ApproveWork&id=5", "approve link")
has(t, sub, "func=RejectWork&id=5", "reject link")
has(t, sub, "| Work | [https://github\\.com/example/repo/pull/1](https://github.com/example/repo/pull/1) |", "work link")
hasNot(t, sub, "func=ClaimPayout", "no payout before deadline")
rejected := renders(t, "quest/6")
has(t, rejected, "## Last reject reason", "reason heading")
has(t, rejected, "> Please add tests ", "reason text")
has(t, rejected, "| Times rejected | 1 |", "reject count")
has(t, renders(t, "quest/1"), "Nothing: this quest is finished and the builder was paid 2 GNOT.", "paid quest")
has(t, renders(t, "quest/3"), "Nothing: this quest was cancelled and the reward went back to the poster", "cancelled quest")
// after the deadlines the late moves appear and the early ones go
testing.SkipHeights(escrow.ReviewBlocks + 1)
late := renders(t, "quest/5")
has(t, late, "func=ClaimPayout&id=5", "payout link after deadline")
hasNot(t, late, "func=RejectWork", "no reject after deadline")
has(t, late, "(passed) |", "deadline passed")
lateClaim := renders(t, "quest/4")
has(t, lateClaim, "func=ReleaseQuest&id=4", "release link after deadline")
hasNot(t, lateClaim, "func=SubmitWork", "no submit after deadline")
}
// User text must never become Markdown structure. These asserts pin the exact
// escaped output for every dangerous character.
func TestRenderInjection(cur realm, t *testing.T) {
resetState()
title := "# A | `c` [x](y)  <script> * _ ) @alice"
details := "Line one\n# not a heading\n- not a list\n| a | b |\n|---|---|\n<script>alert(1)</script>\n [link](https://e.vil)\nsee g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 and @bob\n===\n\n\n indented"
id := postD(cur, alice, gnot, title, details)
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
ClaimQuest(cross(cur), id)
SubmitWork(cross(cur), id, "https://e.vil/a_(b)<c>`d`|e")
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
RejectWork(cross(cur), id, "Bad\n## heading\n[x](https://e.vil) <b>")
// second quest keeps the hostile link visible
id2 := postD(cur, alice, gnot, "Link test", "")
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
ClaimQuest(cross(cur), id2)
SubmitWork(cross(cur), id2, "https://e.vil/a_(b)<c>`d`|e")
escTitle := "\\# A | \\`c\\` \\[x\\]\\(y\\) \\!\\[i\\]\\(z\\) \\<script\\> \\* \\_ \\) \\@alice"
escCellTitle := strings.ReplaceAll(escTitle, "|", "\\|")
q := renders(t, "quest/1")
has(t, q, "# Quest 1: "+escTitle+"\n", "title in heading")
has(t, q, "> Line one \n> \\# not a heading \n> \\- not a list \n> \\| a \\| b \\| \n> \\|\\-\\-\\-\\|\\-\\-\\-\\| \n"+
"> \\<script\\>alert\\(1\\)\\</script\\> \n> \\!\\[img\\]\\(https://e\\.vil/i\\.png\\) \\[link\\]\\(https://e\\.vil\\) \n"+
"> see g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 and \\@bob \n> \\=== \n>\n> indented \n", "details block")
has(t, q, "> Bad \n> \\#\\# heading \n> \\[x\\]\\(https://e\\.vil\\) \\<b\\> \n", "reason block")
home := renders(t, "")
has(t, renders(t, "poster/"+alice.String()), "| 2 | [Link test]("+base+":quest/2) |", "plain title")
has(t, home, "| 1 | ["+escCellTitle+"]("+base+":quest/1) |", "title in table cell")
q2 := renders(t, "quest/2")
// ( ) < > ` | are percent-encoded in the target; the visible text is the
// escaped URL itself
has(t, q2, "| Work | [https://e\\.vil/a\\_\\(b\\)\\<c\\>\\`d\\`\\|e](https://e.vil/a_%28b%29%3Cc%3E%60d%60%7Ce) |", "hostile link made safe")
hasNot(t, q2, "](https://e.vil/a_(", "no raw parenthesis in a link target")
has(t, q2, "_No details given._", "empty details")
for _, page := range []string{q, q2, home} {
hasNot(t, page, "<script>", "raw script tag")
hasNot(t, page, "![", "unescaped image")
hasNot(t, page, "\n# ", "stray heading")
hasNot(t, page, " @alice", "raw mention")
hasNot(t, page, " g1jg8m", "raw address mention")
}
}
func TestRenderBadPaths(cur realm, t *testing.T) {
board(cur)
bad := []string{
"nope", "quest", "quest/", "quest/abc", "quest/0", "quest/999", "quest/-1", "quest/1/2", "quest/+1",
"quest/99999999999999999999999", "quest/1e3", "poster/", "poster/notanaddress",
"poster/g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf6", "builder/<script>", "builder/" + strings.Repeat("g", 500),
"paid/x", "HELP", "../quest/1", "quest/1#x", "%00", "quest/1\n# injected",
}
for _, p := range bad {
out := renders(t, p)
has(t, out, "# Not found", "bad path "+p)
has(t, out, "[Go to the QuestMaster board]("+base+")", "home link "+p)
hasNot(t, out, "script", "path not echoed "+p)
hasNot(t, out, "injected", "path not echoed "+p)
}
// bad page numbers fall back to page 1 or an empty page, never a panic
for _, p := range []string{"?page=-5", "?page=0", "?page=abc", "?page=", "?page=1.5", "?%zz", "?page=99999999999999999999"} {
has(t, renders(t, p), "Page 1 of 2", "page fallback "+p)
}
for _, p := range []string{"?page=1000000", "?page=999999999", "paid?page=999", "poster/" + carol.String() + "?page=50"} {
has(t, renders(t, p), "This page is empty.", "huge page "+p)
}
// a valid address with no quests
has(t, renders(t, "builder/"+testutils.TestAddress("nobody").String()), "No quests yet.", "unknown user")
// query on a quest page is ignored
has(t, renders(t, "quest/1?page=2"), "# Quest 1:", "quest with query")
}
func TestRenderHelp(cur realm, t *testing.T) {
resetState()
h := renders(t, "help")
has(t, h, "**Onyx test network** (`onyx-1`)", "testnet note")
has(t, h, "test GNOT", "test GNOT")
for _, fn := range []string{"PostQuest", "ClaimQuest", "SubmitWork", "ApproveWork", "RejectWork", "CancelQuest", "UnclaimQuest", "ReleaseQuest", "ClaimPayout"} {
has(t, h, `-func "`+fn+`"`, "command for "+fn)
}
has(t, h, `-func "PostQuest" -args "Fix a typo in the docs" -args "Details of the task" -args "20000" -send "5000000ugnot"`, "post with send")
hasNot(t, h, "gnoland-1", "no mainnet")
hasNot(t, h, "rpc.gno.land", "no mainnet rpc")
hasNot(t, h, "rpc.latest", "no moving alias")
uassert.Equal(t, 9, strings.Count(h, "-chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 KEY"), "every command pinned to Onyx")
}
func TestFormatHelpers(t *testing.T) {
cases := map[int64]string{0: "0", 1: "0.000001", 10: "0.00001", 1_000_000: "1", 1_500_000: "1.5", 123_456_789: "123.456789", 5_250_000: "5.25", -2_500_000: "-2.5"}
for in, want := range cases {
uassert.Equal(t, want, gnotStr(in))
}
uassert.Equal(t, "0", blocksStr(0))
uassert.Equal(t, "999", blocksStr(999))
uassert.Equal(t, "1,000", blocksStr(1000))
uassert.Equal(t, "2,200,000", blocksStr(2_200_000))
uassert.Equal(t, "now", approx(0))
uassert.Equal(t, "about a minute", approx(10))
uassert.Equal(t, "about 58 minutes", approx(1_000))
uassert.Equal(t, "about 3 days", approx(75_000))
uassert.Equal(t, "about 7 days", approx(escrow.ReviewBlocks))
uassert.Equal(t, "about 89 days", approx(2_200_000))
uassert.Equal(t, "passed", left(10, 11))
uassert.Equal(t, "about a minute left", left(10, 10))
}
func TestRenderClosing(cur realm, t *testing.T) {
resetState()
cl := claimed(cur, 2*gnot)
sub := submitted(cur, 3*gnot)
// before closing: the poster sees "Close quest" on claimed and submitted quests
has(t, renders(t, "quest/1"), "**Close quest**", "close offered on claimed")
has(t, renders(t, "quest/2"), "**Close quest**", "close offered on submitted")
has(t, renders(t, "quest/1"), "func=CancelQuest&id=1", "close link")
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
CancelQuest(cross(cur), cl)
CancelQuest(cross(cur), sub)
c := renders(t, "quest/1")
has(t, c, "| State | **Claimed (work in progress), closing** |", "closing state")
has(t, c, "> **Closing**: the reward returns to the poster when the current builder's turn ends, unless the work is approved.", "closing note")
has(t, c, "It is closing, so it ends and the reward goes back to the poster.", "unclaim text while closing")
has(t, c, "anyone can end the quest from block", "release text while closing")
hasNot(t, c, "**Close quest**", "no second close")
s := renders(t, "quest/2")
has(t, s, "The quest is closing, so it ends and the reward goes back to the poster.", "reject text while closing")
hasNot(t, s, "**Close quest**", "no second close")
has(t, renders(t, "poster/"+alice.String()), "Claimed (work in progress), closing", "closing mark in table")
has(t, renders(t, ""), "No open quests right now.", "closing quests are not open")
testing.SkipHeights(GetQuest(cl).WorkDeadline - runtime.ChainHeight() + 1)
has(t, renders(t, "quest/1"), "so anyone can end the quest; the reward goes back to the poster.", "release while closing")
}
func TestRenderReviewWarningAndFooter(cur realm, t *testing.T) {
board(cur)
warn := "**Posters: check your quest.** If you do not approve or reject a submission within the review window (about 7 days), the builder is paid automatically."
has(t, renders(t, ""), warn, "warning on home")
has(t, renders(t, "help"), warn, "warning on help")
has(t, renders(t, "help"), "Anyone except you can claim your quest while it is open; once it is claimed, closing it (below) stops new claims.", "claim note on help")
foot := "\n---\n\nBuilt on [gno.land](https://gno.land) · [source](https://github.com/elangrr/questmaster)\n"
for _, p := range append(allPaths, "nope", "quest/999") {
out := renders(t, p)
if !strings.HasSuffix(out, foot) {
t.Fatalf("page %q does not end with the footer", p)
}
}
}
// Math ($...$) and mention links at the start of user text are neutralised.
func TestRenderMathAndLeadingAddress(cur realm, t *testing.T) {
resetState()
addr := "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"
id := postD(cur, alice, gnot, addr+" pays $x$", "$$y$$ and $z$\n"+addr+" line two")
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
ClaimQuest(cross(cur), id)
SubmitWork(cross(cur), id, "https://e.vil/$x$")
testing.SetRealm(testing.NewUserRealm(alice))
testing.SetOriginSend(nil)
RejectWork(cross(cur), id, addr+" no $$m$$")
id2 := postD(cur, alice, gnot, "Link with dollars", "")
testing.SetRealm(testing.NewUserRealm(bob))
testing.SetOriginSend(nil)
ClaimQuest(cross(cur), id2)
SubmitWork(cross(cur), id2, "https://e.vil/$x$")
q := renders(t, "quest/1")
has(t, q, "# Quest 1: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 pays \\$x\\$\n", "title in heading")
has(t, q, "> \\$\\$y\\$\\$ and \\$z\\$ \n> g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 line two \n", "details lines")
has(t, q, "> g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 no \\$\\$m\\$\\$ \n", "reason line")
has(t, renders(t, "poster/"+alice.String()), "| 1 | [g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 pays \\$x\\$]("+base+":quest/1) |", "title in a table cell")
has(t, renders(t, "quest/2"), "| Work | [https://e\\.vil/\\$x\\$](https://e.vil/$x$) |", "dollar in the link text")
for _, p := range []string{q, renders(t, "quest/2")} {
hasNot(t, p, " "+addr, "raw address after a space")
hasNot(t, p, " $", "raw dollar after a space")
}
}