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

dokimi.gno

// Package dokimi is a public registry of pre-registered experiments.
//
// Before a test starts, its owner locks a plan here: the hypothesis, the one
// metric that decides it, the size of change that counts as a win and the
// number of people each arm must reach. The block height and a fingerprint of
// the plan are stored with it. From then on the plan cannot be edited.
//
// While the test runs the owner reports running totals. Every report is kept
// and totals can only go up. A mistake is fixed by adding a correction, which
// is marked as one and never replaces the report it corrects. Closing the
// experiment judges the last report against the plan with the rules in gno.land/p/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v1.
//
// An owner is whoever called Register: a person's account, or another realm
// that wants its own experiments on the public record.
package dokimi

import (
	"chain"
	"chain/runtime"
	"strconv"
	"time"

	core "gno.land/p/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v1"
	"gno.land/p/nt/avl/v0"
)

const (
	// MaxReports bounds how many reports one experiment can hold.
	MaxReports = 100
	// MaxNotes bounds how many notes one experiment can hold.
	MaxNotes = 50
)

// Report is one snapshot of the running totals, kept forever.
type Report struct {
	Height  int64
	Time    time.Time
	Control core.Tally
	Variant core.Tally
	Source  string // where the numbers came from, in the owner's words

	// Correction marks a report that replaces a mistaken one. It is the only
	// kind of report allowed to lower a total, and it is shown as a correction
	// with its reason for as long as the experiment exists.
	Correction bool
	Reason     string
}

// Note is a public remark by the owner, for example a change of plan that
// readers should know about. Notes are added, never edited or removed.
type Note struct {
	Height int64
	Time   time.Time
	Text   string
}

// Experiment is one locked plan and everything recorded against it.
type Experiment struct {
	id           uint64
	owner        address
	plan         core.Plan
	digest       string
	lockedAt     time.Time
	lockedHeight int64
	reports      []Report
	notes        []Note
	closed       bool
	closedAt     time.Time
	closedHeight int64
	verdict      core.Verdict
}

var (
	experiments = avl.NewTree() // key(id) -> *Experiment
	lastID      uint64
)

// Register locks a new plan and returns its id. The caller becomes the owner.
//
// direction is "increase" or "decrease". target is the smallest relative
// change that counts as a win, as a percentage such as "15" or "12.5".
// minSample is the number of exposures each arm must reach before the result
// can count.
func Register(cur realm, title, hypothesis, metric, control, variant, direction, target string, minSample int64) uint64 {
	targetBps, err := core.ParsePercent(target)
	if err != nil {
		panic("target: " + err.Error())
	}
	plan := core.Plan{
		Title:      title,
		Hypothesis: hypothesis,
		Metric:     metric,
		Control:    control,
		Variant:    variant,
		Direction:  core.Direction(direction),
		TargetBps:  targetBps,
		MinSample:  minSample,
	}
	if err := plan.Validate(); err != nil {
		panic(err.Error())
	}

	lastID++
	exp := &Experiment{
		id:           lastID,
		owner:        cur.Previous().Address(),
		plan:         plan,
		digest:       plan.Digest(),
		lockedAt:     time.Now(),
		lockedHeight: runtime.ChainHeight(),
	}
	experiments.Set(key(exp.id), exp)

	chain.Emit(
		"PlanLocked",
		"id", strconv.FormatUint(exp.id, 10),
		"owner", exp.owner.String(),
		"digest", exp.digest,
	)
	return exp.id
}

// AddReport records the running totals for both arms. Only the owner can
// report, only while the experiment is open, and no total may go down.
// source says where the numbers came from, for example a dashboard link.
func AddReport(cur realm, id uint64, controlExposures, controlConversions, variantExposures, variantConversions int64, source string) {
	exp := mustGet(id)
	assertOwner(cur.Previous().Address(), exp)
	if exp.closed {
		panic("experiment is closed")
	}
	if len(exp.reports) >= MaxReports {
		panic("report limit reached, close the experiment")
	}

	control := core.Tally{Exposures: controlExposures, Conversions: controlConversions}
	variant := core.Tally{Exposures: variantExposures, Conversions: variantConversions}
	if err := control.Validate(); err != nil {
		panic(exp.plan.Control + ": " + err.Error())
	}
	if err := variant.Validate(); err != nil {
		panic(exp.plan.Variant + ": " + err.Error())
	}
	if n := len(exp.reports); n > 0 {
		last := exp.reports[n-1]
		if !control.Covers(last.Control) || !variant.Covers(last.Variant) {
			panic("totals cannot go down: report running totals, not the change since last time")
		}
	}
	checkOptionalText("source", source)

	exp.reports = append(exp.reports, Report{
		Height:  runtime.ChainHeight(),
		Time:    time.Now(),
		Control: control,
		Variant: variant,
		Source:  source,
	})

	chain.Emit(
		"ReportAdded",
		"id", strconv.FormatUint(exp.id, 10),
		"report", strconv.Itoa(len(exp.reports)),
	)
}

// AddCorrection replaces the running totals after a mistake, for example a
// mistyped count. Unlike AddReport it may lower a total, so it asks for a
// reason and is shown on the page as a correction. The mistaken report stays
// on the record: a correction is added after it, never written over it.
// Only the owner can correct, and only while the experiment is open.
func AddCorrection(cur realm, id uint64, controlExposures, controlConversions, variantExposures, variantConversions int64, reason string) {
	exp := mustGet(id)
	assertOwner(cur.Previous().Address(), exp)
	if exp.closed {
		panic("experiment is closed")
	}
	if len(exp.reports) == 0 {
		panic("there is no report to correct yet")
	}
	if len(exp.reports) >= MaxReports {
		panic("report limit reached, close the experiment")
	}

	control := core.Tally{Exposures: controlExposures, Conversions: controlConversions}
	variant := core.Tally{Exposures: variantExposures, Conversions: variantConversions}
	if err := control.Validate(); err != nil {
		panic(exp.plan.Control + ": " + err.Error())
	}
	if err := variant.Validate(); err != nil {
		panic(exp.plan.Variant + ": " + err.Error())
	}
	if reason == "" {
		panic("a correction needs a reason")
	}
	checkOptionalText("reason", reason)

	exp.reports = append(exp.reports, Report{
		Height:     runtime.ChainHeight(),
		Time:       time.Now(),
		Control:    control,
		Variant:    variant,
		Correction: true,
		Reason:     reason,
	})

	chain.Emit(
		"CorrectionAdded",
		"id", strconv.FormatUint(exp.id, 10),
		"report", strconv.Itoa(len(exp.reports)),
	)
}

// AddNote attaches a public remark to an experiment. Only the owner can add
// one, at any time, including after the experiment is closed.
func AddNote(cur realm, id uint64, text string) {
	exp := mustGet(id)
	assertOwner(cur.Previous().Address(), exp)
	if len(exp.notes) >= MaxNotes {
		panic("note limit reached")
	}
	if text == "" {
		panic("note is empty")
	}
	checkOptionalText("note", text)

	exp.notes = append(exp.notes, Note{
		Height: runtime.ChainHeight(),
		Time:   time.Now(),
		Text:   text,
	})

	chain.Emit(
		"NoteAdded",
		"id", strconv.FormatUint(exp.id, 10),
		"note", strconv.Itoa(len(exp.notes)),
	)
}

// Close ends an experiment and stores the verdict of its last report judged
// against the locked plan. Only the owner can close, once, and only after at
// least one report. It returns the outcome: "met", "missed" or "inconclusive".
func Close(cur realm, id uint64) string {
	exp := mustGet(id)
	assertOwner(cur.Previous().Address(), exp)
	if exp.closed {
		panic("experiment is already closed")
	}
	if len(exp.reports) == 0 {
		panic("add at least one report before closing")
	}

	last := exp.reports[len(exp.reports)-1]
	exp.verdict = core.Judge(exp.plan, last.Control, last.Variant)
	exp.closed = true
	exp.closedAt = time.Now()
	exp.closedHeight = runtime.ChainHeight()

	chain.Emit(
		"ExperimentClosed",
		"id", strconv.FormatUint(exp.id, 10),
		"outcome", string(exp.verdict.Outcome),
	)
	return string(exp.verdict.Outcome)
}

// Count returns how many experiments have been registered.
func Count() int {
	return experiments.Size()
}

// Status returns "open" while an experiment is running, and afterwards its
// outcome: "met", "missed" or "inconclusive". Other realms can call it to act
// on a result, for example to release a reward only when a target was met.
func Status(id uint64) string {
	exp := mustGet(id)
	if !exp.closed {
		return "open"
	}
	return string(exp.verdict.Outcome)
}

// OwnerOf returns the address that registered the experiment.
func OwnerOf(id uint64) address {
	return mustGet(id).owner
}

// DigestOf returns the fingerprint of the locked plan.
func DigestOf(id uint64) string {
	return mustGet(id).digest
}

// Matches reports whether the given plan text is exactly what was locked
// under id. It recomputes the fingerprint from the arguments, so anyone can
// check a plan they were shown against the public record.
func Matches(id uint64, title, hypothesis, metric, control, variant, direction, target string, minSample int64) bool {
	targetBps, err := core.ParsePercent(target)
	if err != nil {
		return false
	}
	plan := core.Plan{
		Title:      title,
		Hypothesis: hypothesis,
		Metric:     metric,
		Control:    control,
		Variant:    variant,
		Direction:  core.Direction(direction),
		TargetBps:  targetBps,
		MinSample:  minSample,
	}
	return plan.Digest() == mustGet(id).digest
}

// LiftOf returns the lift of the latest report in basis points. ok is false
// when there is no report yet or the lift is undefined.
func LiftOf(id uint64) (liftBps int64, ok bool) {
	exp := mustGet(id)
	if len(exp.reports) == 0 {
		return 0, false
	}
	last := exp.reports[len(exp.reports)-1]
	return core.LiftBps(last.Control, last.Variant)
}

// mustGet returns the experiment or stops the transaction.
func mustGet(id uint64) *Experiment {
	exp, ok := experiments.Get(key(id)).(*Experiment)
	if !ok {
		panic("experiment " + strconv.FormatUint(id, 10) + " not found")
	}
	return exp
}

// assertOwner stops the transaction unless caller owns exp. Pass the direct
// caller of the crossing function: cur.Previous().Address().
func assertOwner(caller address, exp *Experiment) {
	if caller != exp.owner {
		panic("only the owner can do this")
	}
}

// checkOptionalText allows an empty value, and otherwise a single line
// within the package text limit.
func checkOptionalText(name, s string) {
	if len(s) > core.MaxTextLen {
		panic(name + " is longer than " + strconv.Itoa(core.MaxTextLen) + " bytes")
	}
	for i := 0; i < len(s); i++ {
		if s[i] < 0x20 || s[i] == 0x7f {
			panic(name + " must be a single line without control characters")
		}
	}
}

// key turns an id into a fixed-width string so the tree keeps numeric order.
func key(id uint64) string {
	s := strconv.FormatUint(id, 10)
	for len(s) < 20 {
		s = "0" + s
	}
	return s
}

dokimi_test.gno

package dokimi

import (
	"strings"
	"testing"
	"time"

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

var (
	alice = testutils.TestAddress("alice")
	bob   = testutils.TestAddress("bob")
)

// The plan used across the tests: a 15% target and 3,800 exposures per arm.
const (
	tTitle      = "Short signup page vs current page"
	tHypothesis = "A shorter signup page gets more visitors to finish signing up."
	tMetric     = "signup_completed"
	tControl    = "Current page"
	tVariant    = "Short page"
	tDirection  = "increase"
	tTarget     = "15"
	tMinSample  = int64(3800)
)

// reset clears the registry so every test starts from an empty realm.
func reset() {
	experiments = avl.NewTree()
	lastID = 0
}

// Note: testing.SetRealm applies to the frame that calls it, so the tests call
// it directly instead of through a helper.

func TestRegister(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))

	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	uassert.Equal(t, uint64(1), id)
	uassert.Equal(t, 1, Count())
	uassert.Equal(t, "open", Status(id))
	uassert.Equal(t, alice.String(), OwnerOf(id).String())
	uassert.Equal(t, 64, len(DigestOf(id)))

	second := Register(cross(cur), "Second test", tHypothesis, tMetric, tControl, tVariant, "decrease", "2.5%", 100)
	uassert.Equal(t, uint64(2), second)
	uassert.Equal(t, 2, Count())
	uassert.NotEqual(t, DigestOf(id), DigestOf(second))
}

func TestRegisterRejectsBadPlans(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))

	uassert.AbortsContains(t, cur, "title is required", func() {
		Register(cross(cur), "", tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	})
	uassert.AbortsContains(t, cur, "direction must be", func() {
		Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, "up", tTarget, tMinSample)
	})
	uassert.AbortsContains(t, cur, "target:", func() {
		Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, "fifteen", tMinSample)
	})
	uassert.AbortsContains(t, cur, "target must be between", func() {
		Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, "0", tMinSample)
	})
	uassert.AbortsContains(t, cur, "minimum sample", func() {
		Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, 0)
	})
	uassert.AbortsContains(t, cur, "different names", func() {
		Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tControl, tDirection, tTarget, tMinSample)
	})
	uassert.Equal(t, 0, Count(), "a refused plan leaves nothing behind")
}

func TestMatches(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)

	uassert.True(t, Matches(id, tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample))
	uassert.True(t, Matches(id, tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, "15.00%", tMinSample), "same target written another way")
	uassert.False(t, Matches(id, tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, "10", tMinSample), "a lowered target")
	uassert.False(t, Matches(id, tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, 1500), "a lowered sample")
	uassert.False(t, Matches(id, tTitle, tHypothesis+" ", tMetric, tControl, tVariant, tDirection, tTarget, tMinSample), "an edited hypothesis")
	uassert.False(t, Matches(id, tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, "not a number", tMinSample))
}

func TestOnlyOwnerCanWrite(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	AddReport(cross(cur), id, 100, 10, 100, 12, "dashboard")

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "only the owner can do this", func() {
		AddReport(cross(cur), id, 200, 20, 200, 60, "")
	})
	uassert.AbortsWithMessage(t, cur, "only the owner can do this", func() {
		AddNote(cross(cur), id, "nothing to see")
	})
	uassert.AbortsWithMessage(t, cur, "only the owner can do this", func() {
		Close(cross(cur), id)
	})
	uassert.Equal(t, "open", Status(id))
	uassert.Equal(t, 1, len(mustGet(id).reports))
	uassert.Equal(t, 0, len(mustGet(id).notes))
}

func TestReportRules(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)

	uassert.AbortsContains(t, cur, "conversions cannot exceed exposures", func() {
		AddReport(cross(cur), id, 100, 101, 100, 12, "")
	})
	uassert.AbortsContains(t, cur, "counts cannot be negative", func() {
		AddReport(cross(cur), id, 100, 10, -1, 0, "")
	})
	uassert.AbortsContains(t, cur, "source must be a single line", func() {
		AddReport(cross(cur), id, 100, 10, 100, 12, "line one\nline two")
	})

	AddReport(cross(cur), id, 100, 10, 100, 12, "first look")

	// Totals are running totals: none of the four may go down.
	uassert.AbortsContains(t, cur, "totals cannot go down", func() {
		AddReport(cross(cur), id, 99, 10, 100, 12, "")
	})
	uassert.AbortsContains(t, cur, "totals cannot go down", func() {
		AddReport(cross(cur), id, 200, 9, 200, 30, "")
	})
	uassert.AbortsContains(t, cur, "totals cannot go down", func() {
		AddReport(cross(cur), id, 200, 20, 200, 11, "")
	})

	// The same totals again, or higher ones, are accepted.
	AddReport(cross(cur), id, 100, 10, 100, 12, "no new traffic")
	AddReport(cross(cur), id, 200, 20, 210, 30, "")
	uassert.Equal(t, 3, len(mustGet(id).reports))

	lift, ok := LiftOf(id)
	uassert.True(t, ok)
	// (30*200 - 20*210) * 10000 / (20*210) = 4285.7
	uassert.Equal(t, int64(4285), lift)
}

func TestLiftOfWithoutReports(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	_, ok := LiftOf(id)
	uassert.False(t, ok)
}

func TestCloseNeedsAReport(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	uassert.AbortsWithMessage(t, cur, "add at least one report before closing", func() {
		Close(cross(cur), id)
	})
	uassert.Equal(t, "open", Status(id))
}

// A test stopped before the promised sample is inconclusive even when the
// numbers look like a clear win.
func TestCloseStoppedEarly(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	AddReport(cross(cur), id, 1530, 268, 1547, 400, "dashboard")

	outcome := Close(cross(cur), id)
	uassert.Equal(t, "inconclusive", outcome)
	uassert.Equal(t, "inconclusive", Status(id))
}

func TestCloseMissed(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	AddReport(cross(cur), id, 4000, 700, 4000, 784, "dashboard") // +12.00%
	uassert.Equal(t, "missed", Close(cross(cur), id))
	uassert.Equal(t, "missed", Status(id))
}

func TestCloseMet(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	AddReport(cross(cur), id, 4000, 700, 4000, 805, "dashboard") // +15.00%
	uassert.Equal(t, "met", Close(cross(cur), id))
	uassert.Equal(t, "met", Status(id))
}

// The verdict uses the last report, not the best one.
func TestCloseUsesLastReport(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, 1000)
	AddReport(cross(cur), id, 1000, 100, 1000, 130, "day 1") // +30%, would be met
	AddReport(cross(cur), id, 4000, 700, 4000, 784, "day 4") // +12%, missed
	uassert.Equal(t, "missed", Close(cross(cur), id))
}

func TestClosedIsFinal(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	AddReport(cross(cur), id, 4000, 700, 4000, 784, "dashboard")
	Close(cross(cur), id)

	uassert.AbortsWithMessage(t, cur, "experiment is closed", func() {
		AddReport(cross(cur), id, 5000, 900, 5000, 1200, "one more look")
	})
	uassert.AbortsWithMessage(t, cur, "experiment is already closed", func() {
		Close(cross(cur), id)
	})
	uassert.Equal(t, "missed", Status(id))
	uassert.Equal(t, 1, len(mustGet(id).reports))
}

func TestNotes(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)

	uassert.AbortsWithMessage(t, cur, "note is empty", func() {
		AddNote(cross(cur), id, "")
	})
	AddNote(cross(cur), id, "Traffic is simulated in a development environment.")

	AddReport(cross(cur), id, 1530, 268, 1547, 304, "dashboard")
	Close(cross(cur), id)

	// Notes stay open after closing, so an owner can explain what happened next.
	AddNote(cross(cur), id, "Ended early at 92% chance to be best and rolled out anyway.")
	uassert.Equal(t, 2, len(mustGet(id).notes))
}

func TestUnknownExperiment(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsWithMessage(t, cur, "experiment 7 not found", func() {
		AddReport(cross(cur), 7, 1, 0, 1, 0, "")
	})
	uassert.AbortsWithMessage(t, cur, "experiment 0 not found", func() {
		Close(cross(cur), 0)
	})
}

// Another realm can own an experiment. A person cannot then write to it,
// even the person who sent the transaction that made the realm register it.
func TestRealmAsOwner(cur realm, t *testing.T) {
	reset()
	const shop = "gno.land/r/demo/shop"

	testing.SetRealm(testing.NewCodeRealm(shop))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	uassert.NotEqual(t, alice.String(), OwnerOf(id).String())

	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsWithMessage(t, cur, "only the owner can do this", func() {
		AddReport(cross(cur), id, 4000, 700, 4000, 805, "")
	})

	testing.SetRealm(testing.NewCodeRealm(shop))
	AddReport(cross(cur), id, 4000, 700, 4000, 805, "counted by the shop realm")
	uassert.Equal(t, "met", Close(cross(cur), id))
}

func TestHeightsAreRecorded(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	locked := mustGet(id).lockedHeight

	testing.SkipHeights(50)
	AddReport(cross(cur), id, 100, 10, 100, 12, "")
	uassert.Equal(t, locked+50, mustGet(id).reports[0].Height)

	testing.SkipHeights(25)
	Close(cross(cur), id)
	uassert.Equal(t, locked+75, mustGet(id).closedHeight)
}

// A correction may lower a total, needs a reason, and leaves the mistaken
// report on the record.
func TestCorrection(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, 1000)

	uassert.AbortsWithMessage(t, cur, "there is no report to correct yet", func() {
		AddCorrection(cross(cur), id, 100, 10, 100, 12, "nothing to fix")
	})

	AddReport(cross(cur), id, 4000, 700, 4000, 905, "typed 905 instead of 805")
	uassert.AbortsContains(t, cur, "totals cannot go down", func() {
		AddReport(cross(cur), id, 4000, 700, 4000, 805, "")
	})
	uassert.AbortsWithMessage(t, cur, "a correction needs a reason", func() {
		AddCorrection(cross(cur), id, 4000, 700, 4000, 805, "")
	})
	uassert.AbortsContains(t, cur, "conversions cannot exceed exposures", func() {
		AddCorrection(cross(cur), id, 4000, 4001, 4000, 805, "fix")
	})

	AddCorrection(cross(cur), id, 4000, 700, 4000, 805, "Variant conversions were mistyped as 905.")
	exp := mustGet(id)
	uassert.Equal(t, 2, len(exp.reports), "the mistaken report is still there")
	uassert.False(t, exp.reports[0].Correction)
	uassert.True(t, exp.reports[1].Correction)
	uassert.Equal(t, int64(905), exp.reports[0].Variant.Conversions)

	// Later reports build on the corrected totals.
	uassert.AbortsContains(t, cur, "totals cannot go down", func() {
		AddReport(cross(cur), id, 4000, 700, 4000, 804, "")
	})
	AddReport(cross(cur), id, 4100, 715, 4100, 830, "day 5")

	page := Render("1")
	uassert.True(t, strings.Contains(page, "**1 of 3 rows are corrections.**"))
	uassert.True(t, strings.Contains(page, "**Correction.** Variant conversions were mistyped as 905"))
	uassert.True(t, strings.Contains(page, "<gno-form exec=\"AddCorrection\">"))
}

func TestCorrectionRules(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, 1000)
	AddReport(cross(cur), id, 4000, 700, 4000, 905, "")

	// Only the owner can correct.
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "only the owner can do this", func() {
		AddCorrection(cross(cur), id, 4000, 700, 4000, 100, "sabotage")
	})

	// The verdict uses the correction when it is the last report.
	testing.SetRealm(testing.NewUserRealm(alice))
	AddCorrection(cross(cur), id, 4000, 700, 4000, 784, "Read the wrong column.")
	uassert.Equal(t, "missed", Close(cross(cur), id))

	// A closed experiment cannot be corrected.
	uassert.AbortsWithMessage(t, cur, "experiment is closed", func() {
		AddCorrection(cross(cur), id, 4000, 700, 4000, 905, "second thoughts")
	})
	uassert.False(t, strings.Contains(Render("1"), "<gno-form exec=\"AddCorrection\">"))
}

// No form field uses a number input: scrolling over one changes its value.
func TestFormsUseTextInputs(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	AddReport(cross(cur), id, 100, 10, 100, 12, "")
	uassert.False(t, strings.Contains(Render(""), "type=\"number\""))
	uassert.False(t, strings.Contains(Render("1"), "type=\"number\""))
}

func TestSpan(t *testing.T) {
	uassert.Equal(t, "less than a minute", span(0))
	uassert.Equal(t, "less than a minute", span(59*time.Second))
	uassert.Equal(t, "1 minutes", span(60*time.Second))
	uassert.Equal(t, "119 minutes", span(119*time.Minute))
	uassert.Equal(t, "2 hours", span(120*time.Minute))
	uassert.Equal(t, "47 hours", span(47*time.Hour+59*time.Minute))
	uassert.Equal(t, "2 days", span(48*time.Hour))
	uassert.Equal(t, "19 days", span(19*24*time.Hour+3*time.Hour))
}

// The page says how long the plan had been locked when results first arrived.
func TestRenderShowsLockToReportGap(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	testing.SkipHeights(1200)
	AddReport(cross(cur), id, 100, 10, 100, 12, "")
	page := Render("1")
	uassert.True(t, strings.Contains(page, "The first report came 1,200 blocks after the plan was locked"))
}

func TestReportLimit(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	for i := 0; i < MaxReports; i++ {
		AddReport(cross(cur), id, int64(i+1), 0, int64(i+1), 0, "")
	}
	uassert.AbortsContains(t, cur, "report limit reached", func() {
		AddReport(cross(cur), id, 1000, 0, 1000, 0, "")
	})
}

func TestRenderHome(cur realm, t *testing.T) {
	reset()
	home := Render("")
	uassert.True(t, strings.Contains(home, "# Dokimi"))
	uassert.True(t, strings.Contains(home, "None yet."))
	uassert.True(t, strings.Contains(home, "<gno-form exec=\"Register\">"))

	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)
	home = Render("")
	uassert.True(t, strings.Contains(home, "["+tTitle+"]("+webPath+":1)"))
	uassert.True(t, strings.Contains(home, "+15.00%"))
	uassert.True(t, strings.Contains(home, "3,800"))
	uassert.True(t, strings.Contains(home, "| Locked |"))
	uassert.False(t, strings.Contains(home, "None yet."))

	AddReport(cross(cur), id, 100, 10, 100, 12, "")
	uassert.True(t, strings.Contains(Render(""), "| Running |"))
}

func TestRenderExperiment(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Register(cross(cur), tTitle, tHypothesis, tMetric, tControl, tVariant, tDirection, tTarget, tMinSample)

	page := Render("1")
	uassert.True(t, strings.Contains(page, "# "+tTitle))
	uassert.True(t, strings.Contains(page, "> A shorter signup page gets more visitors to finish signing up"))
	uassert.True(t, strings.Contains(page, "[All experiments]("+webPath+")"))
	uassert.True(t, strings.Contains(page, DigestOf(id)))
	uassert.True(t, strings.Contains(page, alice.String()))
	uassert.True(t, strings.Contains(page, "## No results yet"))
	uassert.True(t, strings.Contains(page, "<gno-form exec=\"AddReport\">"))

	AddReport(cross(cur), id, 1530, 268, 1547, 304, "analytics dashboard")
	page = Render("1")
	uassert.True(t, strings.Contains(page, "## Still running"))
	uassert.True(t, strings.Contains(page, "268 of 1,530 (17.51%)"))
	uassert.True(t, strings.Contains(page, "+12.18%"))
	uassert.True(t, strings.Contains(page, "analytics dashboard"))

	AddNote(cross(cur), id, "Ended early.")
	Close(cross(cur), id)
	page = Render("1")
	uassert.True(t, strings.Contains(page, "## Verdict: Inconclusive"))
	uassert.True(t, strings.Contains(page, "Stopped before the planned sample"))
	uassert.True(t, strings.Contains(page, "Ended early"))
	uassert.True(t, strings.Contains(page, "reached 1,530"))
	uassert.False(t, strings.Contains(page, "<gno-form exec=\"AddReport\">"), "no report form once closed")
	uassert.False(t, strings.Contains(page, "<gno-form exec=\"Close\">"), "no close form once closed")
	uassert.True(t, strings.Contains(page, "<gno-form exec=\"AddNote\">"))
}

func TestRenderNotFound(t *testing.T) {
	reset()
	uassert.True(t, strings.Contains(Render("42"), "does not exist"))
	uassert.True(t, strings.Contains(Render("nope"), "# Not found"))
	uassert.True(t, strings.Contains(Render("-1"), "# Not found"))
}

// Text typed by an owner must not be able to break the page layout.
func TestRenderEscapesUserText(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	Register(cross(cur), "Bad | title <b>x</b>", "A # heading attempt", tMetric, "A|B", tVariant, tDirection, tTarget, tMinSample)

	home := Render("")
	uassert.False(t, strings.Contains(home, "Bad | title"), "pipe in a table cell is escaped")
	uassert.False(t, strings.Contains(home, "<b>x</b>"), "raw HTML is escaped")

	page := Render("1")
	uassert.False(t, strings.Contains(page, "<b>x</b>"))
	uassert.False(t, strings.Contains(page, "| A|B |"))
}

gnomod.toml

module = "gno.land/r/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v1"
gno = "0.9"

[addpkg]
  creator = "g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft"
  height = 1519757
  max_deposit = "100000000ugnot"

render.gno

package dokimi

import (
	"strconv"
	"strings"
	"time"

	core "gno.land/p/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v1"
	"gno.land/p/nt/markdown/sanitize/v0"
)

const (
	// listLimit is how many experiments the home page shows, newest first.
	listLimit = 30

	// webPath is this realm's address on gnoweb, used to build links. It is
	// the module path in gnomod.toml without the chain domain.
	webPath = "/r/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v1"

	// rulesPath is the import path of the pure package holding the rules.
	rulesPath = "gno.land/p/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v1"
)

// Render draws the registry for gnoweb.
//
//	""      the home page: the list and the form to lock a new plan
//	"<id>"  one experiment: its plan, reports, notes and verdict
func Render(path string) string {
	if i := strings.IndexByte(path, '?'); i >= 0 {
		path = path[:i]
	}
	path = strings.Trim(path, "/")
	if path == "" {
		return renderHome()
	}
	id, err := strconv.ParseUint(path, 10, 64)
	if err != nil {
		return "# Not found\n\nThere is no page called " + sanitize.InlineCode(path) + ". [Back to all experiments](" + webPath + ")\n"
	}
	exp, ok := experiments.Get(key(id)).(*Experiment)
	if !ok {
		return "# Not found\n\nExperiment " + strconv.FormatUint(id, 10) + " does not exist. [Back to all experiments](" + webPath + ")\n"
	}
	return renderExperiment(exp)
}

func renderHome() string {
	var b strings.Builder
	b.WriteString("# Dokimi\n\n")
	b.WriteString("**Say what would count as a win before the test starts. Then prove you did not move the bar.**\n\n")
	b.WriteString("Dokimi is a public record for experiments such as A/B tests. ")
	b.WriteString("The plan is locked on-chain first. Results are added later and judged only against that plan.\n\n")

	b.WriteString("## Experiments on record\n\n")
	if experiments.Size() == 0 {
		b.WriteString("None yet. Lock the first plan with the form below.\n\n")
	} else {
		b.WriteString("| # | Experiment | Target | Sample per arm | Status |\n")
		b.WriteString("|---|---|---|---|---|\n")
		experiments.ReverseIterateByOffset(0, listLimit, func(_ string, value any) bool {
			exp := value.(*Experiment)
			id := strconv.FormatUint(exp.id, 10)
			b.WriteString("| " + id)
			b.WriteString(" | [" + sanitize.TableCell(exp.plan.Title) + "](" + webPath + ":" + id + ")")
			b.WriteString(" | " + targetLabel(exp.plan))
			b.WriteString(" | " + core.Commas(exp.plan.MinSample))
			b.WriteString(" | " + statusLabel(exp) + " |\n")
			return false
		})
		b.WriteString("\n")
		if experiments.Size() > listLimit {
			b.WriteString("Showing the newest " + strconv.Itoa(listLimit) + " of " + strconv.Itoa(experiments.Size()) + ". Open any experiment by its number: `" + webPath + ":<number>`.\n\n")
		}
	}

	b.WriteString("## Lock a new plan\n\n")
	b.WriteString("Fill this in before your test starts. After you submit, the plan cannot be changed, by you or by anyone else.\n\n")
	b.WriteString("<gno-form exec=\"Register\">\n")
	b.WriteString("<gno-input name=\"title\" type=\"text\" placeholder=\"Title\" description=\"A short name for the experiment\" required=\"true\" />\n")
	b.WriteString("<gno-input name=\"hypothesis\" type=\"text\" placeholder=\"Hypothesis\" description=\"What you expect to happen, in one or two plain sentences on a single line\" required=\"true\" />\n")
	b.WriteString("<gno-input name=\"metric\" type=\"text\" placeholder=\"Metric\" description=\"The one event or number that decides it, for example signup_completed\" required=\"true\" />\n")
	b.WriteString("<gno-input name=\"control\" type=\"text\" placeholder=\"Control name\" description=\"What you have today\" required=\"true\" />\n")
	b.WriteString("<gno-input name=\"variant\" type=\"text\" placeholder=\"Variant name\" description=\"The new version you are testing\" required=\"true\" />\n")
	b.WriteString("<gno-select name=\"direction\" value=\"increase\" selected=\"true\" description=\"Which way the metric should move\" />\n")
	b.WriteString("<gno-select name=\"direction\" value=\"decrease\" />\n")
	b.WriteString("<gno-input name=\"target\" type=\"text\" placeholder=\"Target in percent\" description=\"The smallest relative change that counts as a win, for example 15\" required=\"true\" />\n")
	b.WriteString("<gno-input name=\"minSample\" type=\"text\" placeholder=\"Minimum sample per arm\" description=\"How many people each version must reach before the result counts\" required=\"true\" />\n")
	b.WriteString("</gno-form>\n\n")

	b.WriteString("## How it works\n\n")
	b.WriteString("1. **Lock.** The plan is stored with the block it was written in and a fingerprint of its text.\n")
	b.WriteString("2. **Report.** The owner adds running totals. Every report is kept and no total can go down. A mistake is fixed with a correction, which is shown as one and never replaces the report it corrects.\n")
	b.WriteString("3. **Close.** The last report is judged against the locked plan: **met**, **missed** or **inconclusive**. ")
	b.WriteString("A test stopped before its planned sample is always inconclusive, however good the numbers look.\n\n")
	b.WriteString("Other realms can register their own experiments here, or import the rules from `" + rulesPath + "`.\n")
	return b.String()
}

func renderExperiment(exp *Experiment) string {
	var b strings.Builder
	id := strconv.FormatUint(exp.id, 10)
	p := exp.plan

	b.WriteString("# " + sanitize.InlineText(p.Title) + "\n\n")
	b.WriteString("[All experiments](" + webPath + ") · Experiment " + id + " · **" + statusLabel(exp) + "**\n\n")
	b.WriteString("> " + sanitize.InlineText(p.Hypothesis) + "\n\n")

	b.WriteString("## The locked plan\n\n")
	b.WriteString("| | |\n|---|---|\n")
	b.WriteString("| Metric | " + sanitize.TableCell(p.Metric) + " |\n")
	b.WriteString("| Control | " + sanitize.TableCell(p.Control) + " |\n")
	b.WriteString("| Variant | " + sanitize.TableCell(p.Variant) + " |\n")
	b.WriteString("| Target | " + targetLabel(p) + " relative change in the metric |\n")
	b.WriteString("| Minimum sample | " + core.Commas(p.MinSample) + " exposures for each arm |\n")
	b.WriteString("| Locked | block " + core.Commas(exp.lockedHeight) + ", " + stamp(exp.lockedAt) + " |\n")
	b.WriteString("| Owner | " + exp.owner.String() + " |\n")
	b.WriteString("| Fingerprint | `" + exp.digest + "` |\n\n")

	n := len(exp.reports)
	if exp.closed {
		b.WriteString("## Verdict: " + outcomeLabel(exp.verdict.Outcome) + "\n\n")
		b.WriteString(sanitize.InlineText(exp.verdict.Reason) + "\n\n")
		b.WriteString("Closed at block " + core.Commas(exp.closedHeight) + ", " + stamp(exp.closedAt) + ".\n\n")
	} else if n == 0 {
		b.WriteString("## No results yet\n\n")
		b.WriteString("The plan is locked and waiting for its first report.\n\n")
	} else {
		last := exp.reports[n-1]
		preview := core.Judge(p, last.Control, last.Variant)
		b.WriteString("## Still running\n\n")
		b.WriteString("If it were closed on the latest report, the verdict would be **" + outcomeLabel(preview.Outcome) + "**. ")
		b.WriteString(sanitize.InlineText(preview.Reason) + "\n\n")
	}

	if n > 0 {
		b.WriteString("## Reports\n\n")
		b.WriteString("Running totals as the owner reported them. Each row is permanent. ")
		if c := corrections(exp); c > 0 {
			b.WriteString("**" + strconv.Itoa(c) + " of " + strconv.Itoa(n) + " rows are corrections.** ")
		}
		first := exp.reports[0]
		b.WriteString("The first report came " + core.Commas(first.Height-exp.lockedHeight) + " blocks after the plan was locked (" + span(first.Time.Sub(exp.lockedAt)) + ").\n\n")
		b.WriteString("| # | Block | " + sanitize.TableCell(p.Control) + " | " + sanitize.TableCell(p.Variant) + " | Lift | Source |\n")
		b.WriteString("|---|---|---|---|---|---|\n")
		for i, r := range exp.reports {
			lift := "n/a"
			if l, ok := core.LiftBps(r.Control, r.Variant); ok {
				lift = core.FormatBps(l)
			}
			source := sanitize.TableCell(r.Source)
			if r.Correction {
				source = "**Correction.** " + sanitize.TableCell(r.Reason)
			} else if source == "" {
				source = "not given"
			}
			b.WriteString("| " + strconv.Itoa(i+1))
			b.WriteString(" | " + core.Commas(r.Height))
			b.WriteString(" | " + tallyLabel(r.Control))
			b.WriteString(" | " + tallyLabel(r.Variant))
			b.WriteString(" | " + lift)
			b.WriteString(" | " + source + " |\n")
		}
		b.WriteString("\n")
	}

	if len(exp.notes) > 0 {
		b.WriteString("## Notes from the owner\n\n")
		for _, note := range exp.notes {
			b.WriteString("- Block " + core.Commas(note.Height) + ", " + stamp(note.Time) + ": " + sanitize.InlineText(note.Text) + "\n")
		}
		b.WriteString("\n")
	}

	b.WriteString("## For the owner\n\n")
	b.WriteString("These only work from the account that locked the plan.\n\n")
	if !exp.closed {
		b.WriteString("**Add a report.** Enter totals since the start of the test, not the change since your last report.\n\n")
		b.WriteString("<gno-form exec=\"AddReport\">\n")
		b.WriteString("<gno-input name=\"id\" type=\"text\" value=\"" + id + "\" readonly=\"true\" description=\"Experiment number\" />\n")
		b.WriteString("<gno-input name=\"controlExposures\" type=\"text\" placeholder=\"Control exposures\" description=\"People who saw the control\" required=\"true\" />\n")
		b.WriteString("<gno-input name=\"controlConversions\" type=\"text\" placeholder=\"Control conversions\" description=\"Of those, how many did the thing the metric counts\" required=\"true\" />\n")
		b.WriteString("<gno-input name=\"variantExposures\" type=\"text\" placeholder=\"Variant exposures\" description=\"People who saw the variant\" required=\"true\" />\n")
		b.WriteString("<gno-input name=\"variantConversions\" type=\"text\" placeholder=\"Variant conversions\" description=\"Of those, how many did the thing the metric counts\" required=\"true\" />\n")
		b.WriteString("<gno-input name=\"source\" type=\"text\" placeholder=\"Source\" description=\"Where these numbers come from, for example your analytics dashboard\" />\n")
		b.WriteString("</gno-form>\n\n")

		if n > 0 {
			b.WriteString("**Correct a mistake.** If a report was wrong, enter the right totals and say what happened. The wrong report stays visible and this one is marked as a correction.\n\n")
			b.WriteString("<gno-form exec=\"AddCorrection\">\n")
			b.WriteString("<gno-input name=\"id\" type=\"text\" value=\"" + id + "\" readonly=\"true\" description=\"Experiment number\" />\n")
			b.WriteString("<gno-input name=\"controlExposures\" type=\"text\" placeholder=\"Control exposures\" description=\"The right total of people who saw the control\" required=\"true\" />\n")
			b.WriteString("<gno-input name=\"controlConversions\" type=\"text\" placeholder=\"Control conversions\" description=\"The right total of conversions for the control\" required=\"true\" />\n")
			b.WriteString("<gno-input name=\"variantExposures\" type=\"text\" placeholder=\"Variant exposures\" description=\"The right total of people who saw the variant\" required=\"true\" />\n")
			b.WriteString("<gno-input name=\"variantConversions\" type=\"text\" placeholder=\"Variant conversions\" description=\"The right total of conversions for the variant\" required=\"true\" />\n")
			b.WriteString("<gno-input name=\"reason\" type=\"text\" placeholder=\"Reason\" description=\"What was wrong with the earlier report\" required=\"true\" />\n")
			b.WriteString("</gno-form>\n\n")
		}

		b.WriteString("**Close the experiment.** This stores the verdict for good. No reports can be added afterwards.\n\n")
		b.WriteString("<gno-form exec=\"Close\">\n")
		b.WriteString("<gno-input name=\"id\" type=\"text\" value=\"" + id + "\" readonly=\"true\" description=\"Experiment number\" />\n")
		b.WriteString("</gno-form>\n\n")
	}
	b.WriteString("**Add a note.** Use it to tell readers about anything that changed, such as a test that ended early.\n\n")
	b.WriteString("<gno-form exec=\"AddNote\">\n")
	b.WriteString("<gno-input name=\"id\" type=\"text\" value=\"" + id + "\" readonly=\"true\" description=\"Experiment number\" />\n")
	b.WriteString("<gno-input name=\"text\" type=\"text\" placeholder=\"Note\" description=\"One line, shown publicly with the block it was added in\" required=\"true\" />\n")
	b.WriteString("</gno-form>\n")
	return b.String()
}

// corrections counts the reports that were added as corrections.
func corrections(exp *Experiment) int {
	c := 0
	for _, r := range exp.reports {
		if r.Correction {
			c++
		}
	}
	return c
}

// statusLabel is the one-word state shown in lists and headers.
func statusLabel(exp *Experiment) string {
	if !exp.closed {
		if len(exp.reports) == 0 {
			return "Locked"
		}
		return "Running"
	}
	return outcomeLabel(exp.verdict.Outcome)
}

func outcomeLabel(o core.Outcome) string {
	switch o {
	case core.Met:
		return "Target met"
	case core.Missed:
		return "Target missed"
	}
	return "Inconclusive"
}

// targetLabel renders the target with the sign of the expected direction.
func targetLabel(p core.Plan) string {
	if p.Direction == core.Decrease {
		return core.FormatBps(-p.TargetBps)
	}
	return core.FormatBps(p.TargetBps)
}

// tallyLabel renders "268 of 1,530 (17.51%)".
func tallyLabel(t core.Tally) string {
	return core.Commas(t.Conversions) + " of " + core.Commas(t.Exposures) + " (" + t.RateText() + ")"
}

// span renders how long passed between two block times, in plain words.
func span(d time.Duration) string {
	minutes := int64(d / time.Minute)
	switch {
	case minutes < 1:
		return "less than a minute"
	case minutes < 120:
		return core.Commas(minutes) + " minutes"
	case minutes < 48*60:
		return core.Commas(minutes/60) + " hours"
	}
	return core.Commas(minutes/(24*60)) + " days"
}

// stamp renders a block time in UTC.
func stamp(t time.Time) string {
	return t.UTC().Format("02 Jan 2006 15:04") + " UTC"
}