Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

questmaster.gno

16.11 Kb · 490 lines
  1// Package questmaster is a GNOT bounty board. A poster locks GNOT on a quest,
  2// a builder takes it and submits a link to the work, and the poster approves
  3// (paying the builder) or rejects (reopening the quest). If the poster stays
  4// silent past the review window (about 7 days), the builder can claim the
  5// payout. A poster can cancel an open quest for a refund, or close a claimed
  6// or submitted one: the builder keeps their turn, and if it ends without
  7// approval the reward goes back to the poster.
  8//
  9// The rules live in the pure package p/escrow. This realm stores quests,
 10// holds the coins and moves them only as an escrow move tells it to.
 11//
 12// Callers (v1): every state-changing function accepts only a direct user call
 13// (`gnokey maketx call`, i.e. cur.Previous().IsUserCall()). Calls from other
 14// realms and from `maketx run` scripts are refused. This is what makes the
 15// unsafe.OriginSend() checks sound: for a direct user call, the coins sent with
 16// the call are guaranteed to have landed in this realm. Realm or DAO callers
 17// may be supported in a later version.
 18//
 19// There is no admin, owner, pause, upgrade or sweep function. Nobody can move
 20// escrowed coins except through the quest moves below.
 21//
 22// Coins sent straight to the realm address with a bank send (not through
 23// PostQuest) are not tracked by any quest and cannot be moved by anyone, so
 24// they are lost. On chain the guarantee is therefore: realm balance >= the
 25// locked total, with equality when nobody sends coins outside PostQuest. The
 26// pages and GetTotals use only the tracked numbers, never the balance.
 27//
 28// Nothing here hands out a pointer to stored state: read functions return
 29// plain values (QuestView, Totals, []uint64, strings).
 30package questmaster
 31
 32import (
 33	"chain"
 34	"chain/banker"
 35	"chain/runtime"
 36	"chain/runtime/unsafe"
 37	"strconv"
 38
 39	"gno.land/p/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/escrow"
 40	"gno.land/p/nt/avl/v0"
 41)
 42
 43const (
 44	// Denom is the only coin a quest reward can be paid in.
 45	Denom = "ugnot"
 46	// MinReward is the smallest reward a quest can lock: 1 GNOT.
 47	MinReward int64 = 1_000_000
 48	// MaxPageSize caps how many ids one list call returns.
 49	MaxPageSize = 50
 50)
 51
 52// Panic messages for the realm's own checks. Escrow rule violations panic
 53// with the escrow error's text (prefix "escrow: ").
 54const (
 55	ErrNotUserCall   = "questmaster: only direct user calls (gnokey maketx call) are accepted"
 56	ErrNoCoins       = "questmaster: send the reward in ugnot with the call"
 57	ErrSeveralCoins  = "questmaster: send exactly one coin (ugnot)"
 58	ErrWrongDenom    = "questmaster: the reward must be in ugnot"
 59	ErrRewardTooLow  = "questmaster: the reward is below the minimum of 1 GNOT (1000000ugnot)"
 60	ErrCoinsNotTaken = "questmaster: this function does not take coins; send none"
 61	ErrUnknownQuest  = "questmaster: unknown quest id"
 62)
 63
 64var (
 65	quests    avl.Tree // questKey(id) -> *escrow.Quest
 66	byPoster  avl.Tree // poster address -> *avl.Tree of questKey(id) -> true
 67	byBuilder avl.Tree // builder address -> *avl.Tree of questKey(id) -> true
 68	openIDs   avl.Tree // questKey(id) -> true, quests in state Open
 69	paidIDs   avl.Tree // questKey(id) -> true, quests in state Paid
 70
 71	lastID uint64
 72
 73	totalPosted   int64 // ugnot ever locked by PostQuest
 74	totalLocked   int64 // ugnot held for quests that are Open, Claimed or Submitted
 75	totalPaid     int64 // ugnot paid to builders
 76	totalRefunded int64 // ugnot refunded to posters
 77)
 78
 79// ---------------------------------------------------------------------------
 80// State-changing functions
 81
 82// PostQuest creates a quest. Send the reward with the call as exactly one coin
 83// of ugnot, at least MinReward. workBlocks is the builder's work window in
 84// blocks (escrow.MinWorkBlocks to escrow.MaxWorkBlocks). Returns the new id.
 85func PostQuest(cur realm, title, details string, workBlocks int64) uint64 {
 86	poster := requireUserCall(cur)
 87	reward := requireReward()
 88
 89	id := lastID + 1
 90	q, err := escrow.NewQuest(id, poster, title, details, reward, workBlocks, runtime.ChainHeight())
 91	if err != nil {
 92		panic(err.Error())
 93	}
 94	lastID = id
 95	key := questKey(id)
 96	quests.Set(key, q)
 97	addToIndex(&byPoster, poster, key)
 98	openIDs.Set(key, true)
 99	totalPosted += reward
100	totalLocked += reward
101
102	chain.Emit("QuestPosted", "id", idStr(id), "actor", poster.String(), "amount", amountStr(reward))
103	return id
104}
105
106// ClaimQuest takes an Open quest. The poster cannot claim their own quest.
107func ClaimQuest(cur realm, id uint64) {
108	actor := requireUserCall(cur)
109	requireNoCoins()
110	q := mustGet(id)
111	check(q.Claim(actor, runtime.ChainHeight()))
112
113	key := questKey(id)
114	openIDs.Remove(key)
115	addToIndex(&byBuilder, actor, key)
116
117	chain.Emit("QuestClaimed", "id", idStr(id), "actor", actor.String())
118}
119
120// UnclaimQuest lets the builder give a Claimed quest back. It opens again, or,
121// if the poster closed it, ends with a refund to the poster.
122func UnclaimQuest(cur realm, id uint64) {
123	actor := requireUserCall(cur)
124	requireNoCoins()
125	q := mustGet(id)
126	p, err := q.Unclaim(actor, runtime.ChainHeight())
127	check(err)
128
129	chain.Emit("QuestUnclaimed", "id", idStr(id), "actor", actor.String())
130	endTurn(id, p, actor, "unclaimed", cur)
131}
132
133// ReleaseQuest ends the builder's turn on a Claimed quest whose work deadline
134// has passed. Anyone may call it. The quest opens again, or, if the poster
135// closed it, ends with a refund to the poster.
136func ReleaseQuest(cur realm, id uint64) {
137	actor := requireUserCall(cur)
138	requireNoCoins()
139	q := mustGet(id)
140	p, err := q.Release(actor, runtime.ChainHeight())
141	check(err)
142
143	chain.Emit("QuestReleased", "id", idStr(id), "actor", actor.String())
144	endTurn(id, p, actor, "released", cur)
145}
146
147// SubmitWork sends the link to the work (must start with https://). Only the
148// builder, up to and including the work deadline block.
149func SubmitWork(cur realm, id uint64, link string) {
150	actor := requireUserCall(cur)
151	requireNoCoins()
152	q := mustGet(id)
153	check(q.Submit(actor, link, runtime.ChainHeight()))
154
155	chain.Emit("WorkSubmitted", "id", idStr(id), "actor", actor.String())
156}
157
158// ApproveWork accepts the submitted work and pays the reward to the builder.
159// Only the poster.
160func ApproveWork(cur realm, id uint64) {
161	actor := requireUserCall(cur)
162	requireNoCoins()
163	q := mustGet(id)
164	p, err := q.Approve(actor, runtime.ChainHeight())
165	check(err)
166
167	settlePaid(id, p)
168	chain.Emit("QuestPaid", "id", idStr(id), "actor", actor.String(), "to", p.To.String(), "amount", amountStr(p.Amount), "how", "approved")
169	send(p, cur)
170}
171
172// RejectWork refuses the submitted work with a reason. Its public reject count
173// goes up. The quest opens again, or, if the poster closed it, ends with a
174// refund to the poster. Only the poster, up to and including the review
175// deadline block.
176func RejectWork(cur realm, id uint64, reason string) {
177	actor := requireUserCall(cur)
178	requireNoCoins()
179	q := mustGet(id)
180	builder := q.Builder()
181	p, err := q.Reject(actor, reason, runtime.ChainHeight())
182	check(err)
183
184	chain.Emit("WorkRejected", "id", idStr(id), "actor", actor.String(), "builder", builder.String())
185	endTurn(id, p, actor, "rejected", cur)
186}
187
188// CancelQuest is the poster's way out. Only the poster.
189//   - Open quest: it ends at once and the reward is refunded.
190//   - Claimed or Submitted quest: it is marked as closing and no coins move.
191//     The builder keeps their turn (submit, approval, timeout payout); when
192//     the turn ends without approval (unclaim, release after the work
193//     deadline, or reject), the quest ends and the reward goes back to the
194//     poster instead of the quest opening again.
195func CancelQuest(cur realm, id uint64) {
196	actor := requireUserCall(cur)
197	requireNoCoins()
198	q := mustGet(id)
199	p, err := q.Cancel(actor, runtime.ChainHeight())
200	check(err)
201
202	if !p.Due() {
203		chain.Emit("QuestClosing", "id", idStr(id), "actor", actor.String())
204		return
205	}
206	openIDs.Remove(questKey(id))
207	settleRefund(id, p, actor, "open", cur)
208}
209
210// endTurn finishes Unclaim, Release and Reject: the quest opens again, or a
211// closing quest ends with the refund p.
212func endTurn(id uint64, p escrow.Payout, actor address, how string, rlm realm) {
213	if !p.Due() {
214		openIDs.Set(questKey(id), true)
215		return
216	}
217	settleRefund(id, p, actor, how, rlm)
218}
219
220// settleRefund updates totals, emits QuestCancelled and sends the refund
221// last. The quest is already Cancelled (final) when it is called.
222func settleRefund(id uint64, p escrow.Payout, actor address, how string, rlm realm) {
223	if p.Kind != escrow.RefundPoster {
224		panic("questmaster: internal error: unexpected payout kind")
225	}
226	totalLocked -= p.Amount
227	totalRefunded += p.Amount
228	chain.Emit("QuestCancelled", "id", idStr(id), "actor", actor.String(), "to", p.To.String(), "amount", amountStr(p.Amount), "how", how)
229	send(p, rlm)
230}
231
232// ClaimPayout pays the builder when the poster has not answered within the
233// review window. Only the builder, from the block after the review deadline.
234func ClaimPayout(cur realm, id uint64) {
235	actor := requireUserCall(cur)
236	requireNoCoins()
237	q := mustGet(id)
238	p, err := q.ClaimPayout(actor, runtime.ChainHeight())
239	check(err)
240
241	settlePaid(id, p)
242	chain.Emit("QuestPaid", "id", idStr(id), "actor", actor.String(), "to", p.To.String(), "amount", amountStr(p.Amount), "how", "timeout")
243	send(p, cur)
244}
245
246// ---------------------------------------------------------------------------
247// Read functions. All return plain values.
248
249// QuestView is a read-only copy of one quest at the current block.
250type QuestView struct {
251	ID               uint64
252	Poster           address
253	Title            string
254	Details          string
255	Reward           int64 // ugnot
256	State            escrow.State
257	Builder          address
258	WorkLink         string
259	WorkBlocks       int64
260	CreatedAt        int64
261	ClaimedAt        int64
262	SubmittedAt      int64
263	WorkDeadline     int64 // last block to submit; 0 unless Claimed or Submitted
264	ReviewDeadline   int64 // last block to reject; 0 unless Submitted
265	RejectCount      int
266	LastRejectReason string
267	Closing          bool // the poster closed it; the reward returns when the builder's turn ends without approval
268	CanRelease       bool // ReleaseQuest would succeed now
269	CanClaimPayout   bool // the builder could call ClaimPayout now
270}
271
272// GetQuest returns a copy of quest id. It panics on an unknown id.
273func GetQuest(id uint64) QuestView {
274	q := mustGet(id)
275	h := runtime.ChainHeight()
276	return QuestView{
277		ID:               q.ID(),
278		Poster:           q.Poster(),
279		Title:            q.Title(),
280		Details:          q.Details(),
281		Reward:           q.Reward(),
282		State:            q.State(),
283		Builder:          q.Builder(),
284		WorkLink:         q.WorkLink(),
285		WorkBlocks:       q.WorkBlocks(),
286		CreatedAt:        q.CreatedAt(),
287		ClaimedAt:        q.ClaimedAt(),
288		SubmittedAt:      q.SubmittedAt(),
289		WorkDeadline:     q.WorkDeadline(),
290		ReviewDeadline:   q.ReviewDeadline(),
291		RejectCount:      q.RejectCount(),
292		LastRejectReason: q.LastRejectReason(),
293		Closing:          q.Closing(),
294		CanRelease:       q.CanRelease(h),
295		CanClaimPayout:   q.CanClaimPayout(h),
296	}
297}
298
299// Totals are the board-wide running sums, in ugnot.
300type Totals struct {
301	Quests     uint64 // quests ever posted
302	OpenQuests int    // quests in state Open
303	Posted     int64  // ugnot ever locked
304	Locked     int64  // ugnot held now for Open, Claimed and Submitted quests
305	Paid       int64  // ugnot paid to builders
306	Refunded   int64  // ugnot refunded to posters
307	PaidQuests int    // quests in state Paid
308}
309
310// GetTotals returns the running totals. Posted == Locked + Paid + Refunded.
311func GetTotals() Totals {
312	return Totals{
313		Quests:     lastID,
314		OpenQuests: openIDs.Size(),
315		Posted:     totalPosted,
316		Locked:     totalLocked,
317		Paid:       totalPaid,
318		Refunded:   totalRefunded,
319		PaidQuests: paidIDs.Size(),
320	}
321}
322
323// OpenQuestIDs lists ids of Open quests, newest first. offset skips that many;
324// at most MaxPageSize ids are returned whatever limit is.
325func OpenQuestIDs(offset, limit int) []uint64 {
326	return page(&openIDs, offset, limit)
327}
328
329// PaidQuestIDs lists ids of Paid quests, newest first (by quest id).
330func PaidQuestIDs(offset, limit int) []uint64 {
331	return page(&paidIDs, offset, limit)
332}
333
334// AllQuestIDs lists ids of all quests, newest first.
335func AllQuestIDs(offset, limit int) []uint64 {
336	return page(&quests, offset, limit)
337}
338
339// QuestIDsByPoster lists ids of quests posted by addr, newest first.
340func QuestIDsByPoster(addr address, offset, limit int) []uint64 {
341	return indexPage(&byPoster, addr, offset, limit)
342}
343
344// QuestIDsByBuilder lists ids of quests addr has ever claimed, newest first.
345// It is a history: a quest stays listed after the builder unclaims it, is
346// released or is rejected, even if someone else builds it later. Use
347// GetQuest(id).Builder for the current builder.
348func QuestIDsByBuilder(addr address, offset, limit int) []uint64 {
349	return indexPage(&byBuilder, addr, offset, limit)
350}
351
352// CountByPoster returns how many quests addr has posted.
353func CountByPoster(addr address) int { return indexSize(&byPoster, addr) }
354
355// CountByBuilder returns how many quests addr has ever claimed.
356func CountByBuilder(addr address) int { return indexSize(&byBuilder, addr) }
357
358// ---------------------------------------------------------------------------
359// Internal helpers
360
361// requireUserCall refuses anything but a direct user call and returns the
362// caller's address. See the package doc for why.
363func requireUserCall(cur realm) address {
364	prev := cur.Previous()
365	if !prev.IsUserCall() {
366		panic(ErrNotUserCall)
367	}
368	return prev.Address()
369}
370
371// requireReward checks the coins sent with PostQuest (rules 1 and 2) and
372// returns the amount. Valid only together with requireUserCall.
373func requireReward() int64 {
374	sent := unsafe.OriginSend()
375	if len(sent) == 0 {
376		panic(ErrNoCoins)
377	}
378	if len(sent) > 1 {
379		panic(ErrSeveralCoins)
380	}
381	if sent[0].Denom != Denom {
382		panic(ErrWrongDenom)
383	}
384	if sent[0].Amount < MinReward {
385		panic(ErrRewardTooLow)
386	}
387	return sent[0].Amount
388}
389
390// requireNoCoins refuses coins sent to a function that does not take any
391// (rule 3), so nothing gets stuck in the realm.
392func requireNoCoins() {
393	if len(unsafe.OriginSend()) != 0 {
394		panic(ErrCoinsNotTaken)
395	}
396}
397
398func mustGet(id uint64) *escrow.Quest {
399	v := quests.Get(questKey(id))
400	if v == nil {
401		panic(ErrUnknownQuest)
402	}
403	return v.(*escrow.Quest)
404}
405
406func check(err error) {
407	if err != nil {
408		panic(err.Error())
409	}
410}
411
412// settlePaid updates storage and totals for a PayBuilder payout.
413func settlePaid(id uint64, p escrow.Payout) {
414	if p.Kind != escrow.PayBuilder {
415		panic("questmaster: internal error: unexpected payout kind")
416	}
417	paidIDs.Set(questKey(id), true)
418	totalLocked -= p.Amount
419	totalPaid += p.Amount
420}
421
422// send moves exactly p.Amount ugnot from this realm to p.To. It is called last,
423// after every state change (rule 4), and never sends the realm's balance
424// (rule 5).
425func send(p escrow.Payout, rlm realm) {
426	if p.Amount <= 0 || !p.To.IsValid() {
427		panic("questmaster: internal error: invalid payout")
428	}
429	b := banker.NewBanker(banker.BankerTypeRealmSend, rlm)
430	b.SendCoins(rlm.Address(), p.To, chain.Coins{{Denom: Denom, Amount: p.Amount}})
431}
432
433// questKey zero-pads id so the avl order is numeric order.
434func questKey(id uint64) string {
435	s := strconv.FormatUint(id, 10)
436	for len(s) < 20 {
437		s = "0" + s
438	}
439	return s
440}
441
442func idStr(id uint64) string       { return strconv.FormatUint(id, 10) }
443func amountStr(ugnot int64) string { return strconv.FormatInt(ugnot, 10) }
444
445func addToIndex(idx *avl.Tree, addr address, key string) {
446	var ids *avl.Tree
447	if v := idx.Get(addr.String()); v != nil {
448		ids = v.(*avl.Tree)
449	} else {
450		ids = avl.NewTree()
451		idx.Set(addr.String(), ids)
452	}
453	ids.Set(key, true)
454}
455
456func indexSize(idx *avl.Tree, addr address) int {
457	v := idx.Get(addr.String())
458	if v == nil {
459		return 0
460	}
461	return v.(*avl.Tree).Size()
462}
463
464func indexPage(idx *avl.Tree, addr address, offset, limit int) []uint64 {
465	v := idx.Get(addr.String())
466	if v == nil {
467		return []uint64{}
468	}
469	return page(v.(*avl.Tree), offset, limit)
470}
471
472// page returns up to min(limit, MaxPageSize) ids from t, newest first.
473func page(t *avl.Tree, offset, limit int) []uint64 {
474	if offset < 0 {
475		offset = 0
476	}
477	if limit <= 0 || limit > MaxPageSize {
478		limit = MaxPageSize
479	}
480	ids := []uint64{}
481	t.ReverseIterateByOffset(offset, limit, func(key string, _ any) bool {
482		id, err := strconv.ParseUint(key, 10, 64)
483		if err != nil {
484			panic("questmaster: internal error: bad key")
485		}
486		ids = append(ids, id)
487		return false
488	})
489	return ids
490}