stakehistory.gno
1.34 Kb · 56 lines
1// Package mimir holds the pure helpers Mimir's market realms share: stake
2// history checkpoints (settlement cutoffs) and overflow-safe arithmetic.
3package mimir
4
5// Amounts are cumulative net deposits on each side, and the copied part of each.
6type Amounts struct {
7 A, B, CopiedA, CopiedB int64
8}
9
10type Checkpoint struct {
11 At int64 // unix seconds
12 Amounts Amounts
13}
14
15// History is an append-only list of checkpoints in time order. Deposits in the
16// same second coalesce into one checkpoint. Settlement never scans all deposits.
17type History struct {
18 points []Checkpoint
19}
20
21// Record stores the running totals as of `now`.
22func (h *History) Record(now int64, a Amounts) {
23 n := len(h.points)
24 if n != 0 && h.points[n-1].At == now {
25 h.points[n-1].Amounts = a
26 return
27 }
28 h.points = append(h.points, Checkpoint{At: now, Amounts: a})
29}
30
31// Before returns the totals recorded strictly before cutoff. A cutoff of 0
32// means no cutoff: the latest totals.
33func (h *History) Before(cutoff int64) Amounts {
34 hi := len(h.points)
35 if hi == 0 {
36 return Amounts{}
37 }
38 if cutoff == 0 {
39 return h.points[hi-1].Amounts
40 }
41 lo := 0
42 for lo < hi {
43 mid := lo + (hi-lo)/2
44 if h.points[mid].At < cutoff {
45 lo = mid + 1
46 } else {
47 hi = mid
48 }
49 }
50 if lo == 0 {
51 return Amounts{}
52 }
53 return h.points[lo-1].Amounts
54}
55
56func (h *History) Len() int { return len(h.points) }