mequest.gno
13.05 Kb · 512 lines
1// Package mequest is MeQuest: quests that verify themselves.
2//
3// Projects lock GNOT rewards in this realm when they create a quest.
4// Coins can only leave through a verified claim, a split settle, or a
5// refund of the unclaimed remainder to the funder after expiry.
6// Winners get a soulbound rarity card (Common/Rare/Epic/Legendary).
7package mequest
8
9import (
10 "chain"
11 "chain/banker"
12 "chain/runtime"
13 "chain/runtime/unsafe"
14 "strconv"
15 "strings"
16 "time"
17)
18
19// ---------- rules ----------
20
21const (
22 Common = 1
23 Rare = 2
24 Epic = 3
25 Legendary = 4
26
27 KindManual = "manual" // project reviews a proof
28 KindPush = "push" // partner realm calls Complete
29 KindHold = "hold" // wallet holds at least Arg ugnot
30 KindName = "name" // wallet has a registered gno.land username
31 KindCard = "card" // wallet owns the card from quest Arg (quest chain)
32
33 PayFixed = "fixed" // style A: Reward per winner, paid on claim
34 PaySplit = "split" // style B: pool split equally after expiry
35
36 DailyCap = 10
37 Season = "S1"
38 daySecs = 86400
39)
40
41var (
42 admin address = "g1hwcp3aah5ehwq7zvz74c4x5nzewtgz2qmwjj0l"
43 supplyCap = map[int]int{Common: 0, Rare: 500, Epic: 100, Legendary: 10} // 0 = unlimited
44 cardPts = map[int]int64{Common: 10, Rare: 50, Epic: 200, Legendary: 1000}
45 rarityName = map[int]string{Common: "Common", Rare: "Rare", Epic: "Epic", Legendary: "Legendary"}
46 rankName = map[int]string{0: "Newcomer", Common: "Rookie", Rare: "Explorer", Epic: "Pathfinder", Legendary: "Legend"}
47)
48
49// ---------- state ----------
50
51type Card struct {
52 QuestID int
53 Title string
54 Art string
55 Rarity int
56 Serial int
57 Season string
58 At int64
59}
60
61type Quest struct {
62 ID int
63 Title string
64 Desc string
65 Art string // card art key used by the website
66 Funder address
67 Rarity int
68 Kind string
69 Arg string // hold: min ugnot; push: partner pkg path
70 Pay string
71 Reward int64 // fixed: ugnot per winner
72 Pool int64 // ugnot still locked for this quest
73 Funded int64
74 Max int
75 Expires int64
76 Settled bool
77 Winners []address
78 won map[address]bool
79 pending map[address]string
80}
81
82var (
83 quests []*Quest
84 cards = map[address][]Card{}
85 points = map[address]int64{}
86 daily = map[string]int{}
87 projects = map[address]bool{}
88 players []address
89 log []event
90 paidOut int64
91 minted int
92)
93
94// receipt is a public case file for every payout or rejection.
95type receipt struct {
96 N int
97 Quest int
98 Who address
99 Ok bool
100 Check string
101 Paid int64
102 Height int64
103 At int64
104}
105
106var receipts []receipt
107
108func addReceipt(q *Quest, who address, ok bool, check string, paid int64) {
109 receipts = append(receipts, receipt{len(receipts) + 1, q.ID, who, ok, check, paid, runtime.ChainHeight(), time.Now().Unix()})
110 if len(receipts) > 100 {
111 receipts = receipts[len(receipts)-100:]
112 }
113}
114
115type event struct {
116 At int64
117 Msg string
118}
119
120// ---------- projects ----------
121
122// CreateQuest locks the sent ugnot as the quest pool. Send coins with the tx.
123func CreateQuest(cur realm, title, desc, art string, rarity int, kind, arg, pay string, max int, days int) int {
124 requireWallet(cur)
125 funder := cur.Previous().Address()
126 if rarity < Common || rarity > Legendary {
127 panic("bad rarity")
128 }
129 if rarity >= Epic && !projects[funder] && funder != admin {
130 panic("only approved projects can create Epic or Legendary quests")
131 }
132 if r := validKind(kind, arg); r != "" {
133 panic(r)
134 }
135 if pay != PayFixed && pay != PaySplit {
136 panic("bad pay style")
137 }
138 if pay == PaySplit && rarity < Epic && kind != KindPush {
139 panic("split pay is for Epic/Legendary or partner quests")
140 }
141 if max < 1 || (supplyCap[rarity] > 0 && max > supplyCap[rarity]) {
142 panic("max winners out of range for this rarity")
143 }
144 if days < 1 || days > 90 {
145 panic("days must be 1-90")
146 }
147 if strings.TrimSpace(title) == "" || len(title) > 60 || len(desc) > 400 || len(art) > 24 {
148 panic("title 1-60, desc up to 400, art key up to 24 chars")
149 }
150 sent := unsafe.OriginSend().AmountOf("ugnot")
151 if sent <= 0 {
152 panic("send ugnot to fund the pool")
153 }
154 q := &Quest{
155 ID: len(quests) + 1, Title: title, Desc: desc, Art: art, Funder: funder,
156 Rarity: rarity, Kind: kind, Arg: arg, Pay: pay,
157 Pool: sent, Funded: sent, Max: max,
158 Expires: time.Now().Unix() + int64(days)*daySecs,
159 won: map[address]bool{}, pending: map[address]string{},
160 }
161 if pay == PayFixed {
162 if sent%int64(max) != 0 {
163 panic("pool must divide evenly by max winners")
164 }
165 q.Reward = sent / int64(max)
166 }
167 quests = append(quests, q)
168 posted[funder]++
169 touch(funder)
170 note("quest #" + itoa(q.ID) + " created, pool " + gnot(sent))
171 return q.ID
172}
173
174// Review approves or rejects a manual proof. Funder or admin only.
175func Review(cur realm, id int, wallet address, ok bool) {
176 q := mustQuest(id)
177 caller := cur.Previous().Address()
178 if caller != q.Funder && caller != admin {
179 panic("only the quest funder can review")
180 }
181 if _, has := q.pending[wallet]; !has {
182 panic("no pending proof")
183 }
184 delete(q.pending, wallet)
185 if ok {
186 award(cur, q, wallet)
187 } else {
188 addReceipt(q, wallet, false, "project review → rejected", 0)
189 note("quest #" + itoa(id) + " proof rejected for " + short(wallet))
190 }
191}
192
193// Refund returns the unclaimed pool of an expired fixed quest to its funder.
194func Refund(cur realm, id int) {
195 q := mustQuest(id)
196 if q.Pay != PayFixed {
197 panic("split quests use Settle")
198 }
199 if time.Now().Unix() < q.Expires {
200 panic("quest still running: pool is locked")
201 }
202 if q.Pool == 0 {
203 panic("nothing to refund")
204 }
205 amt := q.Pool
206 q.Pool = 0
207 send(cur, q.Funder, amt)
208 note("quest #" + itoa(id) + " refunded " + gnot(amt) + " to funder")
209}
210
211// Settle pays a split quest after expiry. Anyone can call it.
212func Settle(cur realm, id int) {
213 q := mustQuest(id)
214 if q.Pay != PaySplit || q.Settled {
215 panic("not a split quest or already settled")
216 }
217 if time.Now().Unix() < q.Expires {
218 panic("quest still running")
219 }
220 q.Settled = true
221 n := int64(len(q.Winners))
222 if n > 0 {
223 share := q.Pool / n
224 for _, w := range q.Winners {
225 send(cur, w, share)
226 q.Pool -= share
227 paidOut += share
228 }
229 note("quest #" + itoa(id) + " split " + gnot(share) + " x " + itoa(int(n)))
230 }
231 if q.Pool > 0 {
232 left := q.Pool
233 q.Pool = 0
234 send(cur, q.Funder, left)
235 }
236}
237
238// ---------- questers ----------
239
240// Claim runs the quest's own check on the caller and pays if it passes.
241func Claim(cur realm, id int) {
242 requireWallet(cur)
243 q := mustQuest(id)
244 user := cur.Previous().Address()
245 if r := verifyReason(q, user); r != "" {
246 panic(r)
247 }
248 award(cur, q, user)
249}
250
251// Submit sends a proof (link or text) for a manual quest.
252func Submit(cur realm, id int, proof string) {
253 requireWallet(cur)
254 q := mustQuest(id)
255 user := cur.Previous().Address()
256 if q.Kind != KindManual {
257 panic("not a manual quest")
258 }
259 open(q, user)
260 if len(proof) == 0 || len(proof) > 280 {
261 panic("proof must be 1-280 chars")
262 }
263 touch(user)
264 q.pending[user] = proof
265 note("quest #" + itoa(id) + " proof submitted by " + short(user))
266}
267
268// Complete is called by the partner realm named in a push quest.
269func Complete(cur realm, id int, wallet address) {
270 q := mustQuest(id)
271 if q.Kind != KindPush {
272 panic("not a push quest")
273 }
274 if cur.Previous().PkgPath() != q.Arg {
275 panic("only " + q.Arg + " can complete this quest")
276 }
277 award(cur, q, wallet)
278}
279
280// ---------- admin ----------
281
282func ApproveProject(cur realm, p address, on bool) {
283 onlyAdmin(cur)
284 projects[p] = on
285}
286
287// Revoke removes a card from a cheater wallet.
288func Revoke(cur realm, wallet address, id int) {
289 onlyAdmin(cur)
290 list := cards[wallet]
291 for i, c := range list {
292 if c.QuestID == id {
293 cards[wallet] = append(list[:i], list[i+1:]...)
294 points[wallet] -= cardPts[c.Rarity]
295 note("card from quest #" + itoa(id) + " revoked from " + short(wallet))
296 return
297 }
298 }
299 panic("wallet has no card from that quest")
300}
301
302// ---------- read-only checks (other realms can call these) ----------
303
304func HasCard(wallet address, id int) bool {
305 for _, c := range cards[wallet] {
306 if c.QuestID == id {
307 return true
308 }
309 }
310 return false
311}
312
313func BestRarity(wallet address) int {
314 best := 0
315 for _, c := range cards[wallet] {
316 if c.Rarity > best {
317 best = c.Rarity
318 }
319 }
320 return best
321}
322
323func HasRarity(wallet address, min int) bool { return BestRarity(wallet) >= min }
324func PointsOf(wallet address) int64 { return points[wallet] }
325func CardCount(wallet address) int { return len(cards[wallet]) }
326
327// ---------- internals ----------
328
329func award(cur realm, q *Quest, user address) {
330 if r := gateReason(q, user); r != "" {
331 panic(r)
332 }
333 day := strconv.FormatInt(time.Now().Unix()/daySecs, 10)
334 key := string(user) + ":" + day
335 daily[key]++
336
337 q.won[user] = true
338 q.Winners = append(q.Winners, user)
339 if _, seen := points[user]; !seen {
340 players = append(players, user)
341 }
342 touch(user)
343 if len(cards[user]) == 0 {
344 if inv, ok := inviter[user]; ok {
345 invitesDone[inv]++
346 }
347 }
348 cards[user] = append(cards[user], Card{
349 QuestID: q.ID, Title: q.Title, Art: q.Art, Rarity: q.Rarity,
350 Serial: len(q.Winners), Season: Season, At: time.Now().Unix(),
351 })
352 points[user] += cardPts[q.Rarity]
353 minted++
354
355 paid := int64(0)
356 if q.Pay == PayFixed {
357 paid = q.Reward
358 }
359 addReceipt(q, user, true, checkLabel(q), paid)
360 msg := short(user) + " won " + rarityName[q.Rarity] + " #" + itoa(len(q.Winners)) + " on quest #" + itoa(q.ID)
361 if q.Pay == PayFixed {
362 q.Pool -= q.Reward
363 send(cur, user, q.Reward)
364 paidOut += q.Reward
365 msg += ", paid " + gnot(q.Reward)
366 }
367 note(msg)
368}
369
370func open(q *Quest, user address) {
371 if time.Now().Unix() >= q.Expires {
372 panic("quest expired")
373 }
374 if q.won[user] {
375 panic("already claimed: one win per wallet")
376 }
377}
378
379func send(cur realm, to address, amt int64) {
380 if amt <= 0 {
381 return
382 }
383 b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
384 b.SendCoins(cur.Address(), to, chain.Coins{{"ugnot", amt}})
385}
386
387// requireWallet blocks calls routed through other realms (anti-farming bots,
388// and makes sure sent coins really came from the caller).
389func requireWallet(cur realm) {
390 if !cur.Previous().IsUserCall() {
391 panic("call this directly from your wallet")
392 }
393}
394
395func onlyAdmin(cur realm) {
396 if cur.Previous().Address() != admin {
397 panic("admin only")
398 }
399}
400
401func mustQuest(id int) *Quest {
402 if id < 1 || id > len(quests) {
403 panic("quest not found")
404 }
405 return quests[id-1]
406}
407
408func note(s string) {
409 log = append(log, event{time.Now().Unix(), s})
410 if len(log) > 50 {
411 log = log[len(log)-50:]
412 }
413}
414
415func itoa(n int) string { return strconv.Itoa(n) }
416
417func gnot(ugnot int64) string {
418 whole := ugnot / 1000000
419 frac := ugnot % 1000000
420 if frac == 0 {
421 return strconv.FormatInt(whole, 10) + " GNOT"
422 }
423 f := strings.TrimRight(strconv.FormatInt(frac+1000000, 10)[1:], "0")
424 return strconv.FormatInt(whole, 10) + "." + f + " GNOT"
425}
426
427func short(a address) string {
428 s := string(a)
429 if len(s) < 12 {
430 return s
431 }
432 return s[:7] + "…" + s[len(s)-4:]
433}
434
435// ---------- pages ----------
436
437func Render(path string) string {
438 switch {
439 case strings.HasPrefix(path, "api/"):
440 return renderAPI(path[4:])
441 case path == "":
442 return renderBoard()
443 case strings.HasPrefix(path, "q/"):
444 id, err := strconv.Atoi(path[2:])
445 if err != nil || id < 1 || id > len(quests) {
446 return "quest not found"
447 }
448 return renderQuest(quests[id-1])
449 case strings.HasPrefix(path, "p/"):
450 return renderPassport(address(path[2:]))
451 case path == "top":
452 return renderTop()
453 }
454 return "404"
455}
456
457func renderBoard() string {
458 s := "# MeQuest\n_Quests that verify themselves._ Season " + Season + "\n\n"
459 s += "[Leaderboard](:top)\n\n## Quests\n\n"
460 if len(quests) == 0 {
461 s += "No quests yet.\n"
462 }
463 for i := len(quests) - 1; i >= 0; i-- {
464 q := quests[i]
465 s += "- [#" + itoa(q.ID) + " " + q.Title + "](:q/" + itoa(q.ID) + ") · " + rarityName[q.Rarity] +
466 " · " + itoa(len(q.Winners)) + "/" + itoa(q.Max) + " claimed · pool " + gnot(q.Pool) + " left\n"
467 }
468 s += "\n## Live feed\n\n"
469 for i := len(log) - 1; i >= 0 && i >= len(log)-10; i-- {
470 s += "- " + log[i].Msg + "\n"
471 }
472 return s
473}
474
475func renderQuest(q *Quest) string {
476 s := "# #" + itoa(q.ID) + " " + q.Title + "\n\n" + q.Desc + "\n\n"
477 s += "- Card: **" + rarityName[q.Rarity] + "** (" + Season + ")\n"
478 s += "- Check: " + q.Kind
479 if q.Arg != "" {
480 s += " `" + q.Arg + "`"
481 }
482 s += "\n- Pay: " + q.Pay
483 if q.Pay == PayFixed {
484 s += ", " + gnot(q.Reward) + " per winner"
485 }
486 s += "\n- Pool: " + gnot(q.Pool) + " locked of " + gnot(q.Funded) + " funded\n"
487 s += "- Winners: " + itoa(len(q.Winners)) + "/" + itoa(q.Max) + "\n"
488 s += "- Funder: " + short(q.Funder) + "\n- Ends: " + time.Unix(q.Expires, 0).UTC().Format("2006-01-02 15:04 UTC") + "\n"
489 return s
490}
491
492func renderPassport(w address) string {
493 best := BestRarity(w)
494 s := "# Passport: " + short(w) + "\n\n**" + rankName[best] + "** · " +
495 strconv.FormatInt(points[w], 10) + " pts · " + itoa(len(cards[w])) + " cards\n\n"
496 for _, c := range cards[w] {
497 s += "- " + rarityName[c.Rarity] + " · " + c.Title + " · #" + itoa(c.Serial) + " · " + c.Season + "\n"
498 }
499 return s
500}
501
502func renderTop() string {
503 list := ranked()
504 s := "# Season " + Season + " leaderboard\n\n"
505 for i, w := range list {
506 if i == 10 {
507 break
508 }
509 s += itoa(i+1) + ". [" + short(w) + "](:p/" + string(w) + ") · " + strconv.FormatInt(points[w], 10) + " pts\n"
510 }
511 return s
512}