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.

gild.gno

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