gild.gno
12.28 Kb · 452 lines
1// Package gild is a paid task board.
2//
3// A poster locks a reward in this realm when posting a task. One doer takes
4// the task and sends a link to the work. The poster approves and the realm
5// pays the doer. Two rules protect both sides:
6//
7// - If the poster stays silent for ReviewWindow after the work is sent,
8// the doer can claim the reward.
9// - If nobody takes the task, or the doer never sends work before the
10// deadline, the poster gets the reward back.
11//
12// Every payout is written to a public work record (see p/thesithunyein/rep),
13// which other realms can read through Completed and Earned.
14//
15// v1 adds two things the record makes possible:
16//
17// - Experience-gated tasks: a poster can require that the doer already
18// finished at least MinDone paid tasks on Gild.
19// - Direct hires: a poster can offer a task to one person only.
20//
21// The record counts work from both boards, so history from gild/v0 carries
22// over without being copied.
23package gild
24
25import (
26 "chain"
27 "chain/banker"
28 "chain/runtime/unsafe"
29 "strconv"
30 "strings"
31 "time"
32
33 "gno.land/p/nt/avl/v0"
34 "gno.land/p/nt/seqid/v0"
35 "gno.land/p/g1jw2yrfqnd4fp90qadw88pnjgpden4vgagjvpe6/rep/v0"
36 legacy "gno.land/r/g1jw2yrfqnd4fp90qadw88pnjgpden4vgagjvpe6/gild/v0"
37)
38
39// Rules. They are constants so anyone can read them in the source.
40const (
41 Denom = "ugnot"
42 MinReward int64 = 1_000_000 // 1 GNOT
43 MaxReward int64 = 1_000_000_000_000_000 // 1 billion GNOT, a sanity cap
44 ReviewWindow = 7 * 24 * time.Hour // poster's time to answer sent work
45 ChangesExtension = 3 * 24 * time.Hour // minimum time a doer gets after changes are asked
46 MinDeadline = time.Hour
47 MaxDeadline = 90 * 24 * time.Hour
48
49 MinTitle = 3
50 MaxTitle = 120
51 MaxDetails = 4000
52 MaxDone = 1000
53 MaxURL = 300
54 MaxNote = 1000
55 MaxPage = 50
56 MaxMinDone = 100 // the highest experience a task can require
57)
58
59// Status is where a task is in its life.
60type Status int
61
62const (
63 StatusOpen Status = iota // reward locked, waiting for a doer
64 StatusTaken // a doer is working on it
65 StatusInReview // work sent, waiting for the poster
66 StatusPaid // reward paid to the doer
67 StatusRefunded // reward returned to the poster
68)
69
70func (s Status) String() string {
71 switch s {
72 case StatusOpen:
73 return "open"
74 case StatusTaken:
75 return "taken"
76 case StatusInReview:
77 return "in_review"
78 case StatusPaid:
79 return "paid"
80 case StatusRefunded:
81 return "refunded"
82 }
83 return "unknown"
84}
85
86// Categories a task can have.
87var categories = []string{"code", "docs", "design", "testing", "translation", "other"}
88
89// Task is one posted piece of work.
90type Task struct {
91 ID seqid.ID
92 Title string
93 Details string
94 Done string // what "done" looks like
95 Category string
96 Poster address
97 Doer address
98 Reward int64 // in Denom
99 Status Status
100
101 CreatedAt time.Time
102 Deadline time.Time // a doer must send work before this
103 TakenAt time.Time
104 SubmittedAt time.Time
105 ClosedAt time.Time
106
107 MinDone int // paid Gild tasks the doer must already have; 0 means anyone
108 Invite address // if set, only this address can take the task
109
110 WorkURL string
111 ChangesAsked bool
112 ChangesNote string
113 PaidBy string // "approval" or "silence" once paid
114}
115
116var (
117 tasks avl.Tree // id key -> *Task, every task
118 openTasks avl.Tree // id key -> *Task, only open tasks
119 byPoster avl.Tree // address -> *avl.Tree of id key -> *Task
120 byDoer avl.Tree // address -> *avl.Tree of id key -> *Task
121 byInvite avl.Tree // address -> *avl.Tree of id key -> *Task, direct offers
122 nextID seqid.ID
123 book = rep.NewBook(20)
124
125 lockedTotal int64 // rewards currently held by this realm
126 paidTotal int64 // rewards paid to doers
127
128 webPath string // this realm's gnoweb path, e.g. "/r/thesithunyein/gild/v1"
129)
130
131func init(cur realm) {
132 webPath = strings.TrimPrefix(cur.PkgPath(), "gno.land")
133}
134
135// Post creates a task and locks the coins sent with the call as its reward.
136// It must be called directly by a user (maketx call) with exactly one coin of
137// Denom attached. deadline is a Unix time in seconds.
138//
139// minDone is how many paid Gild tasks a doer must already have (0 = anyone).
140// invite is an address the task is offered to, or "" for an open task.
141func Post(cur realm, title, details, done, category string, deadline int64, minDone int, invite string) int64 {
142 prev := cur.Previous()
143 if !prev.IsUserCall() {
144 panic(ErrUserCallOnly)
145 }
146 reward := rewardFrom(unsafe.OriginSend())
147
148 title = trimSpace(title)
149 details = trimSpace(details)
150 done = trimSpace(done)
151 checkText(title, MinTitle, MaxTitle, ErrTitle)
152 checkText(details, 0, MaxDetails, ErrDetails)
153 checkText(done, 0, MaxDone, ErrDone)
154 if !isCategory(category) {
155 panic(ErrCategory)
156 }
157
158 if minDone < 0 || minDone > MaxMinDone {
159 panic(ErrMinDone)
160 }
161 var inv address
162 if invite = trimSpace(invite); invite != "" {
163 inv = address(invite)
164 if !inv.IsValid() {
165 panic(ErrInvite)
166 }
167 if inv == prev.Address() {
168 panic(ErrInviteSelf)
169 }
170 }
171
172 now := time.Now()
173 dl := time.Unix(deadline, 0)
174 if dl.Before(now.Add(MinDeadline)) || dl.After(now.Add(MaxDeadline)) {
175 panic(ErrDeadline)
176 }
177
178 t := &Task{
179 ID: nextID.Next(),
180 Title: title,
181 Details: details,
182 Done: done,
183 Category: category,
184 Poster: prev.Address(),
185 Reward: reward,
186 Status: StatusOpen,
187 CreatedAt: now,
188 Deadline: dl,
189 MinDone: minDone,
190 Invite: inv,
191 }
192 key := t.ID.Binary()
193 tasks.Set(key, t)
194 openTasks.Set(key, t)
195 index(&byPoster, t.Poster, key, t)
196 if inv != "" {
197 index(&byInvite, inv, key, t)
198 }
199 lockedTotal += reward
200 return int64(t.ID)
201}
202
203// Take assigns an open task to the caller. The poster cannot take their own
204// task, and nobody can take a task after its deadline. A direct offer can only
205// be taken by the invited address, and a gated task only by someone whose
206// record meets its MinDone.
207func Take(cur realm, id int64) {
208 caller := cur.Previous().Address()
209 t := mustGet(id)
210 if t.Status != StatusOpen {
211 panic(ErrNotOpen)
212 }
213 if caller == t.Poster {
214 panic(ErrOwnTask)
215 }
216 now := time.Now()
217 if !now.Before(t.Deadline) {
218 panic(ErrPastDeadline)
219 }
220 if t.Invite != "" && caller != t.Invite {
221 panic(ErrInviteOnly)
222 }
223 if t.MinDone > 0 && !HasCompleted(caller, t.MinDone) {
224 panic(ErrNeedRecord)
225 }
226 t.Doer = caller
227 t.Status = StatusTaken
228 t.TakenAt = now
229 key := t.ID.Binary()
230 openTasks.Remove(key)
231 index(&byDoer, caller, key, t)
232}
233
234// Release gives a taken task back so someone else can take it. Only the doer
235// can call it, and only before work is sent. Any change request is cleared,
236// so the next doer starts fresh.
237func Release(cur realm, id int64) {
238 caller := cur.Previous().Address()
239 t := mustGet(id)
240 if caller != t.Doer {
241 panic(ErrNotDoer)
242 }
243 if t.Status != StatusTaken {
244 panic(ErrNotTaken)
245 }
246 key := t.ID.Binary()
247 unindex(&byDoer, t.Doer, key)
248 t.Doer = ""
249 t.TakenAt = time.Time{}
250 t.WorkURL = ""
251 t.ChangesAsked = false
252 t.ChangesNote = ""
253 t.Status = StatusOpen
254 openTasks.Set(key, t)
255}
256
257// Submit sends a link to the finished work. Only the doer can call it, and
258// only while the task is taken.
259func Submit(cur realm, id int64, workURL string) {
260 caller := cur.Previous().Address()
261 t := mustGet(id)
262 if caller != t.Doer {
263 panic(ErrNotDoer)
264 }
265 if t.Status != StatusTaken {
266 panic(ErrNotTaken)
267 }
268 workURL = trimSpace(workURL)
269 if !isWorkURL(workURL) {
270 panic(ErrURL)
271 }
272 t.WorkURL = workURL
273 t.SubmittedAt = time.Now()
274 t.Status = StatusInReview
275}
276
277// Approve pays the doer. Only the poster can call it, and only after work
278// was sent.
279func Approve(cur realm, id int64) {
280 caller := cur.Previous().Address()
281 t := mustGet(id)
282 if caller != t.Poster {
283 panic(ErrNotPoster)
284 }
285 if t.Status != StatusInReview {
286 panic(ErrNotInReview)
287 }
288 pay(t, cur, "approval")
289}
290
291// RequestChanges sends the task back to the doer once. The doer gets at least
292// ChangesExtension from now before the poster can take the reward back.
293func RequestChanges(cur realm, id int64, note string) {
294 caller := cur.Previous().Address()
295 t := mustGet(id)
296 if caller != t.Poster {
297 panic(ErrNotPoster)
298 }
299 if t.Status != StatusInReview {
300 panic(ErrNotInReview)
301 }
302 if t.ChangesAsked {
303 panic(ErrChangesUsed)
304 }
305 note = trimSpace(note)
306 checkText(note, 1, MaxNote, ErrNote)
307
308 t.ChangesAsked = true
309 t.ChangesNote = note
310 t.Status = StatusTaken
311 t.SubmittedAt = time.Time{}
312 if floor := time.Now().Add(ChangesExtension); t.Deadline.Before(floor) {
313 t.Deadline = floor
314 }
315}
316
317// ClaimAfterSilence pays the doer when the poster has not answered within
318// ReviewWindow of the work being sent.
319func ClaimAfterSilence(cur realm, id int64) {
320 caller := cur.Previous().Address()
321 t := mustGet(id)
322 if caller != t.Doer {
323 panic(ErrNotDoer)
324 }
325 if t.Status != StatusInReview {
326 panic(ErrNotInReview)
327 }
328 if time.Now().Before(t.SubmittedAt.Add(ReviewWindow)) {
329 panic(ErrTooEarly)
330 }
331 pay(t, cur, "silence")
332}
333
334// Cancel returns the reward to the poster. It works while the task is open,
335// or when a doer took it but sent no work before the deadline. It never works
336// once work has been sent, so a poster cannot cancel to avoid paying.
337func Cancel(cur realm, id int64) {
338 caller := cur.Previous().Address()
339 t := mustGet(id)
340 if caller != t.Poster {
341 panic(ErrNotPoster)
342 }
343 switch t.Status {
344 case StatusOpen:
345 openTasks.Remove(t.ID.Binary())
346 case StatusTaken:
347 if time.Now().Before(t.Deadline) {
348 panic(ErrDoerHasTime)
349 }
350 default:
351 panic(ErrCannotCancel)
352 }
353 t.Status = StatusRefunded
354 t.ClosedAt = time.Now()
355 lockedTotal -= t.Reward
356 send(t.Poster, t.Reward, cur)
357}
358
359// Completed returns how many tasks addr finished and was paid for on Gild,
360// across both boards (v0 and v1). Other realms can call it to gate features
361// by proven work.
362func Completed(addr address) int { return legacy.Completed(addr) + book.Completed(addr) }
363
364// Earned returns the total paid to addr on Gild across both boards, in Denom.
365func Earned(addr address) int64 { return legacy.Earned(addr) + book.Earned(addr) }
366
367// HasCompleted reports whether addr finished at least n tasks on Gild.
368func HasCompleted(addr address, n int) bool { return n <= 0 || Completed(addr) >= n }
369
370// pay marks the task paid, records it, then sends the reward. State changes
371// come before the transfer.
372func pay(t *Task, rlm realm, by string) {
373 now := time.Now()
374 t.Status = StatusPaid
375 t.ClosedAt = now
376 t.PaidBy = by
377 lockedTotal -= t.Reward
378 paidTotal += t.Reward
379 book.Add(rep.Record{
380 TaskID: idStr(t.ID),
381 Title: t.Title,
382 Poster: t.Poster,
383 Doer: t.Doer,
384 Amount: t.Reward,
385 Denom: Denom,
386 At: now,
387 })
388 send(t.Doer, t.Reward, rlm)
389}
390
391// send pays amount from this realm to addr. rlm must be the live realm handle.
392func send(to address, amount int64, rlm realm) {
393 b := banker.NewBanker(banker.BankerTypeRealmSend, rlm)
394 b.SendCoins(rlm.Address(), to, chain.Coins{{Denom, amount}})
395}
396
397func rewardFrom(sent chain.Coins) int64 {
398 if len(sent) != 1 || sent[0].Denom != Denom {
399 panic(ErrReward)
400 }
401 amount := sent[0].Amount
402 if amount < MinReward || amount > MaxReward {
403 panic(ErrRewardRange)
404 }
405 return amount
406}
407
408// idStr is the public form of a task id, e.g. "12".
409func idStr(id seqid.ID) string { return strconv.FormatInt(int64(id), 10) }
410
411func mustGet(id int64) *Task {
412 if id < 1 {
413 panic(ErrNotFound)
414 }
415 v := tasks.Get(seqid.ID(id).Binary())
416 if v == nil {
417 panic(ErrNotFound)
418 }
419 return v.(*Task)
420}
421
422func index(tree *avl.Tree, addr address, key string, t *Task) {
423 var sub *avl.Tree
424 if v := tree.Get(addr.String()); v != nil {
425 sub = v.(*avl.Tree)
426 } else {
427 sub = avl.NewTree()
428 tree.Set(addr.String(), sub)
429 }
430 sub.Set(key, t)
431}
432
433func unindex(tree *avl.Tree, addr address, key string) {
434 v := tree.Get(addr.String())
435 if v == nil {
436 return
437 }
438 sub := v.(*avl.Tree)
439 sub.Remove(key)
440 if sub.Size() == 0 {
441 tree.Remove(addr.String())
442 }
443}
444
445func isCategory(c string) bool {
446 for _, k := range categories {
447 if c == k {
448 return true
449 }
450 }
451 return false
452}