till.gno
2.25 Kb · 72 lines
1// Package till is a Cellar challenge about native coins and the origin
2// send envelope.
3package till
4
5import (
6 "chain"
7 "chain/banker"
8 "chain/runtime/unsafe"
9 "strconv"
10 "strings"
11
12 "gno.land/p/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/flag"
13 "gno.land/p/nt/avl/v0"
14)
15
16// Price of a round, in ugnot (0.1 GNOT).
17const Price int64 = 100_000
18
19var (
20 strongbox = address("g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf") // where the till is emptied
21 rounds = avl.NewTree() // address -> rounds poured
22 stolen int // rounds the auditor flagged
23)
24
25// BuyRound pours you a round once the barkeep sees you sent the price.
26// Send the coins with the call: gnokey maketx call -send 100000ugnot.
27func BuyRound(cur realm) {
28 player := flag.MustPlayer(cur.Previous())
29 if unsafe.OriginSend().AmountOf("ugnot") < Price {
30 panic("till: a round is " + strconv.FormatInt(Price, 10) + "ugnot; send it with the call")
31 }
32 n, _ := rounds.Get(player.String()).(int)
33 rounds.Set(player.String(), n+1)
34 audit(cur, player)
35}
36
37// audit counts the till after a round and empties it into the strongbox.
38// A round poured with less than its price in the till was not paid for.
39func audit(cur realm, player address) {
40 bank := banker.NewBanker(banker.BankerTypeRealmSend, cur)
41 inTill := bank.GetCoin(cur.Address(), "ugnot")
42 if inTill < Price {
43 stolen++
44 captures.Record(player)
45 }
46 if inTill > 0 {
47 bank.SendCoins(cur.Address(), strongbox, chain.Coins{chain.NewCoin("ugnot", inTill)})
48 }
49}
50
51// Rounds returns how many rounds addr has been poured.
52func Rounds(addr address) int {
53 n, _ := rounds.Get(addr.String()).(int)
54 return n
55}
56
57// Render shows the bar's books.
58func Render(_ string) string {
59 var b strings.Builder
60 b.WriteString(flag.Card(info, captures))
61 b.WriteString("\n**A round:** " + strconv.FormatInt(Price, 10) + "ugnot · **Rounds the auditor flagged:** " +
62 strconv.Itoa(stolen) + "\n\n## Rounds poured\n\n")
63 if rounds.Size() == 0 {
64 b.WriteString("*The bar is quiet.*\n")
65 }
66 rounds.Iterate("", "", func(addr string, v any) bool {
67 b.WriteString("- `" + addr + "`: " + strconv.Itoa(v.(int)) + "\n")
68 return false
69 })
70 b.WriteString("\n## Captured by\n\n" + flag.Captures(captures, 5))
71 return b.String()
72}