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

devtools.gno

// Package devtools is the worked example of wiring moul's developer packages
// into one realm: what a new realm should copy.
//
// Everything here is a COMBINATION. Any one of these packages has its own demo
// showing it alone; the thing that is hard to find is what they look like used
// together, which is the only form a real realm ever meets them in. So this
// realm imports ten of them and every one earns its place in the output:
//
//	r/moul/config     the notice block, the pause switch, the explorer to link
//	p/moul/mygnoscan  the explorer routes themselves
//	p/moul/debug      a metadata panel behind ?debug=1
//	p/moul/realmpath  reading the query string Render was handed
//	p/moul/kit/ui     escaping what a caller typed, and the tables
//	p/moul/md         the markdown, without hand-rolled strings
//	p/moul/txlink     the "call this function" link
//	p/moul/fifo       the bounded note list, so the state cannot grow forever
//	p/moul/kit/tally  the note leaderboard, ties ordered rather than arbitrary
//	p/moul/kit/num    pricing that list in GNOT rather than raw ugnot
//
// # The three lines worth copying
//
// A realm that does nothing else should still do these:
//
//	func Render(path string) string {
//		return config.TopBlockFor(realmPath) + body + config.BottomBlockFor(realmPath)
//	}
//
//	func Mutate(cur realm, s string) {
//		config.AssertWritableFor(realmPath)  // honours the pause switch
//		notes.Append(ui.Inline(s))           // escapes what a caller typed
//	}
//
// The first gives every realm a place to put a warning and a pause banner
// without shipping banner code. The second is two separate guards that both
// have to be there: the pause one so an incident can stop writes from outside
// the realm, and the escaping one because a string a caller typed is the
// oldest way to break a page.
package devtools

import (
	"strconv"
	"strings"

	"chain/runtime"
	"chain/runtime/unsafe"

	"gno.land/p/nym-moultest123/debug/v0"
	"gno.land/p/nym-moultest123/fifo/v0"
	"gno.land/p/nym-moultest123/kit/num/v0"
	"gno.land/p/nym-moultest123/kit/tally/v0"
	"gno.land/p/nym-moultest123/kit/ui/v0"
	"gno.land/p/nym-moultest123/md/v0"
	"gno.land/p/nym-moultest123/mygnoscan/v0"
	"gno.land/p/nym-moultest123/realmpath/v0"
	"gno.land/p/nym-moultest123/txlink/v0"
	"gno.land/r/nym-moultest123/config/v1"
)

// realmPath is this realm's own path.
//
// Passed explicitly to config rather than relying on its zero-argument helpers.
// Both work (a plain read is borrowed, so config sees this realm as the
// caller), but a constant cannot be wrong, and spelling it out is what a reader
// copying this file needs to see.
const realmPath = "gno.land/r/nym-moultest123/x/allinone/devtools/v0"

// maxNotes bounds the guest list. fifo drops the oldest rather than growing,
// because storage on chain is paid for and never refunded: an unbounded list in
// a demo anyone can write to is a bill with no ceiling.
const maxNotes = 10

var notes = fifo.New(maxNotes)

// authors counts notes per writer. A tally.Board rather than a map: gno map
// iteration order is unspecified, so a leaderboard built by ranging one is not
// reproducible between calls.
var authors = tally.NewBoard()

// depositPerByte is what the chain charges to keep a byte, in ugnot. Used only
// to price the note list on the page, never to settle anything.
const depositPerByte = 100

// Add appends a note. It is the only mutating function here, and it carries
// both guards a real one should.
func Add(cur realm, body string) {
	// 1. The pause switch. Set `pause@r/moul/x/allinone/devtools` on
	//    r/moul/config and this aborts, with the reason, from outside this
	//    realm and without a redeploy.
	config.AssertWritableFor(realmPath)

	body = strings.TrimSpace(body)
	if body == "" {
		panic("empty note")
	}
	if len(body) > 200 {
		panic("note too long: max 200 bytes, got " + strconv.Itoa(len(body)))
	}

	// 2. Escaping. body is a string a caller typed, and it is about to land in
	//    a markdown list. ui.Inline is the repo's standard for exactly this.
	notes.Append(ui.Inline(body))

	// 3. The scoreboard. tally.Board keeps one score per author and orders
	//    ties by key, so two authors on the same count always render in the
	//    same order.
	authors.Add(unsafe.PreviousRealm().Address().String(), 1)
}

// Reset empties the list, so the realm can be put back to a known state
// without a redeploy. Not gated by the pause switch: clearing up is the thing
// you still want to do while paused.
func Reset(cur realm) {
	notes = fifo.New(maxNotes)
	authors = tally.NewBoard()
}

// Render shows every package at work. The root view is deliberately free of
// anything that moves on its own, so an example test can pin it; the live
// numbers live under "chain".
func Render(path string) string {
	req := realmpath.Parse(path)

	var b strings.Builder
	b.WriteString(config.TopBlockFor(realmPath))
	b.WriteString(md.H1("allinone: devtools"))
	b.WriteString("\nTen packages, used together rather than one at a time. ")
	b.WriteString(md.Link("source", config.MygnoscanFor(realmPath)))
	b.WriteString("\n\n")

	switch req.PathPart(0) {
	case "chain":
		b.WriteString(renderChain())
	default:
		b.WriteString(renderHome(path))
	}

	// debug prints its own panel only when ?debug=1 is set, and the empty
	// string otherwise, so this line is safe to leave in a deployed realm.
	b.WriteString(debug.Render(path))
	b.WriteString(config.BottomBlockFor(realmPath))
	return b.String()
}

func renderHome(path string) string {
	var b strings.Builder

	b.WriteString(md.H2("Notes"))
	b.WriteString("\n")
	// renderNotes returns no trailing newline of its own: md.BulletList and
	// ui.Empty already end in one, and adding a second here produced two
	// consecutive blank lines, which gno collapses inside an // Output: block
	// and which therefore no example test can ever pin.
	b.WriteString(renderNotes())
	b.WriteString("\n")

	// txlink builds the "call this function" URL for the CURRENT realm, so it
	// keeps working after a version bump without anything here changing.
	b.WriteString(md.BulletList([]string{
		md.Link("add a note", txlink.NewLink("Add").AddArgs("body", "hello").URL()),
		md.Link("clear them", txlink.Call("Reset")),
		md.Link("live chain values", "/r/nym-moultest123/x/allinone/devtools/v0:chain"),
		md.Link("toggle the debug panel", debug.ToggleURL(path)),
	}))
	b.WriteString("\n")

	b.WriteString(renderBoard())

	b.WriteString(md.H2("What each package does here"))
	b.WriteString("\n")
	t := ui.NewTable("package", "what it contributed")
	t.Row("`r/moul/config`", "the notice block above, the pause guard on `Add`, and which explorer to link")
	t.Row("`p/moul/mygnoscan`", "the explorer routes, so a link survives a route change")
	t.Row("`p/moul/debug`", "the `?debug=1` panel, empty otherwise")
	t.Row("`p/moul/realmpath`", "splitting the render path into a view and a query")
	t.Row("`p/moul/kit/ui`", "escaping a caller's note, and this table")
	t.Row("`p/moul/md`", "every heading, link and list on the page")
	t.Row("`p/moul/txlink`", "the call links above, relative to this realm")
	t.Row("`p/moul/fifo`", "the note list, bounded so storage cannot grow forever")
	t.Row("`p/moul/kit/tally`", "the note leaderboard, with ties ordered by address")
	t.Row("`p/moul/kit/num`", "pricing the note list in GNOT instead of raw ugnot")
	b.WriteString(t.String())

	return b.String()
}

// renderBoard shows who has written the most notes, and what the list costs to
// keep. Both numbers come from a package rather than from arithmetic here.
func renderBoard() string {
	var b strings.Builder
	b.WriteString(md.H2("Who has written the most"))
	b.WriteString("\n")

	top := authors.Top(5)
	if len(top) == 0 {
		b.WriteString(ui.Empty("No notes yet, so nobody is on the board."))
	} else {
		t := ui.NewTable("#", "author", "notes")
		for i, e := range top {
			t.Row(ui.Podium(i+1), ui.AddrOf(e.Key), num.Pad(e.Score, 2))
		}
		b.WriteString(t.String())
	}

	// num.GNOTf, not a hand-rolled divide by a million. The storage deposit is
	// what the chain charges to keep these bytes, so it is the honest price of
	// the list above.
	b.WriteString("\nStorage deposit for the list: **")
	b.WriteString(num.GNOTf(int64(notesBytes()) * depositPerByte))
	b.WriteString("**\n\n")
	return b.String()
}

// notesBytes is the length of every note currently held.
func notesBytes() int {
	n := 0
	for _, v := range notes.Entries() {
		n += len(v.(string))
	}
	return n
}

// renderChain is everything that moves: the height, and the links built from
// it. Kept off the root view so the root can be pinned by an example.
func renderChain() string {
	s := config.Scanner()
	h := runtime.ChainHeight()

	var b strings.Builder
	b.WriteString(md.H2("Live"))
	b.WriteString("\n")

	t := ui.NewTable("what", "value")
	t.Row("chain id", ui.Cell(runtime.ChainID()))
	t.Row("height", strconv.FormatInt(h, 10))
	t.Row("explorer", ui.Cell(s.Base()))
	t.Row("network", ui.Cell(s.Network()))
	b.WriteString(t.String())
	b.WriteString("\n")

	// mygnoscan.Link used directly, rather than through config, to show that
	// the builder is an ordinary value: config only decides where it points.
	b.WriteString(md.BulletList([]string{
		mygnoscan.Link("this block", s.Block(h)),
		mygnoscan.Link("this realm's transactions", s.Realm(realmPath, mygnoscan.TabCalls)),
		mygnoscan.Link("its dependency graph", s.Realm(realmPath, mygnoscan.TabDeps)),
		mygnoscan.Link("the parked deploy queue", s.Packages(mygnoscan.PackagesInert)),
	}))
	b.WriteString("\n")
	b.WriteString(md.Link("back", "/r/nym-moultest123/x/allinone/devtools/v0"))
	b.WriteString("\n")
	return b.String()
}

func renderNotes() string {
	if notes.Size() == 0 {
		return ui.Empty("no notes yet")
	}
	items := []string{}
	for _, e := range notes.Entries() {
		items = append(items, e.(string))
	}
	return md.BulletList(items)
}

devtools_test.gno

package devtools

import (
	"strings"
	"testing"

	"gno.land/p/nym-moultest123/fifo/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/r/nym-moultest123/config/v1"
)

// reset puts the realm back to a just-deployed state. Realm globals live for
// the whole test binary and gno runs every Example AFTER every Test, so without
// this the pinned output would depend on which tests ran before it.
func reset() { notes = fifo.New(maxNotes) }

func TestAdd(cur realm, t *testing.T) {
	reset()

	Add(cross(cur), "hello")
	uassert.Equal(t, 1, notes.Size())
	uassert.Equal(t, "hello", notes.Get(0).(string))

	uassert.AbortsWithMessage(t, cur, "empty note", func() { Add(cross(cur), "   ") })
	uassert.AbortsContains(t, cur, "note too long", func() {
		long := ""
		for i := 0; i < 201; i++ {
			long += "x"
		}
		Add(cross(cur), long)
	})
}

// TestAddEscapes is the guard that matters most in a realm anyone can write to:
// a note is a string a caller typed, and it lands in a markdown list. Without
// ui.Inline the first line below would close the list item and render as a
// heading, and the second would become a link.
func TestAddEscapes(cur realm, t *testing.T) {
	reset()

	Add(cross(cur), "# not a heading")
	Add(cross(cur), "[not](https://evil.example.com)")

	for _, got := range []string{notes.Get(0).(string), notes.Get(1).(string)} {
		uassert.False(t, got == "# not a heading", "markdown survived unescaped")
		uassert.False(t, got == "[not](https://evil.example.com)", "a link survived unescaped")
	}
	uassert.True(t, len(notes.Get(0).(string)) > len("# not a heading"),
		"escaping should have added characters")
}

// TestNotesAreBounded pins the reason fifo is here rather than a slice: storage
// is paid for and never refunded, so a list anyone can append to needs a
// ceiling in the type, not in a comment.
func TestNotesAreBounded(cur realm, t *testing.T) {
	reset()

	for i := 0; i < maxNotes+5; i++ {
		Add(cross(cur), "note "+string(rune('a'+i)))
	}
	uassert.Equal(t, maxNotes, notes.Size(), "the list stops growing at maxNotes")
	uassert.Equal(t, maxNotes, notes.MaxSize())
}

// TestAddHonoursThePause is the whole point of importing r/moul/config: this
// realm can be stopped from outside, by a transaction against another realm,
// with no redeploy here. It cannot set that from this package (config has its
// own authority), so it asserts the wiring: Add goes through the pause check
// and passes while nothing is set.
func TestAddHonoursThePause(cur realm, t *testing.T) {
	reset()
	uassert.False(t, config.IsPausedFor(realmPath), "nothing configured means running")
	Add(cross(cur), "allowed while running")
	uassert.Equal(t, 1, notes.Size())
}

func TestReset(cur realm, t *testing.T) {
	reset()
	Add(cross(cur), "one")
	Reset(cross(cur))
	uassert.Equal(t, 0, notes.Size())
}

// ExampleRender pins the root view. It is free of the height and the chain id
// on purpose: those live under :chain, so this one is stable.
func ExampleRender() {
	reset()
	print(Render(""))
	// Output:
	// # allinone: devtools
	//
	// Ten packages, used together rather than one at a time. [source](https://mygnoscan.moul.p2p.team/realm/r/nym-moultest123/x/allinone/devtools/v0)
	//
	// ## Notes
	//
	// *no notes yet*
	//
	// - [add a note](/r/nym-moultest123/x/allinone/devtools/v0$help&func=Add&body=hello)
	// - [clear them](/r/nym-moultest123/x/allinone/devtools/v0$help&func=Reset)
	// - [live chain values](/r/nym-moultest123/x/allinone/devtools/v0:chain)
	// - [toggle the debug panel](/r/nym-moultest123/x/allinone/devtools/v0:?debug=1)
	//
	// ## Who has written the most
	//
	// *No notes yet, so nobody is on the board.*
	//
	// Storage deposit for the list: **0 GNOT**
	//
	// ## What each package does here
	//
	// | package | what it contributed |
	// | --- | --- |
	// | `r/moul/config` | the notice block above, the pause guard on `Add`, and which explorer to link |
	// | `p/moul/mygnoscan` | the explorer routes, so a link survives a route change |
	// | `p/moul/debug` | the `?debug=1` panel, empty otherwise |
	// | `p/moul/realmpath` | splitting the render path into a view and a query |
	// | `p/moul/kit/ui` | escaping a caller's note, and this table |
	// | `p/moul/md` | every heading, link and list on the page |
	// | `p/moul/txlink` | the call links above, relative to this realm |
	// | `p/moul/fifo` | the note list, bounded so storage cannot grow forever |
	// | `p/moul/kit/tally` | the note leaderboard, with ties ordered by address |
	// | `p/moul/kit/num` | pricing the note list in GNOT instead of raw ugnot |
}

// TestBoardRanksAuthorsAndPricesTheList exercises the two kit packages this
// realm adopted, because ExampleRender only ever sees the empty page.
func TestBoardRanksAuthorsAndPricesTheList(cur realm, t *testing.T) {
	Reset(cross(cur))

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

	testing.SetRealm(testing.NewUserRealm(alice))
	Add(cross(cur), "one")
	testing.SetRealm(testing.NewUserRealm(alice))
	Add(cross(cur), "two")
	testing.SetRealm(testing.NewUserRealm(bob))
	Add(cross(cur), "three")

	uassert.Equal(t, int64(2), authors.Score(alice.String()))
	uassert.Equal(t, int64(1), authors.Score(bob.String()))
	uassert.Equal(t, 1, authors.Rank(alice.String()))
	uassert.Equal(t, 2, authors.Rank(bob.String()))

	// "one"+"two"+"three" is 11 bytes at 100 ugnot each, which num renders as
	// GNOT rather than as 1100.
	out := Render("")
	uassert.True(t, strings.Contains(out, "0.0011 GNOT"))
	uassert.True(t, strings.Contains(out, "## Who has written the most"))

	Reset(cross(cur))
	uassert.Equal(t, 0, authors.Len())
}

gnomod.toml

module = "gno.land/r/nym-moultest123/x/allinone/devtools/v0"
gno = "0.9"
private = true

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