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.

ledger.gno

1.97 Kb · 77 lines
 1package flag
 2
 3import (
 4	"chain/runtime"
 5
 6	"gno.land/p/nt/avl/v0"
 7)
 8
 9// Capture is the proof that a player broke a challenge.
10type Capture struct {
11	Player address
12	Height int64 // block height of the capture
13	Order  int   // 1 for the first capture of this challenge
14}
15
16// Ledger records captures for one challenge.
17//
18// Keep a Ledger in an unexported variable of your realm and never return a
19// pointer to it: its methods mutate, and a method call on a leaked pointer
20// commits under your realm's authority. (Challenge "rack" is about
21// exactly that.)
22type Ledger struct {
23	captures *avl.Tree // address -> Capture
24	order    []address // players in capture order
25}
26
27// NewLedger returns an empty Ledger.
28func NewLedger() *Ledger {
29	return &Ledger{captures: avl.NewTree()}
30}
31
32// Record stores a capture for player at the current height. It returns
33// the stored capture and true, or the earlier capture and false if the
34// player had already captured.
35func (l *Ledger) Record(player address) (Capture, bool) {
36	if prev, ok := l.Get(player); ok {
37		return prev, false
38	}
39	c := Capture{
40		Player: player,
41		Height: runtime.ChainHeight(),
42		Order:  len(l.order) + 1,
43	}
44	l.captures.Set(player.String(), c)
45	l.order = append(l.order, player)
46	return c, true
47}
48
49// Captured reports whether player has captured.
50func (l *Ledger) Captured(player address) bool {
51	return l.captures.Has(player.String())
52}
53
54// Get returns the capture of player, if any.
55func (l *Ledger) Get(player address) (Capture, bool) {
56	v := l.captures.Get(player.String())
57	if v == nil {
58		return Capture{}, false
59	}
60	return v.(Capture), true
61}
62
63// Count returns the number of distinct players who captured.
64func (l *Ledger) Count() int { return len(l.order) }
65
66// Recent returns up to n captures, newest first.
67func (l *Ledger) Recent(n int) []Capture {
68	if n > len(l.order) {
69		n = len(l.order)
70	}
71	out := make([]Capture, 0, n)
72	for i := len(l.order) - 1; i >= len(l.order)-n; i-- {
73		c, _ := l.Get(l.order[i])
74		out = append(out, c)
75	}
76	return out
77}