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

actions.gno

package nsdata

import (
	"strconv"
	"strings"
	"time"

	"chain"

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

/*
TIMELOCKED ADMIN ACTIONS: the vault's clock behind the logic realm's most
dangerous calls.

THE GAP THIS CLOSES. The timelock above guarded two things — granting a
logic realm and rotating a role — and everything the logic realm let the
admin do was instant. An audit took a paid name from its holder, made
names in grace reclaimable by anybody, deleted live names and redirected
all revenue, each in one multi-message transaction with a 48-hour delay
in force and nothing ever proposed. No monitor could act between the
steps.

THE SHAPE. The policy stays in the logic realm — which calls are
dangerous, and what exactly a call's arguments are — and the delay lives
here, where no logic swap can shorten it:

	ProposeAction(id)   admin only, as a direct wallet call; stamped with
	                    the timelock delay in force; emits ActionProposed.
	CancelAction(id)    admin or recovery, instantly; CancelAllActions for
	                    an incident.
	ConsumeAction(id)   trusted logic only; panics unless the action has
	                    matured and has not expired; removes it.

An id names one call and its arguments, canonically — nslogic uses
"<Function> <arg> <arg>…" — so a proposal authorizes exactly one change,
and the event a monitor sees is the change itself rather than a hash it
has to trust. The vault does not interpret ids at all.

A matured action stays executable for actionWindow and is void after it,
so a proposal nobody acted on cannot be executed by surprise a year later.
At most maxPendingActions wait at once; expired ones make room. Every
pending action dies when the admin rotates (dropAdminProposals): an
evicted key's plans do not outlive the key.
*/

type pendingAction struct {
	at      int64 // unix second it becomes executable
	expires int64 // unix second it stops being executable
	by      address
}

var (
	pendingActions avl.Tree // id -> *pendingAction

	maxPendingActions = 32

	// Seconds a matured action stays executable. Settable within bounds by
	// admin or recovery: shortening it only voids proposals sooner, and
	// lengthening it cannot make anything mature faster.
	actionWindow int64 = 7 * 24 * 60 * 60
)

const (
	maxActionIDLen   = 2048
	minActionWindow  = int64(60 * 60)
	maxActionWindowS = int64(90 * 24 * 60 * 60)
)

func getAction(id string) *pendingAction {
	if v := pendingActions.Get(id); v != nil {
		return v.(*pendingAction)
	}
	return nil
}

func assertActionID(id string) {
	if id == "" || len(id) > maxActionIDLen {
		panic("nsdata: an action id is 1-" + strconv.Itoa(maxActionIDLen) + " bytes")
	}
	if strings.ContainsAny(id, "\n\r") {
		panic("nsdata: an action id may not contain newlines")
	}
}

// ProposeAction starts the clock on one admin action. Proposing an id
// already pending restarts its clock: the latest proposal is the one that
// must survive its window.
func ProposeAction(cur realm, id string) {
	assertIsAdmin(cur)
	assertActionID(id)
	// Not while recovery is replacing the admin, nor for one timelock after
	// recovery vetoed one of its actions (governance.gno, re-audit M-1).
	assertAdminMayPropose(cur.Previous().Address(), "action")
	now := time.Now().Unix()
	if getAction(id) == nil {
		pruneExpiredActions(now)
		if pendingActions.Size() >= maxPendingActions {
			panic("nsdata: " + strconv.Itoa(maxPendingActions) + " actions are already pending; cancel some first")
		}
	}
	at := now + int64(timelockDelay/time.Second)
	a := &pendingAction{at: at, expires: at + actionWindow, by: cur.Previous().Address()}
	pendingActions.Set(id, a)
	chain.Emit("ActionProposed", "id", id,
		"executableAt", strconv.FormatInt(a.at, 10),
		"expiresAt", strconv.FormatInt(a.expires, 10),
		"by", a.by.String())
}

// CancelAction withdraws one pending action. Admin or recovery: the admin
// changing its mind, or recovery vetoing a key it no longer trusts.
func CancelAction(cur realm, id string) {
	assertIsAdminOrRecovery(cur)
	a := getAction(id)
	if a == nil {
		return // idempotent: see CancelPending
	}
	pendingActions.Remove(id)
	veto(cur.Previous().Address(), "action", a.by)
	chain.Emit("ActionCancelled", "id", id, "by", cur.Previous().Address().String())
}

// CancelAllActions withdraws every pending action at once — the incident
// call, when nobody wants to read a list before acting. From recovery it
// is a veto: the admin proposes no action for one timelock.
func CancelAllActions(cur realm) {
	assertIsAdminOrRecovery(cur)
	n := dropAllActions("cancelled")
	if n > 0 {
		veto(cur.Previous().Address(), "action", admin)
	}
	chain.Emit("ActionsCancelled", "count", strconv.Itoa(n), "by", cur.Previous().Address().String())
}

/*
ConsumeAction spends a matured action. Trusted logic only, so it is also
gated by the pause: a paused registry executes nothing, timelocked or not.

It refuses an action proposed by anybody but the CURRENT admin. Rotation
already drops them all; this is the second lock on the same door, because
a matured proposal is a loaded instruction and the vault should not rely
on one rule to unload it.
*/
func ConsumeAction(cur realm, id string) {
	assertIsTrustedLogic(cur)
	if EvictionPending() {
		panic("nsdata: recovery is replacing the admin; timelocked actions wait for that, and die with it")
	}
	a := getAction(id)
	if a == nil {
		panic("nsdata: action `" + id + "` was never proposed; the admin proposes it with ProposeAction and it waits out the timelock")
	}
	now := time.Now().Unix()
	if now < a.at {
		panic("nsdata: action `" + id + "` is in its timelock until unix " + strconv.FormatInt(a.at, 10))
	}
	if now >= a.expires {
		panic("nsdata: action `" + id + "` expired at unix " + strconv.FormatInt(a.expires, 10) + "; propose it again")
	}
	if a.by != admin {
		panic("nsdata: action `" + id + "` was proposed by a previous admin")
	}
	pendingActions.Remove(id)
	chain.Emit("ActionExecuted", "id", id, "by", cur.Previous().Address().String())
}

// ActionReady reports whether an action could be consumed right now.
func ActionReady(id string) bool {
	a := getAction(id)
	if a == nil {
		return false
	}
	now := time.Now().Unix()
	return now >= a.at && now < a.expires && a.by == admin && !EvictionPending()
}

// GetAction reports a pending action: when it matures, when it expires,
// and who proposed it. All zero when nothing by that id is pending.
func GetAction(id string) (executableAt, expiresAt int64, by address) {
	a := getAction(id)
	if a == nil {
		return 0, 0, ""
	}
	return a.at, a.expires, a.by
}

// ListActions pages through pending action ids, ONE PER LINE: an id may
// contain commas (a price rule does), never a newline.
func ListActions(after string, limit int) (ids, next string) {
	if limit <= 0 || limit > maxPage {
		limit = maxPage
	}
	var b strings.Builder
	n := 0
	last, more := "", false
	pendingActions.Iterate("", "", func(key string, v any) bool {
		if after != "" && key <= after {
			return false
		}
		if n >= limit {
			more = true
			return true
		}
		if n > 0 {
			b.WriteString("\n")
		}
		b.WriteString(key)
		last = key
		n++
		return false
	})
	if !more {
		last = ""
	}
	return b.String(), last
}

func GetActionWindow() int64 { return actionWindow }

// SetActionWindow sets how long a matured action stays executable,
// between an hour and ninety days.
func SetActionWindow(cur realm, seconds int64) {
	assertIsAdminOrRecovery(cur)
	if seconds < minActionWindow || seconds > maxActionWindowS {
		panic("nsdata: the action window is 3600-7776000 seconds")
	}
	actionWindow = seconds
	chain.Emit("ActionWindowSet", "seconds", strconv.FormatInt(seconds, 10),
		"by", cur.Previous().Address().String())
}

// pruneExpiredActions frees the slots of actions nobody can execute any
// more. Bounded by maxPendingActions.
func pruneExpiredActions(now int64) {
	var dead []string
	pendingActions.Iterate("", "", func(key string, v any) bool {
		if now >= v.(*pendingAction).expires {
			dead = append(dead, key)
		}
		return false
	})
	for _, k := range dead {
		pendingActions.Remove(k)
		chain.Emit("ActionExpired", "id", k)
	}
}

func dropAllActions(reason string) int {
	var ids []string
	pendingActions.Iterate("", "", func(key string, v any) bool {
		ids = append(ids, key)
		return false
	})
	for _, k := range ids {
		pendingActions.Remove(k)
		chain.Emit("ActionInvalidated", "id", k, "reason", reason)
	}
	return len(ids)
}

auth.gno

package nsdata

import (
	"chain"

	"gno.land/r/nym-mnsrehearsal001/nsnft/v1"
)

// isFresh reports whether a name's profile data belongs to the token's
// CURRENT ownership epoch. See Name.epoch and freshen.
func isFresh(n *Name, tid string) bool { return freshAt(n, nsnft.Epoch(tid)) }

// freshAt is isFresh with the ledger's answer passed in. See freshenTo.
func freshAt(n *Name, epoch int64) bool { return n.epoch == epoch }

// ownsNow reports whether `addr` holds the token right now, per the ledger.
func ownsNow(addr address, tid string) bool {
	return addr != "" && nsnft.OwnerOf(tid) == addr
}

// isValidNow / isReclaimable are pure integer math over `termLength` and
// `gracePeriod`, both of which are settable — so the lifecycle rules
// themselves can be retuned after deployment. All times are unix seconds.
func isValidNow(expires, now int64) bool {
	return now < expires
}

// isReclaimable compares the elapsed time with the grace period instead of
// adding the grace period to the expiry. The sum wrapped: an expiry of
// math.MaxInt64 — the natural "never expires" value — read as valid AND
// reclaimable at once, and a stranger could take the name (audit L-2). A
// name that has not expired is never reclaimable, whatever grace says.
func isReclaimable(expires, now int64) bool {
	if now < expires {
		return false
	}
	return now-expires >= gracePeriod
}

// streakOf derives how many whole terms a holder has actually lived
// through, replacing the counter that used to be stored on the record.
//
// The stored version counted RENEWAL CALLS, so it measured transactions
// rather than time: prepaying five years bumped it five times on a name
// registered that morning, and an earlier version could be run up
// arbitrarily by calling renew in a loop within one block. Deriving it
// from the registration date makes it unbuyable by construction — the
// only way to increase it is for time to pass — and it resets on its own
// when a lapsed name is reclaimed, because a reclaim writes a fresh
// record with a new `registered`.
//
// termLength is settable and could legitimately be zero, which would
// otherwise divide by zero in a realm that cannot be redeployed.
func streakOf(registered, now int64) int64 {
	if termLength <= 0 || now <= registered {
		return 0
	}
	return (now - registered) / termLength
}

// assertIsTrustedLogic is the gate on every mutation function below.
// cur.Previous().Address() resolves to the CALLING realm's own address
// when invoked via cross(cur) from another realm — same idiom already
// used for assertIsAdmin, just checking a different address. A stray
// call from anywhere else (a different realm, a direct user tx trying
// to call these directly) is rejected.
func assertIsTrustedLogic(cur realm) {
	// The pause check lives here rather than in each mutation so it can
	// never be forgotten on a new one: every write in the realm passes
	// through this gate.
	if paused {
		panic("nsdata: registry is paused")
	}
	// A WALLET IS NEVER LOGIC, even if somebody trusted one (audit L-4).
	// The trust set takes any address, and a wallet granted by mistake —
	// or "temporarily", for a migration — could call every write here
	// directly, policy-free. A run script carries its signer's address, so
	// it is refused too.
	if prev := cur.Previous(); prev.IsUser() || prev.IsEphemeral() {
		panic("nsdata: trusted logic is a deployed realm, never a wallet or a run script")
	}
	if trustedLogicSet.Get(cur.Previous().Address().String()) == nil {
		panic("nsdata: restricted to a trusted logic realm")
	}
}

// -- key encodings --
//
// Two DIFFERENT orderings, deliberately, and it matters which is which:
//
//   storage key : domain + "*" + label   (nameTreeKey)
//   token ID    : label  + "*" + domain  (nameTokenID)
//
// The storage key is DOMAIN-first so that every per-domain query is a
// RANGED scan over a contiguous key span instead of a full-tree scan
// with a filter. Before this, ListNames/CountNames walked every name in
// the registry to answer a question about one domain, which made the
// gnoweb home page O(domains × names) — a permanent, unfixable DoS in an
// immutable realm once the registry grew. Since this realm is deployed
// exactly once, the key layout is a forever decision; it is made here.
//
// The token ID stays label-first because that is the user-facing
// identity (`alice*meme`), it is what the NFT exposes to every external
// tool, and it is what `primary` stores for reverse resolution.
//
// Neither a label nor a domain may contain "*" (enforced by
// validateLabel in the logic realm), so both encodings split
// unambiguously on the first "*".

func nameTreeKey(label, domain string) string { return domain + "*" + label }

func nameTokenID(label, domain string) string { return label + "*" + domain }

// There is no domainTokenID any more: domains are records, not tokens.
// See MIGRATION.md, second attempt, rule 7.

// domainRange returns the [start, end) key bounds covering exactly the
// names stored under `domain`. '+' (0x2B) is the next byte after '*'
// (0x2A), so `domain+"+"` sorts immediately past every `domain+"*"+...`
// key while still sorting before any longer domain (e.g. "meme+" falls
// between "meme*zzz" and "memes*a").
func domainRange(domain string) (start, end string) {
	return domain + "*", domain + "+"
}

// accountKey is the per-address store's key: the address, a colon, the
// field. A bech32 address never contains ":" and a field may not (see
// assertAccountKey), so the split is unambiguous, and every field of one
// address sorts into one span.
func accountKey(owner address, field string) string { return owner.String() + ":" + field }

// accountRange bounds exactly one address's fields. ';' (0x3B) is the byte
// after ':' (0x3A), the same trick domainRange plays with '*' and '+'.
func accountRange(owner address) (start, end string) {
	s := owner.String()
	return s + ":", s + ";"
}

// splitTokenID splits a `label*domain` TOKEN ID. Do not use it on a
// storage key — see the ordering note above.
func splitTokenID(tid string) (label, domain string) {
	for i := 0; i < len(tid); i++ {
		if tid[i] == '*' {
			return tid[:i], tid[i+1:]
		}
	}
	return tid, ""
}

// -- lookups --

func mustGetDomain(label string) *Domain {
	v := domains.Get(label)
	if v == nil {
		panic("nsdata: unknown domain: " + label)
	}
	return v.(*Domain)
}

func getDomain(label string) (*Domain, bool) {
	v := domains.Get(label)
	if v == nil {
		return nil, false
	}
	return v.(*Domain), true
}

func mustGetName(label, domain string) *Name {
	v := names.Get(nameTreeKey(label, domain))
	if v == nil {
		panic("nsdata: unknown name: " + nameTokenID(label, domain))
	}
	return v.(*Name)
}

func getName(label, domain string) (*Name, bool) {
	v := names.Get(nameTreeKey(label, domain))
	if v == nil {
		return nil, false
	}
	return v.(*Name), true
}

// clearPrimaryIfPointingAt drops `owner`'s reverse-resolution pointer
// when (and only when) it still points at `tid`. Called on every
// ownership change — transfer and reclaim.
//
// Without this, `primary` was a write-only tree: it had a Set path and
// no Remove path anywhere in the realm, so selling or losing a name left
// the previous holder permanently reverse-resolving to a name somebody
// else now owns. Reverse resolution asserting ownership that is no
// longer true is the one thing a name service must never do.
func clearPrimaryIfPointingAt(owner address, tid string) {
	k := owner.String()
	if v := primary.Get(k); v != nil && v.(string) == tid {
		primary.Remove(k)
		chain.Emit("PrimaryCleared", "owner", k, "tid", tid, "auto", "true")
	}
}

events.gno

package nsdata

import (
	"strconv"

	"chain"
)

/*
EVERY RECORD AND CONFIG CHANGE EMITS, FROM THE VAULT.

There were no events here outside governance, and none in the logic realm
at all, so the audit's stolen-admin attacks were invisible until the
ledger's Burn and Mint showed the result (audit M-6). PREFLIGHT.md and
MAINNET.md make monitoring the mitigation — "a timelock is worthless if
nobody watches it" — and there was nothing to watch.

They are emitted here rather than in nslogic so the coverage survives a
logic swap: whatever realm writes, the vault says what changed. Each one
carries `by`, the realm that made the write. For record writes that is a
trusted logic realm, which is the point — a write from a realm a monitor
did not expect IS the incident. nslogic adds its own AdminAction event with
the signer and the call.

Profile writes name the field and never the value: the value is in the
transaction already, and an event index is not the place to collect
people's addresses a second time.
*/

func emitBy(cur realm, typ string, kv ...string) {
	kv = append(kv, "by", cur.Previous().Address().String())
	chain.Emit(typ, kv...)
}

func i64(n int64) string { return strconv.FormatInt(n, 10) }

func boolStr(b bool) string {
	if b {
		return "true"
	}
	return "false"
}

// emitConfig is the one event for every typed vault setting.
func emitConfig(cur realm, key, value string) {
	emitBy(cur, "ConfigSet", "key", key, "value", value)
}

export.gno

package nsdata

import (
	"strings"

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

// Snapshot support: the other half of the contingency plan.
//
// Governance protects against a stolen or lost key. This file protects
// against the case no key can fix — a VM-level corruption, a chain
// migration, a defect in this realm discovered too late — where the only
// way out is to reconstruct the registry somewhere else. That is
// possible only if the whole state can be read out reliably and
// repeatably, which needs pagination: an unpaginated listing of a
// registry with tens of thousands of names is one query that is too
// large to ever return, and a snapshot you cannot take is not a backup.
//
// Recovery shape, should it ever be needed:
//   1. Pause() — freeze the registry so it cannot drift from the snapshot.
//   2. Page through the exports here to reconstruct state off-chain.
//   3. Deploy a successor, import the snapshot.
//   4. SetSuccessor() on this realm so readers can follow the move.
//
// The exports are also just useful: an operator who takes a snapshot
// every week has an off-chain record independent of any single chain.

const maxPage = 200

// pageKeys walks a key span and returns up to `limit` keys after the
// `after` cursor, plus the cursor to pass next (empty when exhausted).
func pageKeys(t *avl.Tree, start, end, after string, limit int) (csv, next string) {
	if limit <= 0 || limit > maxPage {
		limit = maxPage
	}
	from := start
	if after != "" && after > from {
		from = after
	}
	var b strings.Builder
	n := 0
	hasMore := false
	last := ""
	t.Iterate(from, end, func(key string, v any) bool {
		if after != "" && key <= after {
			return false
		}
		if n >= limit {
			hasMore = true
			return true
		}
		if n > 0 {
			b.WriteString(",")
		}
		b.WriteString(key)
		last = key
		n++
		return false
	})
	if !hasMore {
		last = ""
	}
	return b.String(), last
}

// ExportDomains pages through every domain label.
func ExportDomains(after string, limit int) (labels, next string) {
	return pageKeys(&domains, "", "", after, limit)
}

// ExportNames pages through every name in the registry, as raw storage
// keys (`domain*label`). Pass an empty domainLabel to walk the whole
// tree, or a domain to walk just that domain's span.
func ExportNames(domainLabel, after string, limit int) (keys, next string) {
	if domainLabel == "" {
		return pageKeys(&names, "", "", after, limit)
	}
	start, end := domainRange(domainLabel)
	return pageKeys(&names, start, end, after, limit)
}

// ExportPrimary pages through the reverse-resolution table as owner
// addresses; pair with GetPrimary to read each value.
func ExportPrimary(after string, limit int) (owners, next string) {
	return pageKeys(&primary, "", "", after, limit)
}

// ExportGlobalKeys lists the package-level extension slot's keys; pair
// with GetGlobal for values.
func ExportGlobalKeys(after string, limit int) (keys, next string) {
	return pageKeys(&globals, "", "", after, limit)
}

// ExportAccounts pages through the per-address store as raw keys
// `<address>:<field>`; pair with GetAccount for each value. Field names
// are comma-free by construction (see assertAccountKey).
func ExportAccounts(after string, limit int) (keys, next string) {
	return pageKeys(&accounts, "", "", after, limit)
}

// AccountCount is how many per-address fields exist, so a snapshot of
// the store can be checked for completeness. A separate read rather than
// a fifth value from Sizes, whose shape the snapshot tools already parse.
func AccountCount() int { return accounts.Size() }

// ExportDomainExtraKeys / ExportNameExtraKeys list a record's extension
// keys so a snapshot can capture data this realm has no schema for.
// Keys are comma-free by construction (see assertExtraKey), so a CSV
// listing is unambiguous.
func ExportDomainExtraKeys(label, after string, limit int) (keys, next string) {
	d := mustGetDomain(label)
	return pageKeys(&d.extra, "", "", after, limit)
}

// A previous holder's keys are not exported. A snapshot that captured them
// would carry the seller's payment addresses into a restore as the buyer's.
func ExportNameExtraKeys(label, domainLabel, after string, limit int) (keys, next string) {
	n := mustGetName(label, domainLabel)
	if !isFresh(n, nameTokenID(label, domainLabel)) {
		return "", ""
	}
	return pageKeys(&n.extra, "", "", after, limit)
}

// KNOWN SNAPSHOT GAP, recorded rather than left to be discovered during
// an actual recovery: GRC-721 OPERATOR APPROVALS live inside nsnft's
// token state and are not enumerable
// through any read this realm exposes. Every other piece of state is
// reachable — record fields via GetDomainInfo/GetNameInfo, extension keys
// via the Export*ExtraKeys pagers, reverse resolution via ExportPrimary,
// globals via ExportGlobalKeys, per-address state via ExportAccounts —
// but operator approvals are not, so a
// reconstructed registry will silently lack them and holders would need
// to re-grant. Treated as acceptable (an approval is a revocable
// convenience, not ownership) but it must not be assumed complete.

// Sizes let an operator verify a snapshot is complete rather than
// trusting that pagination terminated correctly.
func Sizes() (domainCount, nameCount, primaryCount, globalCount int) {
	return domains.Size(), names.Size(), primary.Size(), globals.Size()
}

genesis.gno

package nsdata

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

/*
GENESIS — the state a registry is born with.

WHY IT LIVES IN THE PACKAGE. This project has been through three chains
(topaz-1, sapphire-1, pearl-1), and every time the price list, the
referral tiers and the domain list existed only as somebody's memory of an
afternoon spent in the admin panel. A value set by hand after deployment
is a value that is lost with the chain. A value in this file ships with
the realm.

WHY nsdata AND NOT nslogic. This realm owns the state it writes, so init
can write it with no permission from anybody. nslogic cannot: it writes
through this realm's trust gate, and trust is granted by a timelocked
proposal AFTER deployment — an init in nslogic would panic before the
grant existed and take the deploy down with it.

WHY DOMAINS CAN BE CREATED HERE AT ALL. They used to be tokens, and
minting one needs nsnft to trust this realm, which it cannot yet do during
init. Domains are records now (MIGRATION.md, rule 7), so creating one is a
tree write and nothing more.

WHAT IS NOT HERE. Names. No holder's records carry from one chain to the
next — that is the owner's decision (see the mainnet checklist): testnet
wallets get an entitlement, not their old records. And nothing that names
a generation — the token URI base, the lab domain — because this file is
meant to be the same for the sandbox and for mainnet.

EVERY VALUE IS VALIDATED AND A BAD ONE PANICS. A genesis file that quietly
skipped a malformed global would deploy a registry that looks configured
and is missing its price list, and nothing would say so until somebody was
charged the fallback. Failing the deploy costs one retry.

The data itself is generated into genesis_data.gno by
tools/freeze-genesis.py, from a snapshot of a chain that was configured by
hand. Edit the chain, snapshot it, regenerate; do not edit the data file.
*/

// Genesis domains get a long runway. They are project-owned and all
// created in the same block, so a single term would have every one of them
// lapse on the same day a year later — and a lapsed domain refuses every
// registration under it. Renewing them is still the admin's job; this
// just stops the first renewal being a cliff.
const genesisDomainTerms = 10

/*
refusedInGenesis names what may never be baked into a registry's birth.

Anything whose VALUE is an address: a key that holds power — the free-tier
granter was the one that shipped by accident — is set deliberately, after
deploy, on the chain it belongs to, never inherited from whatever chain a
snapshot was taken on. And the lab nomination, which belongs to a sandbox
generation and would otherwise let a hand-edited data file ship a lab on
a real domain.

No regexp: one compiled pattern costs more storage than this whole file.
*/
func refusedInGenesis(key, value string) bool {
	if key == "labdomain" || key == "granter" {
		return true
	}
	return looksLikeAddress(value)
}

func looksLikeAddress(v string) bool {
	if len(v) != 40 || v[0] != 'g' || v[1] != '1' {
		return false
	}
	for i := 2; i < len(v); i++ {
		c := v[i]
		if !((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
			return false
		}
	}
	return true
}

type genesisCfg struct {
	termLength, gracePeriod                           int64
	minLabelLen, maxLabelLen                          int
	maxExtraKeyLen, maxExtraValueLen, maxExtraEntries int
	maxDeletePerCall                                  int
}

type genesisDomain struct {
	label string
	extra [][2]string
}

func applyGenesis(deployer address, now int64) {
	// Limits first, so every extra written below is held to them.
	c := genesisConfig()
	if c.maxExtraKeyLen > 0 {
		maxExtraKeyLen = c.maxExtraKeyLen
	}
	if c.maxExtraValueLen > 0 {
		maxExtraValueLen = c.maxExtraValueLen
	}
	if c.maxExtraEntries > 0 {
		maxExtraEntries = c.maxExtraEntries
	}
	if c.maxDeletePerCall > 0 {
		maxDeletePerCall = c.maxDeletePerCall
	}
	if c.minLabelLen > 0 {
		minLabelLen = c.minLabelLen
	}
	if c.maxLabelLen > 0 {
		maxLabelLen = c.maxLabelLen
	}
	if c.termLength > 0 {
		termLength = c.termLength
	}
	if c.gracePeriod > 0 {
		gracePeriod = c.gracePeriod
	}
	// The one invariant the lifecycle setters guard, guarded here too:
	// anchoring a renewal to its previous due date only makes sense while a
	// renewal cannot land more than one term late.
	if gracePeriod > termLength {
		panic("nsdata genesis: grace period is longer than the term")
	}

	for _, kv := range genesisGlobals() {
		for _, r := range reservedGlobals {
			if kv[0] == r {
				panic("nsdata genesis: " + r + " belongs to the restore machinery")
			}
		}
		if refusedInGenesis(kv[0], kv[1]) {
			panic("nsdata genesis: " + kv[0] + " holds an address or names a generation; set it after deploy, deliberately")
		}
		if err := setGlobal(kv[0], kv[1]); err != nil {
			panic("nsdata genesis: global " + kv[0] + ": " + err.Error())
		}
	}

	for _, g := range genesisDomains() {
		if err := assertLabelKeySafe(g.label); err != nil {
			panic("nsdata genesis: domain " + g.label + ": " + err.Error())
		}
		if len(g.label) < minLabelLen || len(g.label) > maxLabelLen {
			panic("nsdata genesis: domain " + g.label + " is outside the label length limits")
		}
		if _, dup := getDomain(g.label); dup {
			panic("nsdata genesis: domain " + g.label + " is listed twice")
		}
		// Owned by the deployer, like every domain the admin registers.
		// Under `gno test` there is no deployer, and the domains are still
		// created so the tests exercise the same registry a chain gets.
		d := &Domain{owner: deployer, registered: now,
			expires: now + genesisDomainTerms*termLength, extra: avl.Tree{}}
		for _, kv := range g.extra {
			if err := setExtra(&d.extra, kv[0], kv[1]); err != nil {
				panic("nsdata genesis: domain " + g.label + " key " + kv[0] + ": " + err.Error())
			}
		}
		domains.Set(g.label, d)
	}
}

genesis_data.gno

package nsdata

// GENERATED FILE — do not hand-edit. Rebuild with:
//
//     node tools/snapshot.js && python3 tools/freeze-genesis.py
//
// Frozen from pearl-1 at height 803285, snapshot taken 2026-09-29T05:49:24.859Z.
// 53 domains, 3 globals. Left out: granter.

func genesisConfig() genesisCfg {
	return genesisCfg{
		termLength:       31536000,
		gracePeriod:      7776000,
		minLabelLen:      1,
		maxLabelLen:      63,
		maxExtraKeyLen:   32,
		maxExtraValueLen: 512,
		maxExtraEntries:  24,
		maxDeletePerCall: 100,
	}
}

func genesisGlobals() [][2]string {
	return [][2]string{
		{"cardfx", "from:12-31;to:01-01;dir:burst;n:5;c:#f87171;c2:#facc15;c3:#60a5fa;k:10;s:3;d:9|from:12-01;to:01-06;dir:fall;n:26;c:#ffffff;c2:#dbeafe;sv:2;s:3;d:11|from:10-24;to:11-02;dir:rise;n:22;c:#f97316;c2:#facc15;s:2;d:8|from:09-25;to:10-23;dir:fall;n:18;c:#f59e0b;c2:#b45309;c3:#dc2626;sh:leaf;sv:1;s:4;d:12|from:03-15;to:04-15;dir:fall;n:16;c:#f9a8d4;c2:#fce7f3;c3:#fbcfe8;sh:petal;s:3;d:13|from:09-01;to:09-07;dir:fall;n:30;c:#22d3ee;c2:#f472b6;c3:#facc15;s:3;d:7"},
		{"refcut", "0:5"},
		{"refdisc", "0:5"},
	}
}

func genesisDomains() []genesisDomain {
	return []genesisDomain{
		{"1337", nil},
		{"420", nil},
		{"69", nil},
		{"alpha", nil},
		{"anon", nil},
		{"ape", nil},
		{"atom", nil},
		{"based", nil},
		{"beta", nil},
		{"bitcoin", nil},
		{"btc", nil},
		{"buidl", nil},
		{"chad", nil},
		{"cooked", nil},
		{"cope", nil},
		{"cosmos", nil},
		{"crypto", nil},
		{"degen", nil},
		{"doge", nil},
		{"eth", nil},
		{"fomo", nil},
		{"fren", nil},
		{"frog", [][2]string{
			{"open", "0"},
		}},
		{"gm", nil},
		{"gn", nil},
		{"gnoland", nil},
		{"gnome", nil},
		{"gnot", nil},
		{"goat", nil},
		{"hodl", nil},
		{"king", nil},
		{"lambo", nil},
		{"meme", [][2]string{
			{"free", "1"},
		}},
		{"mid", nil},
		{"moon", nil},
		{"nft", nil},
		{"ngmi", nil},
		{"og", nil},
		{"omega", nil},
		{"pepe", nil},
		{"photon", nil},
		{"pleb", nil},
		{"rekt", nil},
		{"rich", nil},
		{"ser", nil},
		{"sol", nil},
		{"soon", nil},
		{"sus", nil},
		{"thoon", nil},
		{"troll", nil},
		{"wagie", nil},
		{"wagmi", nil},
		{"whale", nil},
	}
}

gnomod.toml

module = "gno.land/r/nym-mnsrehearsal001/nsdata/v1"
gno = "0.9"

[addpkg]
  creator = "g1lh4rrf9pq9k9tvka9p6vwhyv70e4h09szap6zu"
  height = 452684
  max_deposit = "120000000ugnot"

governance.gno

package nsdata

import (
	"strconv"
	"time"

	"chain"

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

// Governance and emergency response for a realm that can never be
// redeployed. Everything here is callable ONLY by a direct wallet
// transaction — never through a logic realm — so a compromised or buggy
// logic realm can never touch it.
//
// Three powers, deliberately not held by the same key:
//
//	admin     — day-to-day authority: grants/revokes logic realms, tunes
//	            config. The warm key.
//	recovery  — cannot operate the registry at all. Can only rotate
//	            admin, cancel a pending change, revoke a logic realm,
//	            and pause. MUST be a multisig in production; see the
//	            trust note below for why that is not optional.
//	guardian  — can ONLY pause. Nothing else. Safe to keep hot (a
//	            monitoring bot), because its compromise costs an
//	            outage, never the registry.
//
// GRANTING POWER IS SLOW, REVOKING IT IS INSTANT. Handing authority to a
// new admin or a new logic realm goes through a timelock, and so — since
// actions.gno — does every admin action in the logic realm that destroys
// or moves names or money (deletion, lifecycle and treasury changes,
// unfreezing, reassigning, pricing rules, large price moves). Revocation,
// cancellation and pause are immediate; undoing a pause takes recovery or
// the timelock. An attacker holding one key cannot act instantly: they
// must announce and wait, and every step emits an event.
//
// EACH ROLE CAN ROTATE THE OTHER, AND THE ADMIN CANNOT VETO ITS OWN
// REPLACEMENT. A rotation recovery proposes — of the admin, or of itself —
// can be cancelled or displaced only by recovery. An admin-initiated
// rotation of recovery is the admin's to withdraw and, since the re-audit
// of 2026-10-16, recovery's to veto too: recovery is the root (see the
// trust note below), and a veto it could not send in its incident sitting
// reverted the whole sitting, eviction included. A LOST recovery cancels
// nothing, so the admin can still replace it. Proposals live in PER-KIND
// slots so an admin rotation and a recovery rotation can never contend for
// the same slot — an earlier single-slot design let one in-flight proposal
// freeze the entire governance surface, which meant the honest key could
// not even propose a response.
//
// THE TRUST ASYMMETRY, chosen rather than papered over. Both roles rotate
// the other on the same timelock, and it used to be that whichever proposed
// FIRST matured first and won — so a thief holding the admin key, acting
// before anybody noticed, could take recovery too. Since the re-audit of
// 2026-10-16 (M-1) RECOVERY WINS: once recovery's eviction is pending,
// nothing the admin proposed executes before it, a rotation of recovery the
// admin queued earlier included, and the eviction drops all of it. Every
// asymmetry hands the mirror-image power to whoever steals the favoured
// role, and this one is deliberate, the same as the ledger's (nsnft
// governance.gno): a stolen RECOVERY key now beats an honest admin, which
// is why recovery must be the cold multisig and the admin the key that is
// used.
//
// The mitigation is therefore operational as well as contractual:
//   - recovery MUST be a multisig, so no single stolen key can use it;
//   - timelockDelay must be long enough that you will actually notice an
//     event within it;
//   - watch for GovernanceProposed and ActionProposed and treat one you
//     did not initiate as an active incident.
//
// THE INCIDENT RUNBOOK, in this order (MAINNET.md §1b has it in full).
// First RevokeTrustedLogic on every entry of ListTrustedLogic(): guardian,
// admin or recovery may, it is instant, and re-granting needs the
// timelock, so no stolen key can switch the logic back on. Then Pause, and
// Disarm (incident.gno). Then, from recovery: the counter-rotation FIRST and
// alone — proposing it drops everything the admin had pending — then
// VoidGrantsSince and SetQuarantine (incident.gno), and CancelAllActions /
// CancelPending on anything left, which cannot revert; execute the eviction
// at maturity, before anything else.
//
// Pause does NOT stop ExecutePending — it stops registry mutations, which
// limits damage but does not stop a rotation. Do not rely on it for that.
//
// RECOVERY'S EVICTION LANDS FIRST, by rule (re-audit 2026-10-16, M-1). An
// eviction used to drop the admin's plans only when it executed, and anyone
// chose the order matured proposals ran in: the thief could re-propose a
// cancelled grant the block after recovery's sitting, or execute recovery's
// own move to a new cold key first, which dropped recovery's eviction. Now:
//
//	recovery proposing the eviction DROPS everything the admin had pending
//	— grants, delay, unpause, a rotation of recovery, every timelocked
//	action — so nothing of the admin's is held to spring back if the
//	eviction is cancelled; while it is pending (EvictionPending) the admin
//	proposes nothing, nothing it proposed may execute, and logic can spend
//	none of its actions;
//
//	a veto holds: what recovery cancels of the admin's, the admin may not
//	propose again for one timelock (any action, after an action veto), so
//	the sitting cannot be re-proposed around; recovery's eviction landing
//	clears the vetoes, and nothing else does;
//
//	recovery moving ITSELF keeps its eviction: the eviction is protected by
//	the recovery role, which the new key holds, and recovery's rotation of
//	itself is recovery's alone to cancel or displace. Only an
//	admin-initiated replacement of recovery drops the replaced key's
//	eviction.
//
//	recovery's cancellations are idempotent: cancelling what is no longer
//	pending does nothing, so a thief withdrawing its own proposal first
//	cannot make recovery's batched sitting revert.
type pendingOp struct {
	kind string // "admin" | "recovery" | "grantLogic" | "delay" | "unpause"
	addr address
	dur  time.Duration
	at   time.Time // when it becomes executable

	// protectorRole names the role that has EXCLUSIVE control of this
	// proposal — "" means either admin or recovery may cancel it. Set to
	// "recovery" on a recovery-initiated admin rotation, and to "admin"
	// on an admin-initiated recovery rotation, so the role being replaced
	// cannot veto its own replacement.
	protectorRole string

	// by is who proposed it. Recorded so that nobody has to reconstruct
	// it from events, and so the rotation rule below is checkable.
	by address
}

var (
	recovery address
	guardian address
	paused   bool

	// Delay applied to every power-granting change. Starts at zero so
	// local development and initial wiring are not painful; raise it
	// before the registry holds anything worth stealing. Changing it is
	// itself timelocked, or an attacker would simply set it to zero.
	timelockDelay time.Duration

	// Upper bound on timelockDelay. Without it, one execution of an
	// absurd delay would stamp every FUTURE proposal with an unreachable
	// maturity and permanently brick governance in a realm that cannot be
	// redeployed. Settable, but itself bounded by absoluteMaxTimelock.
	maxTimelockDelay = 30 * 24 * time.Hour

	// One genuine hard ceiling: a bound that could itself be raised
	// without limit would not be a bound.
	absoluteMaxTimelock = 365 * 24 * time.Hour

	// Per-kind proposal slots, keyed by kind. Per-kind rather than a
	// single slot so that one in-flight proposal cannot freeze the whole
	// governance surface.
	pendingOps avl.Tree

	// If this registry is ever abandoned in favour of a successor
	// deployment, this is how readers discover where it went.
	successor string

	// kind -> unix second until which the admin may not propose that kind
	// again, because recovery vetoed it; "action" for timelocked actions.
	// See the note above pendingOp. Cleared when the admin rotates.
	vetoUntil avl.Tree
)

// -- role checks --

func assertIsAdmin(cur realm) {
	if cur.Previous().Address() != admin {
		panic("nsdata: restricted to admin")
	}
}

func assertIsAdminOrRecovery(cur realm) {
	a := cur.Previous().Address()
	if a != admin && a != recovery {
		panic("nsdata: restricted to admin or recovery")
	}
}

func assertCanPause(cur realm) {
	a := cur.Previous().Address()
	if a != admin && a != recovery && a != guardian {
		panic("nsdata: restricted to admin, recovery or guardian")
	}
}

// -- emergency stop --

// Pause halts every registry mutation, timelocked actions included.
// Reads are unaffected, so names stay resolvable while writes are frozen.
//
// It deliberately does NOT gate ExecutePending: governance must keep
// working during an incident — recovery's counter-rotation above all.
//
// A pause also drops a pending admin-proposed unpause, so the guardian
// bot can hold the registry paused against a stolen admin key simply by
// pausing again whenever it sees UnpauseProposed.
func Pause(cur realm) {
	assertCanPause(cur)
	paused = true
	if getPendingOp("unpause") != nil {
		pendingOps.Remove("unpause")
		chain.Emit("GovernanceInvalidated", "kind", "unpause", "reason", "paused again")
	}
	chain.Emit("Paused", "by", cur.Previous().Address().String())
}

/*
Unpause restarts the registry at once, and only RECOVERY may do that.

It used to be open to the admin too, which made a pause useless against
the key most likely to be stolen: the admin could unpause in the same
multi-message transaction as whatever it did next, so a pause stopped only
writers that did not hold admin. An audit showed it. The admin can still
unpause — ProposeUnpause, then the timelock — so a false alarm costs a
delay rather than the cold key; recovery can cancel that proposal, and any
new pause drops it. The guardian is excluded as before: a hot key that can
stop the system must not also be able to restart it.
*/
func Unpause(cur realm) {
	if cur.Previous().Address() != recovery {
		panic("nsdata: an instant unpause takes the recovery key; the admin may ProposeUnpause and wait out the timelock")
	}
	paused = false
	if getPendingOp("unpause") != nil {
		pendingOps.Remove("unpause")
	}
	chain.Emit("Unpaused", "by", cur.Previous().Address().String())
}

// ProposeUnpause is the admin's way back from a pause: a proposal like
// any grant of power, executable by anyone once it matures.
func ProposeUnpause(cur realm) {
	assertIsAdmin(cur)
	if !paused {
		panic("nsdata: the registry is not paused")
	}
	setPending(cur, &pendingOp{kind: "unpause"})
}

func IsPaused() bool { return paused }

// -- trusted logic realms (a set, not a single slot) --

func IsTrustedLogic(addr address) bool {
	return trustedLogicSet.Get(addr.String()) != nil
}

func ListTrustedLogic() string {
	out := ""
	trustedLogicSet.Iterate("", "", func(key string, v any) bool {
		if out != "" {
			out += ","
		}
		out += key
		return false
	})
	return out
}

// RevokeTrustedLogic is INSTANT and available to the guardian, because
// cutting off a misbehaving logic realm is the emergency action that must
// never wait on a timelock.
func RevokeTrustedLogic(cur realm, logicAddr address) {
	assertCanPause(cur)
	trustedLogicSet.Remove(logicAddr.String())
	chain.Emit("TrustedLogicRevoked", "addr", logicAddr.String(), "by", cur.Previous().Address().String())
}

// -- timelocked proposals --

// ProposeAdminTransfer starts an admin rotation. When recovery initiates
// it, only recovery may cancel it — the admin being replaced gets no veto
// over their own replacement.
func ProposeAdminTransfer(cur realm, newAdmin address) {
	assertIsAdminOrRecovery(cur)
	if !newAdmin.IsValid() {
		panic("nsdata: invalid address")
	}
	role := ""
	if cur.Previous().Address() == recovery && recovery != admin {
		role = "recovery"
	}
	setPending(cur, &pendingOp{kind: "admin", addr: newAdmin, protectorRole: role})
	if role == "recovery" {
		// AN EVICTION DROPS THE ADMIN'S PLANS WHEN IT IS PROPOSED, not only
		// when it lands: held instead, they all sprang back the moment the
		// eviction was cancelled — to fix a typo in its target, say — and a
		// rotation of recovery the admin queued outlived it (re-audit
		// follow-up, 2026-10-16).
		dropPendingProtectedBy("recovery", "admin")
		dropAdminProposals("recovery is replacing the admin")
	}
}

// ProposeRecoveryTransfer is the mirror image: when admin initiates it,
// only admin may cancel it, so a compromised recovery key cannot block
// its own replacement either.
func ProposeRecoveryTransfer(cur realm, newRecovery address) {
	assertIsAdminOrRecovery(cur)
	if !newRecovery.IsValid() {
		panic("nsdata: invalid address")
	}
	role := ""
	if cur.Previous().Address() == admin && recovery != admin {
		role = "admin"
	}
	// Recovery's rotation of itself is recovery's alone: unprotected, the
	// admin could cancel it, or displace it with a rotation of its own that
	// recovery could then neither cancel nor replace.
	if cur.Previous().Address() == recovery && recovery != admin {
		role = "recovery"
	}
	setPending(cur, &pendingOp{kind: "recovery", addr: newRecovery, protectorRole: role})
}

func ProposeTrustedLogicGrant(cur realm, logicAddr address) {
	assertIsAdmin(cur)
	if !logicAddr.IsValid() {
		panic("nsdata: invalid address")
	}
	setPending(cur, &pendingOp{kind: "grantLogic", addr: logicAddr})
}

// ProposeTimelockDelay is bounded on BOTH sides. An unbounded delay would
// let a single execution stamp every future proposal with an unreachable
// maturity, permanently disabling governance in an unredeployable realm.
func ProposeTimelockDelay(cur realm, seconds int64) {
	assertIsAdmin(cur)
	if seconds < 0 {
		panic("nsdata: delay cannot be negative")
	}
	d := time.Duration(seconds) * time.Second
	// Guard the multiplication itself, not just the input: seconds is
	// attacker-chosen and time.Duration is int64 nanoseconds, so a large
	// value would overflow to a negative (instantly-mature) delay.
	if seconds > int64(absoluteMaxTimelock/time.Second) || d < 0 || d > maxTimelockDelay {
		panic("nsdata: delay out of range")
	}
	setPending(cur, &pendingOp{kind: "delay", dur: d})
}

// SetMaxTimelockDelay raises or lowers the ceiling on timelockDelay.
// Bounded by absoluteMaxTimelock, and it cannot be set below the delay
// currently in force.
func SetMaxTimelockDelay(cur realm, seconds int64) {
	assertIsAdminOrRecovery(cur)
	// Bound the input before multiplying: a huge value used to wrap to a
	// sub-second ceiling and be accepted (audit L-3a).
	if seconds < 0 || seconds > int64(absoluteMaxTimelock/time.Second) {
		panic("nsdata: max delay out of range")
	}
	d := time.Duration(seconds) * time.Second
	if d < 0 || d > absoluteMaxTimelock || d < timelockDelay {
		panic("nsdata: max delay out of range")
	}
	maxTimelockDelay = d
	chain.Emit("MaxTimelockDelaySet", "seconds", strconv.FormatInt(int64(d/time.Second), 10),
		"by", cur.Previous().Address().String())
}

func canControl(op *pendingOp, caller address) bool {
	switch op.protectorRole {
	case "recovery":
		return caller == recovery
	case "admin":
		// The admin's rotation of recovery: the admin's to withdraw, and
		// recovery's to veto (see the note at the top).
		return caller == admin || caller == recovery
	default:
		return caller == admin || caller == recovery
	}
}

func getPendingOp(kind string) *pendingOp {
	if v := pendingOps.Get(kind); v != nil {
		return v.(*pendingOp)
	}
	return nil
}

// EvictionPending reports a pending rotation of the admin that recovery
// proposed while the two roles are separate keys: recovery replacing an
// admin it no longer trusts. See the note above pendingOp.
func EvictionPending() bool {
	op := getPendingOp("admin")
	return op != nil && op.protectorRole == "recovery"
}

// adminAlone: the address is the admin and not also recovery — the case
// every eviction rule is about. While one key holds both, nothing is.
func adminAlone(a address) bool { return a == admin && a != recovery }

// assertAdminMayPropose refuses the admin while recovery is replacing it,
// and for one timelock after recovery vetoed a proposal of this kind.
func assertAdminMayPropose(caller address, kind string) {
	if !adminAlone(caller) {
		return
	}
	if EvictionPending() {
		panic("nsdata: recovery is replacing the admin; the admin proposes nothing until that lands")
	}
	if v := vetoUntil.Get(kind); v != nil && time.Now().Unix() < v.(int64) {
		panic("nsdata: recovery vetoed the admin's " + kind + "; the admin may propose one again from unix " +
			strconv.FormatInt(v.(int64), 10))
	}
}

// veto starts the cooldown on a kind, when recovery has just cancelled
// something the admin proposed.
func veto(caller address, kind string, proposer address) {
	if caller != recovery || caller == admin || !adminAlone(proposer) || timelockDelay <= 0 {
		return
	}
	until := time.Now().Unix() + int64(timelockDelay/time.Second)
	vetoUntil.Set(kind, until)
	chain.Emit("GovernanceVetoed", "kind", kind, "until", strconv.FormatInt(until, 10), "by", caller.String())
}

func setPending(cur realm, op *pendingOp) {
	caller := cur.Previous().Address()
	if existing := getPendingOp(op.kind); existing != nil {
		// You may replace only what you could cancel. Slots are per-kind,
		// so this contends only with another proposal of the SAME kind.
		if !canControl(existing, caller) {
			panic("nsdata: a change of this kind is pending and you may not replace it")
		}
		chain.Emit("GovernanceDisplaced", "kind", existing.kind, "by", caller.String())
	}
	assertAdminMayPropose(caller, op.kind)
	op.at = time.Now().Add(timelockDelay)
	op.by = caller
	pendingOps.Set(op.kind, op)
	// `seconds` carries a delay proposal's value, which this event used to
	// leave out, so "set the delay to zero" and "raise it" looked the same
	// to a monitor (audit L-3c).
	chain.Emit("GovernanceProposed",
		"kind", op.kind,
		"addr", op.addr.String(),
		"seconds", strconv.FormatInt(int64(op.dur/time.Second), 10),
		"executableAt", op.at.Format(time.RFC3339),
		"by", caller.String())
}

// CancelPending cancels the pending change of one kind. A proposal with a
// protectorRole can be cancelled only by that role, so a compromised key
// cannot veto its own replacement.
func CancelPending(cur realm, kind string) {
	assertIsAdminOrRecovery(cur)
	op := getPendingOp(kind)
	if op == nil {
		return // idempotent, so a batched incident sitting cannot be made to revert
	}
	if !canControl(op, cur.Previous().Address()) {
		panic("nsdata: only the " + op.protectorRole + " key may cancel this change")
	}
	pendingOps.Remove(kind)
	veto(cur.Previous().Address(), kind, op.by)
	chain.Emit("GovernanceCancelled", "kind", kind, "by", cur.Previous().Address().String())
}

// ExecutePending applies a matured change. Callable by anyone on purpose:
// execution must not depend on a particular key still being available,
// since key unavailability is one of the things being recovered from. It
// only applies what was already proposed and survived its window.
func ExecutePending(cur realm, kind string) {
	op := getPendingOp(kind)
	if op == nil {
		panic("nsdata: nothing pending of that kind")
	}
	if time.Now().Before(op.at) {
		panic("nsdata: still in the timelock window")
	}
	// The ceiling may have been lowered since this was proposed; the
	// ceiling in force wins (audit L-3b). Checked before anything moves.
	if op.kind == "delay" && op.dur > maxTimelockDelay {
		panic("nsdata: that delay is above the ceiling now in force")
	}
	// The eviction lands first, whoever picks the order: nothing the admin
	// proposed runs while recovery is replacing it (see above pendingOp).
	if op.kind != "admin" && adminAlone(op.by) && EvictionPending() {
		panic("nsdata: recovery is replacing the admin; the admin's pending changes wait for that, and die with it")
	}
	pendingOps.Remove(kind)
	switch op.kind {
	case "admin":
		admin = op.addr
		// Recovery's eviction landing clears the vetoes it was fighting with;
		// an admin moving to a key of its own choosing does not.
		if op.protectorRole == "recovery" {
			vetoUntil = avl.Tree{}
		}
		// The admin that was just replaced cannot leave behind a live
		// proposal to replace recovery...
		dropPendingProtectedBy("recovery", "admin")
		// ...nor anything else only an admin could have proposed. This
		// used to drop the recovery rotation alone, so an evicted thief's
		// grantLogic survived the eviction — re-proposed just before it,
		// it matured a delay later and the thief, holding no role at all,
		// executed it (anyone may): a realm of their choosing trusted with
		// every vault write. An audit proved it. The new admin re-proposes
		// whatever it actually wants.
		dropAdminProposals("admin rotated")
	case "recovery":
		recovery = op.addr
		// Likewise: a superseded recovery key's pending admin rotation
		// dies with it, so a stolen key cannot keep acting after the
		// operator has rotated it out — when the ADMIN replaced it. Recovery
		// moving itself keeps its eviction, which the recovery role (now the
		// new key) still protects: executing that rotation first used to be
		// the thief's way to void the eviction (re-audit M-1 b).
		if op.protectorRole == "admin" {
			dropPendingProtectedBy("admin", "recovery")
		}
	case "grantLogic":
		trustedLogicSet.Set(op.addr.String(), true)
	case "delay":
		timelockDelay = op.dur
	case "unpause":
		paused = false
	default:
		panic("nsdata: unknown pending kind")
	}
	chain.Emit("GovernanceExecuted", "kind", op.kind, "addr", op.addr.String(),
		"seconds", strconv.FormatInt(int64(op.dur/time.Second), 10),
		"proposedBy", op.by.String(), "by", cur.Previous().Address().String())
}

// dropPendingProtectedBy removes the pending change of `kind` when it is
// protected by `role` — used when that role's key has just been replaced.
func dropPendingProtectedBy(kind, role string) {
	if op := getPendingOp(kind); op != nil && op.protectorRole == role {
		pendingOps.Remove(kind)
		chain.Emit("GovernanceInvalidated", "kind", kind, "reason", role+" rotated")
	}
}

// adminOnlyKinds are the proposals only the admin can make. Every one of
// them dies when the admin rotates: whoever proposed it no longer holds
// the key that could, and an eviction that leaves the evicted key's plans
// running has not evicted anybody.
var adminOnlyKinds = []string{"grantLogic", "delay", "unpause"}

func dropAdminProposals(reason string) {
	for _, k := range adminOnlyKinds {
		if getPendingOp(k) != nil {
			pendingOps.Remove(k)
			chain.Emit("GovernanceInvalidated", "kind", k, "reason", reason)
		}
	}
	// Timelocked admin actions too (actions.gno): every one was proposed
	// by the key that just lost the role, or is about to.
	dropAllActions(reason)
}

func GetPending(kind string) (addr address, executableAt time.Time, protectorRole string) {
	op := getPendingOp(kind)
	if op == nil {
		return "", time.Time{}, ""
	}
	return op.addr, op.at, op.protectorRole
}

// GetPendingDetail is GetPending with the rest of the proposal: the delay
// a "delay" proposal would install, in seconds — which GetPending could
// not show, so "set the delay to zero" and "raise it" looked identical —
// and who proposed it.
func GetPendingDetail(kind string) (addr address, seconds int64, executableAt time.Time, protectorRole string, by address) {
	op := getPendingOp(kind)
	if op == nil {
		return "", 0, time.Time{}, "", ""
	}
	return op.addr, int64(op.dur / time.Second), op.at, op.protectorRole, op.by
}

func ListPending() string {
	out := ""
	pendingOps.Iterate("", "", func(key string, v any) bool {
		if out != "" {
			out += ","
		}
		out += key
		return false
	})
	return out
}

// -- instant, low-risk admin settings --

// SetGuardian takes the RECOVERY key, to seat a guardian as much as to
// replace one.
//
// Replacing took recovery from the start: otherwise the first move of
// anyone who steals the admin key is to point the guardian at themselves,
// disarming the emergency stop before you can use it. Seating an EMPTY
// seat used to be the admin's too, and that was the same hole: a stolen
// admin key seated its own bot, and after its eviction that bot could
// still pause and revoke, removable only by recovery (re-audit 2026-10-16,
// L-4). The deploy seats the guardian while its key still holds recovery.
func SetGuardian(cur realm, addr address) {
	if cur.Previous().Address() != recovery {
		if guardian == "" {
			panic("nsdata: seating a guardian takes the recovery key")
		}
		panic("nsdata: replacing an existing guardian requires the recovery key")
	}
	guardian = addr
	chain.Emit("GuardianSet", "addr", addr.String(), "by", cur.Previous().Address().String())
}

/*
ClearGuardian stands the pause capability down.

"Removing a power is never the dangerous direction" was the old
reasoning here, and it is wrong in one specific way: removing this power
restores the state in which SetGuardian is admin-callable. SetGuardian
demands the RECOVERY key whenever a guardian is already set, and says
why — a stolen admin key must not be able to disarm the emergency stop.
ClearGuardian then SetGuardian was a two-transaction admin-only
replacement of a live guardian, which defeats exactly that rule.

So standing down a LIVE guardian now takes the same key that replacing
one takes. Clearing when there is no guardian stays open to either role,
because then there is nothing to defeat.

The practical stakes are small — assertCanPause admits admin, recovery
and guardian, so an operator holding recovery keeps Pause and
RevokeTrustedLogic either way. It is fixed because this realm can never
be redeployed, and a documented authorization rule that a two-call
sequence walks around is not something to leave in permanent code.
*/
func ClearGuardian(cur realm) {
	assertIsAdminOrRecovery(cur)
	if guardian != "" && cur.Previous().Address() != recovery {
		panic("nsdata: standing down a live guardian takes the recovery key, the same as replacing one")
	}
	guardian = ""
	chain.Emit("GuardianSet", "addr", "", "by", cur.Previous().Address().String())
}

// SetSuccessor records where this registry moved, if it ever has to be
// abandoned. Pair it with Pause() so the retired registry cannot drift
// away from the snapshot its successor was built from.
func SetSuccessor(cur realm, s string) {
	assertIsAdminOrRecovery(cur)
	successor = s
	chain.Emit("SuccessorSet", "successor", s, "by", cur.Previous().Address().String())
}

func GetAdmin() address                  { return admin }
func GetRecovery() address               { return recovery }
func GetGuardian() address               { return guardian }
func GetSuccessor() string               { return successor }
func GetTimelockDelay() time.Duration    { return timelockDelay }
func GetMaxTimelockDelay() time.Duration { return maxTimelockDelay }

incident.gno

package nsdata

import (
	"strconv"
	"time"

	"chain"
)

/*
THE INCIDENT SWITCHES: the undo for what a stolen admin key set instantly
(re-audit 2026-10-16, M-2).

The admin's instant powers leave their marks in this realm — credits it
granted its own wallets, the claim window it opened, the granter's and the
keeper's seats — and those outlive its eviction. The incident runbook could
not undo them in time: every logic write passes the trust gate and the
pause, so while the logic was revoked and the registry paused nothing could
be disarmed, and the moment recovery unpaused, the thief's wallets redeemed
in the same block. So these are DIRECT WALLET CALLS on the vault, by the
governance roles, that work while paused and with every logic realm
revoked — which is exactly when they are needed — and that only ever take
something away:

	Disarm           admin, recovery or guardian. Deletes the globals whose
	                 presence is a power (disarmKeys): the claim window, the
	                 granter and the keeper. Instant and idempotent, so the
	                 guardian bot may send it without reading first.

	VoidGrantsSince  recovery. Everything a logic realm granted at or after
	                 `since`, up to this second, is void — nslogic reads its
	                 credits through GrantVoided. Windows only accumulate;
	                 none is ever lifted, so nothing voided comes back to
	                 life. Past maxGrantVoids the two with the smallest gap
	                 merge. The admin grants again what was legitimate.

	SetQuarantine    recovery. Until `until`, nothing that gives a name away
	                 runs — nslogic: credit redemption, RegisterFor, free
	                 grants — whatever the claim window says, so the registry
	                 can be unpaused before the new admin has finished
	                 cleaning up. At most maxQuarantine ahead; recovery may
	                 shorten or lift it.

THE REGISTRY STILL DOES NOT DECIDE. The key names below are the logic
realm's, like the restore machinery's own keys, and a logic realm must keep
"absent" the safe reading of each: no claim window is a closed one, no
granter and no keeper is nobody. What a void or a quarantine covers is the
logic realm's to say; the vault keeps the clocks and the roles.
*/

// disarmKeys are the globals whose presence is a power and whose absence is
// the safe reading (nslogic: credits.gno, freetier.gno, keeper.gno).
var disarmKeys = []string{"claimend", "granter", "keeper"}

const (
	maxGrantVoids = 8                       // void windows kept; the oldest two merge past it
	maxQuarantine = int64(30 * 24 * 60 * 60) // the furthest a quarantine may reach, in seconds
)

var (
	// grantVoids are [from, to] windows, unix seconds inclusive, oldest
	// first: a grant whose time falls inside any of them is void.
	grantVoids [][2]int64

	// quarantineUntil is the unix second giveaways may run again; 0 none.
	quarantineUntil int64
)

func assertIsRecovery(cur realm) {
	if a := cur.Previous().Address(); a == "" || a != recovery {
		panic("nsdata: restricted to recovery")
	}
}

// Disarm deletes the claim window, the granter and the keeper at once.
// Admin, recovery or guardian, as a direct wallet call; it works while the
// registry is paused and with every logic realm revoked.
func Disarm(cur realm) {
	assertCanPause(cur)
	had := ""
	for _, k := range disarmKeys {
		if globals.Get(k) != nil {
			globals.Remove(k)
			if had != "" {
				had += ","
			}
			had += k
		}
	}
	chain.Emit("Disarmed", "keys", had, "by", cur.Previous().Address().String())
}

// VoidGrantsSince voids every grant made at or after `since`, up to now.
// Recovery only. `since` may be 0 (everything so far) and may not be in the
// future. The window joins the ones already in force; past maxGrantVoids
// the two oldest merge, which can only void more, never less.
func VoidGrantsSince(cur realm, since int64) {
	assertIsRecovery(cur)
	now := time.Now().Unix()
	if since < 0 || since > now {
		panic("nsdata: a void starts in the past, at 0 or later")
	}
	grantVoids = insertVoid(grantVoids, [2]int64{since, now})
	for len(grantVoids) > maxGrantVoids {
		// Merge the two windows with the smallest gap between them, so the
		// fewest legitimate grants fall into the merged span (re-audit
		// follow-up), and say what was merged.
		best := 0
		for i := 1; i+1 < len(grantVoids); i++ {
			if grantVoids[i+1][0]-grantVoids[i][1] < grantVoids[best+1][0]-grantVoids[best][1] {
				best = i
			}
		}
		a, b := grantVoids[best], grantVoids[best+1]
		m := [2]int64{a[0], a[1]}
		if b[1] > m[1] {
			m[1] = b[1]
		}
		chain.Emit("GrantVoidsMerged", "from", strconv.FormatInt(m[0], 10), "to", strconv.FormatInt(m[1], 10))
		grantVoids = append(append(append([][2]int64{}, grantVoids[:best]...), m), grantVoids[best+2:]...)
	}
	chain.Emit("GrantsVoided", "from", strconv.FormatInt(since, 10), "to", strconv.FormatInt(now, 10),
		"by", cur.Previous().Address().String())
}

// insertVoid keeps the windows sorted by start and folds overlapping ones
// together, so "the gap between two windows" means what it says.
func insertVoid(ws [][2]int64, w [2]int64) [][2]int64 {
	out := [][2]int64{}
	placed := false
	for _, x := range ws {
		if !placed && w[0] < x[0] {
			out = append(out, w)
			placed = true
		}
		out = append(out, x)
	}
	if !placed {
		out = append(out, w)
	}
	merged := [][2]int64{}
	for _, x := range out {
		if n := len(merged); n > 0 && x[0] <= merged[n-1][1] {
			if x[1] > merged[n-1][1] {
				merged[n-1][1] = x[1]
			}
			continue
		}
		merged = append(merged, x)
	}
	return merged
}

// GrantVoided reports whether a grant made at unix second `at` falls inside
// a void recovery declared.
func GrantVoided(at int64) bool {
	for _, w := range grantVoids {
		if at >= w[0] && at <= w[1] {
			return true
		}
	}
	return false
}

// GrantVoids lists the void windows, "from-to" comma-separated, oldest first.
func GrantVoids() string {
	out := ""
	for i, w := range grantVoids {
		if i > 0 {
			out += ","
		}
		out += strconv.FormatInt(w[0], 10) + "-" + strconv.FormatInt(w[1], 10)
	}
	return out
}

// SetQuarantine holds every giveaway shut until `until` (unix seconds), at
// most maxQuarantine ahead; 0 lifts it. Recovery only.
func SetQuarantine(cur realm, until int64) {
	assertIsRecovery(cur)
	now := time.Now().Unix()
	if until != 0 && (until <= now || until > now+maxQuarantine) {
		panic("nsdata: a quarantine ends in the future and at most " +
			strconv.FormatInt(maxQuarantine/86400, 10) + " days ahead; 0 lifts it")
	}
	quarantineUntil = until
	chain.Emit("QuarantineSet", "until", strconv.FormatInt(until, 10), "by", cur.Previous().Address().String())
}

// QuarantineUntil is the unix second giveaways may run again, 0 for none.
func QuarantineUntil() int64 { return quarantineUntil }

// Quarantined reports whether a quarantine holds right now.
func Quarantined() bool { return time.Now().Unix() < quarantineUntil }

nft.gno

package nsdata

import (
	"time"

	"gno.land/r/nym-mnsrehearsal001/nsnft/v1"
)

/*
The token reads, answered by the ledger.

These used to be the vault's own grc721 state. They are now read-throughs
to nsnft, kept here under the same names so nsview, nsskin, nsvote and
the site can go on asking the registry — while an external marketplace
asks nsnft directly and gets the identical answer, because there is only
one ledger to ask.

Token ids here are plain strings. The grc721.TokenID type was the vault's
import; this realm no longer imports grc721 at all.
*/

func isTokenValid(tid string) bool {
	label, domainLabel := splitTokenID(tid)
	n, ok := getName(label, domainLabel)
	return ok && isValidNow(n.expires, time.Now().Unix())
}

// BalanceOf counts every token an address holds — including free-tier
// tokens, which are held rather than absent. That is a real change from
// the previous generation, where a free name had no token and counted
// for nothing; nsvote gates on this, so free-tier holders now have a vote.
func BalanceOf(owner address) int64 { return nsnft.BalanceOf(owner) }

// OwnerOf hides the owner of an expired token — the anti-scam pattern,
// so our own pages never present a lapsed name as somebody's. nsnft
// itself answers regardless; see MIGRATION.md, rule 6.
func OwnerOf(tid string) address {
	owner := nsnft.OwnerOf(tid)
	if owner == "" {
		panic("nsdata: no such token: " + tid)
	}
	if !isTokenValid(tid) {
		panic("nsdata: token is expired, no current owner")
	}
	return owner
}

// GetApproved answers totally: the zero address means nobody is approved
// or there is no such token. See the long note this replaced in git
// history for why a panic here broke the marketplace once already.
func GetApproved(tid string) address { return nsnft.GetApproved(tid) }

// IsApprovedFor is the question a marketplace actually has: may this
// operator move this token, by either route?
func IsApprovedFor(tid string, operator address) bool {
	owner := nsnft.OwnerOf(tid)
	if owner == "" {
		return false
	}
	if owner == operator || nsnft.IsApprovedForAll(owner, operator) {
		return true
	}
	return nsnft.GetApproved(tid) == operator
}

func IsApprovedForAll(owner, operator address) bool {
	return nsnft.IsApprovedForAll(owner, operator)
}

// TokenURI returns a pointer at whichever view realm renders the art.
// nsnft has its own URI base for external marketplaces; both are set to
// the same view realm at wiring time.
func TokenURI(tid string) string {
	return tokenURIBase + tid
}

read.gno

package nsdata

import (
	"strings"
	"time"

	"gno.land/r/nym-mnsrehearsal001/nsnft/v1"
)

// Plain reads — no `cur realm` parameter, no authentication, since there
// is no caller identity to check on a read. Everything here returns raw
// stored values; formatting them for display is the view realm's job,
// not the vault's. (Status strings like "VALID (363 days left)" used to
// live here. They were display logic in a realm that can never be
// redeployed, so they moved to nsview.)

func ListDomains() string {
	var b strings.Builder
	first := true
	domains.Iterate("", "", func(key string, v any) bool {
		if !first {
			b.WriteString(",")
		}
		b.WriteString(key)
		first = false
		return false
	})
	return b.String()
}

// ListNames and CountNames scan only the key span belonging to
// `domainLabel` (see domainRange in auth.gno), costing O(names in that
// domain) rather than O(every name in the registry).
func ListNames(domainLabel string) string {
	var b strings.Builder
	first := true
	start, end := domainRange(domainLabel)
	// The label is the part of the key after "domain*". Records no
	// longer carry their own label — the key already held it, and
	// storing it twice cost storage forever to say the same thing.
	cut := len(domainLabel) + 1
	names.Iterate(start, end, func(key string, v any) bool {
		if !first {
			b.WriteString(",")
		}
		b.WriteString(key[cut:])
		first = false
		return false
	})
	return b.String()
}

func CountNames(domainLabel string) int64 {
	var count int64
	start, end := domainRange(domainLabel)
	names.Iterate(start, end, func(key string, v any) bool {
		count++
		return false
	})
	return count
}

func CountDomains() int64 { return int64(domains.Size()) }

func DomainExists(label string) bool            { _, ok := getDomain(label); return ok }
func NameExists(label, domainLabel string) bool { _, ok := getName(label, domainLabel); return ok }

func GetDomainOwner(label string) address { return mustGetDomain(label).owner }

// GetNameOwner asks the ledger. It still panics for an unknown NAME, as it
// always did, so callers that relied on that are unchanged.
func GetNameOwner(label, domainLabel string) address {
	mustGetName(label, domainLabel)
	return nsnft.OwnerOf(nameTokenID(label, domainLabel))
}

// GetDomainInfo / GetNameInfo return a whole record in one call, so a
// view realm can render a page without six round trips.
// Timestamps come back as unix SECONDS. They used to be time.Time,
// which vm/qeval rendered using gno's internal epoch, so every consumer
// had to know to subtract 62135596800 — our own frontend did exactly
// that. Returning unix seconds stops leaking that offset into every
// integration, and it is what the records now hold anyway.
//
// `streak` is computed from the registration date rather than read from
// a stored field. See streakOf.
func GetDomainInfo(label string) (owner address, registered, expires, streak int64, frozen bool) {
	d := mustGetDomain(label)
	return d.owner, d.registered, d.expires, streakOf(d.registered, time.Now().Unix()), d.frozen
}

/*
GetNameInfo keeps its six-value shape so every existing reader — nslogic,
nsview, nsskin, nsvote, the site, both snapshot tools — goes on parsing it
unchanged. Two of the six are now answered differently:

	owner  is read from nsnft, never stored here. The snapshot tools record
	       whatever this returns, so they now record the real owner — the
	       restore-hands-sold-names-back bug the first attempt had cannot
	       happen, because there is no stale copy for them to read.

	paid   replaces isNFT and means exactly one thing: the name is NOT
	       held as an un-upgraded free-tier record. It is deliberately not
	       "transferable" — a frozen paid name is locked too, and reading
	       the lock would have made a frozen paid name look free, which is
	       precisely the proxy bug that let free renewals renew paid names.
*/
func GetNameInfo(label, domainLabel string) (owner address, registered, expires, streak int64, frozen, paid bool) {
	n := mustGetName(label, domainLabel)
	tid := nameTokenID(label, domainLabel)
	return nsnft.OwnerOf(tid), n.registered, n.expires,
		streakOf(n.registered, time.Now().Unix()), n.frozen,
		nsnft.LockBits(tid)&(1<<lockBitFree) == 0
}

// GetNameTTL / GetDomainTTL report how long a resolver may cache an
// answer about this record, in seconds, where 0 MEANS NEVER CACHE — the
// ENS registry's rule, deliberately, so integrators need not read
// anything of ours to handle it correctly.
// A TTL written for a previous holder is not this holder's cache policy.
// A stale one reads as 0 — never cache — which is the safe answer during
// exactly the window after a sale when a cached answer pays the seller.
func GetNameTTL(label, domainLabel string) int64 {
	n := mustGetName(label, domainLabel)
	if !isFresh(n, nameTokenID(label, domainLabel)) {
		return 0
	}
	return n.ttl
}
func GetDomainTTL(label string) int64 { return mustGetDomain(label).ttl }

// GetNameHeldSince is when the current holder's holding began, in unix
// seconds — or 0 when the ledger has moved on since this registry last
// saw the record (a sale it has not yet observed). It can understate a
// holding, never overstate one. See Name.since.
func GetNameHeldSince(label, domainLabel string) int64 {
	n := mustGetName(label, domainLabel)
	if !isFresh(n, nameTokenID(label, domainLabel)) {
		return 0
	}
	return n.since
}

// RestoredFor reports whom a restore wrote this record for, or empty.
// See Name.restoredFor.
func RestoredFor(label, domainLabel string) address {
	return mustGetName(label, domainLabel).restoredFor
}

// IsNamePaid reports that a name is not held as an un-upgraded free-tier
// record. See GetNameInfo on why this is not "transferable".
func IsNamePaid(label, domainLabel string) bool {
	mustGetName(label, domainLabel)
	return nsnft.LockBits(nameTokenID(label, domainLabel))&(1<<lockBitFree) == 0
}

func IsDomainValid(label string) bool {
	d, ok := getDomain(label)
	return ok && isValidNow(d.expires, time.Now().Unix())
}

func IsNameValid(label, domainLabel string) bool {
	n, ok := getName(label, domainLabel)
	return ok && isValidNow(n.expires, time.Now().Unix())
}

// -- extension slots --

func GetDomainExtra(label, key string) string {
	v := mustGetDomain(label).extra.Get(key)
	if v == nil {
		return ""
	}
	return v.(string)
}

/*
GetNameExtra answers EMPTY for data written in a previous ownership epoch.

This is the read half of the lazy wipe. A sale that settles on nsnft —
through our marketplace or anybody else's — never calls this realm, so
nothing here can clear the seller's payment addresses at the moment it
happens. What this CAN do is refuse to repeat them: the instant the
ledger's epoch moves, every extra on the name stops answering, for every
reader, before anybody has written anything.

The write half, which destroys the stale data rather than hiding it, is
freshen in write.gno. Both halves are needed: hiding alone is what the
first attempt shipped, and the buyer's first edit brought the seller's
Bitcoin address back as the buyer's.
*/
func GetNameExtra(label, domainLabel, key string) string {
	n := mustGetName(label, domainLabel)
	if !isFresh(n, nameTokenID(label, domainLabel)) {
		return ""
	}
	v := n.extra.Get(key)
	if v == nil {
		return ""
	}
	return v.(string)
}

func GetGlobal(key string) string {
	v := globals.Get(key)
	if v == nil {
		return ""
	}
	return v.(string)
}

// GetAccount reads one field of an address's own record, or "" when it
// has none. See `accounts` in types.gno.
func GetAccount(owner address, key string) string {
	v := accounts.Get(accountKey(owner, key))
	if v == nil {
		return ""
	}
	return v.(string)
}

// GetPrimary is a raw pointer lookup. It reports what an address last
// SELECTED, not what it still owns — callers presenting this as reverse
// resolution must re-check ownership (see nslogic.ResolveAddress).
func GetPrimary(owner address) string {
	v := primary.Get(owner.String())
	if v == nil {
		return ""
	}
	return v.(string)
}

// -- config reads --

func GetTreasury() address                { return treasury }
func GetTermLength() int64                { return termLength }
func GetGracePeriod() int64               { return gracePeriod }
func GetMaxDeletePerCall() int            { return maxDeletePerCall }
func GetLabelPattern() string             { return labelPattern }
func GetLabelLength() (min, max int)      { return minLabelLen, maxLabelLen }
func GetTokenURIBase() string             { return tokenURIBase }
func GetExtraLimits() (k, v, entries int) { return maxExtraKeyLen, maxExtraValueLen, maxExtraEntries }
func GetGlobalEntryLimit() int            { return maxGlobalEntries }
func GetAccountLimits() (k, v, entries int) {
	return maxAccountKeyLen, maxAccountValueLen, maxAccountEntries
}

render.gno

package nsdata

// The real human-facing view moved OUT of this realm into `nsview`
// (2026-08-21), after an adversarial review found three separate
// defects in the old Render() — unescaped profile-field injection into
// the markdown, an O(domains × names) home page any user could inflate
// into a permanent DoS, and links that 404'd — none of which could ever
// be fixed, because this realm is deployed once and never replaced.
//
// The lesson generalised: "it's only display code, it has no
// authorization surface" was the wrong test for what belongs in an
// immutable realm. The right test is whether a bug in it would be
// permanent. Display code changes far more often than storage schemas
// do, so it belongs in something swappable.
//
// What remains here is deliberately a fixed string: no user-authored
// data, no iteration over state, nothing that can be wrong later.
func Render(path string) string {
	return "# Meme Name Service — data realm\n\n" +
		"This realm stores records only: name and domain ownership, " +
		"configuration, and the NFT state.\n\n" +
		"The human-facing view lives in the `nsview` realm; writes go " +
		"through `nslogic`.\n"
}

types.gno

// Package nsdata is the registry — the records behind every name.
//
// IT IS REPLACEABLE NOW, and that changes what every comment below means.
//
// Until this generation the vault held ownership as well as records, which
// made it the one realm that could never be redeployed: a "new nsdata"
// was an empty registry and everybody's names with it. So everything here
// was written as if it would ship forever — no constants, no policy, no
// display code — and the comments say "can never be replaced" throughout.
//
// Ownership has moved to nsnft, the small frozen token realm. This realm
// keeps records — dates, the frozen bit, TTL, profile data, reverse
// resolution, pricing globals, domains — and reads every owner from the
// ledger rather than storing one. Replacing it is a new package plus one
// Trust call on nsnft; no token moves, no holder notices. The integration
// address the outside world keeps is nsnft's, not this one's.
//
// The two old rules still hold, for a better reason than before:
//
//  1. NOTHING IS A CONSTANT. Term length, grace period, size caps — all
//     settable. Not because a mistake would be permanent any more, but
//     because a registry that needs a redeploy to change a number is a
//     registry that gets redeployed carelessly.
//
//  2. THE REGISTRY STORES, IT DOES NOT DECIDE. Pricing math, validation,
//     what a profile field means — all of it lives in nslogic. Anything
//     this realm "knows" is a rule that needs a migration to change.
//
// Rule 2 is why Domain and Name carry an `extra` tree instead of a
// growing list of typed fields.
package nsdata

import (
	"time"

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

// Timestamps are unix SECONDS, not time.Time, and that is the single
// biggest storage decision in this file. Measured on three throwaway
// realms (MAINNET.md §3d-i): two time.Time fields were 70% of a record,
// because each carries an unused nanosecond field and a *Location
// pointer for a value that is always UTC. Switching to int64 takes a
// real 7,385-byte domain record to 6,246 bytes on its own, and turns
// every lifecycle comparison into integer arithmetic.
//
// Nothing here stores a label. The AVL key already holds it — `label`
// for a domain, `domain*label` for a name — so a copy inside the record
// was paying storage forever to duplicate the thing used to find it.
type Domain struct {
	owner      address
	registered int64 // unix seconds
	expires    int64 // unix seconds
	frozen     bool

	// How long a resolver may cache an answer about this record, in
	// seconds, where 0 MEANS NEVER CACHE. Copied deliberately from the
	// ENS registry, which stores exactly this field with exactly this
	// rule, so integrators already know what to do with it.
	//
	// It exists because a name can be sold at any moment, and a cached
	// resolution then sends funds to the previous owner. A blanket
	// policy would be wrong for somebody receiving payments and
	// wastefully strict for somebody using a name as a handle, so the
	// person who knows the risk sets it. Typed rather than an `extra`
	// key because an avl entry costs an order of magnitude more than
	// eight bytes, and because integrators read it.
	ttl int64

	// Pricing, and anything a future logic realm needs. Not typed
	// fields, because pricing is policy and policy belongs in the
	// swappable half — the vault only has to remember the values.
	extra avl.Tree
}

/*
Name has NO OWNER FIELD, and that absence is the whole design.

The first attempt at moving ownership into a token realm kept a copy of
the owner here, and every bug it had followed from the copy: renewal
checked the copy and refused the real owner after a sale, snapshots
recorded the copy and would have handed sold names back to their sellers
on restore. There is one owner and it lives in nsnft. Every read asks it.

It also has no isNFT flag. Every name is a token; a free-tier name is a
token with a hold on it (lockBitFree). Four separate places used to read
"has no token" as "is free", and deleting the flag deletes that class of
bug rather than fixing four instances of it.
*/
type Name struct {
	registered int64
	expires    int64
	frozen     bool
	ttl        int64

	/* THE OWNERSHIP EPOCH this record's profile data belongs to.

	   nsnft moves a token's epoch on every mint and transfer. When the two
	   disagree, the extras and TTL here were written for a previous holder
	   — possibly through a sale on a marketplace this realm never hears
	   about — and they are treated as absent on read and destroyed before
	   the next write. See freshen in write.gno. */
	epoch int64

	/* WHEN THE CURRENT HOLDING BEGAN, as far as this registry has seen.

	   Unix seconds, stamped together with `epoch`: at registration, at the
	   paid upgrade, at a restore, and at the first write after a transfer
	   (freshen). Meaningful only while `epoch` matches the ledger. A sale
	   that settles on nsnft moves the epoch without telling this realm, so
	   a buyer's clock starts at their first write here and never earlier:
	   it can understate how long somebody has held a name, never overstate
	   it. The paid upgrade restarts it, because a held free-tier name and a
	   sellable one are not the same holding.

	   A fact, not a policy: nslogic decides what it is good for (a
	   referral code earns only once its holder has kept a paid name for
	   thirty days). See GetNameHeldSince. */
	since int64

	/* WHO A RESTORE WROTE THIS RECORD FOR, or empty if no restore did.

	   nslogic.RestoreNameField replays profile data — pay addresses among
	   it — and may do so only onto a record a restore created, and only
	   while the ledger still says the snapshot's owner holds it. Without
	   this, a name sold between the snapshot and the restore had the
	   seller's pay addresses written onto the buyer's name, and any name a
	   user registered during the restore window could have its pay fields
	   rewritten with the admin key alone. */
	restoredFor address

	// Profile fields, cross-chain addresses, management-key hashes,
	// referrer — see the package comment. Only meaningful while `epoch`
	// matches the ledger.
	extra avl.Tree
}

/*
THE REGISTRY'S HOLD BITS on a token in nsnft. nsnft stores them and

	never interprets them; the vocabulary is this realm's.

	Separate bits so the two holds cannot undo each other: unfreezing a
	free-tier name must not make it sellable, and upgrading a frozen name
	must not unfreeze it.
*/
const (
	lockBitFree   = 0 // free tier, not yet paid for: not sellable
	lockBitFrozen = 1 // frozen by an admin: not movable while disputed
)

// There is deliberately no `streak` field. It used to be stored and
// incremented on renewal, which breaks the moment multi-year
// registration exists: prepaying five years bumps it five times, so a
// name minted this morning would render "5 years held". A streak is
// meant to say how long somebody stuck around, and buying time is not
// the same as spending it. It is now derived from `registered` — see
// streakOf in auth.gno — which is always truthful, cannot be bought,
// resets naturally on reclaim, and removes a field instead of adding
// one.

var (
	domains avl.Tree
	names   avl.Tree
	primary avl.Tree

	// Package-level extension slot, same reasoning as Domain/Name.extra:
	// somewhere to put global CONFIGURATION nobody has thought of yet
	// without needing a new package var. Not per-wallet state: that is
	// `accounts`, below.
	globals avl.Tree

	/* PER-ADDRESS STATE, in a tree of its own.

	   Credits for a free registration, and per-wallet counters such as
	   referrals, are about an ADDRESS, and there was nowhere to put them.
	   globals caps a key at 32 bytes and an address alone is 40, and its
	   entry cap was shared with every name's and domain's extras, so each
	   new wallet would have competed with the price list for the same 24
	   slots. An audit found the referral counter had never once been
	   written, for exactly that reason, and that every referred
	   registration reverted because of it.

	   Keyed address + ":" + field (see accountKey), so one wallet's fields
	   are one contiguous span. Bounded three ways — field name, value and
	   fields per address — so a wallet's footprint is small whatever a
	   logic realm writes. Written only by trusted logic, like every record;
	   what a field MEANS is the logic realm's business. */
	accounts avl.Tree

	admin address // the vault door — see governance.gno for the full role model

	// The set of realms currently allowed to call mutations. A set, not a
	// single address, because the project will plausibly grow more than
	// one writer (a free-tier realm, a custodial relayer) and a single
	// slot would force them all into one realm.
	trustedLogicSet avl.Tree

	// -- config: every value below is settable, none is a const --
	treasury address

	// Seconds, matching the record timestamps. These were time.Duration,
	// which meant every lifecycle comparison converted, and every read
	// through vm/qeval printed a nanosecond count that each caller had to
	// know to divide.
	termLength  int64 = 365 * 24 * 60 * 60
	gracePeriod int64 = 90 * 24 * 60 * 60

	labelPattern = `^[a-z0-9]+(-[a-z0-9]+)*$`
	minLabelLen  = 1
	maxLabelLen  = 63

	// Bounds on the extension slots. Storage written here is permanent
	// and paid for by the realm, so unbounded strings are griefing.
	maxExtraKeyLen   = 32
	maxExtraValueLen = 512
	maxExtraEntries  = 24

	// globals' OWN entry cap. It used to be maxExtraEntries, shared with
	// every record, and the logic realm's fixed keys alone (prices, rate,
	// fee, free tier, eight premium pages, eight block-list chunks,
	// referral rules, restore state) number more than 24 — so raising it
	// meant loosening every name and domain by the same factor.
	maxGlobalEntries = 64

	// Bounds on the per-address store. Small on purpose: a field is a
	// counter or a short tuple, and these are paid for by whoever's
	// transaction writes them.
	maxAccountKeyLen   = 16
	maxAccountValueLen = 128
	maxAccountEntries  = 8

	// Upper bound on how many name records a single DeleteDomainRecord
	// call will destroy. Deletion is unbounded work over a domain that
	// may hold any number of names, and an unbounded loop in a realm
	// that cannot be redeployed is a domain that can never be deleted
	// at all once it grows past one block's gas. Settable, because the
	// right number depends on chain parameters nobody knows yet.
	maxDeletePerCall = 100

	// Prefix for TokenURI. Points at whichever view realm currently
	// renders the artwork; settable so the art can be replaced without
	// touching this realm. See nft.gno.
	tokenURIBase = "/r/demo/nsview:token/"
)

func init(cur realm) {
	deployer := cur.Previous().Address()
	admin = deployer
	recovery = deployer
	treasury = deployer

	// THE REGISTRY ARRIVES CONFIGURED. Domains, prices, referral tiers and
	// lifecycle settings are baked into genesis_data.gno and written here,
	// so a fresh chain is usable the moment this package lands — no trust
	// grant and no admin call needed, because this realm owns the state
	// it is writing. See genesis.gno.
	applyGenesis(deployer, time.Now().Unix())
	// The trusted-logic set starts EMPTY and timelockDelay starts at
	// zero: deploy nsdata, deploy nslogic, then propose+execute the
	// grant. No mutation is callable until that happens.
	//
	// FIRST OPERATIONAL STEP AFTER DEPLOY, before anything of value
	// exists here: move `recovery` to a key held separately from
	// `admin` (ideally cold, ideally a multisig), then raise
	// timelockDelay. Until that is done both roles are the same key and
	// the whole recovery design is inert — it protects against one key
	// being lost or stolen, not against one key being both.
}

write.gno

package nsdata

import (
	"unicode/utf8"
	"errors"
	"math"
	"strings"
	"time"

	"chain"

	"gno.land/p/nt/avl/v0"
	"gno.land/r/nym-mnsrehearsal001/nsnft/v1"
)

// Every function here is gated to trustedLogic and does exactly what it
// is told. Authorization beyond "is this the current logic realm" is
// deliberately NOT duplicated here: the vault stores, the logic realm
// decides. Re-checking policy in an unfixable realm sounds safer but
// bakes today's rules in permanently — a future feature that legitimately
// needs an admin to touch someone's record would be unbuildable.

// -- domains --

func RegisterDomainRecord(cur realm, label string, owner address, now int64) error {
	assertIsTrustedLogic(cur)
	if !owner.IsValid() {
		return errStr("invalid owner address")
	}
	if err := assertLabelKeySafe(label); err != nil {
		return err
	}
	if d, ok := getDomain(label); ok {
		if d.frozen {
			return errStr("domain is frozen")
		}
		if !isReclaimable(d.expires, now) {
			return errStr("domain already registered and not yet reclaimable")
		}
		// No token to burn and no reverse pointer to clear: domains are
		// records, not tokens, and `primary` only ever held name ids.
		domains.Remove(label)
	}
	domains.Set(label, &Domain{
		owner: owner, registered: now, expires: now + termLength,
		extra: avl.Tree{},
	})
	emitBy(cur, "DomainRegistered", "label", label, "owner", owner.String(), "expires", i64(now+termLength))
	return nil
}

/*
ReassignDomainRecord moves a domain to a new owner and leaves its
configuration exactly where it was.

This is the durable fix nslogic.ReassignDomain's comment was waiting for.
The old path moved a domain through the name-transfer machinery, whose
wipe exists to clear a SELLER'S payment addresses — and so it silently
reopened closed domains, dropped their pricing to the default and released
their term caps, during the key-compromise recovery it exists for. A
domain's extras are its settings, not a previous holder's data, and there
is no previous holder: domains never reach a third party.

TTL resets, because it is the one field that is a caching promise made by
whoever held the record.
*/
func ReassignDomainRecord(cur realm, label string, to address) error {
	assertIsTrustedLogic(cur)
	if !to.IsValid() {
		return errStr("invalid owner address")
	}
	d, ok := getDomain(label)
	if !ok {
		return errStr("unknown domain")
	}
	d.owner = to
	d.ttl = 0
	emitBy(cur, "DomainReassigned", "label", label, "to", to.String())
	return nil
}

func RenewDomainRecord(cur realm, label string, caller address, now int64) error {
	assertIsTrustedLogic(cur)
	d, ok := getDomain(label)
	if !ok {
		return errStr("unknown domain")
	}
	if isReclaimable(d.expires, now) {
		return errStr("domain expired beyond grace period")
	}
	if caller != d.owner {
		return errStr("restricted to domain owner")
	}
	d.expires = advanceTerm(d.expires, now)
	emitBy(cur, "DomainRenewed", "label", label, "expires", i64(d.expires))
	return nil
}

// advanceTerm extends a term by exactly one term-length from its
// PREVIOUS due date — never from `now`, because the grace period must
// not silently extend the term somebody paid for.
//
// It no longer returns a streak. The streak used to be maintained here,
// with a guard against renewing repeatedly in one block to inflate it;
// that whole class of problem disappeared when the streak became a
// function of the registration date instead of a stored counter. See
// streakOf in auth.gno.
func advanceTerm(expires, now int64) int64 {
	// Anchoring to the previous due date is only safe while a renewal
	// cannot happen more than one term after it — i.e. while
	// gracePeriod <= termLength. That invariant held silently under the
	// old hardcoded constants and stopped holding the moment both became
	// settable: with a grace period longer than the term, a renewal paid
	// late in grace would return an expiry ALREADY IN THE PAST, leaving
	// the payer with a name that is still expired. Clamp forward so a
	// paid renewal always buys a live term, while keeping the anchor
	// behaviour in every normal case.
	// Saturate rather than wrap: renewing a far-future expiry used to
	// overflow and SHORTEN it to now + term (audit L-2).
	if expires > math.MaxInt64-termLength {
		return math.MaxInt64
	}
	next := expires + termLength
	if next <= now {
		next = now + termLength
	}
	return next
}

func SetDomainFrozen(cur realm, label string, frozen bool) {
	assertIsTrustedLogic(cur)
	mustGetDomain(label).frozen = frozen
	emitBy(cur, "DomainFrozen", "label", label, "frozen", boolStr(frozen))
}

func SetDomainExpiryRecord(cur realm, label string, expires int64) {
	assertIsTrustedLogic(cur)
	mustGetDomain(label).expires = expires
	emitBy(cur, "DomainExpirySet", "label", label, "expires", i64(expires))
}

// SetDomainTTLRecord sets how long a resolver may cache answers about
// this domain, in seconds, where 0 means never cache. See Domain.ttl.
func SetDomainTTLRecord(cur realm, label string, ttl int64) error {
	assertIsTrustedLogic(cur)
	if ttl < 0 {
		return errStr("ttl may not be negative")
	}
	d, ok := getDomain(label)
	if !ok {
		return errStr("unknown domain")
	}
	d.ttl = ttl
	emitBy(cur, "DomainTTLSet", "label", label, "ttl", i64(ttl))
	return nil
}

// SetDomainExtraRecord writes one arbitrary key on a domain — pricing,
// or whatever a future logic realm needs. An empty value deletes the
// key, so storage can be reclaimed.
func SetDomainExtraRecord(cur realm, label, key, value string) error {
	assertIsTrustedLogic(cur)
	d, ok := getDomain(label)
	if !ok {
		return errStr("unknown domain")
	}
	if err := setExtra(&d.extra, key, value); err != nil {
		return err
	}
	emitBy(cur, "DomainExtraSet", "label", label, "key", key, "value", value)
	return nil
}

// DeleteDomainRecord destroys a domain and the names beneath it: it
// burns every token, drops every reverse-resolution pointer into them,
// removes the records, and finally removes the domain itself.
//
// WHY IT EXISTS. Retiring a domain after a brand complaint, recovering
// the storage deposit on a domain that never sold, and clearing out fad
// domains nobody renewed. A logic realm cannot provide any of this,
// because the vault owns the trees and exposed no delete path — the only
// Remove call for a domain lived inside RegisterDomainRecord as the
// evict-and-replace step of re-registration.
//
// IT DELIBERATELY WORKS ON A DOMAIN WITH LIVE NAMES UNDER IT. The case
// this exists for is a demand to remove a domain entirely, where waiting
// for names to lapse is not an option. Compensating the holders is
// handled off chain and is deliberately not a contract concern.
//
// WHERE THIS DEPARTS FROM THE SPEC, stated plainly because it is a real
// difference: MAINNET.md §3d asks for all of it "in one call". It is
// bounded instead, deleting at most maxDeletePerCall names per call and
// reporting whether it finished. An unbounded loop over a tree that may
// hold any number of names is a transaction that stops fitting in a
// block once a domain gets popular — which would mean the domains most
// likely to attract a complaint are exactly the ones that could never be
// deleted, in a realm that can never be fixed. The caller repeats until
// `done`; for any domain of realistic size that is one call, so the
// no-preconditions requirement is preserved. What is NOT preserved is
// atomicity: a multi-call deletion is visible half-done between calls.
// Freeze the domain first if that matters, so nothing new lands under it
// meanwhile. Not Pause(): a paused registry deletes nothing at all, since
// this passes the same trust gate as every write.
//
// Calling it on a domain that does not exist is a no-op reporting done,
// so a repeat loop terminates cleanly rather than panicking on the call
// that follows the last one.
func DeleteDomainRecord(cur realm, label string) (removed int64, done bool) {
	assertIsTrustedLogic(cur)
	d, ok := getDomain(label)
	if !ok {
		return 0, true
	}

	// Collect first, mutate second. Removing entries from the tree while
	// iterating it is undefined, and this loop exists precisely to remove
	// entries.
	start, end := domainRange(label)
	var keys []string
	names.Iterate(start, end, func(key string, v any) bool {
		if len(keys) >= maxDeletePerCall {
			return true
		}
		keys = append(keys, key)
		return false
	})

	for _, key := range keys {
		v := names.Get(key)
		if v == nil {
			continue
		}
		n := v.(*Name)
		// The name label is whatever follows "domain*" in the storage
		// key — the record no longer stores its own label.
		nameLabel := key[len(label)+1:]
		tid := nameTokenID(nameLabel, label)
		_ = n
		owner := nsnft.OwnerOf(tid)
		clearPrimaryIfPointingAt(owner, tid)
		// Every name has a token, but a registry swapped in mid-migration
		// could meet a record whose token was already dealt with. Burning a
		// token that does not exist panics and would strand the domain
		// half-deleted, so ask first.
		if owner != "" {
			nsnft.Burn(cross(cur), tid)
		}
		names.Remove(key)
		removed++
	}

	// Anything left means the cap was hit; the domain record has to stay
	// so the next call can still find its name span.
	more := false
	names.Iterate(start, end, func(key string, v any) bool {
		more = true
		return true
	})
	if more {
		emitBy(cur, "DomainDeleted", "label", label, "removed", i64(removed), "done", "false")
		return removed, false
	}

	_ = d
	domains.Remove(label)
	emitBy(cur, "DomainDeleted", "label", label, "removed", i64(removed), "done", "true")
	return removed, true
}

// -- names --

/*
RegisterNameRecord creates `label*domain` and mints its token in nsnft.

`paid` false registers a FREE-TIER name: the token is minted with the free
hold already set, so there is never an instant in which it could be
approved and sold before a lock arrived. There is no longer any such thing
as a name without a token — see Name.

RECLAIM burns the previous holder's token first. The owner is read from
the ledger, never from the record, because the record has no owner.

AN ORPHAN TOKEN IS REFUSED. A token that exists with no record behind it
means a registry swap is mid-migration or something has gone wrong; either
way, registering over it would mint a second claim to a name somebody
already holds. RestoreNameRecord is the door for adopting one.
*/
func RegisterNameRecord(cur realm, label, domainLabel string, owner address, now int64, paid bool) error {
	assertIsTrustedLogic(cur)
	if !owner.IsValid() {
		return errStr("invalid owner address")
	}
	if err := assertLabelKeySafe(label); err != nil {
		return err
	}
	d, ok := getDomain(domainLabel)
	if !ok {
		return errStr("unknown domain")
	}
	if d.frozen {
		return errStr("domain is frozen")
	}
	if isReclaimable(d.expires, now) {
		return errStr("domain has lapsed past its grace period")
	}
	treeKey := nameTreeKey(label, domainLabel)
	tid := nameTokenID(label, domainLabel)
	var reclaimedFrom address
	if n, ok := getName(label, domainLabel); ok {
		if n.frozen {
			return errStr("name is frozen")
		}
		if !isReclaimable(n.expires, now) {
			return errStr("name already registered and not yet reclaimable")
		}
		// Evict the previous holder completely. The reverse pointer goes
		// first: leaving it would make the old owner resolve to a name the
		// reclaimer now owns.
		prev := nsnft.OwnerOf(tid)
		reclaimedFrom = prev
		clearPrimaryIfPointingAt(prev, tid)
		if prev != "" {
			nsnft.Burn(cross(cur), tid)
		}
		names.Remove(treeKey)
	} else if nsnft.OwnerOf(tid) != "" {
		return errStr("a token for " + tid + " exists with no record behind it; restore it rather than registering over it")
	}

	nsnft.Mint(cross(cur), owner, tid, holdBits(paid, false))
	names.Set(treeKey, &Name{
		registered: now, expires: now + termLength,
		epoch: nsnft.Epoch(tid), since: now, extra: avl.Tree{},
	})
	setPrimaryIfNone(owner, tid)
	emitBy(cur, "NameRegistered", "tid", tid, "owner", owner.String(),
		"expires", i64(now+termLength), "paid", boolStr(paid), "reclaimedFrom", reclaimedFrom.String())
	return nil
}

func holdBits(paid, frozen bool) int {
	b := 0
	if !paid {
		b |= 1 << lockBitFree
	}
	if frozen {
		b |= 1 << lockBitFrozen
	}
	return b
}

/*
setPrimaryIfNone gives an address a reverse pointer when it has none — or
when the one it has points at a name it no longer holds.

The second half is new. A pointer used to be cleared on every transfer,
because transfers went through this realm. They no longer do: a sale that
settles on nsnft leaves the seller's pointer aimed at a name they sold.
nslogic.ResolveAddress already refuses to answer with it, so it never
misleads anybody — but left in place it also blocked the seller's NEXT
registration from becoming their primary, which would have looked like a
bug in registration rather than a stale pointer.
*/
func setPrimaryIfNone(owner address, tid string) {
	k := owner.String()
	if v := primary.Get(k); v == nil || !ownsNow(owner, v.(string)) {
		primary.Set(k, tid)
		// Reverse resolution is the one record that publishes a wallet's
		// persona, so even the automatic pointer says so.
		chain.Emit("PrimarySet", "owner", k, "tid", tid, "auto", "true")
	}
}

/*
UpgradeFreeRecord lifts the free-tier hold — the paid upgrade.

Preserves the dates: this is not a re-registration.

`newOwner` exists because the common case is somebody who decided to sell
and, in the same moment, wants the name in a wallet they control rather
than the key they were given. That move is a burn and a mint here, because
a held token cannot be transferred by design.

THE PROFILE DOES NOT GO WITH IT, and it used to. The move re-stamped the
old data to the new epoch and gave the recipient a reverse pointer — and
`newOwner` can be ANY address. An audit spelled out the attack: fill a
free name's profile with your own pay addresses, pay list price to upgrade
it into a victim's wallet, and the victim's name now asks people to pay
you, their address reverse-resolves to it, and their own later edits do
not clear it because the epoch is already current. So the data is left in
the previous epoch, where every read hides it and the next write destroys
it, and the recipient gets no pointer they never chose. A person moving
their own name to a new wallet re-enters their profile once; that is the
price of the move not being usable against somebody else.

Refused for a frozen name. Upgrading must never be the way a disputed name
gets out of its hold.
*/
func UpgradeFreeRecord(cur realm, label, domainLabel string, newOwner address) error {
	assertIsTrustedLogic(cur)
	if !newOwner.IsValid() {
		return errStr("invalid owner address")
	}
	n, ok := getName(label, domainLabel)
	if !ok {
		return errStr("unknown name")
	}
	if n.frozen {
		return errStr("name is frozen")
	}
	tid := nameTokenID(label, domainLabel)
	owner := nsnft.OwnerOf(tid)
	if owner == "" {
		return errStr("name has no token")
	}
	bits := nsnft.LockBits(tid)
	if bits&(1<<lockBitFree) == 0 {
		return errStr("name is already paid for")
	}
	if newOwner == owner {
		nsnft.SetLock(cross(cur), tid, lockBitFree, false)
		// Paid from now: time spent on the free tier is not time spent
		// holding a sellable name. See Name.since.
		n.since = time.Now().Unix()
		emitBy(cur, "NameUpgraded", "tid", tid, "owner", owner.String())
		return nil
	}
	nsnft.Burn(cross(cur), tid)
	nsnft.Mint(cross(cur), newOwner, tid, bits&^(1<<lockBitFree))
	clearPrimaryIfPointingAt(owner, tid)
	// n.epoch is deliberately NOT moved, and no pointer is given — see
	// above. n.since belongs to that old epoch too; the new owner's clock
	// starts at their first write.
	emitBy(cur, "NameUpgraded", "tid", tid, "owner", newOwner.String(), "from", owner.String())
	return nil
}

/*
RestoreNameRecord is the migration door: records move, tokens do not.

A registry swapped in behind the same nsnft finds tokens that already
exist. This writes the record for one and ADOPTS its token, or mints one
when the ledger has none. It never moves a token: a snapshot must never
take a name from its current holder.

WHEN THE LEDGER DISAGREES WITH THE SNAPSHOT, IT WINS. This used to refuse,
and an audit showed where refusing leads: a name sold between the snapshot
and the restore panics the batch, gets dropped to finish the rest, and the
window seals — leaving the buyer's token with no record behind it, unable
to be renewed, resolved or registered, forever. So the record is written
for whoever holds the token now, and the snapshot's profile data is NOT
replayable onto it (restoredFor stays empty), because it was the seller's.

Gated like every write, and nslogic only reaches it through the restore
window, which is one-shot.
*/
func RestoreNameRecord(cur realm, label, domainLabel string, owner address, registered int64, paid bool) error {
	assertIsTrustedLogic(cur)
	if !owner.IsValid() {
		return errStr("invalid owner address")
	}
	if err := assertLabelKeySafe(label); err != nil {
		return err
	}
	if _, ok := getDomain(domainLabel); !ok {
		return errStr("unknown domain")
	}
	if _, ok := getName(label, domainLabel); ok {
		return errStr("name already has a record")
	}
	tid := nameTokenID(label, domainLabel)
	held := nsnft.OwnerOf(tid)
	if held == "" {
		nsnft.Mint(cross(cur), owner, tid, holdBits(paid, false))
		held = owner
	} else {
		/* NEVER ADOPT WHILE ANOTHER REGISTRY CAN STILL MINT.

		   The ledger's trust set is a set so an old and a new registry can
		   both be live during a migration — and an audit showed what that
		   allows: a name adopted here and renewed here still has its OLD
		   record, with its old expiry, in the old registry. Once that
		   lapses past grace, anyone registers the name through the old
		   logic realm, which burns the token and mints it to them. The
		   holder's paid, renewed name is gone. So adoption requires that
		   this registry is the only one the ledger trusts: pause and
		   untrust the old registry first, then restore. */
		if nsnft.Trusted() != cur.Address().String() {
			return errStr("adopting " + tid + " while the ledger trusts another registry would let that registry reclaim it; untrust the old registry first")
		}
		// Adopt. BOTH holds are set from what is being restored: the free
		// hold from the snapshot, and the frozen hold cleared, so a freeze
		// left by the old registry cannot linger on a record that reads
		// unfrozen. nslogic re-freezes after this if the snapshot says so.
		nsnft.SetLock(cross(cur), tid, lockBitFree, !paid)
		nsnft.SetLock(cross(cur), tid, lockBitFrozen, false)
	}
	// `since` is the restore, not the snapshot's registration date: this
	// registry cannot know when the holder acquired the token, and the
	// clock may understate a holding but never overstate one.
	rec := &Name{
		registered: registered, expires: registered + termLength,
		epoch: nsnft.Epoch(tid), since: time.Now().Unix(), extra: avl.Tree{},
	}
	if held == owner {
		rec.restoredFor = owner
		setPrimaryIfNone(owner, tid)
	}
	names.Set(nameTreeKey(label, domainLabel), rec)
	emitBy(cur, "NameRestored", "tid", tid, "owner", held.String(), "snapshotOwner", owner.String())
	return nil
}

func RenewNameRecord(cur realm, label, domainLabel string, caller address, now int64) error {
	assertIsTrustedLogic(cur)
	n, ok := getName(label, domainLabel)
	if !ok {
		return errStr("unknown name")
	}
	if isReclaimable(n.expires, now) {
		return errStr("name expired beyond grace period")
	}
	/* THE CHECK THE FIRST ATTEMPT GOT WRONG. It compared the caller to the
	   record's own owner copy, which stopped updating the moment ownership
	   moved to the token — so a buyer could not renew what they bought,
	   watched it lapse, and lost it to whoever re-registered. There is no
	   copy now. The ledger answers. */
	if caller != nsnft.OwnerOf(nameTokenID(label, domainLabel)) {
		return errStr("restricted to name owner")
	}
	n.expires = advanceTerm(n.expires, now)
	emitBy(cur, "NameRenewed", "tid", nameTokenID(label, domainLabel), "expires", i64(n.expires))
	return nil
}

/*
SetNameFrozen sets the record's frozen bit AND the matching hold on the
token, in the same call.

The record bit alone used to be the whole mechanism, and it bound nothing
outside our own transfer wrappers — a disputed name could be moved on any
marketplace that called the token directly. The hold in nsnft binds every
path there is.
*/
func SetNameFrozen(cur realm, label, domainLabel string, frozen bool) {
	assertIsTrustedLogic(cur)
	mustGetName(label, domainLabel).frozen = frozen
	nsnft.SetLock(cross(cur), nameTokenID(label, domainLabel), lockBitFrozen, frozen)
	emitBy(cur, "NameFrozen", "tid", nameTokenID(label, domainLabel), "frozen", boolStr(frozen))
}

// SetNameExpiryRecord sets an expiry directly. Backs the admin
// free-extension lever (SPEC.md §19) and any future term mechanic;
// the logic realm decides who may call it.
func SetNameExpiryRecord(cur realm, label, domainLabel string, expires int64) {
	assertIsTrustedLogic(cur)
	mustGetName(label, domainLabel).expires = expires
	emitBy(cur, "NameExpirySet", "tid", nameTokenID(label, domainLabel), "expires", i64(expires))
}

// SetNameTTLRecord sets how long a resolver may cache answers about this
// name, in seconds, where 0 means never cache. See Domain.ttl for why
// this exists and why the owner rather than the registry sets it.
func SetNameTTLRecord(cur realm, label, domainLabel string, ttl int64) error {
	assertIsTrustedLogic(cur)
	if ttl < 0 {
		return errStr("ttl may not be negative")
	}
	n, ok := getName(label, domainLabel)
	if !ok {
		return errStr("unknown name")
	}
	freshen(n, nameTokenID(label, domainLabel))
	n.ttl = ttl
	emitBy(cur, "NameTTLSet", "tid", nameTokenID(label, domainLabel), "ttl", i64(ttl))
	return nil
}

// SetNameExtraRecord writes one arbitrary key on a name. This is where
// profile fields, cross-chain addresses, management-key hashes and tier
// markers live. An empty value deletes the key.
func SetNameExtraRecord(cur realm, label, domainLabel, key, value string) error {
	assertIsTrustedLogic(cur)
	n, ok := getName(label, domainLabel)
	if !ok {
		return errStr("unknown name")
	}
	freshen(n, nameTokenID(label, domainLabel))
	if err := setExtra(&n.extra, key, value); err != nil {
		return err
	}
	// The field, never the value: see events.gno.
	emitBy(cur, "NameExtraSet", "tid", nameTokenID(label, domainLabel), "key", key)
	return nil
}

/*
freshen is the WRITE half of the lazy wipe, and it is the half the first
attempt described in prose and never wrote.

If a name's data belongs to a previous ownership epoch, every extra and the
TTL are destroyed, and the record is re-stamped to the current epoch —
BEFORE the new value is written. So the buyer's first edit cannot carry
the seller's Bitcoin address forward as the buyer's: by the time the edit
lands, the address is gone.

It wipes everything rather than a list of sensitive keys, for the same
reason the old transfer wipe did: which keys matter is policy, and a list
kept here would be wrong the first time nslogic invents a key.

The read half — hiding stale data from everybody the instant the epoch
moves — is isFresh, used by every name read.

It is also where a buyer's holding clock starts (Name.since): the first
moment this realm can see that the ledger has moved on.
*/
func freshen(n *Name, tid string) {
	before := n.epoch
	freshenTo(n, nsnft.Epoch(tid), time.Now().Unix())
	if n.epoch != before {
		chain.Emit("NameFreshened", "tid", tid, "since", i64(n.since))
	}
}

// freshenTo is freshen with the ledger's answer and the clock passed in,
// so the rule itself can be tested without a registry the ledger trusts.
func freshenTo(n *Name, epoch, now int64) {
	if n.epoch != epoch {
		n.extra = avl.Tree{}
		n.ttl = 0
		n.epoch = epoch
		n.since = now
	}
}

// FreshenNameRecord applies freshen and writes nothing else: the way a
// holder who bought a name starts its clock (Name.since) without having
// to invent a profile edit. For the current holder, freshen destroys only
// data every read already hides.
func FreshenNameRecord(cur realm, label, domainLabel string) error {
	assertIsTrustedLogic(cur)
	n, ok := getName(label, domainLabel)
	if !ok {
		return errStr("unknown name")
	}
	freshen(n, nameTokenID(label, domainLabel)) // emits NameFreshened when it changed anything
	return nil
}

func SetPrimaryRecord(cur realm, owner address, label, domainLabel string) error {
	assertIsTrustedLogic(cur)
	if _, ok := getName(label, domainLabel); !ok {
		return errStr("unknown name")
	}
	tid := nameTokenID(label, domainLabel)
	// nslogic checks this too. Checked here as well because a pointer at a
	// name somebody does not hold is the one thing reverse resolution must
	// never be able to say, and the ledger is one read away.
	if !ownsNow(owner, tid) {
		return errStr("restricted to the name's current owner")
	}
	primary.Set(owner.String(), tid)
	emitBy(cur, "PrimarySet", "owner", owner.String(), "tid", tid)
	return nil
}

func ClearPrimaryRecord(cur realm, owner address) {
	assertIsTrustedLogic(cur)
	primary.Remove(owner.String())
	emitBy(cur, "PrimaryCleared", "owner", owner.String())
}

// -- there are no raw NFT operations here any more --
//
// RawTransferNFT, RawApprove, RawSetApprovalForAll and TransferRecordOwner
// are gone. Transfers and approvals happen on nsnft, called directly by the
// holder or by a marketplace they approved — exactly how an external
// marketplace does it, so ours has no privileged path. A registry that
// could move tokens would be a registry that could steal them.

// -- config: all settable, none constant --

func SetTreasuryRecord(cur realm, addr address) {
	assertIsTrustedLogic(cur)
	treasury = addr
	emitConfig(cur, "treasury", addr.String())
}

// The lifecycle setters refuse the two values that would break the
// lifecycle for everybody: a term of zero or less, and a negative grace
// period, which made live names reclaimable early (audit L-2). nslogic
// bounds both too; a future logic realm need not.
func SetTermLengthRecord(cur realm, seconds int64) {
	assertIsTrustedLogic(cur)
	if seconds <= 0 {
		panic("nsdata: a term must be positive")
	}
	termLength = seconds
	emitConfig(cur, "termLength", i64(seconds))
}

func SetGracePeriodRecord(cur realm, seconds int64) {
	assertIsTrustedLogic(cur)
	if seconds < 0 {
		panic("nsdata: a grace period cannot be negative")
	}
	gracePeriod = seconds
	emitConfig(cur, "gracePeriod", i64(seconds))
}

// SetMaxDeletePerCallRecord tunes how much work one DeleteDomainRecord
// call will do. See maxDeletePerCall in types.gno.
func SetMaxDeletePerCallRecord(cur realm, n int) {
	assertIsTrustedLogic(cur)
	if n < 1 {
		n = 1
	}
	maxDeletePerCall = n
	emitConfig(cur, "maxDeletePerCall", i64(int64(n)))
}
func SetLabelPatternRecord(cur realm, pattern string) {
	assertIsTrustedLogic(cur)
	labelPattern = pattern
	emitConfig(cur, "labelPattern", pattern)
}

func SetTokenURIBaseRecord(cur realm, base string) {
	assertIsTrustedLogic(cur)
	tokenURIBase = base
	emitConfig(cur, "tokenURIBase", base)
}

func SetLabelLengthRecord(cur realm, minLen, maxLen int) {
	assertIsTrustedLogic(cur)
	minLabelLen, maxLabelLen = minLen, maxLen
	emitConfig(cur, "labelLength", i64(int64(minLen))+","+i64(int64(maxLen)))
}

func SetExtraLimitsRecord(cur realm, keyLen, valueLen, entries int) {
	assertIsTrustedLogic(cur)
	maxExtraKeyLen, maxExtraValueLen, maxExtraEntries = keyLen, valueLen, entries
	emitConfig(cur, "extraLimits", i64(int64(keyLen))+","+i64(int64(valueLen))+","+i64(int64(entries)))
}

// SetGlobalEntryLimitRecord sets how many keys globals may hold, apart
// from the per-record extras cap. See maxGlobalEntries.
func SetGlobalEntryLimitRecord(cur realm, entries int) {
	assertIsTrustedLogic(cur)
	if entries < 1 {
		panic("nsdata: the globals cap must be at least 1")
	}
	maxGlobalEntries = entries
	emitConfig(cur, "globalEntries", i64(int64(entries)))
}

// SetAccountLimitsRecord bounds the per-address store. Lowering a cap
// never deletes anything; it only refuses the next write that exceeds it.
func SetAccountLimitsRecord(cur realm, keyLen, valueLen, entries int) {
	assertIsTrustedLogic(cur)
	if keyLen < 1 || valueLen < 1 || entries < 1 {
		panic("nsdata: account limits must be positive")
	}
	maxAccountKeyLen, maxAccountValueLen, maxAccountEntries = keyLen, valueLen, entries
	emitConfig(cur, "accountLimits", i64(int64(keyLen))+","+i64(int64(valueLen))+","+i64(int64(entries)))
}

// -- per-address state --

/*
SetAccountRecord writes one field of an address's own record: a credit
balance, a counter, whatever a logic realm keeps per wallet. An empty
value deletes the field, so its storage can be reclaimed.

Bounded like the extras, with caps of its own: the field name, the value,
and how many fields one address may hold. The fields-per-address cap is
what keeps any single wallet's footprint small, whoever pays for it.
*/
func SetAccountRecord(cur realm, owner address, key, value string) error {
	assertIsTrustedLogic(cur)
	if !owner.IsValid() {
		return errStr("invalid address")
	}
	// Deleting first, before the field-name limit, as setExtraCapped does
	// (re-audit L-2): a delete frees storage and grants nothing.
	if value == "" {
		if key == "" || strings.ContainsAny(key, ":\n\r") {
			return errStr("bad account field")
		}
		accounts.Remove(accountKey(owner, key))
		emitBy(cur, "AccountSet", "addr", owner.String(), "key", key, "value", "")
		return nil
	}
	if err := assertAccountKey(key); err != nil {
		return err
	}
	k := accountKey(owner, key)
	if len(value) > maxAccountValueLen {
		return errStr("account value too long")
	}
	if !utf8.ValidString(value) {
		return errStr("account values must be valid UTF-8")
	}
	if accounts.Get(k) == nil && accountFields(owner) >= maxAccountEntries {
		return errStr("too many fields on this address")
	}
	accounts.Set(k, value)
	emitBy(cur, "AccountSet", "addr", owner.String(), "key", key, "value", value)
	return nil
}

// accountFields counts one address's fields, stopping at the cap: the
// only question asked of it is whether the cap is reached, and an
// unbounded walk is not something a write path should contain.
func accountFields(owner address) int {
	n := 0
	start, end := accountRange(owner)
	accounts.Iterate(start, end, func(key string, v any) bool {
		n++
		return n >= maxAccountEntries
	})
	return n
}

// assertAccountKey keeps field names short and free of the characters
// that would make a snapshot listing ambiguous, and of ':', which
// separates the address from the field.
func assertAccountKey(key string) error {
	if key == "" || len(key) > maxAccountKeyLen {
		return errStr("bad account field")
	}
	if strings.ContainsAny(key, ",:\n\r") {
		return errStr("account field may not contain commas, colons or newlines")
	}
	return nil
}

// SetGlobalRecord writes one arbitrary package-level key — fee rates,
// default prices, a custodian address, points balances, claim records.
// Anything global that does not exist yet goes here instead of needing a
// package variable that could never be added after deployment.
// Keys the restore machinery owns. Written only by RestoreGlobal's own
// path, never by a general setter — because nslogic's SetGlobal forwards
// whatever key an admin passes, and one call writing "restore" reopened
// a seal that restore.gno calls irreversible. Enforced HERE as well as
// there, so a future logic realm cannot drop the guard by forgetting it.
var reservedGlobals = []string{"restore", "restored"}

func SetGlobalRecord(cur realm, key, value string) error {
	assertIsTrustedLogic(cur)
	for _, r := range reservedGlobals {
		if key == r {
			return errStr("that key belongs to the restore machinery and is not settable here")
		}
	}
	if err := setGlobal(key, value); err != nil {
		return err
	}
	emitBy(cur, "GlobalSet", "key", key, "value", value)
	return nil
}

// setGlobal is setExtra held to globals' own entry cap.
func setGlobal(key, value string) error {
	return setExtraCapped(&globals, key, value, maxGlobalEntries)
}

// SetReservedGlobalRecord is the restore machinery's own door to the
// keys above. Same trust gate; separate name, so a general-purpose
// setter can never reach them by accident.
func SetReservedGlobalRecord(cur realm, key, value string) error {
	assertIsTrustedLogic(cur)
	found := false
	for _, r := range reservedGlobals {
		if key == r {
			found = true
		}
	}
	if !found {
		return errStr("not a reserved key; use SetGlobalRecord")
	}
	// THE RESTORE DOOR MOVES ONE WAY, here as well as in the logic realm:
	// never opened, then opened once, then sealed — and from "sealed"
	// nowhere. The seal is the public promise that this registry's history
	// can no longer be rewritten on request, and "opened exactly once" is
	// what keeps a window from being closed quietly and opened again later;
	// a promise any trusted logic could undo with one write was only as
	// good as the newest logic generation. Re-writing "sealed" is harmless.
	if key == "restore" {
		if state := GetGlobal("restore"); state == "sealed" && value != "sealed" {
			return errStr("restore is sealed, and a seal does not come undone")
		} else if state != "" && value != "sealed" {
			return errStr("the restore window opens once; from here it can only be sealed")
		}
	}
	if err := setGlobal(key, value); err != nil {
		return err
	}
	emitBy(cur, "ReservedGlobalSet", "key", key, "value", value)
	return nil
}

// setExtra applies the shared bounds and the delete-on-empty rule to a
// name's or a domain's extras.
func setExtra(t *avl.Tree, key, value string) error {
	return setExtraCapped(t, key, value, maxExtraEntries)
}

func setExtraCapped(t *avl.Tree, key, value string, maxEntries int) error {
	// DELETING COMES FIRST, before any limit is checked: removing a key
	// frees storage and grants nothing, and with the key check in front a
	// single SetExtraLimits(1, ...) made every global undeletable — the
	// guardian's ClearKeeper, SetGranter(""), SetClaimWindow(0) included
	// (re-audit 2026-10-16, L-2).
	if value == "" {
		if key == "" {
			return errStr("bad extra key")
		}
		t.Remove(key)
		return nil
	}
	if err := assertExtraKey(key); err != nil {
		return err
	}
	// Bytes the snapshot can carry back. The vault used to store anything,
	// and a value with invalid UTF-8 came back from a snapshot three bytes
	// per bad byte, too long to replay (re-audit L-8).
	if !utf8.ValidString(key) || !utf8.ValidString(value) {
		return errStr("extra keys and values must be valid UTF-8")
	}
	if len(value) > maxExtraValueLen {
		return errStr("extra value too long")
	}
	if t.Get(key) == nil && t.Size() >= maxEntries {
		return errStr("too many extra entries")
	}
	t.Set(key, value)
	return nil
}

// assertExtraKey keeps extension keys free of the characters that would
// make a snapshot ambiguous. Export lists keys as CSV, so a key
// containing a comma or a newline would silently corrupt a backup — and
// a backup you cannot trust is the one thing this realm cannot afford.
func assertExtraKey(key string) error {
	if key == "" || len(key) > maxExtraKeyLen {
		return errStr("bad extra key")
	}
	if strings.ContainsAny(key, ",\n\r") {
		return errStr("extra key may not contain commas or newlines")
	}
	return nil
}

// assertLabelKeySafe is a STRUCTURAL check, not a policy one. Character
// policy lives in the logic realm's tunable labelPattern; this is the
// narrow set of characters that would break the vault's own machinery no
// matter what policy is in force:
//
//	"*"  is the separator in both key encodings, so a label containing
//	     one makes storage keys and token ids ambiguous;
//	","  and newlines would corrupt the CSV snapshot exports, which are
//	     the disaster-recovery guarantee — assertExtraKey already refuses
//	     them for extension keys, and labels become keys just as much;
//	""   cannot address a record at all.
//
// Enforcing it here rather than trusting the logic realm matters because
// labelPattern is admin-tunable: loosening it must never be able to
// silently corrupt a backup in a realm that cannot be redeployed.
func assertLabelKeySafe(label string) error {
	if label == "" {
		return errStr("empty label")
	}
	if strings.ContainsAny(label, "*,\n\r") {
		return errStr("label may not contain '*', commas or newlines")
	}
	return nil
}

func errStr(s string) error { return errors.New(s) }