Playground
accrual.gno
// Package accrual is stock that fills at a rate while nobody is playing: the
// resource field of an idle game, the warehouse of a 4X, anything whose state
// is a function of how long it has been left alone.
//
// The shape is always the same. Store what you had and when, and compute the
// rest on demand; a player who does nothing for a month costs nothing, and the
// realm needs no cron, no keeper and no per-block hook. That much is obvious.
// What is not obvious is that the obvious implementation is wrong in three
// ways, each of which has been observed in this repository rather than
// reasoned about.
//
// # 1. Re-anchoring to now makes acting more often pay
//
// Written naively, a claim advances the anchor to now and computes
// elapsed/Period whole periods of production. The division truncates, so every
// claim silently forfeits the part-period it lands in, and a player who claims
// twice forfeits twice. Run in reverse on a decaying stat it is worse than
// unfair, it is free: [r/moul/x/daily/tamagotchi] decayed by elapsed/2 and
// elapsed/3, so at elapsed == 1 it decayed by nothing at all, and feeding once
// per block made the pet immortal while every other cadence died inside 240
// blocks. It was fixed in #221.
//
// The invariant that rules it out is worth stating on its own, because it is
// the whole contract of this package:
//
// Advance(s, a, c) == Advance(Advance(s, a, b), b, c) for a <= b <= c
//
// How often you call must not change where you end up. [Rate.Advance] gets
// there by advancing the anchor only by the WHOLE periods it paid for, leaving
// the remainder on the clock rather than throwing it away. TestSplitInvariant
// asserts it over pseudo-random partitions rather than over a handful of
// hand-picked spans, because the hand-picked spans are exactly the ones a
// wrong implementation already passes.
//
// # 2. A view that does not share the write path's arithmetic drifts from it
//
// The same realm had a second copy of the decay for its Render, so the page
// showed a pet the next call would not honour. Two implementations of one rule
// means one of them is the stale one somebody acts on. Here there is one
// function: [Rate.At] is [Rate.Advance] with the anchor discarded, so a view
// cannot disagree with a write even in principle.
//
// # 3. A projection that is not closed form cannot be rendered at all
//
// Render runs under a query gas limit and may not write, so whatever it
// computes has to be bounded however long the player was away. Anything
// iterative, stepping a simulation once per block, is fine in a transaction
// and unusable in a page: the player who comes back after a month is exactly
// the one whose page times out. Everything here is O(1) in elapsed time, which
// is the property that makes a live-updating page possible, not an
// optimisation.
//
// Times are int64 and the unit is the caller's, block heights or unix seconds,
// as long as it is consistent. Prefer a timestamp: a block-height rate drifts
// in wall-clock terms every time the chain's block time moves, and gno.land's
// has moved from about 4.1s to 3.405s inside one month. Nothing here reads the
// chain, so a realm can test a year of its own economy without one.
//
// A game built on this package is at
// [r/moul/x/games/idle](/r/nym-moultest123/x/games/idle/v0).
//
// [r/moul/x/daily/tamagotchi]: /r/nym-moultest123/x/daily/tamagotchi/v0
package accrual
import "errors"
const maxInt64 = int64(9223372036854775807)
var (
// ErrBadAmount is returned when the amount produced per period is not
// positive. A zero rate is a bug in the caller, not a valid still life:
// it makes Full unanswerable and every Advance a no-op.
ErrBadAmount = errors.New("accrual: amount must be positive")
// ErrBadPeriod is returned when the period is not positive.
ErrBadPeriod = errors.New("accrual: period must be positive")
// ErrBadCap is returned when the cap is negative. Zero is legal and
// means unbounded.
ErrBadCap = errors.New("accrual: cap must not be negative")
// ErrNegativeStock is returned when the stock handed in is negative,
// which would let a caller mint by going through zero.
ErrNegativeStock = errors.New("accrual: stock must not be negative")
// ErrBackwards is returned when now falls before the anchor. Time moving
// backwards is a caller bug (a stored anchor from another clock, a test
// that rewound), and silently treating it as zero elapsed would hide it.
ErrBackwards = errors.New("accrual: now must not fall before the anchor")
// ErrOverflow is returned when the arithmetic would wrap int64.
ErrOverflow = errors.New("accrual: int64 overflow")
)
// Rate is production per unit of time, against a ceiling. Construct with New
// so the invariants are checked once instead of on every call.
type Rate struct {
Amount int64 // produced each whole Period
Period int64 // time units in one period
Cap int64 // ceiling on the stock; zero means unbounded
}
// New validates and returns a Rate. A zero cap means unbounded.
func New(amount, period, capacity int64) (Rate, error) {
if amount <= 0 {
return Rate{}, ErrBadAmount
}
if period <= 0 {
return Rate{}, ErrBadPeriod
}
if capacity < 0 {
return Rate{}, ErrBadCap
}
return Rate{Amount: amount, Period: period, Cap: capacity}, nil
}
// Advance returns the stock and the new anchor at time now, given stock held
// since anchor.
//
// The new anchor is NOT now. It is the anchor plus the whole periods actually
// paid out, so the part-period in progress stays on the clock and splitting a
// span into pieces yields exactly what advancing it in one go would:
//
// Advance(s, a, c) == Advance(Advance(s, a, b), b, c) for a <= b <= c
//
// Production past the cap is lost, which is what a cap is for. Saturation is
// idempotent, so it does not break the equality above, and it means a CAPPED
// rate can never return ErrOverflow: the answer is the cap however long the
// player was away. Only an uncapped rate can run out of int64.
func (r Rate) Advance(stock, anchor, now int64) (int64, int64, error) {
if err := r.check(); err != nil {
return 0, 0, err
}
if stock < 0 {
return 0, 0, ErrNegativeStock
}
if now < anchor {
return 0, 0, ErrBackwards
}
// now-anchor wraps only when the anchor is negative and now is far
// enough above it. maxInt64+anchor is safe to compute precisely because
// anchor is negative there.
if anchor < 0 && now > maxInt64+anchor {
return 0, 0, ErrOverflow
}
periods := (now - anchor) / r.Period
// The anchor only moves by what was paid for. periods*r.Period cannot
// overflow, it is at most now-anchor, and adding it back cannot pass now.
newAnchor := anchor + periods*r.Period
if r.Cap > 0 && stock >= r.Cap {
return stock, newAnchor, nil
}
// Production is only computed when its exact value can matter. A capped
// rate whose payout would wrap int64 has an answer regardless of what
// that payout is, so it gets one instead of an error.
if periods > maxInt64/r.Amount {
return r.saturate(newAnchor)
}
produced := periods * r.Amount
if produced > maxInt64-stock {
return r.saturate(newAnchor)
}
total := stock + produced
if r.Cap > 0 && total > r.Cap {
total = r.Cap
}
return total, newAnchor, nil
}
// saturate answers an accrual too large for int64: the cap if there is one,
// and an error if there is not. A capped Rate therefore never overflows,
// which is the property that lets a realm size a warehouse without also
// having to bound its own lifetime.
func (r Rate) saturate(newAnchor int64) (int64, int64, error) {
if r.Cap == 0 {
return 0, 0, ErrOverflow
}
return r.Cap, newAnchor, nil
}
// At is Advance with the anchor discarded: the read-only view of the same
// arithmetic, for a Render that must not write. It is defined in terms of
// Advance on purpose, so a page can never show a number a write would not
// honour.
func (r Rate) At(stock, anchor, now int64) (int64, error) {
got, _, err := r.Advance(stock, anchor, now)
return got, err
}
// Full returns the time at which the stock first reaches the cap, for a realm
// that wants to tell a player when their production starts being wasted.
//
// An uncapped rate returns zero, meaning never. A stock already at or past the
// cap returns the anchor, meaning now.
func (r Rate) Full(stock, anchor int64) (int64, error) {
if err := r.check(); err != nil {
return 0, err
}
if stock < 0 {
return 0, ErrNegativeStock
}
if r.Cap == 0 {
return 0, nil
}
if stock >= r.Cap {
return anchor, nil
}
// Whole periods needed to cover the shortfall, rounded UP: the cap is
// reached by the payout that crosses it, not by the one before.
need := r.Cap - stock
periods := need / r.Amount
if need%r.Amount != 0 {
periods++
}
if periods > maxInt64/r.Period {
return 0, ErrOverflow
}
span := periods * r.Period
if span > maxInt64-anchor {
return 0, ErrOverflow
}
return anchor + span, nil
}
// check rejects a zero Rate built by struct literal instead of New, so a
// caller that skipped the constructor gets the same error it would have.
func (r Rate) check() error {
if r.Amount <= 0 {
return ErrBadAmount
}
if r.Period <= 0 {
return ErrBadPeriod
}
if r.Cap < 0 {
return ErrBadCap
}
return nil
}
accrual_test.gno
package accrual
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
func mustNew(t *testing.T, amount, period, capacity int64) Rate {
t.Helper()
r, err := New(amount, period, capacity)
uassert.NoError(t, err)
return r
}
func TestNewValidation(t *testing.T) {
cases := []struct {
name string
amount, period, capacity int64
want error
}{
{"zero amount", 0, 60, 100, ErrBadAmount},
{"negative amount", -1, 60, 100, ErrBadAmount},
{"zero period", 1, 0, 100, ErrBadPeriod},
{"negative period", 1, -60, 100, ErrBadPeriod},
{"negative cap", 1, 60, -1, ErrBadCap},
{"zero cap is unbounded", 1, 60, 0, nil},
{"all positive", 5, 60, 100, nil},
}
for _, tc := range cases {
_, err := New(tc.amount, tc.period, tc.capacity)
if tc.want == nil {
uassert.NoError(t, err, tc.name)
continue
}
uassert.ErrorIs(t, err, tc.want, tc.name)
}
}
func TestAdvance(t *testing.T) {
cases := []struct {
name string
amount, period, capacity int64
stock, anchor, now int64
wantStock, wantAnchor int64
}{
{"nothing elapsed", 1, 60, 0, 0, 1000, 1000, 0, 1000},
{"less than one period", 1, 60, 0, 0, 1000, 1059, 0, 1000},
{"exactly one period", 1, 60, 0, 0, 1000, 1060, 1, 1060},
{"one period and change keeps the change", 1, 60, 0, 0, 1000, 1119, 1, 1060},
{"ten periods", 3, 60, 0, 0, 1000, 1600, 30, 1600},
{"adds to what was held", 3, 60, 0, 7, 1000, 1600, 37, 1600},
{"saturates at the cap", 1, 60, 10, 0, 1000, 9000, 10, 8980},
{"already full produces nothing", 1, 60, 10, 10, 1000, 9000, 10, 8980},
{"over the cap is left alone", 1, 60, 10, 25, 1000, 9000, 25, 8980},
{"uncapped keeps going", 1, 60, 0, 0, 0, 604800, 10080, 604800},
}
for _, tc := range cases {
r := mustNew(t, tc.amount, tc.period, tc.capacity)
gotStock, gotAnchor, err := r.Advance(tc.stock, tc.anchor, tc.now)
uassert.NoError(t, err, tc.name)
uassert.Equal(t, tc.wantStock, gotStock, tc.name+": stock")
uassert.Equal(t, tc.wantAnchor, gotAnchor, tc.name+": anchor")
}
}
// TestAnchorKeepsTheRemainder pins the one decision the whole package rests
// on: the new anchor is not now. Advancing to a time halfway through a period
// leaves that half on the clock, which is what makes splitting free.
func TestAnchorKeepsTheRemainder(t *testing.T) {
r := mustNew(t, 1, 60, 0)
_, anchor, err := r.Advance(0, 0, 599)
uassert.NoError(t, err)
uassert.Equal(t, int64(540), anchor, "anchor must stop at the last whole period, not at now")
}
// TestSplitInvariant is the contract of this package:
//
// Advance(s, a, c) == Advance(Advance(s, a, b), b, c)
//
// It runs over pseudo-random partitions rather than hand-picked ones, because
// an implementation that re-anchors to now passes every round span and only
// fails on the ones that land mid-period. The generator is a fixed LCG, so a
// failure is reproducible.
func TestSplitInvariant(t *testing.T) {
rates := []Rate{
mustNew(t, 1, 60, 0), // one a minute, unbounded
mustNew(t, 7, 13, 0), // coprime, so remainders never line up
mustNew(t, 1, 60, 500), // capped
mustNew(t, 250, 3600, 0), // coarse period
mustNew(t, 1, 1, 0), // degenerate: every tick pays
mustNew(t, 3, 1000, 1234), // capped and coarse
}
seed := uint64(0x9E3779B97F4A7C15)
next := func(n int64) int64 {
seed = seed*6364136223846793005 + 1442695040888963407
return int64(seed>>33) % n
}
for _, r := range rates {
for i := 0; i < 400; i++ {
start := next(10000)
span := next(100000)
stock := next(600)
end := start + span
wantStock, wantAnchor, err := r.Advance(stock, start, end)
uassert.NoError(t, err)
// Cut the span into between one and six pieces and walk them.
cuts := next(6) + 1
gotStock, gotAnchor := stock, start
at := start
for c := int64(0); c < cuts; c++ {
remaining := end - at
if remaining <= 0 {
break
}
step := next(remaining + 1)
if c == cuts-1 {
step = remaining
}
at += step
gotStock, gotAnchor, err = r.Advance(gotStock, gotAnchor, at)
uassert.NoError(t, err)
}
// Land on the end whatever the cuts did.
gotStock, gotAnchor, err = r.Advance(gotStock, gotAnchor, end)
uassert.NoError(t, err)
uassert.Equal(t, wantStock, gotStock, "split stock diverged")
uassert.Equal(t, wantAnchor, gotAnchor, "split anchor diverged")
}
}
}
// TestClaimingEveryTickIsNotFree is the regression for the bug this package
// exists to make unrepresentable. r/moul/x/daily/tamagotchi truncated its
// per-call decay, so acting every tick cost nothing and acting rarely cost
// everything. Here the two agree exactly.
func TestClaimingEveryTickIsNotFree(t *testing.T) {
r := mustNew(t, 1, 60, 0)
const span = 6000 // 100 whole periods
oneShot, _, err := r.Advance(0, 0, span)
uassert.NoError(t, err)
for _, cadence := range []int64{1, 2, 7, 60, 61, 599, 3000} {
stock, anchor := int64(0), int64(0)
for at := cadence; at <= span; at += cadence {
stock, anchor, err = r.Advance(stock, anchor, at)
uassert.NoError(t, err)
}
stock, _, err = r.Advance(stock, anchor, span)
uassert.NoError(t, err)
uassert.Equal(t, oneShot, stock, "cadence changed the payout")
}
}
// TestAtMatchesAdvance pins that the read path cannot drift from the write
// path, which was the second and quieter half of the tamagotchi bug.
func TestAtMatchesAdvance(t *testing.T) {
r := mustNew(t, 5, 17, 900)
for now := int64(3); now < 4000; now += 37 {
want, _, err := r.Advance(11, 3, now)
uassert.NoError(t, err)
got, err := r.At(11, 3, now)
uassert.NoError(t, err)
uassert.Equal(t, want, got, "At diverged from Advance")
}
}
func TestAdvanceRejects(t *testing.T) {
r := mustNew(t, 1, 60, 0)
_, _, err := r.Advance(-1, 0, 100)
uassert.ErrorIs(t, err, ErrNegativeStock)
_, _, err = r.Advance(0, 100, 99)
uassert.ErrorIs(t, err, ErrBackwards)
// A Rate built by literal instead of New is still checked.
_, _, err = Rate{}.Advance(0, 0, 100)
uassert.ErrorIs(t, err, ErrBadAmount)
_, _, err = Rate{Amount: 1}.Advance(0, 0, 100)
uassert.ErrorIs(t, err, ErrBadPeriod)
_, _, err = Rate{Amount: 1, Period: 1, Cap: -1}.Advance(0, 0, 100)
uassert.ErrorIs(t, err, ErrBadCap)
}
func TestAdvanceOverflow(t *testing.T) {
// An uncapped rate that would pass int64 refuses rather than wrapping
// into a negative stock, which is how a large vesting grant once
// reported a negative balance.
r := mustNew(t, maxInt64/2, 1, 0)
_, _, err := r.Advance(0, 0, 100)
uassert.ErrorIs(t, err, ErrOverflow)
// The same rate with a cap always has an answer, so it gives one
// instead of an error, whichever of the two guards it trips.
capped := mustNew(t, maxInt64/2, 1, 1000)
got, anchor, err := capped.Advance(0, 0, 100)
uassert.NoError(t, err)
uassert.Equal(t, int64(1000), got)
uassert.Equal(t, int64(100), anchor, "a saturated advance still moves the anchor")
got, _, err = capped.Advance(999, 0, 1)
uassert.NoError(t, err)
uassert.Equal(t, int64(1000), got, "the sum guard saturates too")
// A negative anchor far enough below now wraps the elapsed span itself.
slow := mustNew(t, 1, maxInt64, 0)
_, _, err = slow.Advance(0, -10, maxInt64-5)
uassert.ErrorIs(t, err, ErrOverflow)
}
func TestFull(t *testing.T) {
cases := []struct {
name string
amount, period, capacity int64
stock, anchor int64
want int64
}{
{"uncapped never fills", 1, 60, 0, 0, 1000, 0},
{"already full is now", 1, 60, 10, 10, 1000, 1000},
{"past full is now", 1, 60, 10, 99, 1000, 1000},
{"empty takes the whole cap", 1, 60, 10, 0, 1000, 1600},
{"partly full takes the rest", 1, 60, 10, 4, 1000, 1360},
{"rounds up to the payout that crosses", 3, 60, 10, 0, 0, 240},
{"exact division does not round up", 5, 60, 10, 0, 0, 120},
}
for _, tc := range cases {
r := mustNew(t, tc.amount, tc.period, tc.capacity)
got, err := r.Full(tc.stock, tc.anchor)
uassert.NoError(t, err, tc.name)
uassert.Equal(t, tc.want, got, tc.name)
}
}
// TestFullAgreesWithAdvance checks the two halves of the API against each
// other: at the time Full names, the stock is at the cap, and one period
// earlier it is not.
func TestFullAgreesWithAdvance(t *testing.T) {
for _, r := range []Rate{
mustNew(t, 1, 60, 10),
mustNew(t, 3, 60, 10),
mustNew(t, 7, 13, 1000),
mustNew(t, 250, 3600, 875),
} {
full, err := r.Full(0, 0)
uassert.NoError(t, err)
atFull, err := r.At(0, 0, full)
uassert.NoError(t, err)
uassert.Equal(t, r.Cap, atFull, "not full at the time Full named")
before, err := r.At(0, 0, full-r.Period)
uassert.NoError(t, err)
if before >= r.Cap {
t.Errorf("already full a period early: %d >= %d", before, r.Cap)
}
}
}
func TestFullRejects(t *testing.T) {
r := mustNew(t, 1, 60, 10)
_, err := r.Full(-1, 0)
uassert.ErrorIs(t, err, ErrNegativeStock)
_, err = Rate{}.Full(0, 0)
uassert.ErrorIs(t, err, ErrBadAmount)
far := mustNew(t, 1, maxInt64/2, 1000)
_, err = far.Full(0, 0)
uassert.ErrorIs(t, err, ErrOverflow)
}
gnomod.toml
module = "gno.land/p/nym-moultest123/x/games/accrual/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186406 max_deposit = "9000000ugnot"