escrow.gno
17.64 Kb · 550 lines
1// Package escrow holds the rules of a single-builder bounty escrow: the
2// Quest type, its states and every legal move between them.
3//
4// The package is pure. It holds no coins, no banker and no storage. A realm
5// that imports it keeps the *Quest values, moves the coins, and asks this
6// package whether a move is allowed. Every move takes the acting address and
7// the current block height as arguments, so the rules can be tested without a
8// chain and cannot be bypassed by the caller's own logic.
9//
10// Moves that can release money (Cancel, Unclaim, Release, Approve, Reject,
11// ClaimPayout) return a Payout telling the realm exactly whom to pay and how
12// much; a zero Payout (Due() == false) means no coins move. A non-zero Payout
13// is only ever returned together with a move into a final state (Paid or
14// Cancelled), and a final quest accepts no further move, so a quest can
15// produce at most one non-zero Payout.
16//
17// A realm using this package must:
18// - lock exactly Reward() in its own balance before calling NewQuest,
19// - apply the move first and send the coins of the returned Payout after,
20// - treat any returned error as fatal (panic) so the transaction reverts.
21//
22// States and moves:
23//
24// (none) Post (NewQuest) anyone -> Open
25// Open Claim anyone except the poster -> Claimed
26// Open Cancel poster -> Cancelled refund Reward to poster
27// Claimed Cancel ("close") poster -> Claimed, closing
28// Submitted Cancel ("close") poster -> Submitted, closing
29// Claimed Submit(link) builder, until work deadline -> Submitted
30// Claimed Unclaim builder -> Open (closing: Cancelled, refund)
31// Claimed Release anyone, after work deadline -> Open (closing: Cancelled, refund)
32// Submitted Approve poster -> Paid pay Reward to builder
33// Submitted Reject(reason) poster, until review deadline -> Open (closing: Cancelled, refund)
34// Submitted ClaimPayout builder, after review deadline-> Paid pay Reward to builder
35//
36// Closing: a poster cannot take the reward back while a builder holds the
37// quest, but can close it. The current builder keeps every right (submit,
38// get approved, claim the timeout payout); any move that would put the quest
39// back to Open ends it instead and refunds the poster. So a builder can hold
40// a closing quest for at most one work window, and nobody can re-claim it.
41// Closing cannot be undone.
42//
43// Deadlines are block heights. "Until" a deadline includes the deadline block
44// itself; "after" a deadline starts at the next block.
45package escrow
46
47import (
48 "errors"
49 "strings"
50 "unicode"
51 "unicode/utf8"
52)
53
54// Limits. Text limits count Unicode characters (runes).
55const (
56 MaxTitleLen = 80
57 MaxDetailsLen = 1000
58 MaxLinkLen = 300
59 MaxReasonLen = 300
60
61 // Windows are in blocks. Measured block time on 2026-11-23 was about
62 // 3.4 s (Onyx) to 3.5 s (mainnet); the values below assume 3.5 s.
63 // See docs/gno-notes.md for the maths.
64
65 // MinWorkBlocks and MaxWorkBlocks bound the work window a poster may set:
66 // about 1 hour and about 90 days.
67 MinWorkBlocks int64 = 1_000
68 MaxWorkBlocks int64 = 2_200_000
69
70 // ReviewBlocks is the fixed review window every quest gets after Submit,
71 // about 7 days. If the poster neither approves nor rejects within it, the
72 // builder may call ClaimPayout.
73 ReviewBlocks int64 = 172_800
74)
75
76// State is the stage a quest is in.
77type State uint8
78
79const (
80 // Open: waiting for a builder.
81 Open State = iota + 1
82 // Claimed: a builder is working on it.
83 Claimed
84 // Submitted: work link sent, waiting for the poster's review.
85 Submitted
86 // Paid: reward paid to the builder. Final.
87 Paid
88 // Cancelled: reward refunded to the poster. Final.
89 Cancelled
90)
91
92// String returns the state name.
93func (s State) String() string {
94 switch s {
95 case Open:
96 return "Open"
97 case Claimed:
98 return "Claimed"
99 case Submitted:
100 return "Submitted"
101 case Paid:
102 return "Paid"
103 case Cancelled:
104 return "Cancelled"
105 }
106 return "Unknown"
107}
108
109// IsFinal reports whether no further move is possible from s.
110func (s State) IsFinal() bool {
111 return s == Paid || s == Cancelled
112}
113
114// PayoutKind says why coins must move.
115type PayoutKind uint8
116
117const (
118 // PayBuilder: send the reward to the builder (Approve, ClaimPayout).
119 PayBuilder PayoutKind = iota + 1
120 // RefundPoster: send the reward back to the poster (Cancel).
121 RefundPoster
122)
123
124// String returns the payout kind name.
125func (k PayoutKind) String() string {
126 switch k {
127 case PayBuilder:
128 return "PayBuilder"
129 case RefundPoster:
130 return "RefundPoster"
131 }
132 return "Unknown"
133}
134
135// Payout is the transfer a realm must make after a successful move. The zero
136// Payout means no transfer. When Due, Amount is always the quest's stored
137// Reward.
138type Payout struct {
139 Kind PayoutKind
140 To address
141 Amount int64
142}
143
144// Due reports whether coins must move.
145func (p Payout) Due() bool {
146 return p.Kind != 0
147}
148
149// Errors returned by the moves. Realms usually panic with err.Error().
150var (
151 ErrInvalidPoster = errors.New("escrow: invalid poster address")
152 ErrInvalidActor = errors.New("escrow: invalid caller address")
153 ErrInvalidReward = errors.New("escrow: reward must be positive")
154 ErrInvalidHeight = errors.New("escrow: invalid block height")
155 ErrTitleEmpty = errors.New("escrow: title is empty")
156 ErrTitleTooLong = errors.New("escrow: title is too long")
157 ErrTitleControlChar = errors.New("escrow: title must not contain control characters such as newlines or tabs")
158 ErrDetailsTooLong = errors.New("escrow: details are too long")
159 ErrWorkBlocksTooLow = errors.New("escrow: work window is below the minimum")
160 ErrWorkBlocksTooHigh = errors.New("escrow: work window is above the maximum")
161 ErrLinkEmpty = errors.New("escrow: work link is empty")
162 ErrLinkTooLong = errors.New("escrow: work link is too long")
163 ErrLinkNotHTTPS = errors.New("escrow: work link must start with https://")
164 ErrLinkInvalid = errors.New("escrow: work link contains spaces or control characters")
165 ErrReasonEmpty = errors.New("escrow: reject reason is empty")
166 ErrReasonTooLong = errors.New("escrow: reject reason is too long")
167 ErrInvalidText = errors.New("escrow: text is not valid UTF-8")
168
169 ErrWrongState = errors.New("escrow: move not allowed in the quest's current state")
170 ErrNotPoster = errors.New("escrow: only the poster can do this")
171 ErrNotBuilder = errors.New("escrow: only the builder can do this")
172 ErrPosterCannotClaim = errors.New("escrow: the poster cannot claim their own quest")
173 ErrWorkDeadlinePassed = errors.New("escrow: work deadline has passed")
174 ErrWorkDeadlineNotPassed = errors.New("escrow: work deadline has not passed yet")
175 ErrReviewDeadlinePassed = errors.New("escrow: review deadline has passed")
176 ErrReviewDeadlineNotPassed = errors.New("escrow: review deadline has not passed yet")
177 ErrAlreadyClosing = errors.New("escrow: the quest is already closing")
178)
179
180// Quest is one bounty. Its fields are private so that only the moves below
181// can change it; read them with the getters.
182type Quest struct {
183 id uint64
184 poster address
185 title string
186 details string
187 reward int64
188 state State
189 builder address
190 workLink string
191 workBlocks int64
192 createdAt int64
193 claimedAt int64
194 submittedAt int64
195
196 rejectCount int
197 lastRejectReason string
198
199 closing bool // set by Cancel on a Claimed or Submitted quest
200}
201
202// NewQuest validates a new quest and returns it in the Open state. The caller
203// must already hold reward (in its own coin) for this quest. id is chosen by
204// the caller and is not checked for uniqueness here.
205func NewQuest(id uint64, poster address, title, details string, reward, workBlocks, height int64) (*Quest, error) {
206 if !poster.IsValid() {
207 return nil, ErrInvalidPoster
208 }
209 if reward <= 0 {
210 return nil, ErrInvalidReward
211 }
212 if height < 0 {
213 return nil, ErrInvalidHeight
214 }
215 if err := ValidateTitle(title); err != nil {
216 return nil, err
217 }
218 if err := ValidateDetails(details); err != nil {
219 return nil, err
220 }
221 if err := ValidateWorkBlocks(workBlocks); err != nil {
222 return nil, err
223 }
224 return &Quest{
225 id: id,
226 poster: poster,
227 title: title,
228 details: details,
229 reward: reward,
230 state: Open,
231 workBlocks: workBlocks,
232 createdAt: height,
233 }, nil
234}
235
236// Claim lets anyone except the poster take an Open quest. The work window
237// starts at height.
238func (q *Quest) Claim(actor address, height int64) error {
239 if q.state != Open {
240 return ErrWrongState
241 }
242 if !actor.IsValid() {
243 return ErrInvalidActor
244 }
245 if actor == q.poster {
246 return ErrPosterCannotClaim
247 }
248 if height < q.createdAt {
249 return ErrInvalidHeight
250 }
251 q.state = Claimed
252 q.builder = actor
253 q.claimedAt = height
254 return nil
255}
256
257// Cancel is the poster's way out.
258// - On an Open quest it ends the quest at once: Cancelled, and the returned
259// Payout refunds the reward to the poster.
260// - On a Claimed or Submitted quest it only marks the quest as closing and
261// returns a zero Payout: the current builder keeps every right, and the
262// reward goes back to the poster when the builder's turn ends without
263// approval (Unclaim, Release or Reject). A second call fails.
264func (q *Quest) Cancel(actor address, height int64) (Payout, error) {
265 switch q.state {
266 case Open, Claimed, Submitted:
267 default:
268 return Payout{}, ErrWrongState
269 }
270 if actor != q.poster {
271 return Payout{}, ErrNotPoster
272 }
273 if q.state == Open {
274 return q.cancel(), nil
275 }
276 if q.closing {
277 return Payout{}, ErrAlreadyClosing
278 }
279 q.closing = true
280 return Payout{}, nil
281}
282
283// Submit lets the builder hand in a work link, up to and including the work
284// deadline block. The review window starts at height.
285func (q *Quest) Submit(actor address, link string, height int64) error {
286 if q.state != Claimed {
287 return ErrWrongState
288 }
289 if actor != q.builder {
290 return ErrNotBuilder
291 }
292 if height < q.claimedAt {
293 return ErrInvalidHeight
294 }
295 if height > q.WorkDeadline() {
296 return ErrWorkDeadlinePassed
297 }
298 if err := ValidateLink(link); err != nil {
299 return err
300 }
301 q.state = Submitted
302 q.workLink = link
303 q.submittedAt = height
304 return nil
305}
306
307// Unclaim lets the builder give a Claimed quest back. It becomes Open again,
308// or, if it is closing, Cancelled with a refund to the poster.
309func (q *Quest) Unclaim(actor address, height int64) (Payout, error) {
310 if q.state != Claimed {
311 return Payout{}, ErrWrongState
312 }
313 if actor != q.builder {
314 return Payout{}, ErrNotBuilder
315 }
316 return q.endTurn(), nil
317}
318
319// Release lets anyone end the builder's turn on a Claimed quest once the
320// work deadline has passed (from WorkDeadline()+1 on) without a submission.
321// The quest becomes Open again, or, if it is closing, Cancelled with a refund
322// to the poster.
323func (q *Quest) Release(actor address, height int64) (Payout, error) {
324 if q.state != Claimed {
325 return Payout{}, ErrWrongState
326 }
327 if !actor.IsValid() {
328 return Payout{}, ErrInvalidActor
329 }
330 if height <= q.WorkDeadline() {
331 return Payout{}, ErrWorkDeadlineNotPassed
332 }
333 return q.endTurn(), nil
334}
335
336// Approve lets the poster accept the submitted work. The returned Payout pays
337// the reward to the builder. Approving after the review deadline is allowed:
338// it pays the same builder as ClaimPayout would.
339func (q *Quest) Approve(actor address, height int64) (Payout, error) {
340 if q.state != Submitted {
341 return Payout{}, ErrWrongState
342 }
343 if actor != q.poster {
344 return Payout{}, ErrNotPoster
345 }
346 q.state = Paid
347 return Payout{Kind: PayBuilder, To: q.builder, Amount: q.reward}, nil
348}
349
350// Reject lets the poster refuse the submitted work, up to and including the
351// review deadline block. The builder is cleared, and the reject count and
352// last reason are kept on the quest for everyone to see. The quest becomes
353// Open again, or, if it is closing, Cancelled with a refund to the poster.
354func (q *Quest) Reject(actor address, reason string, height int64) (Payout, error) {
355 if q.state != Submitted {
356 return Payout{}, ErrWrongState
357 }
358 if actor != q.poster {
359 return Payout{}, ErrNotPoster
360 }
361 if height > q.ReviewDeadline() {
362 return Payout{}, ErrReviewDeadlinePassed
363 }
364 if err := ValidateReason(reason); err != nil {
365 return Payout{}, err
366 }
367 q.rejectCount++
368 q.lastRejectReason = reason
369 return q.endTurn(), nil
370}
371
372// ClaimPayout lets the builder take the reward when the poster has not
373// answered within the review window (from ReviewDeadline()+1 on). The
374// returned Payout pays the reward to the builder.
375func (q *Quest) ClaimPayout(actor address, height int64) (Payout, error) {
376 if q.state != Submitted {
377 return Payout{}, ErrWrongState
378 }
379 if actor != q.builder {
380 return Payout{}, ErrNotBuilder
381 }
382 if height <= q.ReviewDeadline() {
383 return Payout{}, ErrReviewDeadlineNotPassed
384 }
385 q.state = Paid
386 return Payout{Kind: PayBuilder, To: q.builder, Amount: q.reward}, nil
387}
388
389// endTurn ends the current builder's turn: it clears the builder and the
390// work, then puts the quest back to Open, or, if it is closing, cancels it
391// and returns the refund.
392func (q *Quest) endTurn() Payout {
393 q.builder = ""
394 q.workLink = ""
395 q.claimedAt = 0
396 q.submittedAt = 0
397 if q.closing {
398 return q.cancel()
399 }
400 q.state = Open
401 return Payout{}
402}
403
404// cancel ends the quest and returns the refund to the poster. It is the only
405// place that returns a RefundPoster payout.
406func (q *Quest) cancel() Payout {
407 q.state = Cancelled
408 return Payout{Kind: RefundPoster, To: q.poster, Amount: q.reward}
409}
410
411// WorkDeadline is the last block at which the builder may submit. It is 0
412// unless the quest is Claimed or Submitted.
413func (q *Quest) WorkDeadline() int64 {
414 if q.state != Claimed && q.state != Submitted {
415 return 0
416 }
417 return q.claimedAt + q.workBlocks
418}
419
420// ReviewDeadline is the last block at which the poster may reject. It is 0
421// unless the quest is Submitted.
422func (q *Quest) ReviewDeadline() int64 {
423 if q.state != Submitted {
424 return 0
425 }
426 return q.submittedAt + ReviewBlocks
427}
428
429// CanRelease reports whether Release would succeed at height.
430func (q *Quest) CanRelease(height int64) bool {
431 return q.state == Claimed && height > q.WorkDeadline()
432}
433
434// CanClaimPayout reports whether the builder could call ClaimPayout at height.
435func (q *Quest) CanClaimPayout(height int64) bool {
436 return q.state == Submitted && height > q.ReviewDeadline()
437}
438
439// Getters.
440
441func (q *Quest) ID() uint64 { return q.id }
442func (q *Quest) Poster() address { return q.poster }
443func (q *Quest) Title() string { return q.title }
444func (q *Quest) Details() string { return q.details }
445func (q *Quest) Reward() int64 { return q.reward }
446func (q *Quest) State() State { return q.state }
447func (q *Quest) Builder() address { return q.builder }
448func (q *Quest) WorkLink() string { return q.workLink }
449func (q *Quest) WorkBlocks() int64 { return q.workBlocks }
450func (q *Quest) CreatedAt() int64 { return q.createdAt }
451func (q *Quest) ClaimedAt() int64 { return q.claimedAt }
452func (q *Quest) SubmittedAt() int64 { return q.submittedAt }
453func (q *Quest) RejectCount() int { return q.rejectCount }
454func (q *Quest) LastRejectReason() string { return q.lastRejectReason }
455
456// Closing reports whether the poster has closed the quest while a builder
457// held it: the reward returns to the poster when the builder's turn ends
458// without approval.
459func (q *Quest) Closing() bool { return q.closing }
460
461// HoldsFunds reports whether the quest's reward is still held in escrow
462// (Open, Claimed or Submitted). The sum of Reward() over quests that hold
463// funds must equal what the realm holds for them.
464func (q *Quest) HoldsFunds() bool {
465 return !q.state.IsFinal()
466}
467
468// Validators. They are exported so a realm can check input early.
469
470// ValidateTitle checks a quest title: not blank, at most MaxTitleLen
471// characters, and no control characters (newline, tab, etc.) or Unicode line
472// and paragraph separators, because titles are shown inside Markdown tables
473// and links.
474func ValidateTitle(s string) error {
475 if !utf8.ValidString(s) {
476 return ErrInvalidText
477 }
478 if strings.TrimSpace(s) == "" {
479 return ErrTitleEmpty
480 }
481 if utf8.RuneCountInString(s) > MaxTitleLen {
482 return ErrTitleTooLong
483 }
484 for _, r := range s {
485 if unicode.IsControl(r) || r == '\u2028' || r == '\u2029' {
486 return ErrTitleControlChar
487 }
488 }
489 return nil
490}
491
492// ValidateDetails checks quest details: at most MaxDetailsLen characters (may be empty).
493func ValidateDetails(s string) error {
494 if !utf8.ValidString(s) {
495 return ErrInvalidText
496 }
497 if utf8.RuneCountInString(s) > MaxDetailsLen {
498 return ErrDetailsTooLong
499 }
500 return nil
501}
502
503// ValidateWorkBlocks checks that w is within [MinWorkBlocks, MaxWorkBlocks].
504func ValidateWorkBlocks(w int64) error {
505 if w < MinWorkBlocks {
506 return ErrWorkBlocksTooLow
507 }
508 if w > MaxWorkBlocks {
509 return ErrWorkBlocksTooHigh
510 }
511 return nil
512}
513
514// ValidateLink checks a work link: starts with "https://", has something
515// after it, at most MaxLinkLen characters, and has no spaces or control
516// characters.
517func ValidateLink(s string) error {
518 if s == "" {
519 return ErrLinkEmpty
520 }
521 if !utf8.ValidString(s) {
522 return ErrInvalidText
523 }
524 if utf8.RuneCountInString(s) > MaxLinkLen {
525 return ErrLinkTooLong
526 }
527 if !strings.HasPrefix(s, "https://") || len(s) == len("https://") {
528 return ErrLinkNotHTTPS
529 }
530 for _, r := range s {
531 if r <= ' ' || r == 0x7f {
532 return ErrLinkInvalid
533 }
534 }
535 return nil
536}
537
538// ValidateReason checks a reject reason: not blank, at most MaxReasonLen characters.
539func ValidateReason(s string) error {
540 if !utf8.ValidString(s) {
541 return ErrInvalidText
542 }
543 if strings.TrimSpace(s) == "" {
544 return ErrReasonEmpty
545 }
546 if utf8.RuneCountInString(s) > MaxReasonLen {
547 return ErrReasonTooLong
548 }
549 return nil
550}