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

blocks.gno

package config

import "strings"

// The notice blocks: two strings a realm drops at the top and the bottom of its
// Render, empty by default, so moul can put a warning, a changelog line or a
// bit of news on every realm at once or on one of them.
//
//	func Render(path string) string {
//		return config.TopBlock() + body + config.BottomBlock()
//	}
//
// Both are set with the ordinary Set, which is what keeps this realm's surface
// from growing a function per idea:
//
//	Set block.top            "> Chain migration on Tuesday."   # every realm
//	Set block.top@r/moul/gns "> v2 shipped, see the changelog" # this one only
const (
	// KeyBlockTop is the notice rendered above a realm's content.
	KeyBlockTop = "block.top"
	// KeyBlockBottom is the notice rendered below it.
	KeyBlockBottom = "block.bottom"
)

// TopBlock returns the notice for the realm calling in, ready to concatenate
// in front of its content. Empty when there is nothing to say, which is the
// default and the usual case.
//
// Three things can appear, in this order, separated by blank lines:
//
//  1. the pause banner, when this realm or every realm is paused
//  2. the global block.top
//  3. this realm's own block.top
//
// The pause banner comes first because it is the one a reader has to see, and
// it is included here rather than left to the realm so that guarding writes
// with AssertWritable is enough to also explain the refusal on the page.
//
// Global and scoped are BOTH shown rather than one overriding the other: a
// chain-wide warning and a per-realm changelog are different messages, and
// dropping either because the other exists is the surprising behaviour.
func TopBlock() string { return TopBlockFor(caller()) }

// TopBlockFor is TopBlock for a named realm. Use it from a crossing function,
// where the caller cannot be read off the stack, or to render another realm's
// notice.
func TopBlockFor(pkgPath string) string {
	global, scoped := scopedPair(KeyBlockTop, pkgPath)
	return joinBlocks(PauseFor(pkgPath).Notice(), global, scoped)
}

// BottomBlock returns the notice for the realm calling in, ready to
// concatenate after its content.
//
// No pause banner here: one is enough, and the top is where it is read.
func BottomBlock() string { return BottomBlockFor(caller()) }

// BottomBlockFor is BottomBlock for a named realm.
func BottomBlockFor(pkgPath string) string {
	global, scoped := scopedPair(KeyBlockBottom, pkgPath)
	return joinBlocks(global, scoped)
}

// joinBlocks assembles the non-empty parts into one markdown fragment.
//
// Each part is separated by a blank line, because two markdown blocks with
// only a newline between them are one paragraph, and a blockquote followed
// directly by text swallows the text into the quote.
//
// The result ends with a blank line when there is anything at all, so a realm
// can write config.TopBlock() + body without a separator of its own and get
// the same output whether or not a notice is set. Nothing to say means the
// empty string, and the page is byte-for-byte what it was before.
func joinBlocks(parts ...string) string {
	var kept []string
	for _, p := range parts {
		if p = strings.TrimSpace(p); p != "" {
			kept = append(kept, p)
		}
	}
	if len(kept) == 0 {
		return ""
	}
	return strings.Join(kept, "\n\n") + "\n\n"
}

blocks_test.gno

package config

import (
	"testing"

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

const otherRealm = "gno.land/r/nym-moultest123/gns"

func TestKeyGrammar(t *testing.T) {
	uassert.Equal(t, "pause", KeyFor("pause", ""))
	uassert.Equal(t, "pause@r/moul/home", KeyFor("pause", "gno.land/r/nym-moultest123/home"))
	uassert.Equal(t, "pause@r/moul/home", KeyFor("pause", "r/moul/home"))

	// A path this cannot scope to falls back to the global key rather than
	// inventing one nobody can type.
	uassert.Equal(t, "pause", KeyFor("pause", "not a path"))
	uassert.Equal(t, "pause", KeyFor("pause", "gno.land/"))

	name, scope := SplitKey("block.top@r/moul/home")
	uassert.Equal(t, "block.top", name)
	uassert.Equal(t, "r/moul/home", scope)

	name, scope = SplitKey("block.top")
	uassert.Equal(t, "block.top", name)
	uassert.Equal(t, "", scope)
}

func TestScope(t *testing.T) {
	uassert.Equal(t, "r/moul/home", Scope("gno.land/r/nym-moultest123/home"))
	uassert.Equal(t, "r/moul/home", Scope("r/moul/home"))
	uassert.Equal(t, "p/moul/kit/ui", Scope("gno.land/p/nym-moultest123/kit/ui"))
	uassert.Equal(t, "", Scope(""))
	uassert.Equal(t, "", Scope("gno.land/"))
	uassert.Equal(t, "", Scope("r/moul/ho me"))
	uassert.Equal(t, "", Scope("r//moul"))
}

// TestBlocksDefaultEmpty is the property every realm depends on: a realm that
// renders config.TopBlock() unconditionally must be byte-for-byte what it was
// before, until moul sets something.
func TestBlocksDefaultEmpty(t *testing.T) {
	resetSettings()
	uassert.Equal(t, "", TopBlockFor(otherRealm))
	uassert.Equal(t, "", BottomBlockFor(otherRealm))
}

func TestBlocksGlobalAndScoped(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyBlockTop, "> chain migration on Tuesday")

	// Global alone reaches every realm, and ends with a blank line so a realm
	// can concatenate without a separator of its own.
	uassert.Equal(t, "> chain migration on Tuesday\n\n", TopBlockFor(otherRealm))
	uassert.Equal(t, "> chain migration on Tuesday\n\n", TopBlockFor("gno.land/r/nym-moultest123/home"))

	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyFor(KeyBlockTop, otherRealm), "> v2 shipped")

	// BOTH are shown, global first. A chain-wide warning and a per-realm
	// changelog are different messages; dropping either would be the
	// surprising behaviour.
	uassert.Equal(t,
		"> chain migration on Tuesday\n\n> v2 shipped\n\n",
		TopBlockFor(otherRealm))

	// And the scoped one reaches only its own realm.
	uassert.Equal(t, "> chain migration on Tuesday\n\n", TopBlockFor("gno.land/r/nym-moultest123/home"))
}

func TestBottomBlock(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyBlockBottom, "built by moul")

	uassert.Equal(t, "built by moul\n\n", BottomBlockFor(otherRealm))

	// The pause banner belongs to the top only: one banner is enough, and the
	// top is where it gets read.
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyPause, "paused")
	uassert.Equal(t, "built by moul\n\n", BottomBlockFor(otherRealm))
}

// TestTopBlockCarriesPause is the integration that makes guarding writes
// enough: a realm that calls AssertWritable and renders TopBlock explains the
// refusal on its own page without writing a line of banner code.
func TestTopBlockCarriesPause(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyPause, "readonly: migrating storage")

	uassert.Equal(t,
		"> **Read-only.** This realm is still readable, but not accepting changes. migrating storage\n\n",
		TopBlockFor(otherRealm))

	// And it comes first, before the messages.
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyBlockTop, "> news")
	uassert.Equal(t,
		"> **Read-only.** This realm is still readable, but not accepting changes. migrating storage\n\n> news\n\n",
		TopBlockFor(otherRealm))
}

// TestZeroArgFormsNameTheCaller pins the borrow behaviour the whole
// zero-argument API rests on: these are plain reads with no `cur realm`, so
// gno opens no realm frame and the realm asking is the realm answered about.
//
// If this ever fails, every zero-argument helper here has silently started
// answering for gno.land/r/nym-moultest123/config instead, and the …For variants are the
// only correct ones.
func TestZeroArgFormsNameTheCaller(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyFor(KeyBlockTop, otherRealm), "> only for gns")

	testing.SetRealm(testing.NewCodeRealm(otherRealm))
	uassert.Equal(t, "> only for gns\n\n", TopBlock())
	uassert.Equal(t, otherRealm, caller())

	testing.SetRealm(testing.NewCodeRealm("gno.land/r/nym-moultest123/home"))
	uassert.Equal(t, "", TopBlock(), "another realm sees nothing")
	uassert.Equal(t, "gno.land/r/nym-moultest123/home", caller())
}

config.gno

// Package config is the one realm moul's other realms read their settings
// from: a key/value store plus the manager list that decides who may write it.
//
// # Why a realm and not a constant
//
// A value shared by several contracts, hardcoded in each, is changed by
// redeploying each. On mainnet a public realm cannot even be redeployed at its
// own path, so "changing it" means a new version and a new path for every
// consumer. Here it is a transaction.
//
// # Bump rarely, and never for a new setting
//
// This realm IS public and versioned, so its path moves on every bump. That
// makes a bump expensive, which is exactly why the settings API is generic: a
// new setting is a new KEY, and a key costs one transaction. Only a change to
// the shape of this realm (a new function, a changed signature) is worth a
// version.
//
// # When a bump does happen, the state does not move
//
// A later version imports this one and relays to it rather than holding
// anything of its own, so v1, v2 and v3 all read and write the same settings,
// the same pause and the same member list. Delegation only runs backwards in
// time, which is why the root is the oldest version that has the state and not
// the newest. See proxy.gno.
//
// # What lives here
//
// settings.gno  the key/value store, and the mygnoscan accessors over it
// keys.gno      the key grammar: a name, optionally scoped to one realm
// blocks.gno    the notice a realm renders above and below its content
// pause.gno     the switch a realm checks before it acts
// proxy.gno     the relay that lets a later version share this state
// config.gno    the member list, unchanged from v0
//
// # Governance
//
// init seeds the authority with the deploying EOA. Everything that writes goes
// through Authorizer, so transferring authority to a DAO transfers the
// settings with it: there is no address hardcoded on the write path.
package config

import (
	"errors"

	"gno.land/p/nym-moultest123/authz/v0"
)

var Authorizer *authz.Authorizer

func init(cur realm) {
	if !cur.Previous().IsUserCall() {
		panic("r/moul/config must be initialized by an EOA")
	}
	Authorizer = authz.NewWithMembers(cur.Previous().Address())
}

// AddManager adds a new address to the list of authorized managers.
// This only works if the current authority is a MemberAuthority.
// The caller must be authorized by the current authority.
func AddManager(cur realm, addr address) error {
	memberAuth, ok := Authorizer.Authority().(*authz.MemberAuthority)
	if !ok {
		return errors.New("current authority is not a MemberAuthority, cannot add manager directly")
	}
	return memberAuth.AddMember(0, cur, addr)
}

// RemoveManager removes an address from the list of authorized managers.
// This only works if the current authority is a MemberAuthority.
// The caller must be authorized by the current authority.
func RemoveManager(cur realm, addr address) error {
	memberAuth, ok := Authorizer.Authority().(*authz.MemberAuthority)
	if !ok {
		return errors.New("current authority is not a MemberAuthority, cannot remove manager directly")
	}
	return memberAuth.RemoveMember(0, cur, addr)
}

// TransferManagement transfers the authority to manage keys to a new authority.
// The caller must be authorized by the current authority.
func TransferManagement(cur realm, newAuthority authz.Authority) error {
	if newAuthority == nil {
		return errors.New("new authority cannot be nil")
	}
	return Authorizer.Transfer(0, cur, newAuthority)
}

// ListManagers returns a slice of all managed keys.
func ListManagers(cur realm) []address {
	var keyList []address
	memberAuth, ok := Authorizer.Authority().(*authz.MemberAuthority)
	if !ok {
		return keyList
	}
	tree := memberAuth.Tree()
	if !ok || tree == nil {
		return keyList // Return empty list if tree is not as expected or nil
	}
	tree.Iterate("", "", func(key string, _ any) bool {
		keyList = append(keyList, address(key))
		return false
	})
	return keyList
}

func HasManager(cur realm, addr address) bool {
	memberAuth, ok := Authorizer.Authority().(*authz.MemberAuthority)
	if !ok {
		return false // Return false if not a MemberAuthority or doesn't exist
	}
	// Use the MemberAuthority's specific RemoveMember method,
	// which internally performs the authorization check.
	return memberAuth.Has(addr)
}

config_test.gno

package config

import (
	"chain"
	"chain/runtime/unsafe"
	"errors"
	"testing"

	"gno.land/p/nym-moultest123/authz/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

var (
	originAddr     = testutils.TestAddress("origin")
	manager1Addr   = testutils.TestAddress("manager1")
	manager2Addr   = testutils.TestAddress("manager2")
	nonManagerAddr = testutils.TestAddress("nonManager")
)

// Helper to reset the Authorizer for each test, simulating initialization.
func setupTest(cur realm, t *testing.T) {
	t.Helper()

	// Set the initial caller context
	testing.SetRealm(testing.NewUserRealm(originAddr))
	// Initialize the Authorizer with the originAddr as the sole member,
	// simulating the state after NewWithOrigin() in a real deployment.
	Authorizer = authz.NewWithAuthority(authz.NewMemberAuthority(originAddr))
	// Ensure the origin address is the initial manager
	uassert.True(t, HasManager(cur, originAddr), "origin should be the initial manager")
}

func TestAddManager(cur realm, t *testing.T) {
	setupTest(cur, t)

	// Origin adds manager1 - Should succeed
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err := AddManager(cross(cur), manager1Addr)
	uassert.NoError(t, err, "origin adding manager1 should succeed")
	uassert.True(t, HasManager(cur, manager1Addr), "manager1 should now be a manager")

	// Non-manager tries to add manager2 - Should fail
	testing.SetRealm(testing.NewUserRealm(nonManagerAddr))
	err = AddManager(cross(cur), manager2Addr)
	uassert.Error(t, err, "non-manager adding manager2 should fail")
	uassert.False(t, HasManager(cur, manager2Addr), "manager2 should not have been added")

	// Manager1 adds manager2 - Should succeed
	testing.SetRealm(testing.NewUserRealm(manager1Addr))
	err = AddManager(cross(cur), manager2Addr)
	uassert.NoError(t, err, "manager1 adding manager2 should succeed")
	uassert.True(t, HasManager(cur, manager2Addr), "manager2 should now be a manager")

	// Transfer authority away from MemberAuthority
	testing.SetRealm(testing.NewUserRealm(originAddr)) // Origin transfers
	err = TransferManagement(cross(cur), authz.NewAutoAcceptAuthority())
	uassert.NoError(t, err, "transferring authority should succeed")

	// Try adding after transfer - Should fail (wrong authority type)
	testing.SetRealm(testing.NewUserRealm(manager1Addr))
	err = AddManager(cross(cur), nonManagerAddr) // Try adding someone new
	uassert.ErrorContains(t, err, "current authority is not a MemberAuthority", "adding manager should fail after transfer")
}

func TestRemoveManager(cur realm, t *testing.T) {
	setupTest(cur, t)

	// Add manager1 first
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err := AddManager(cross(cur), manager1Addr)
	uassert.NoError(t, err, "setup: failed to add manager1")
	uassert.True(t, HasManager(cur, manager1Addr), "setup: manager1 should be added")

	// Non-manager tries to remove manager1 - Should fail
	testing.SetRealm(testing.NewUserRealm(nonManagerAddr))
	err = RemoveManager(cross(cur), manager1Addr)
	uassert.Error(t, err, "non-manager removing manager1 should fail")
	uassert.True(t, HasManager(cur, manager1Addr), "manager1 should still be a manager")

	// Origin removes manager1 - Should succeed
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err = RemoveManager(cross(cur), manager1Addr)
	uassert.NoError(t, err, "origin removing manager1 should succeed")
	uassert.False(t, HasManager(cur, manager1Addr), "manager1 should now be removed")

	// Add manager1 again for next test case
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err = AddManager(cross(cur), manager1Addr)
	uassert.NoError(t, err, "setup: failed to re-add manager1")

	// Transfer authority
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err = TransferManagement(cross(cur), authz.NewAutoAcceptAuthority())
	uassert.NoError(t, err, "transferring authority should succeed")

	// Try removing after transfer - Should fail (wrong authority type)
	testing.SetRealm(testing.NewUserRealm(originAddr)) // Use origin, doesn't matter which user now
	err = RemoveManager(cross(cur), manager1Addr)
	uassert.ErrorContains(t, err, "current authority is not a MemberAuthority", "removing manager should fail after transfer")
}

func TestListManagers(cur realm, t *testing.T) {
	setupTest(cur, t)
	initialList := ListManagers(cross(cur))
	assertAddrSliceEqual(t, []address{originAddr}, initialList)
	// Add manager1 and manager2
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err := AddManager(cross(cur), manager1Addr)
	uassert.NoError(t, err)
	err = AddManager(cross(cur), manager2Addr)
	uassert.NoError(t, err)

	// List should contain origin, manager1, manager2
	list1 := ListManagers(cross(cur))
	expected1 := []address{manager2Addr, manager1Addr, originAddr}
	assertAddrSliceEqual(t, expected1, list1)

	// Remove manager1
	testing.SetRealm(testing.NewUserRealm(originAddr)) // Can be origin or manager2
	err = RemoveManager(cross(cur), manager1Addr)
	uassert.NoError(t, err)

	// List should contain origin, manager2
	list2 := ListManagers(cross(cur))
	expected2 := []address{manager2Addr, originAddr}
	assertAddrSliceEqual(t, expected2, list2)

	// Transfer authority
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err = TransferManagement(cross(cur), authz.NewAutoAcceptAuthority())
	uassert.NoError(t, err)

	// List should be empty after transfer
	list3 := ListManagers(cross(cur))
	uassert.True(t, len(list3) == 0, "manager list should be empty after transfer")
}

func TestHasManager(cur realm, t *testing.T) {
	setupTest(cur, t)

	// Initially, only origin is manager
	uassert.True(t, HasManager(cross(cur), originAddr), "origin should initially be a manager")
	uassert.False(t, HasManager(cross(cur), manager1Addr), "manager1 should not initially be a manager")
	uassert.False(t, HasManager(cross(cur), nonManagerAddr), "nonManager should not initially be a manager")

	// Add manager1
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err := AddManager(cross(cur), manager1Addr)
	uassert.NoError(t, err)

	// Check again
	uassert.True(t, HasManager(cross(cur), originAddr), "origin should still be a manager")
	uassert.True(t, HasManager(cross(cur), manager1Addr), "manager1 should now be a manager")
	uassert.False(t, HasManager(cross(cur), nonManagerAddr), "nonManager should still not be a manager")

	// Transfer authority
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err = TransferManagement(cross(cur), authz.NewAutoAcceptAuthority())
	uassert.NoError(t, err)

	// After transfer, HasManager should always return false for MemberAuthority checks
	uassert.False(t, HasManager(cross(cur), originAddr), "HasManager should be false after transfer")
	uassert.False(t, HasManager(cross(cur), manager1Addr), "HasManager should be false after transfer")
	uassert.False(t, HasManager(cross(cur), nonManagerAddr), "HasManager should be false after transfer")
}

func TestTransferManagement(cur realm, t *testing.T) {
	setupTest(cur, t)

	// Add manager1
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err := AddManager(cross(cur), manager1Addr)
	uassert.NoError(t, err)

	// Create a new authority (MemberAuthority with manager2)
	newAuthority := authz.NewMemberAuthority(manager2Addr)

	// Non-manager tries to transfer - Should fail
	testing.SetRealm(testing.NewUserRealm(nonManagerAddr))
	err = TransferManagement(cross(cur), newAuthority)
	uassert.Error(t, err, "non-manager transfer should fail")
	_, isMemberAuth := Authorizer.Authority().(*authz.MemberAuthority)
	uassert.True(t, isMemberAuth, "authority should still be MemberAuthority") // Verify it didn't change

	// Manager1 tries to transfer - Should succeed
	testing.SetRealm(testing.NewUserRealm(manager1Addr))
	err = TransferManagement(cross(cur), newAuthority)
	uassert.NoError(t, err, "manager1 transfer should succeed")

	// Verify current authority is the new one
	currentAuth := Authorizer.Authority()
	uassert.True(t, currentAuth == newAuthority, "current authority should be the new one")

	// Verify origin is no longer a manager under the *new* authority
	testing.SetRealm(testing.NewUserRealm(manager2Addr)) // Need new manager to check
	uassert.False(t, HasManager(cross(cur), originAddr), "origin should not be manager under new authority")
	uassert.False(t, HasManager(cross(cur), manager1Addr), "manager1 should not be manager under new authority")
	uassert.True(t, HasManager(cross(cur), manager2Addr), "manager2 should be manager under new authority")

	// Try adding a manager using the old origin - Should fail
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err = AddManager(cross(cur), nonManagerAddr)
	uassert.Error(t, err, "origin should not be able to add manager after transfer")

	// Try adding a manager using the new manager (manager2) - Should succeed
	testing.SetRealm(testing.NewUserRealm(manager2Addr))
	err = AddManager(cross(cur), nonManagerAddr)
	uassert.NoError(t, err, "new manager (manager2) should be able to add managers")
	uassert.True(t, HasManager(cross(cur), nonManagerAddr), "nonManager should be added by manager2")

	// Try transferring to nil - Should fail
	testing.SetRealm(testing.NewUserRealm(manager2Addr))
	err = TransferManagement(cross(cur), nil)
	uassert.ErrorContains(t, err, "new authority cannot be nil", "transferring to nil should fail")
}

func TestTransferToContractAuthority(cur realm, t *testing.T) {
	setupTest(cur, t) // Origin is the initial manager

	contractPath := "gno.land/r/testcontract"
	contractRealm := testing.NewCodeRealm(contractPath) // Simulate contract realm

	// Define a simple contract authority handler
	handlerExecuted := false // Track if the handler itself gets called
	contractAuth := authz.NewContractAuthority(contractPath, func(title string, action authz.PrivilegedAction) error {
		// Simulate contract checking the caller *before* executing
		caller := unsafe.CurrentRealm().Address()
		expectedContractAddr := chain.PackageAddress(contractPath)
		if caller != expectedContractAddr {
			// Fail before marking executed or running action
			// Note: In a real scenario, this handler might just ignore the call
			// if the caller isn't right, rather than returning an error,
			// depending on the desired contract logic. Returning an error
			// here helps the test verify the handler wasn't improperly called.
			return errors.New("handler: caller is not the contract")
		}

		// Only mark executed and run action if caller is correct
		handlerExecuted = true
		return action()
	})

	// Origin transfers management to the contract authority
	testing.SetRealm(testing.NewUserRealm(originAddr))
	err := TransferManagement(cross(cur), contractAuth)
	uassert.NoError(t, err, "transfer to contract authority failed")
	uassert.True(t, Authorizer.Authority() == contractAuth, "authority should now be the contract authority")

	// Now, actions like AddManager/RemoveManager should fail because the current
	// authority is no longer a MemberAuthority. The contract would need its own
	// logic executed via Authorizer.DoByCurrent() to manage members if desired.

	// Try adding a manager (will check authority type) - Should fail
	testing.SetRealm(testing.NewUserRealm(originAddr)) // Caller doesn't matter for this check
	err = AddManager(cross(cur), manager1Addr)
	uassert.ErrorContains(t, err, "current authority is not a MemberAuthority", "AddManager should fail with ContractAuthority")

	// Simulate an action authorized *by the contract* using Authorizer.Do
	var contractActionExecuted bool
	handlerExecuted = false         // Reset tracker
	testing.SetRealm(contractRealm) // Call must originate from the contract now
	err = Authorizer.DoByCurrent(0, cur, "some_contract_action", func() error {
		contractActionExecuted = true
		// Imagine contract logic here
		return nil
	})
	uassert.NoError(t, err, "contract action via Authorizer.Do failed")
	uassert.True(t, handlerExecuted, "handler should have been executed by contract call") // Verify handler ran
	uassert.True(t, contractActionExecuted, "contract action should have been executed")

	// Simulate an action from a user - Should fail before handler is called
	var userActionExecuted bool
	handlerExecuted = false // Reset tracker
	testing.SetRealm(testing.NewUserRealm(nonManagerAddr))
	err = Authorizer.DoByCurrent(0, cur, "some_user_action", func() error {
		userActionExecuted = true
		return nil
	})
	// A plain ContractAuthority defaults its proposer to the contract
	// itself, so a user caller is rejected UPSTREAM (at the proposer) and
	// the handler is never reached — the handler's own CurrentRealm check
	// above is now belt-and-braces, not the guard being relied on.
	uassert.Error(t, err, "user action via Authorizer.Do should fail when contract is authority")
	uassert.ErrorContains(t, err, "unauthorized", "rejection should come from the contract-identity proposer")
	uassert.False(t, handlerExecuted, "handler should NOT have been executed by user call")
	uassert.False(t, userActionExecuted, "user action should not have been executed")
}

// Helper to check if a slice contains a specific address
func containsAddr(list []address, addr address) bool {
	for _, item := range list {
		if item == addr {
			return true
		}
	}
	return false
}

func assertAddrSliceEqual(t *testing.T, expected, actual []address) {
	t.Helper()
	if len(expected) != len(actual) {
		t.Fatalf("expected slice length %d, got %d. Expected: %v, Got: %v", len(expected), len(actual), expected, actual)
	}

	for i := range expected {
		if expected[i] != actual[i] {
			t.Fatalf("slices differ at index %d. Expected: %v, Got: %v", i, expected, actual)
		}
	}
}

gnomod.toml

module = "gno.land/r/nym-moultest123/config/v1"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186412
  max_deposit = "36000000ugnot"

keys.gno

package config

import (
	"strings"

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

// The key grammar.
//
// A key is a NAME, optionally followed by "@" and a SCOPE:
//
//	pause                  applies to every realm that asks
//	pause@r/moul/home      applies to that realm only
//
// The scope is a package path with the chain domain stripped, because the
// domain is the same for every realm reading this one and repeating it in a
// few dozen keys buys nothing but storage.
//
// Two settings therefore answer every scoped question, and each reader decides
// how they combine: pause takes the stricter of the two (pausable.Strictest),
// while the notice blocks show both. That choice belongs to the reader and not
// here, because "stricter wins" and "show both" are both right, for different
// settings.
const (
	// ScopeSep separates a name from the realm it applies to. "@" and not "."
	// so a scope can never be mistaken for a longer name, and not ":" because
	// gno realm render paths already use that.
	ScopeSep = "@"

	maxNameLen  = 64
	maxScopeLen = 128
)

// realmPath is this realm's own path, including its version. Stated once so
// the page can link to itself and the proxy check can recognise a sibling
// version without either restating the string.
const realmPath = "gno.land/r/nym-moultest123/config/v1"

// validName reports whether name is a legal setting name: 1..maxNameLen bytes
// of [a-z0-9._-]. The dot is the namespace separator ("block.top"), lowercase
// only so a setting has exactly one name, and no whitespace so a name
// round-trips through Manifest's tab-separated lines.
func validName(name string) bool {
	if len(name) == 0 || len(name) > maxNameLen {
		return false
	}
	for i := 0; i < len(name); i++ {
		c := name[i]
		switch {
		case c >= 'a' && c <= 'z', c >= '0' && c <= '9':
		case c == '-', c == '_', c == '.':
		default:
			return false
		}
	}
	return true
}

// validScope reports whether scope is shaped like a package path with the
// domain stripped: 1..maxScopeLen bytes of [a-z0-9._/-], no empty segment.
func validScope(scope string) bool {
	if len(scope) == 0 || len(scope) > maxScopeLen {
		return false
	}
	lastSlash := true // a leading slash would be an empty first segment
	for i := 0; i < len(scope); i++ {
		c := scope[i]
		switch {
		case c >= 'a' && c <= 'z', c >= '0' && c <= '9':
			lastSlash = false
		case c == '-', c == '_', c == '.':
			lastSlash = false
		case c == '/':
			if lastSlash {
				return false
			}
			lastSlash = true
		default:
			return false
		}
	}
	return !lastSlash
}

// validKey reports whether key is a legal name, or a legal name and scope
// joined by ScopeSep.
func validKey(key string) bool {
	name, scope := SplitKey(key)
	if scope == "" {
		return !strings.Contains(key, ScopeSep) && validName(name)
	}
	return validName(name) && validScope(scope)
}

// SplitKey takes a key apart. An unscoped key returns an empty scope, and so
// does a malformed one: callers pair this with validKey rather than trusting
// the split.
func SplitKey(key string) (name, scope string) {
	i := strings.Index(key, ScopeSep)
	if i < 0 {
		return key, ""
	}
	return key[:i], key[i+1:]
}

// Scope turns a package path into the scope half of a key, stripping the chain
// domain: "gno.land/r/nym-moultest123/home" and "r/moul/home" both give "r/moul/home".
//
// A path that is not shaped like one comes back empty, and every caller here
// treats that as "no scope", falling back to the global setting rather than
// inventing a key nobody can type.
//
// The chain domain is tried first and the literal "gno.land/" second, so a key
// written on one chain still resolves on another whose domain differs. Twin of
// mygnoscan.TrimDomain, which answers the same question for a URL and is
// stricter about the characters, because its output lands inside a link.
func Scope(pkgPath string) string {
	s := strings.TrimPrefix(pkgPath, runtime.ChainDomain()+"/")
	s = strings.TrimPrefix(s, "gno.land/")
	s = strings.Trim(s, "/")
	if !validScope(s) {
		return ""
	}
	return s
}

// KeyFor builds the scoped key for a setting on one realm, and returns the
// bare name when pkgPath names no realm this can scope to.
//
// This is what a realm should render when it wants to tell a manager which
// setting to change, so the command in the page is the command that works.
func KeyFor(name, pkgPath string) string {
	scope := Scope(pkgPath)
	if scope == "" {
		return name
	}
	return name + ScopeSep + scope
}

// caller is the package path of the realm that called into this one.
//
// Every exported function here that uses it is a plain read with no `cur realm`
// parameter, so it can only ever be BORROWED: gno runs it without opening a
// realm frame, and unsafe.CurrentRealm() therefore reports the borrower. That
// is what makes the zero-argument helpers (TopBlock, IsPaused, …) able to name
// their caller at all.
//
// Measured in the test harness on 2026-09-22: a call from a code realm at
// gno.land/r/test/caller reports CurrentRealm=gno.land/r/test/caller and
// PreviousRealm=gno.land/r/nym-moultest123/config/v1.
//
// The moment one of these grows a `cur realm` parameter this stops being true
// and starts reporting this realm instead. Do not add one. Anything that needs
// a realm frame takes the path explicitly, which is what the …For variants are.
func caller() string { return unsafe.CurrentRealm().PkgPath() }

// scopedPair reads both halves of a scoped setting: the global one and the one
// for pkgPath, either of which may be empty.
func scopedPair(name, pkgPath string) (global, scoped string) {
	global = Get(name)
	if scope := Scope(pkgPath); scope != "" {
		scoped = Get(name + ScopeSep + scope)
	}
	return global, scoped
}

pause.gno

package config

import "gno.land/p/nym-moultest123/pausable/v0"

// The pause switch: one setting that stops every realm reading this one, and
// one per realm that stops just that one.
//
//	Set pause              "paused: incident, back in an hour"
//	Set pause@r/moul/gns   "readonly"
//	Unset pause            # running again
//
// A realm guards its writes and leaves its reads alone, which is what makes
// "readonly" the level worth having: the page keeps rendering and explains
// itself through TopBlock, and nothing new lands.
//
//	func Post(cur realm, body string) {
//		config.AssertWritable()
//		…
//	}
//
// The levels, the fail-closed parse and the stricter-of-two rule all live in
// gno.land/p/nym-moultest123/pausable; this file is only the wiring to storage.
const KeyPause = "pause"

// Pause returns the pause state of the realm calling in: the stricter of the
// global setting and that realm's own.
func Pause() pausable.State { return PauseFor(caller()) }

// PauseFor is Pause for a named realm.
//
// A stale per-realm entry can never re-open a realm during a global pause,
// because the two combine with pausable.Strictest rather than one overriding
// the other. The cost is that exempting one realm from a global pause is not
// expressible: clear the global and set the others.
func PauseFor(pkgPath string) pausable.State {
	global, scoped := scopedPair(KeyPause, pkgPath)
	return pausable.Strictest(pausable.MustParse(global), pausable.MustParse(scoped))
}

// IsPaused reports whether the realm calling in is held back at all, ReadOnly
// as well as fully paused.
func IsPaused() bool { return Pause().IsPaused() }

// IsPausedFor is IsPaused for a named realm.
func IsPausedFor(pkgPath string) bool { return PauseFor(pkgPath).IsPaused() }

// AssertWritable aborts unless the realm calling in may still change state.
// This is the one line a mutating function needs.
func AssertWritable() { Pause().AssertWritable() }

// AssertWritableFor is AssertWritable for a named realm, for a crossing
// function that cannot be read off the stack.
func AssertWritableFor(pkgPath string) { PauseFor(pkgPath).AssertWritable() }

// AssertReadable aborts unless the realm calling in may still be read.
//
// Most realms should NOT put this in Render. A page that aborts tells a reader
// nothing; TopBlock tells them what happened and when to come back. Reach for
// this only where serving stale data is itself the harm.
func AssertReadable() { Pause().AssertReadable() }

// AssertReadableFor is AssertReadable for a named realm.
func AssertReadableFor(pkgPath string) { PauseFor(pkgPath).AssertReadable() }

pause_test.gno

package config

import (
	"testing"

	"gno.land/p/nym-moultest123/pausable/v0"
	"gno.land/p/nt/uassert/v0"
)

func TestPauseDefaultRunning(t *testing.T) {
	resetSettings()
	uassert.False(t, IsPausedFor(otherRealm))
	uassert.True(t, PauseFor(otherRealm).AllowsRead())
	uassert.True(t, PauseFor(otherRealm).AllowsWrite())
	AssertWritableFor(otherRealm)
	AssertReadableFor(otherRealm)
}

func TestPauseGlobal(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyPause, "readonly")

	// Reaches every realm.
	for _, path := range []string{otherRealm, "gno.land/r/nym-moultest123/home", "gno.land/r/someone/else"} {
		uassert.True(t, IsPausedFor(path), path+" should be held back")
		uassert.True(t, PauseFor(path).AllowsRead(), path+" should still read")
		uassert.False(t, PauseFor(path).AllowsWrite(), path+" should refuse writes")
	}

	uassert.PanicsWithMessage(t, cur, "writes are paused", func() {
		AssertWritableFor(otherRealm)
	})
	AssertReadableFor(otherRealm)
}

func TestPauseScoped(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyFor(KeyPause, otherRealm), "paused: incident")

	uassert.True(t, IsPausedFor(otherRealm))
	uassert.False(t, PauseFor(otherRealm).AllowsRead())
	uassert.False(t, IsPausedFor("gno.land/r/nym-moultest123/home"), "another realm is unaffected")

	uassert.PanicsWithMessage(t, cur, "paused: incident", func() {
		AssertReadableFor(otherRealm)
	})
}

// TestGlobalPauseCannotBeDefeated is the reason the two combine with
// Strictest. A per-realm entry left behind from last month must not re-open a
// realm during a global halt.
func TestGlobalPauseCannotBeDefeated(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyFor(KeyPause, otherRealm), "running")
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyPause, "paused: chain incident")

	uassert.False(t, PauseFor(otherRealm).AllowsRead(),
		"an explicit per-realm 'running' does not survive a global pause")
	uassert.Equal(t, "chain incident", PauseFor(otherRealm).Reason)

	// The other direction works: a per-realm pause under a running global.
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyFor(KeyPause, otherRealm), "paused: just this one")
	uassert.False(t, PauseFor(otherRealm).AllowsRead())
	uassert.True(t, PauseFor("gno.land/r/nym-moultest123/home").AllowsRead())
}

// TestPauseValueValidatedOnWrite is the other half of failing closed. Because
// pausable.MustParse turns an unreadable value into Paused, an unvalidated
// typo here would take every realm offline at the next render; refusing the
// write turns that into a failed transaction the writer sees at once.
func TestPauseValueValidatedOnWrite(cur realm, t *testing.T) {
	resetSettings()

	for _, bad := range []string{"yes", "true", "1", "stop", "read-only"} {
		testing.SetRealm(testing.NewUserRealm(originAddr))
		uassert.AbortsContains(t, cur, "invalid pause value", func() {
			Set(cross(cur), KeyPause, bad)
		})
	}
	uassert.Equal(t, 0, Size(), "no bad value was stored")

	// The scoped key is validated too: the check is on the key's NAME, so it
	// cannot be sidestepped by scoping it.
	testing.SetRealm(testing.NewUserRealm(originAddr))
	uassert.AbortsContains(t, cur, "invalid pause value", func() {
		Set(cross(cur), KeyFor(KeyPause, otherRealm), "yes")
	})

	// And every value the reader understands is accepted.
	for _, good := range []string{"", "running", "readonly", "paused", "paused: why"} {
		testing.SetRealm(testing.NewUserRealm(originAddr))
		Set(cross(cur), KeyPause, good)
		uassert.Equal(t, good, Get(KeyPause))
	}

	// A setting that is not pause is not subject to the grammar.
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), "some.key", "yes")
	uassert.Equal(t, "yes", Get("some.key"))
}

func TestPauseZeroArgFormsNameTheCaller(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyFor(KeyPause, otherRealm), "paused")

	testing.SetRealm(testing.NewCodeRealm(otherRealm))
	uassert.True(t, IsPaused())
	uassert.Equal(t, int(pausable.Paused), int(Pause().Level))

	testing.SetRealm(testing.NewCodeRealm("gno.land/r/nym-moultest123/home"))
	uassert.False(t, IsPaused(), "another realm is unaffected")
	AssertWritable()
}

proxy.gno

package config

import (
	"strings"

	"chain"

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

// Version chaining: how v2 and v3 get built without splitting the state.
//
// # The shape, and why it is this way round
//
// This realm is public, so its path is permanent and a new API means a new
// version at a new path. Left alone, that fragments everything: a realm
// importing v1 and a realm importing v2 would read two different member lists
// and two different pause switches, and the second one to be written would win
// for half the callers.
//
// Delegation fixes it, and it can only run one way. A version can import the
// versions that already existed when it was written; it can never import one
// that does not exist yet. So the STATE STAYS IN THE OLDEST version that has
// it, and every later version is a thin relay in front:
//
//	v3  ->  v2  ->  v1        (this one: the root, and where everything lives)
//
// A realm importing v1, v2 or v3 is then reading the same settings, the same
// pause and the same managers, whichever door it came through. That is the
// property worth all of this.
//
// v0 cannot take part: it is already on chain and has no settings store at
// all. It keeps answering for its own member list and nothing else.
//
// # Writing v2
//
// v2 imports this package, holds no state of its own, and for each write it
// exposes, calls SetAs or UnsetAs with the address it was called by:
//
//	func Set(cur realm, key, value string) {
//		config.SetAs(cross(cur), cur.Previous().Address(), key, value)
//	}
//
// Reads need none of this. They are plain borrowed calls, so v2 just forwards:
//
//	func Get(key string) string { return config.Get(key) }
//
// Then, once, from a manager's address:
//
//	AllowProxy gno.land/r/nym-moultest123/config/v2
//
// # What a proxy is trusted with, exactly
//
// A registered proxy is trusted to say WHO is asking, not to decide whether
// they may. SetAs still puts the principal through the Authorizer, so the
// member list stays the single answer to "who may change config" for every
// version at once, and adding a manager here works through v2 and v3 with no
// further deploys.
//
// It is not a security boundary against the proxy's own code: a proxy that
// lies about its principal writes whatever it likes. It does not have to be,
// because the same person deploys both and registering one is a deliberate,
// revocable act. What it buys is that v2 never carries a copy of the member
// list, so the two can never disagree.

// proxies holds the package paths allowed to relay, keyed by path, valued by
// the address that path resolves to. The address is what an incoming call is
// actually compared against; the path is stored so Render and ListProxies can
// show something a human recognises.
var proxies = avl.NewTree() // pkgPath -> address

// AllowProxy registers a newer version of this realm as a relay. Manager only.
//
// It takes a package path rather than an address because a path is what a
// manager can check by eye; the address is derived here with the same function
// the chain uses, so the two cannot drift.
func AllowProxy(cur realm, pkgPath string) {
	assertProxyPath(pkgPath)
	assertAuthorized(cur, "config.AllowProxy:"+pkgPath)

	proxies.Set(pkgPath, chain.PackageAddress(pkgPath))
	settingsRev++
	chain.Emit("ConfigAllowProxy", "path", pkgPath,
		"address", chain.PackageAddress(pkgPath).String())
}

// RevokeProxy withdraws a relay. Manager only.
//
// Revoking one that was never registered aborts rather than passing quietly:
// at this point in an incident, "done" and "you misspelled it" must not look
// the same.
func RevokeProxy(cur realm, pkgPath string) {
	assertProxyPath(pkgPath)
	assertAuthorized(cur, "config.RevokeProxy:"+pkgPath)

	if _, removed := proxies.Remove(pkgPath); !removed {
		panic("no such proxy: " + pkgPath)
	}
	settingsRev++
	chain.Emit("ConfigRevokeProxy", "path", pkgPath)
}

// IsProxy reports whether addr is a registered relay.
func IsProxy(addr address) bool {
	if addr == "" {
		return false
	}
	found := false
	proxies.Iterate("", "", func(_ string, value any) bool {
		if value.(address) == addr {
			found = true
			return true // stop
		}
		return false
	})
	return found
}

// ListProxies returns the registered relay paths, in sorted order.
func ListProxies() []string {
	out := []string{}
	proxies.Iterate("", "", func(key string, _ any) bool {
		out = append(out, key)
		return false
	})
	return out
}

// SetAs is Set, performed by a registered proxy on behalf of principal.
//
// Two checks, and both have to hold: the caller is a registered relay, and the
// principal it names is authorized. Neither is redundant. Dropping the first
// would let any realm claim any principal; dropping the second would make a
// registered proxy an unconditional bypass of the member list.
func SetAs(cur realm, principal address, key, value string) {
	assertRelay(cur)
	assertWritableKey(key)
	assertValue(key, value)
	assertPrincipal(principal, "config.Set:"+key)
	writeSetting(key, value)
}

// UnsetAs is Unset, performed by a registered proxy on behalf of principal.
func UnsetAs(cur realm, principal address, key string) {
	assertRelay(cur)
	assertWritableKey(key)
	assertPrincipal(principal, "config.Unset:"+key)
	removeSetting(key)
}

// assertRelay aborts unless the immediate caller is a registered proxy.
func assertRelay(cur realm) {
	from := cur.Previous().Address()
	if !IsProxy(from) {
		panic("not a registered proxy: " + from.String())
	}
}

// assertPrincipal puts an address through the Authorizer without it being the
// caller, which is what a relay needs and what DoByPrevious cannot express.
//
// With the default MemberAuthority this is a membership test. With an
// authority that inspects the caller instead (a ContractAuthority), the
// relayed path asks that authority about the principal, so check what it does
// before transferring management while a proxy is registered.
func assertPrincipal(principal address, title string) {
	if principal == "" {
		panic("unauthorized: no principal")
	}
	allowed := false
	err := Authorizer.Authority().Authorize(principal, title, func() error {
		allowed = true
		return nil
	})
	if err != nil {
		panic("unauthorized: " + err.Error())
	}
	if !allowed {
		panic("unauthorized")
	}
}

// assertProxyPath refuses anything that is not a realm path under this
// namespace. A proxy is by definition a later version of this realm, so
// nothing else should ever be registered, and the narrow check turns a
// fat-fingered AllowProxy into an abort rather than a standing grant to an
// unrelated realm.
func assertProxyPath(pkgPath string) {
	const want = "gno.land/r/nym-moultest123/config/v"
	if !strings.HasPrefix(pkgPath, want) {
		panic("a proxy must be a later version of this realm, got " + pkgPath)
	}
	rest := strings.TrimPrefix(pkgPath, want)
	if rest == "" || !isDigits(rest) {
		panic("a proxy must be a later version of this realm, got " + pkgPath)
	}
}

func isDigits(s string) bool {
	for i := 0; i < len(s); i++ {
		if s[i] < '0' || s[i] > '9' {
			return false
		}
	}
	return len(s) > 0
}

proxy_test.gno

package config

import (
	"testing"

	"chain"

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

// v2Path is a plausible next version. Nothing is deployed there; the tests
// only need the address the path resolves to, which is what an incoming
// relayed call is actually compared against.
const v2Path = "gno.land/r/nym-moultest123/config/v2"

func v2Addr() address { return chain.PackageAddress(v2Path) }

func TestAllowAndRevokeProxy(cur realm, t *testing.T) {
	resetSettings()
	uassert.Equal(t, 0, len(ListProxies()))
	uassert.False(t, IsProxy(v2Addr()))

	testing.SetRealm(testing.NewUserRealm(originAddr))
	AllowProxy(cross(cur), v2Path)

	uassert.True(t, IsProxy(v2Addr()))
	uassert.Equal(t, 1, len(ListProxies()))
	uassert.Equal(t, v2Path, ListProxies()[0])

	testing.SetRealm(testing.NewUserRealm(originAddr))
	RevokeProxy(cross(cur), v2Path)
	uassert.False(t, IsProxy(v2Addr()))
	uassert.Equal(t, 0, len(ListProxies()))
}

func TestProxyRegistrationIsManagerOnly(cur realm, t *testing.T) {
	resetSettings()

	testing.SetRealm(testing.NewUserRealm(nonManagerAddr))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		AllowProxy(cross(cur), v2Path)
	})
	uassert.False(t, IsProxy(v2Addr()), "a rejected registration leaves nothing behind")
}

// TestProxyPathMustBeASiblingVersion keeps a fat-fingered AllowProxy from
// becoming a standing write grant to an unrelated realm.
func TestProxyPathMustBeASiblingVersion(cur realm, t *testing.T) {
	resetSettings()

	bad := []string{
		"gno.land/r/someone/evil",
		"gno.land/r/nym-moultest123/home",
		"gno.land/r/nym-moultest123/configuration/v2", // prefix-adjacent, not a sibling
		"gno.land/r/nym-moultest123/config/v",         // no number
		"gno.land/r/nym-moultest123/config/vnext",
		"gno.land/r/nym-moultest123/config/v2/sub",
		"",
	}
	for _, path := range bad {
		testing.SetRealm(testing.NewUserRealm(originAddr))
		uassert.AbortsContains(t, cur, "must be a later version", func() {
			AllowProxy(cross(cur), path)
		})
	}
	uassert.Equal(t, 0, len(ListProxies()))
}

func TestRevokeUnknownProxyAborts(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	uassert.AbortsWithMessage(t, cur, "no such proxy: "+v2Path, func() {
		RevokeProxy(cross(cur), v2Path)
	})
}

// TestRelayNeedsRegistration is the first of the relay's two checks: without
// it, any realm could claim to be acting for any principal.
func TestRelayNeedsRegistration(cur realm, t *testing.T) {
	resetSettings()

	testing.SetRealm(testing.NewCodeRealm(v2Path))
	uassert.AbortsContains(t, cur, "not a registered proxy", func() {
		SetAs(cross(cur), originAddr, "some.key", "value")
	})
	uassert.Equal(t, 0, Size())
}

// TestRelayStillChecksThePrincipal is the second check, and the reason a proxy
// is not simply an unconditional bypass: the member list stays the single
// answer to "who may change config", for every version at once.
func TestRelayStillChecksThePrincipal(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	AllowProxy(cross(cur), v2Path)

	testing.SetRealm(testing.NewCodeRealm(v2Path))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		SetAs(cross(cur), nonManagerAddr, "some.key", "value")
	})
	uassert.Equal(t, 0, Size())

	// An empty principal is not a wildcard.
	testing.SetRealm(testing.NewCodeRealm(v2Path))
	uassert.AbortsContains(t, cur, "no principal", func() {
		SetAs(cross(cur), "", "some.key", "value")
	})
}

// TestRelayWritesTheSameState is the property the whole version chain exists
// for: a write arriving through a later version lands in exactly the store
// that a direct write lands in, so v1 and v2 readers never disagree.
func TestRelayWritesTheSameState(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	AllowProxy(cross(cur), v2Path)

	testing.SetRealm(testing.NewCodeRealm(v2Path))
	SetAs(cross(cur), originAddr, KeyMygnoscanURL, "https://scan.example.com")

	uassert.Equal(t, "https://scan.example.com", Get(KeyMygnoscanURL))
	uassert.Equal(t, "https://scan.example.com", MygnoscanURL(),
		"the typed accessor sees the relayed write too")

	testing.SetRealm(testing.NewCodeRealm(v2Path))
	UnsetAs(cross(cur), originAddr, KeyMygnoscanURL)
	uassert.False(t, Has(KeyMygnoscanURL))
}

// TestRelayValidatesLikeTheDirectPath: a relay is a different door, not a
// different set of rules. Key shape and value grammar are checked identically.
func TestRelayValidatesLikeTheDirectPath(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	AllowProxy(cross(cur), v2Path)

	testing.SetRealm(testing.NewCodeRealm(v2Path))
	uassert.AbortsContains(t, cur, "invalid key", func() {
		SetAs(cross(cur), originAddr, "Bad Key", "value")
	})

	testing.SetRealm(testing.NewCodeRealm(v2Path))
	uassert.AbortsContains(t, cur, "invalid pause value", func() {
		SetAs(cross(cur), originAddr, KeyPause, "yes")
	})
}

// TestRevokedProxyCannotWrite: revocation is the emergency brake on the relay
// itself, so it has to bite immediately.
func TestRevokedProxyCannotWrite(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	AllowProxy(cross(cur), v2Path)

	testing.SetRealm(testing.NewCodeRealm(v2Path))
	SetAs(cross(cur), originAddr, "some.key", "before")

	testing.SetRealm(testing.NewUserRealm(originAddr))
	RevokeProxy(cross(cur), v2Path)

	testing.SetRealm(testing.NewCodeRealm(v2Path))
	uassert.AbortsContains(t, cur, "not a registered proxy", func() {
		SetAs(cross(cur), originAddr, "some.key", "after")
	})
	uassert.Equal(t, "before", Get("some.key"))
}

// TestManagerChangesReachTheRelay is what makes one member list serve every
// version: adding a manager here works through v2 with no further deploys.
func TestManagerChangesReachTheRelay(cur realm, t *testing.T) {
	resetSettings()
	testing.SetRealm(testing.NewUserRealm(originAddr))
	AllowProxy(cross(cur), v2Path)

	testing.SetRealm(testing.NewCodeRealm(v2Path))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		SetAs(cross(cur), manager1Addr, "some.key", "value")
	})

	testing.SetRealm(testing.NewUserRealm(originAddr))
	uassert.NoError(t, AddManager(cross(cur), manager1Addr))

	testing.SetRealm(testing.NewCodeRealm(v2Path))
	SetAs(cross(cur), manager1Addr, "some.key", "value")
	uassert.Equal(t, "value", Get("some.key"))
}

// ExampleRender_proxies pins the section that only exists once a later version
// is registered, which is the state this realm spends most of its life NOT in.
func ExampleRender_proxies() {
	resetSettings()
	proxies.Set(v2Path, chain.PackageAddress(v2Path))
	print(Render(""))
	// Output:
	// # gno.land/r/nym-moultest123/config
	//
	// moul's settings, read by his other realms. rev 0 · 0 setting(s)
	//
	// ## Settings
	//
	// _none set; every reader is on its built-in default_
	//
	// ## Pause
	//
	// _running; no global pause_
	//
	// ## Authority
	//
	// `member_authority[g1daexjemfde047h6lta047h6lta047h6ld2pug6]`
	//
	// ## Proxies
	//
	// Later versions of this realm that may relay a write:
	//
	// - `gno.land/r/nym-moultest123/config/v2`
	//
	// ---
	//
	// [explorer](https://mygnoscan.moul.p2p.team/realm/r/nym-moultest123/config/v1) · [source](https://mygnoscan.moul.p2p.team/realm/r/nym-moultest123/config/v1?tab=source) · [calls](https://mygnoscan.moul.p2p.team/realm/r/nym-moultest123/config/v1?tab=calls) · [deps](https://mygnoscan.moul.p2p.team/realm/r/nym-moultest123/config/v1?tab=deps)
}

settings.gno

package config

import (
	"strconv"
	"strings"

	"chain"
	"chain/runtime"

	"gno.land/p/nym-moultest123/mygnoscan/v0"
	"gno.land/p/nym-moultest123/pausable/v0"
	"gno.land/p/nt/avl/v0"
)

// The keys this realm answers for by name. A key is just a string and any key
// can be set, but one the rest of the repo reads gets a constant here so the
// reader and the writer cannot drift apart on a typo.
const (
	// KeyMygnoscanURL is the explorer instance every realm of moul's links to.
	KeyMygnoscanURL = "mygnoscan.url"
	// KeyMygnoscanNetwork overrides the ?network= id, for an instance that
	// names the chain something other than what mygnoscan.NetworkFor expects.
	// Unset is the normal case: the chain-id decides.
	KeyMygnoscanNetwork = "mygnoscan.network"
)

// maxValueLen bounds one write. Storage is paid for and never refunded, so
// this realm holds settings, not content: a URL, a flag, a short list.
//
// A notice block is the one that pushes against it, and 1024 bytes is several
// paragraphs of markdown. A realm that needs more than that is asking this one
// to be a CMS, which is what its own slots are for.
const maxValueLen = 1024

type setting struct {
	value   string
	rev     int
	updated int64
}

var (
	settings    = avl.NewTree() // key -> *setting
	settingsRev int
)

// Set creates or replaces a setting. Only an address the Authorizer accepts
// may call it.
//
// It panics rather than returning an error, which is the opposite of the
// manager functions in config.gno, and deliberately so: a returned error from
// a realm call leaves the transaction SUCCESSFUL. A rejected config write that
// reports success is the one outcome worth ruling out here, because the caller
// then walks away believing the new value is live and every realm reading this
// key keeps serving the old one. The manager functions predate that reasoning
// and are frozen on chain at v0; new surface does not inherit the mistake.
func Set(cur realm, key, value string) {
	assertWritableKey(key)
	assertValue(key, value)
	assertAuthorized(cur, "config.Set:"+key)
	writeSetting(key, value)
}

// Unset removes a setting, so readers fall back to their built-in default.
// Removing a key that is not set is an error, not a no-op: it almost always
// means the key was misspelled here or in the realm that reads it.
func Unset(cur realm, key string) {
	assertWritableKey(key)
	assertAuthorized(cur, "config.Unset:"+key)
	removeSetting(key)
}

// writeSetting is the only place a setting is stored, shared by the direct and
// the relayed path so a new caller cannot forget the revision or the event.
func writeSetting(key, value string) {
	settingsRev++
	settings.Set(key, &setting{
		value:   value,
		rev:     settingsRev,
		updated: runtime.ChainHeight(),
	})
	chain.Emit("ConfigSet", "key", key, "value", value, "rev", strconv.Itoa(settingsRev))
}

// removeSetting is writeSetting's twin.
func removeSetting(key string) {
	if _, removed := settings.Remove(key); !removed {
		panic("no such setting: " + key)
	}
	settingsRev++
	chain.Emit("ConfigUnset", "key", key, "rev", strconv.Itoa(settingsRev))
}

func assertWritableKey(key string) {
	if !validKey(key) {
		panic("invalid key: want <name> or <name>" + ScopeSep + "<realm-path>, " +
			"name being 1-" + strconv.Itoa(maxNameLen) + " bytes of [a-z0-9._-], got " +
			strconv.Quote(key))
	}
}

// assertValue rejects a value the reader could not make sense of.
//
// Only pause has a grammar today, and it is exactly the setting where a
// silently unreadable value matters: pausable.MustParse fails CLOSED, so a
// typo stored here would take every realm offline at the next render. Catching
// it on the way in costs one comparison and turns that into a failed
// transaction the writer sees immediately.
func assertValue(key, value string) {
	if len(value) > maxValueLen {
		panic("value too long: max " + strconv.Itoa(maxValueLen) +
			" bytes, got " + strconv.Itoa(len(value)))
	}
	if name, _ := SplitKey(key); name == KeyPause {
		if _, ok := pausable.Parse(value); !ok {
			panic("invalid pause value " + strconv.Quote(value) +
				": want \"\", \"running\", \"readonly\" or \"paused\", each optionally followed by \": <reason>\"")
		}
	}
}

// assertAuthorized runs the write through the Authorizer, so whoever holds
// authority today decides: the member list at first, a DAO or a contract after
// a TransferManagement. The action closure is what authz authorizes; the write
// itself happens after, because a nil error is the only thing that reaches it.
func assertAuthorized(cur realm, title string) {
	allowed := false
	err := Authorizer.DoByPrevious(0, cur, title, func() error {
		allowed = true
		return nil
	})
	if err != nil {
		panic("unauthorized: " + err.Error())
	}
	if !allowed {
		panic("unauthorized")
	}
}

// Get returns a setting's value, or "" when it is not set. Reads are open: a
// realm importing this one calls Get on every render and pays nothing beyond
// the cross-realm call.
func Get(key string) string {
	v := settings.Get(key)
	if v == nil {
		return ""
	}
	return v.(*setting).value
}

// GetOr returns a setting's value, or fallback when it is unset or empty.
// This is the shape every consumer wants: a realm should still render on a
// chain where this one was never deployed with that key.
func GetOr(key, fallback string) string {
	if v := Get(key); v != "" {
		return v
	}
	return fallback
}

// Has reports whether key is set, including to the empty string, which GetOr
// cannot distinguish from unset.
func Has(key string) bool { return settings.Has(key) }

// Keys returns every set key, in sorted order.
func Keys() []string {
	out := []string{}
	settings.Iterate("", "", func(key string, _ any) bool {
		out = append(out, key)
		return false
	})
	return out
}

// Size returns how many settings are set.
func Size() int { return settings.Size() }

// SettingsRevision counts every settings write this realm has accepted. A
// client that caches config polls this one int to learn that nothing moved.
func SettingsRevision() int { return settingsRev }

// Manifest returns one tab-separated line per setting:
//
//	<key>\t<rev>\t<height>\t<value>
//
// It is the whole config in one vm/qeval read, for a tool that wants to diff
// the chain against a local file without a call per key. The value is last
// because it is the only field that can contain a tab.
func Manifest() string {
	var b strings.Builder
	settings.Iterate("", "", func(key string, value any) bool {
		s := value.(*setting)
		b.WriteString(key)
		b.WriteString("\t")
		b.WriteString(strconv.Itoa(s.rev))
		b.WriteString("\t")
		b.WriteString(strconv.FormatInt(s.updated, 10))
		b.WriteString("\t")
		b.WriteString(s.value)
		b.WriteString("\n")
		return false
	})
	return b.String()
}

// MygnoscanURL returns the explorer base moul's realms should link to, falling
// back to the package default when nothing is set here.
func MygnoscanURL() string { return GetOr(KeyMygnoscanURL, mygnoscan.DefaultBase) }

// Scanner returns a link builder pointed at the configured explorer, on
// whichever network answers for the running chain (or at the KeyMygnoscanNetwork
// override, when one is set).
//
// This is the function other realms are meant to call:
//
//	config.Scanner().Realm("gno.land/r/nym-moultest123/home")
//	config.Scanner().Address(someAddr)
//
// Changing where every one of them points is then one transaction against this
// realm, not a redeploy of each.
func Scanner() mygnoscan.Scanner {
	s := mygnoscan.New(MygnoscanURL())
	if net := Get(KeyMygnoscanNetwork); net != "" {
		s = s.WithNetwork(net)
	}
	return s
}

// Mygnoscan is the explorer page of the realm calling in.
func Mygnoscan() string { return MygnoscanFor(caller()) }

// MygnoscanFor is Mygnoscan for a named realm.
func MygnoscanFor(pkgPath string) string { return Scanner().Realm(pkgPath) }

// MygnoscanFooter is the render-ready form: the markdown line the realm
// calling in appends under its output.
func MygnoscanFooter() string { return MygnoscanFooterFor(caller()) }

// MygnoscanFooterFor is MygnoscanFooter for a named realm.
func MygnoscanFooterFor(pkgPath string) string { return Scanner().RealmFooter(pkgPath) }

// Render shows the whole configuration: the settings, who may change them, and
// where this realm itself can be inspected.
func Render(path string) string {
	var b strings.Builder

	b.WriteString("# gno.land/r/nym-moultest123/config\n\n")
	b.WriteString("moul's settings, read by his other realms. ")
	b.WriteString("rev ")
	b.WriteString(strconv.Itoa(settingsRev))
	b.WriteString(" · ")
	b.WriteString(strconv.Itoa(settings.Size()))
	b.WriteString(" setting(s)\n\n")

	b.WriteString("## Settings\n\n")
	if settings.Size() == 0 {
		b.WriteString("_none set; every reader is on its built-in default_\n")
	} else {
		b.WriteString("| key | value | rev | height |\n")
		b.WriteString("| --- | --- | ---: | ---: |\n")
		settings.Iterate("", "", func(key string, value any) bool {
			s := value.(*setting)
			b.WriteString("| `")
			b.WriteString(key)
			b.WriteString("` | ")
			b.WriteString(renderValue(s.value))
			b.WriteString(" | ")
			b.WriteString(strconv.Itoa(s.rev))
			b.WriteString(" | ")
			b.WriteString(strconv.FormatInt(s.updated, 10))
			b.WriteString(" |\n")
			return false
		})
	}

	b.WriteString("\n## Pause\n\n")
	b.WriteString(renderPause())

	b.WriteString("\n## Authority\n\n")
	b.WriteString("`")
	b.WriteString(Authorizer.String())
	b.WriteString("`\n")

	b.WriteString(renderProxies())

	b.WriteString("\n---\n\n")
	b.WriteString(MygnoscanFooterFor(realmPath))
	b.WriteString("\n")

	return b.String()
}

// renderPause reports the global pause only. A per-realm one is a setting like
// any other and is already in the table above; repeating them here would be a
// second list to keep in step, and the one a reader of THIS page wants is the
// switch that covers everything.
func renderPause() string {
	st := pausable.MustParse(Get(KeyPause))
	if !st.IsPaused() {
		return "_running; no global pause_\n"
	}
	return st.Notice() + "\n"
}

// renderProxies lists the later versions allowed to relay writes here. The
// section is omitted entirely while there are none, which is the state this
// realm ships in and stays in until a v2 exists.
func renderProxies() string {
	paths := ListProxies()
	if len(paths) == 0 {
		return ""
	}
	var b strings.Builder
	b.WriteString("\n## Proxies\n\n")
	b.WriteString("Later versions of this realm that may relay a write:\n\n")
	for _, p := range paths {
		b.WriteString("- `")
		b.WriteString(p)
		b.WriteString("`\n")
	}
	return b.String()
}

// renderValue puts a value in a code span and neutralises the two characters
// that would otherwise break out of the table cell it sits in. Only a manager
// can write a value, so this is about a stray pipe in a URL and not about an
// attacker, but a config page that silently loses a column is its own bug.
func renderValue(v string) string {
	if v == "" {
		return "_(empty)_"
	}
	v = strings.ReplaceAll(v, "|", "\\|")
	v = strings.ReplaceAll(v, "`", "'")
	v = strings.ReplaceAll(v, "\n", " ")
	return "`" + v + "`"
}

settings_test.gno

package config

import (
	"strconv"
	"testing"

	"chain/runtime"

	"gno.land/p/nym-moultest123/authz/v0"
	"gno.land/p/nym-moultest123/mygnoscan/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/uassert/v0"
)

// resetSettings 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 ExampleRender output would depend on which tests
// ran before it and in what order.
func resetSettings() {
	settings = avl.NewTree()
	proxies = avl.NewTree()
	settingsRev = 0
	Authorizer = authz.NewWithAuthority(authz.NewMemberAuthority(originAddr))
}

func TestValidKey(t *testing.T) {
	tests := []struct {
		key  string
		want bool
	}{
		{"mygnoscan.url", true},
		{"a", true},
		{"a-b_c.d0", true},
		{"", false},
		{"Upper", false},
		{"has space", false},
		{"tab\there", false},
		{"colon:here", false},
		// A bare slash is not a name; it is only legal inside a scope.
		{"slash/here", false},
		// Scoped keys.
		{"pause" + ScopeSep + "r/moul/home", true},
		{"block.top" + ScopeSep + "p/moul/kit/ui", true},
		{"pause" + ScopeSep, false},           // scope separator with no scope
		{ScopeSep + "r/moul/home", false},     // scope with no name
		{"pause" + ScopeSep + "r//moul", false},
		{"pause" + ScopeSep + "r/moul/", false},
		{"pause" + ScopeSep + "R/Moul/Home", false},
		{"pause" + ScopeSep + "a" + ScopeSep + "b", false},
	}
	for _, tt := range tests {
		uassert.Equal(t, tt.want, validKey(tt.key), "validKey("+tt.key+")")
	}

	// 64 bytes is the last legal length, 65 the first illegal one.
	long := ""
	for i := 0; i < maxNameLen; i++ {
		long += "a"
	}
	uassert.True(t, validKey(long), "a name of exactly maxNameLen is legal")
	uassert.False(t, validKey(long+"a"), "one byte over maxNameLen is not")
}

func TestSetGetUnset(cur realm, t *testing.T) {
	resetSettings()

	uassert.Equal(t, "", Get("mygnoscan.url"))
	uassert.False(t, Has("mygnoscan.url"))
	uassert.Equal(t, "fallback", GetOr("mygnoscan.url", "fallback"))
	uassert.Equal(t, 0, SettingsRevision())

	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyMygnoscanURL, "https://scan.example.com")

	uassert.Equal(t, "https://scan.example.com", Get(KeyMygnoscanURL))
	uassert.True(t, Has(KeyMygnoscanURL))
	uassert.Equal(t, "https://scan.example.com", GetOr(KeyMygnoscanURL, "fallback"))
	uassert.Equal(t, 1, SettingsRevision())
	uassert.Equal(t, 1, Size())

	// Overwriting is an ordinary write and bumps the revision again.
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyMygnoscanURL, "https://scan2.example.com")
	uassert.Equal(t, "https://scan2.example.com", Get(KeyMygnoscanURL))
	uassert.Equal(t, 2, SettingsRevision())
	uassert.Equal(t, 1, Size())

	testing.SetRealm(testing.NewUserRealm(originAddr))
	Unset(cross(cur), KeyMygnoscanURL)
	uassert.Equal(t, "", Get(KeyMygnoscanURL))
	uassert.False(t, Has(KeyMygnoscanURL))
	uassert.Equal(t, 0, Size())
	uassert.Equal(t, 3, SettingsRevision())
}

// TestEmptyValueIsSet pins the one case GetOr cannot see: a key set to "" is
// set, and every reader falls back anyway. That is deliberate (a reader's
// default beats an empty string) but it means Unset and Set("") are not the
// same operation, and only Has tells them apart.
func TestEmptyValueIsSet(cur realm, t *testing.T) {
	resetSettings()

	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), "some.key", "")

	uassert.True(t, Has("some.key"))
	uassert.Equal(t, "", Get("some.key"))
	uassert.Equal(t, "fallback", GetOr("some.key", "fallback"))
}

func TestSetRequiresAuthority(cur realm, t *testing.T) {
	resetSettings()

	testing.SetRealm(testing.NewUserRealm(nonManagerAddr))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		Set(cross(cur), "some.key", "value")
	})
	uassert.Equal(t, 0, Size(), "a rejected write leaves nothing behind")
	uassert.Equal(t, 0, SettingsRevision(), "and does not move the revision")

	// A manager added by the origin can write, which is the whole point of
	// routing through the Authorizer instead of a hardcoded address.
	testing.SetRealm(testing.NewUserRealm(originAddr))
	uassert.NoError(t, AddManager(cross(cur), manager1Addr))

	testing.SetRealm(testing.NewUserRealm(manager1Addr))
	Set(cross(cur), "some.key", "value")
	uassert.Equal(t, "value", Get("some.key"))

	// And loses it again when removed.
	testing.SetRealm(testing.NewUserRealm(originAddr))
	uassert.NoError(t, RemoveManager(cross(cur), manager1Addr))

	testing.SetRealm(testing.NewUserRealm(manager1Addr))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		Set(cross(cur), "other.key", "value")
	})
}

func TestUnsetRequiresAuthority(cur realm, t *testing.T) {
	resetSettings()

	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), "some.key", "value")

	testing.SetRealm(testing.NewUserRealm(nonManagerAddr))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		Unset(cross(cur), "some.key")
	})
	uassert.Equal(t, "value", Get("some.key"), "a rejected unset leaves the value")
}

func TestUnsetMissingKeyAborts(cur realm, t *testing.T) {
	resetSettings()

	testing.SetRealm(testing.NewUserRealm(originAddr))
	uassert.AbortsWithMessage(t, cur, "no such setting: never.set", func() {
		Unset(cross(cur), "never.set")
	})
}

func TestInvalidInputAborts(cur realm, t *testing.T) {
	resetSettings()

	testing.SetRealm(testing.NewUserRealm(originAddr))
	uassert.AbortsContains(t, cur, "invalid key", func() {
		Set(cross(cur), "Bad Key", "value")
	})

	long := ""
	for i := 0; i < maxValueLen+1; i++ {
		long += "x"
	}
	testing.SetRealm(testing.NewUserRealm(originAddr))
	uassert.AbortsContains(t, cur, "value too long", func() {
		Set(cross(cur), "some.key", long)
	})

	uassert.Equal(t, 0, Size(), "neither rejection wrote anything")
}

// TestKeyValidatedBeforeAuthority pins the check order: an unauthorised caller
// passing a malformed key is told the key is wrong, not that they are. Nothing
// secret leaks either way, and validating first means a manager's typo gets
// the useful message rather than a misleading "unauthorized".
func TestKeyValidatedBeforeAuthority(cur realm, t *testing.T) {
	resetSettings()

	testing.SetRealm(testing.NewUserRealm(nonManagerAddr))
	uassert.AbortsContains(t, cur, "invalid key", func() {
		Set(cross(cur), "Bad Key", "value")
	})
}

func TestKeysAndManifest(cur realm, t *testing.T) {
	resetSettings()

	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), "zzz.last", "z")
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), "aaa.first", "a")

	keys := Keys()
	uassert.Equal(t, 2, len(keys))
	uassert.Equal(t, "aaa.first", keys[0], "Keys is sorted, not insertion-ordered")
	uassert.Equal(t, "zzz.last", keys[1])

	// rev is the realm-wide counter at the time of that key's last write, so
	// zzz.last carries 1 and aaa.first carries 2 despite sorting first. The
	// height column is read back from the chain rather than hardcoded: gno's
	// test harness has no absolute height setter, so tests inherit whatever
	// height ran before them and a literal here would break on the next test
	// added above this one.
	h := strconv.FormatInt(runtime.ChainHeight(), 10)
	uassert.Equal(t,
		"aaa.first\t2\t"+h+"\ta\nzzz.last\t1\t"+h+"\tz\n",
		Manifest())
}

func TestScannerFollowsSettings(cur realm, t *testing.T) {
	resetSettings()

	// Unset, every reader is on the package default.
	uassert.Equal(t, mygnoscan.DefaultBase, MygnoscanURL())
	uassert.Equal(t,
		mygnoscan.DefaultBase+"/realm/r/nym-moultest123/home",
		MygnoscanFor("gno.land/r/nym-moultest123/home"))

	// One transaction moves every realm that reads this one.
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyMygnoscanURL, "https://scan.example.com")

	uassert.Equal(t, "https://scan.example.com", MygnoscanURL())
	uassert.Equal(t,
		"https://scan.example.com/realm/r/nym-moultest123/home",
		MygnoscanFor("gno.land/r/nym-moultest123/home"))

	// The network override is independent of the base, for an instance that
	// names the chain differently. The test harness runs as chain-id "dev",
	// which maps to no network at all, so this is the only way to see one.
	uassert.Equal(t, "", Scanner().Network())
	testing.SetRealm(testing.NewUserRealm(originAddr))
	Set(cross(cur), KeyMygnoscanNetwork, "gnoland1")
	uassert.Equal(t, "gnoland1", Scanner().Network())
	uassert.Equal(t,
		"https://scan.example.com/realm/r/nym-moultest123/home?network=gnoland1",
		MygnoscanFor("gno.land/r/nym-moultest123/home"))
}

func TestMygnoscanFooter(cur realm, t *testing.T) {
	resetSettings()
	uassert.Equal(t,
		mygnoscan.DefaultBase+"/realm/r/nym-moultest123/config",
		mygnoscan.Default().Realm("gno.land/r/nym-moultest123/config"),
		"the footer and a direct build agree while nothing is configured")
	uassert.True(t, len(MygnoscanFooterFor("gno.land/r/nym-moultest123/config")) > 0)
	uassert.Equal(t, "", MygnoscanFooterFor(""))
}

// ExampleRender pins the page as it looks right after deployment. It resets
// first: examples run after every Test in the binary and would otherwise
// render whatever state they left.
func ExampleRender() {
	resetSettings()
	print(Render(""))
	// Output:
	// # gno.land/r/nym-moultest123/config
	//
	// moul's settings, read by his other realms. rev 0 · 0 setting(s)
	//
	// ## Settings
	//
	// _none set; every reader is on its built-in default_
	//
	// ## Pause
	//
	// _running; no global pause_
	//
	// ## Authority
	//
	// `member_authority[g1daexjemfde047h6lta047h6lta047h6ld2pug6]`
	//
	// ---
	//
	// [explorer](https://mygnoscan.moul.p2p.team/realm/r/nym-moultest123/config/v1) · [source](https://mygnoscan.moul.p2p.team/realm/r/nym-moultest123/config/v1?tab=source) · [calls](https://mygnoscan.moul.p2p.team/realm/r/nym-moultest123/config/v1?tab=calls) · [deps](https://mygnoscan.moul.p2p.team/realm/r/nym-moultest123/config/v1?tab=deps)
}

// ExampleRender_populated pins the settings table and the global pause banner,
// which together are the view a manager actually looks at during an incident.
func ExampleRender_populated() {
	resetSettings()
	settings.Set(KeyMygnoscanURL, &setting{value: "https://scan.example.com", rev: 1, updated: 42})
	settings.Set(KeyPause, &setting{value: "readonly: migrating storage", rev: 2, updated: 43})
	settings.Set(KeyFor(KeyBlockTop, "gno.land/r/nym-moultest123/gns"), &setting{value: "> v2 shipped", rev: 3, updated: 44})
	settingsRev = 3
	print(Render(""))
	// Output:
	// # gno.land/r/nym-moultest123/config
	//
	// moul's settings, read by his other realms. rev 3 · 3 setting(s)
	//
	// ## Settings
	//
	// | key | value | rev | height |
	// | --- | --- | ---: | ---: |
	// | `block.top@r/moul/gns` | `> v2 shipped` | 3 | 44 |
	// | `mygnoscan.url` | `https://scan.example.com` | 1 | 42 |
	// | `pause` | `readonly: migrating storage` | 2 | 43 |
	//
	// ## Pause
	//
	// > **Read-only.** This realm is still readable, but not accepting changes. migrating storage
	//
	// ## Authority
	//
	// `member_authority[g1daexjemfde047h6lta047h6lta047h6ld2pug6]`
	//
	// ---
	//
	// [explorer](https://scan.example.com/realm/r/nym-moultest123/config/v1) · [source](https://scan.example.com/realm/r/nym-moultest123/config/v1?tab=source) · [calls](https://scan.example.com/realm/r/nym-moultest123/config/v1?tab=calls) · [deps](https://scan.example.com/realm/r/nym-moultest123/config/v1?tab=deps)
}