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.

Playground

clock.gno

// Package clock is a deadline that actions push forward, with the two guards a
// naive "extend on every action" clock lacks.
//
// Any last-action-wins game has the same clock: every action buys more time, so
// the game ends only when nobody acts. Written naively it has two failure modes,
// and both have been observed on chain rather than reasoned about.
//
// The first is that it never ends. If the grant per action is constant, a
// contested pot is extended forever and the prize is always worth one more
// action. Life is the terminator: an absolute end, fixed when the clock opens,
// that no bump can pass. A game with real money in it needs one.
//
// The second is the opposite, and it shows up as soon as the grant decays to
// relieve the pressure of the first: a grant that is a share of the life left
// shrinks toward zero near the end, so the last stretch becomes too short for a
// transaction to land in, and whoever is holding when that happens simply wins.
// Floor is the anti-snipe: a bump always leaves at least that much on the
// clock, however little is left to share.
//
// Times are int64 and the unit is the caller's: block heights or unix seconds,
// as long as it is consistent. Nothing here reads the chain, so a realm can
// test its whole endgame without one.
//
// A game built on this package is at
// [r/moul/x/games/lastwords](/r/nym-moultest123/x/games/lastwords/v0).
package clock

import "errors"

const maxInt64 = int64(9223372036854775807)

var (
	// ErrBadWindow is returned when the opening grant is not positive.
	ErrBadWindow = errors.New("clock: window must be positive")
	// ErrBadFloor is returned when the floor is negative or exceeds the window.
	ErrBadFloor = errors.New("clock: floor must be between zero and the window")
	// ErrBadLife is returned when the life is negative, or positive but shorter
	// than the opening window, which would close the clock before it opened.
	ErrBadLife = errors.New("clock: life must be zero (unbounded) or at least the window")
	// ErrBadShare is returned when a share is outside 0..100.
	ErrBadShare = errors.New("clock: share must be a percentage between 0 and 100")
	// ErrUnbounded is returned when a share of the remaining life is asked of a
	// clock that has no hard end to measure against.
	ErrUnbounded = errors.New("clock: a share of the life needs a bounded clock")
	// ErrOverflow is returned when the requested times do not fit in an int64.
	ErrOverflow = errors.New("clock: times overflow int64")
)

// Clock is a deadline plus the three bounds that make it terminate: the window
// a bump grants, the floor a bump always leaves, and the life it can never pass.
//
// The zero Clock is not usable; build one with New.
type Clock struct {
	start    int64
	deadline int64
	window   int64
	floor    int64
	life     int64 // 0 means unbounded
}

// New opens a clock at now, due now+window.
//
// window is what a plain Bump grants. floor is the minimum a bump leaves on the
// clock, and must not exceed the window (a floor above the window would mean
// every bump granting more than the window, which is not a floor). life is the
// total lifetime from now, after which the deadline can no longer move; zero
// leaves the clock unbounded, which is the shape that never terminates, so pass
// it deliberately.
func New(now, window, floor, life int64) (*Clock, error) {
	if window <= 0 {
		return nil, ErrBadWindow
	}
	if floor < 0 || floor > window {
		return nil, ErrBadFloor
	}
	if life < 0 || (life > 0 && life < window) {
		return nil, ErrBadLife
	}
	if window > maxInt64-now || life > maxInt64-now {
		return nil, ErrOverflow
	}
	return &Clock{
		start:    now,
		deadline: now + window,
		window:   window,
		floor:    floor,
		life:     life,
	}, nil
}

// Start returns when the clock opened.
func (c *Clock) Start() int64 { return c.start }

// Deadline returns the time the clock currently expires at.
func (c *Clock) Deadline() int64 { return c.deadline }

// Window returns the grant a plain Bump aims for.
func (c *Clock) Window() int64 { return c.window }

// Floor returns the minimum a bump leaves on the clock.
func (c *Clock) Floor() int64 { return c.floor }

// Life returns the configured lifetime, zero when unbounded.
func (c *Clock) Life() int64 { return c.life }

// HardEnd returns the time no bump can push the deadline past, or zero when the
// clock is unbounded.
func (c *Clock) HardEnd() int64 {
	if c.life == 0 {
		return 0
	}
	return c.start + c.life
}

// Expired reports whether the clock has run out at now. The deadline itself is
// past it: a clock due at 100 is expired at 100, so an action and an expiry can
// never both be valid at the same instant.
func (c *Clock) Expired(now int64) bool { return now >= c.deadline }

// Remaining returns how much time is left at now, never negative.
func (c *Clock) Remaining(now int64) int64 {
	if now >= c.deadline {
		return 0
	}
	return c.deadline - now
}

// Elapsed returns how long the clock has been open at now, never negative.
func (c *Clock) Elapsed(now int64) int64 {
	if now <= c.start {
		return 0
	}
	return now - c.start
}

// Final reports whether the deadline has reached the hard end, so no further
// bump can move it. A game should say so on its page: it is the only moment at
// which holding is worth more than acting.
func (c *Clock) Final() bool { return c.life > 0 && c.deadline >= c.HardEnd() }

// Bump extends the deadline by the window. See BumpBy for the guards.
func (c *Clock) Bump(now int64) int64 { return c.BumpBy(now, c.window) }

// BumpBy extends the deadline to now+grant and returns the new deadline.
//
// The caller owns the policy, so grant is whatever it wants: a constant, a share
// of what is left, a function of the amount paid. The clock owns the four
// invariants that policy keeps getting wrong:
//
//   - An expired clock never restarts. Once it has run out the deadline is
//     frozen, so a late action cannot reopen a settled game.
//   - The deadline never moves backwards. A small grant late in the game leaves
//     the existing deadline alone rather than shortening it.
//   - A bump always leaves at least the floor on the clock, so a decaying grant
//     cannot be shaved below the time a transaction needs to land.
//   - The deadline never passes the hard end.
func (c *Clock) BumpBy(now, grant int64) int64 {
	if c.Expired(now) {
		return c.deadline
	}
	if grant < c.floor {
		grant = c.floor
	}
	want := c.deadline
	if grant <= maxInt64-now && now+grant > want {
		want = now + grant
	} else if grant > maxInt64-now {
		want = maxInt64
	}
	if end := c.HardEnd(); c.life > 0 && want > end {
		want = end
	}
	c.deadline = want
	return c.deadline
}

// BumpShare grants pct percent of the time left until the hard end, and is the
// decaying grant a converging game wants.
//
// A grant that is a share of what is left on the DEADLINE cannot extend
// anything: now+(deadline-now)*pct/100 is always before the deadline itself. A
// share of the distance to the hard end is the one that works. Each action
// closes a fraction of the gap, so the deadline crawls toward the hard end and
// the grants shrink as it does, which is exactly the "the pot is worth one more
// action" pressure a fixed grant never relieves. The floor is what stops the
// tail of that curve from becoming too short to act in.
//
// It requires a bounded clock: there is no distance to share without one.
func (c *Clock) BumpShare(now, pct int64) (int64, error) {
	if c.life == 0 {
		return c.deadline, ErrUnbounded
	}
	if pct < 0 || pct > 100 {
		return c.deadline, ErrBadShare
	}
	left := c.HardEnd() - now
	if left < 0 {
		left = 0
	}
	var grant int64
	if left > maxInt64/100 {
		grant = left / 100 * pct // lossy, but only where exactness is meaningless
	} else {
		grant = left * pct / 100 // multiply first, so a small gap still grants
	}
	return c.BumpBy(now, grant), nil
}

clock_test.gno

package clock

import (
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func mustNew(t *testing.T, now, window, floor, life int64) *Clock {
	t.Helper()
	c, err := New(now, window, floor, life)
	uassert.NoError(t, err)
	return c
}

func TestNewValidation(t *testing.T) {
	cases := []struct {
		name                     string
		now, window, floor, life int64
		want                     error
	}{
		{"zero window", 0, 0, 0, 0, ErrBadWindow},
		{"negative window", 0, -1, 0, 0, ErrBadWindow},
		{"negative floor", 0, 100, -1, 0, ErrBadFloor},
		{"floor above window", 0, 100, 101, 0, ErrBadFloor},
		{"negative life", 0, 100, 10, -1, ErrBadLife},
		{"life shorter than window", 0, 100, 10, 99, ErrBadLife},
		{"window overflows", maxInt64 - 5, 100, 0, 0, ErrOverflow},
		{"life overflows", maxInt64 - 500, 100, 0, 1000, ErrOverflow},
		{"unbounded is legal", 0, 100, 10, 0, nil},
		{"life equal to window is legal", 0, 100, 10, 100, nil},
		{"floor equal to window is legal", 0, 100, 100, 0, nil},
	}
	for _, tc := range cases {
		_, err := New(tc.now, tc.window, tc.floor, tc.life)
		if tc.want == nil {
			uassert.NoError(t, err, tc.name)
			continue
		}
		uassert.ErrorIs(t, err, tc.want, tc.name)
	}
}

func TestOpensDueAtWindow(t *testing.T) {
	c := mustNew(t, 1000, 100, 10, 500)
	uassert.Equal(t, int64(1000), c.Start())
	uassert.Equal(t, int64(1100), c.Deadline())
	uassert.Equal(t, int64(1500), c.HardEnd())
	uassert.Equal(t, int64(100), c.Remaining(1000))
	uassert.Equal(t, int64(0), c.Elapsed(1000))
	uassert.False(t, c.Expired(1099))
	uassert.True(t, c.Expired(1100), "the deadline itself is expired")
	uassert.False(t, c.Final())
}

func TestUnboundedHasNoHardEnd(t *testing.T) {
	c := mustNew(t, 0, 100, 0, 0)
	uassert.Equal(t, int64(0), c.HardEnd())
	uassert.False(t, c.Final(), "an unbounded clock is never final")
	c.Bump(90)
	c.Bump(180)
	uassert.Equal(t, int64(280), c.Deadline(), "nothing caps it")
}

// TestBumpNeverMovesBackwards is the invariant a caller supplying its own grant
// gets wrong first: a late, small grant must not shorten the clock.
func TestBumpNeverMovesBackwards(t *testing.T) {
	c := mustNew(t, 0, 1000, 0, 0)
	uassert.Equal(t, int64(1000), c.Deadline())

	uassert.Equal(t, int64(1000), c.BumpBy(10, 5), "now+5 is before the deadline")
	uassert.Equal(t, int64(1000), c.BumpBy(900, 0), "a zero grant leaves it alone")
	uassert.Equal(t, int64(1100), c.BumpBy(900, 200), "a grant past the deadline moves it")
}

// TestFloorSurvivesATinyGrant is the anti-snipe: whatever the policy grants, a
// bump leaves at least the floor, so the last stretch stays reachable.
func TestFloorSurvivesATinyGrant(t *testing.T) {
	c := mustNew(t, 0, 1000, 50, 0)
	c.BumpBy(990, 1)
	uassert.Equal(t, int64(1040), c.Deadline(), "1 was raised to the floor of 50")
	uassert.Equal(t, int64(50), c.Remaining(990))

	c2 := mustNew(t, 0, 1000, 50, 0)
	c2.BumpBy(990, 0)
	uassert.Equal(t, int64(50), c2.Remaining(990), "even a zero grant leaves the floor")
}

// TestHardEndCapsEveryBump is the terminator: without it a contested clock is
// extended forever and the game has no end.
func TestHardEndCapsEveryBump(t *testing.T) {
	c := mustNew(t, 0, 100, 10, 250)
	uassert.Equal(t, int64(250), c.HardEnd())

	c.BumpBy(90, 100)
	uassert.Equal(t, int64(190), c.Deadline())
	c.BumpBy(180, 100)
	uassert.Equal(t, int64(250), c.Deadline(), "capped at the hard end, not 280")
	uassert.True(t, c.Final())

	c.BumpBy(240, 1000000)
	uassert.Equal(t, int64(250), c.Deadline(), "the cap holds against any grant")
	uassert.Equal(t, int64(10), c.Remaining(240), "and it beats the floor")
}

// TestExpiredClockNeverRestarts stops a late action from reopening a settled
// game, which is the difference between a closed pot and a stolen one.
func TestExpiredClockNeverRestarts(t *testing.T) {
	c := mustNew(t, 0, 100, 10, 0)
	uassert.True(t, c.Expired(100))
	uassert.Equal(t, int64(100), c.BumpBy(100, 500), "exactly at the deadline")
	uassert.Equal(t, int64(100), c.Bump(5000), "long after")
	uassert.Equal(t, int64(0), c.Remaining(100))

	settled := mustNew(t, 0, 100, 10, 1000)
	uassert.True(t, settled.Expired(100))
	got, err := settled.BumpShare(200, 50)
	uassert.NoError(t, err)
	uassert.Equal(t, int64(100), got, "not even a large share reopens it")
}

func TestBumpShareValidation(t *testing.T) {
	c := mustNew(t, 0, 100, 0, 500)
	_, err := c.BumpShare(10, -1)
	uassert.ErrorIs(t, err, ErrBadShare)
	_, err = c.BumpShare(10, 101)
	uassert.ErrorIs(t, err, ErrBadShare)
	uassert.Equal(t, int64(100), c.Deadline(), "a rejected share changes nothing")

	unbounded := mustNew(t, 0, 100, 0, 0)
	_, err = unbounded.BumpShare(10, 50)
	uassert.ErrorIs(t, err, ErrUnbounded, "no hard end, nothing to take a share of")
}

// TestBumpShareDecays is why the share grant exists: each action closes a
// fraction of the gap to the hard end, so the grants shrink as the game runs
// and the pressure to act one more time is relieved instead of compounding.
func TestBumpShareDecays(t *testing.T) {
	c := mustNew(t, 0, 100, 1, 1000)
	first, err := c.BumpShare(10, 50)
	uassert.NoError(t, err)
	uassert.Equal(t, int64(505), first, "half the 990 left to the hard end")

	second, err := c.BumpShare(500, 50)
	uassert.NoError(t, err)
	uassert.Equal(t, int64(750), second, "half of the 500 now left, a smaller grant")

	third, err := c.BumpShare(700, 50)
	uassert.NoError(t, err)
	uassert.Equal(t, int64(850), third, "smaller again")
	uassert.True(t, third < c.HardEnd(), "it approaches the hard end without reaching it")
}

// TestBumpShareRoundingStillGrants is the multiply-first lesson: a share of a
// gap smaller than the divisor must not truncate to a zero grant.
func TestBumpShareRoundingStillGrants(t *testing.T) {
	// 52 due, 50 left to the hard end: a tenth of that is 5, and dividing
	// before multiplying would truncate it to a grant of zero.
	c := mustNew(t, 0, 52, 0, 100)
	got, err := c.BumpShare(50, 10)
	uassert.NoError(t, err)
	uassert.Equal(t, int64(55), got, "a tenth of the 50 left is 5, not 0")
}

func TestBumpShareRespectsFloorAndCap(t *testing.T) {
	c := mustNew(t, 0, 100, 20, 150)
	got, err := c.BumpShare(95, 10) // a tenth of the 55 left is 5, floored to 20
	uassert.NoError(t, err)
	uassert.Equal(t, int64(115), got)

	got, err = c.BumpShare(110, 100) // would be 150 exactly, and never past it
	uassert.NoError(t, err)
	uassert.Equal(t, int64(150), got)
	uassert.True(t, c.Final())
}

// TestHugeGrantDoesNotWrap keeps a bump total at the extremes: a wrapped
// deadline would land in the past and settle the game instantly.
func TestHugeGrantDoesNotWrap(t *testing.T) {
	c := mustNew(t, 0, 100, 0, 0)
	uassert.Equal(t, maxInt64, c.BumpBy(50, maxInt64), "clamped, not wrapped")
	uassert.True(t, c.Deadline() > 0)

	big := mustNew(t, maxInt64/2, 1000, 0, maxInt64/4)
	got, err := big.BumpShare(maxInt64/2+1, 100)
	uassert.NoError(t, err)
	uassert.True(t, got > maxInt64/2, "a huge remaining share does not wrap")
}

func TestElapsedAndRemainingAreNeverNegative(t *testing.T) {
	c := mustNew(t, 100, 100, 0, 0)
	uassert.Equal(t, int64(0), c.Elapsed(50), "before the start")
	uassert.Equal(t, int64(100), c.Remaining(100))
	uassert.Equal(t, int64(0), c.Remaining(9999), "long past the deadline")
	uassert.Equal(t, int64(9899), c.Elapsed(9999))
}

gnomod.toml

module = "gno.land/p/nym-moultest123/x/games/clock/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186406
  max_deposit = "8000000ugnot"