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

art.gno

package nsnft

import (
	"chain"
	"encoding/base64"
	"strings"

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

/*
WHAT A WALLET SHOWS, AND WHY THIS FROZEN REALM DOES NOT DRAW IT.

Adena puts TokenURI(tid) straight into an <img src>, so it must return
the image itself (a data:image/svg+xml URI), and it reads TokenMetadata
as a camelCase JSON string. Both have to be answered HERE, because the
collection id names this realm. But the card is the most cosmetic and
most-revised thing in the project, and this realm can never change — so
the drawing is delegated to a view realm through a Renderer, and only
the delegation is frozen.

This realm cannot import the view: the view reads the registry, which
reads this ledger, and imports may not form a cycle. So the view hands
this realm an object at runtime instead. gno runs a method declared in
another realm with THAT realm's storage authority (the declaring-realm
borrow), so the renderer can read anything and write nothing of ours —
it gets no `cur`, so it cannot cross into anything as us either. What it
can do is draw something wrong, slow or broken, which is a display
problem: ClearRenderer withdraws it in one transaction (admin, recovery
or guardian) and wallets fall back to the built-in card below.

Who may register is pinned to ONE package path, approved through the
timelock (ProposeRenderer), because what every wallet shows for every
name is worth a waiting period: a hostile card could tell holders to pay
somebody. The ledger is born approving its own generation's view.
*/

// Renderer draws one token for wallets. Implemented by the view realm.
type Renderer interface {
	// TokenImage returns the image itself, as a data: URI.
	TokenImage(tid string) string
	// TokenMetadata returns the metadata as a JSON string: name,
	// description, externalUrl, attributes [{traitType, value}].
	TokenMetadata(tid string) string
}

var (
	// The one realm allowed to register a renderer; "" for none.
	rendererPath string
	// What it registered; nil means the built-in card.
	renderer Renderer
)

// RegisterRenderer is called BY the approved view realm, handing over
// the object that draws. Refused from anywhere else.
func RegisterRenderer(cur realm, r Renderer) {
	assertNoSend(cur)
	registerRenderer(cur.Previous().PkgPath(), r)
}

func registerRenderer(callerPath string, r Renderer) {
	if rendererPath == "" || callerPath != rendererPath {
		panic("nsnft: only the approved view realm may register a renderer")
	}
	if r == nil {
		panic("nsnft: no renderer given")
	}
	renderer = r
	chain.Emit("RendererRegistered", "path", callerPath)
}

// ClearRenderer withdraws the art at once, approval included, so the
// realm that drew it cannot simply register again: approving one takes
// the timelock. Admin, recovery or guardian.
func ClearRenderer(cur realm) {
	assertNoSend(cur)
	clearRenderer(cur.Previous().Address())
}

func clearRenderer(caller address) {
	assertCanRevoke(caller)
	prev := rendererPath
	rendererPath = ""
	renderer = nil
	chain.Emit("RendererCleared", "path", prev, "by", caller.String())
}

func RendererPath() string { return rendererPath }
func HasRenderer() bool    { return renderer != nil }

// TokenURI is the token's image, as a data: URI, for a token that exists.
// A renderer that answers nothing gets the built-in card instead: an
// empty <img src> is a broken picture in every wallet.
func TokenURI(tid string) (string, error) {
	if !Exists(tid) {
		return "", grc721.ErrInvalidTokenId
	}
	if renderer != nil {
		if img := renderer.TokenImage(tid); img != "" {
			return img, nil
		}
	}
	return builtinImage(tid), nil
}

// TokenMetadata is the token's metadata as a camelCase JSON string, the
// shape Adena reads. The image is not in it; that is TokenURI.
func TokenMetadata(tid string) (string, error) {
	if !Exists(tid) {
		return "", grc721.ErrInvalidTokenId
	}
	if renderer != nil {
		if meta := renderer.TokenMetadata(tid); meta != "" {
			return meta, nil
		}
	}
	return builtinMetadata(tid), nil
}

/*
THE BUILT-IN CARD, for when no view is registered: the name, plainly.

Deliberately plain and deliberately free of anything that could go
stale. No URL — a domain this realm named could lapse and be bought by
somebody else, and the link would then live in every wallet forever — and
no colours or claims that a policy change could make wrong.
*/
func builtinImage(tid string) string {
	size := 40
	if n := len(tid); n > 16 {
		size = 640 / n
		if size < 8 {
			size = 8
		}
	}
	svg := `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">` +
		`<rect width="400" height="400" fill="#0b0d10"/>` +
		`<text x="200" y="200" text-anchor="middle" font-family="monospace" font-size="` +
		itoa(int64(size)) + `" fill="#f4f4f5">` + escapeXML(tid) + `</text>` +
		`<text x="200" y="372" text-anchor="middle" font-family="monospace" font-size="13"` +
		` letter-spacing="3" fill="#71717a">MEME NAME SERVICE</text></svg>`
	return "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(svg))
}

func builtinMetadata(tid string) string {
	return `{"name":"` + escapeJSON(tid) + `",` +
		`"description":"A name on the Meme Name Service.",` +
		`"attributes":[]}`
}

func escapeXML(s string) string {
	s = strings.ReplaceAll(s, "&", "&amp;")
	s = strings.ReplaceAll(s, "<", "&lt;")
	s = strings.ReplaceAll(s, ">", "&gt;")
	s = strings.ReplaceAll(s, `"`, "&quot;")
	s = strings.ReplaceAll(s, "'", "&apos;")
	return s
}

func escapeJSON(s string) string {
	var b strings.Builder
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch {
		case c == '"':
			b.WriteString(`\"`)
		case c == '\\':
			b.WriteString(`\\`)
		case c < 0x20:
			const hex = "0123456789abcdef"
			b.WriteString(`\u00`)
			b.WriteByte(hex[c>>4])
			b.WriteByte(hex[c&0xf])
		default:
			b.WriteByte(c)
		}
	}
	return b.String()
}

gnomod.toml

module = "gno.land/r/nym-mnsrehearsal001/nsnft/v2"
gno = "0.9"

[addpkg]
  creator = "g1lh4rrf9pq9k9tvka9p6vwhyv70e4h09szap6zu"
  height = 453050
  max_deposit = "18000000ugnot"

governance.gno

package nsnft

import (
	"chain"
	"chain/runtime"
	"strings"
	"time"

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

/*
GOVERNANCE, AND WHY THE SMALLEST REALM NEEDED SOME.

The first version had one admin key and an instant Trust. Whoever held
that key could trust a realm of their own, burn any name and mint it to
themselves, in one block — and none of the vault's protections applied,
because its timelock, recovery role and guardian all live in nsdata and
nothing in that flow touches nsdata. In the generation where this is the
realm that can never change, it had the weakest governance of all. Two
audits (2026-10-15, H2/H3 and H-2) asked for this before it ships.

The model mirrors nsdata/governance.gno, with the two lessons its own
audit taught applied from the start:

	admin     the warm key. Proposes every power-granting change. Can
	          withdraw a registry's trust or the art instantly.
	recovery  the cold key, a multisig in production. Operates nothing.
	          Cancels ANY pending change, rotates admin, withdraws trust.
	guardian  hot (a monitoring bot), seated by recovery. Withdraws trust
	          or the art, and cancels the admin's grants (a registry, the
	          art, the timelock) but never a rotation. Nothing else, so its
	          theft costs an outage, never a name.

GRANTING IS SLOW, REVOKING IS INSTANT. Trusting a registry (the only way
anything can mint or burn), approving a view realm for the art, changing
the timelock and rotating either role all wait `timelockDelay` (an admin
replacing recovery waits twice that), are announced with an event, and
can be cancelled in the meantime. Withdrawing a registry's trust or the
art takes one transaction.

RECOVERY IS THE ROOT, AND THAT IS A DELIBERATE DEPARTURE. nsdata lets
each role rotate the other with neither able to cancel its own
replacement, which means a stolen admin key can propose a recovery
rotation recovery cannot stop. Here recovery may cancel anything and the
admin only what the admin proposed. A stolen admin key therefore gets
nothing that survives the timelock: every proposal it makes can be
cancelled and recovery can evict it. What it CAN do at once is withdraw
— untrust the registry, clear the art — which stops registrations until
an honest admin re-grants them, an outage and not a theft. The admin can
still replace a LOST recovery key — nobody cancels that proposal, so it
lands after twice the delay — which is the case the symmetry was there
for. The price is that a stolen recovery key is the one theft this realm
cannot contain, which is why it must be a cold multisig.

A ROTATION TAKES ITS PREDECESSOR'S PROPOSALS WITH IT. nsdata's audit (M-1)
found an evicted admin's pending grant surviving the eviction, executable
by anyone a delay later. Here, whenever a role changes hands, every
pending change proposed by an address that no longer holds a role is
dropped, with an event.

RECOVERY WINS THE EVICTION RACE, BY RULE AND NOT BY TIMING (re-audit
2026-10-16, M-1). An eviction used to drop the thief's proposals only at
the moment it executed, and anybody — the thief included — chose the order
in which matured proposals ran. So the thief re-proposed a cancelled trust
the block after recovery's sitting, executed it the moment it matured
(seconds after the eviction did), and minted through its registry in the
same transaction; or it executed recovery's own move to a new cold key
first, which orphaned recovery's eviction. Three rules close it:

	recovery proposing the eviction DROPS everything the admin had
	pending, and while the eviction is pending the admin proposes nothing
	and nothing it proposed may execute — so nothing of the admin's is
	held to spring back if the eviction lapses or is cancelled;

	a veto holds: when recovery or the guardian cancels what the admin
	proposed, the admin may not propose that kind again for one timelock,
	so recovery's sitting cannot be re-proposed around while it is still
	gathering signatures. Recovery's eviction landing clears the vetoes;
	replacing or standing down a guardian clears that guardian's; nothing
	else does, not an admin moving to a key of its own;

	recovery moving to a new key HANDS its eviction to that key (it was
	recovery's, and recovery still holds the role), so executing
	recovery's own rotation first no longer voids it. An admin replacing a
	lost recovery still drops the old key's plans.

Cancelling what is no longer pending does nothing, so a thief withdrawing
its own proposal first cannot make a batched sitting revert.

PROPOSALS EXPIRE. A matured change stays executable for executeWindow and
is void after it, so a forgotten proposal cannot be executed by a stranger
a year later (nsdata audit L-1).

ROLES NEVER MERGE. A rotation that would leave admin and recovery the
same key is refused, at proposal and again at execution: with one key in
both seats every protection above silently disappears (nsdata audit I-5).
They start merged on the deployer, which hands them out while the
timelock is still zero.

ExecutePending is open to anyone, as in nsdata: applying a change that
was announced and survived its window must not depend on a particular key
still being available. Every entry point below is a thin wrapper that
reads the caller and the clock and hands them to an unexported function,
so the rules themselves can be tested directly.
*/

const (
	// The ceiling on the timelock: a constant, not a setting, so a stolen
	// key cannot raise it and an absurd value cannot brick governance.
	maxTimelock int64 = 30 * 24 * 60 * 60
	// How long a matured proposal stays executable before it is void.
	executeWindow int64 = 14 * 24 * 60 * 60
	maxPathLen          = 256

	kindAdmin    = "admin"
	kindRecovery = "recovery"
	kindTrust    = "trust"
	kindDelay    = "delay"
	kindRenderer = "renderer"
)

type pendingOp struct {
	kind     string
	target   string  // what it changes to, as text: an address, a package path, or seconds
	addr     address // admin and recovery: the new holder; trust: the registry's address
	secs     int64   // delay: the new timelock
	at       int64   // unix seconds: executable from
	until    int64   // unix seconds: void after
	proposer address
}

var (
	admin    address
	recovery address
	guardian address

	// Seconds every power-granting change waits. Starts at zero so the
	// deploy can wire and hand out roles in one sitting; the deploy raises
	// it before anything is worth stealing. Changing it is itself
	// timelocked, or a thief would simply set it to zero.
	timelockDelay int64

	// One slot per kind (kind -> *pendingOp), so one in-flight proposal
	// cannot freeze the whole governance surface.
	pending avl.Tree

	// kind -> *veto: until when the admin may not propose that kind again,
	// because recovery or the guardian vetoed it, and who did (see the note
	// at the top).
	vetoes avl.Tree
)

type veto struct {
	until int64
	by    address
}

// -- roles: an empty role matches nobody --

func isAdmin(a address) bool    { return admin.IsValid() && a == admin }
func isRecovery(a address) bool { return recovery.IsValid() && a == recovery }
func isGuardian(a address) bool { return guardian.IsValid() && a == guardian }

func assertAdmin(caller address) {
	if !isAdmin(caller) {
		panic("nsnft: admin only")
	}
}

func assertAdminOrRecovery(caller address) {
	if !isAdmin(caller) && !isRecovery(caller) {
		panic("nsnft: admin or recovery only")
	}
}

func assertCanRevoke(caller address) {
	if !isAdmin(caller) && !isRecovery(caller) && !isGuardian(caller) {
		panic("nsnft: admin, recovery or guardian only")
	}
}

/*
isRealmPath accepts only a realm package path on this chain. A registry
or a view proves what it is by BEING that realm, and its address is
derived from the path here, so a wallet can never be trusted (nsdata
audit L-4): no wallet address is the hash of a realm path. Ephemeral
`maketx run` realms (gno.land/e/...), pure packages (/p/) and sub-realm
paths (with ':') are refused with it.
*/
func isRealmPath(p string) bool {
	prefix := runtime.ChainDomain() + "/r/"
	if len(p) <= len(prefix) || len(p) > maxPathLen || !strings.HasPrefix(p, prefix) {
		return false
	}
	if strings.HasSuffix(p, "/") || strings.Contains(p, "//") {
		return false
	}
	for i := 0; i < len(p); i++ {
		c := p[i]
		if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '/' || c == '_' || c == '-' || c == '.' {
			continue
		}
		return false
	}
	return true
}

// -- the pending slots --

// liveOp is the pending change of one kind, or nil — an expired one is
// treated as absent everywhere, so it can be neither executed nor used to
// block a new proposal.
func liveOp(kind string, now int64) *pendingOp {
	v := pending.Get(kind)
	if v == nil {
		return nil
	}
	op := v.(*pendingOp)
	if now > op.until {
		return nil
	}
	return op
}

/*
canCancel: recovery may cancel anything; the admin what the admin
proposed; the guardian the admin's GRANTS — a registry, the art, the
timelock — and never a rotation. A hot key able to block rotations
could, with recovery lost, block the one change that replaces recovery
(and with it, the guardian) for good.
*/
func canCancel(op *pendingOp, caller address) bool {
	if isRecovery(caller) {
		return true
	}
	if isAdmin(caller) && caller == op.proposer {
		return true
	}
	if isGuardian(caller) && op.proposer != recovery &&
		(op.kind == kindTrust || op.kind == kindRenderer || op.kind == kindDelay) {
		return true
	}
	return false
}

// delayFor is the wait a proposal gets. An admin replacing RECOVERY waits
// twice the timelock: it is the one move by which a stolen admin key
// could eventually take the root role, so it gets the longest window for
// recovery to see it and cancel it. The case it exists for — recovery
// lost — only costs a slower replacement.
func delayFor(kind string, caller address) int64 {
	if kind == kindRecovery && !isRecovery(caller) {
		return 2 * timelockDelay
	}
	return timelockDelay
}

/*
evicting reports a live rotation of the admin that recovery proposed —
recovery replacing a key it no longer trusts. While admin and recovery are
still one key, at the deploy, nothing is an eviction.
*/
func evicting(now int64) bool {
	op := liveOp(kindAdmin, now)
	return op != nil && isRecovery(op.proposer) && !isAdmin(op.proposer)
}

// byTheAdminAlone: proposed by the admin, and the admin is not also recovery.
func byTheAdminAlone(a address) bool { return isAdmin(a) && !isRecovery(a) }

// vetoedUntil is when the admin may propose `kind` again, or 0.
func vetoedUntil(kind string, now int64) int64 {
	if v := vetoes.Get(kind); v != nil && now < v.(*veto).until {
		return v.(*veto).until
	}
	return 0
}

// dropVetoesBy lifts the vetoes one key sent: a guardian replaced or stood
// down, perhaps because it was stolen, does not keep the admin shut out.
func dropVetoesBy(by address) {
	var gone []string
	vetoes.Iterate("", "", func(k string, v any) bool {
		if v.(*veto).by == by {
			gone = append(gone, k)
		}
		return false
	})
	for _, k := range gone {
		vetoes.Remove(k)
		chain.Emit("GovernanceVetoLifted", "kind", k, "by", by.String())
	}
}

// dropProposalsOf removes every pending change `who` proposed: the admin's
// plans, the moment recovery proposes to evict it.
func dropProposalsOf(who address, reason string) {
	var gone []string
	pending.Iterate("", "", func(k string, v any) bool {
		if op := v.(*pendingOp); op.proposer == who && k != kindAdmin {
			gone = append(gone, k)
		}
		return false
	})
	for _, k := range gone {
		op := pending.Get(k).(*pendingOp)
		pending.Remove(k)
		chain.Emit("GovernanceInvalidated", "kind", k, "target", op.target,
			"proposer", op.proposer.String(), "reason", reason)
	}
}

func setPending(caller address, op *pendingOp, now int64) {
	if existing := liveOp(op.kind, now); existing != nil {
		// You may replace only what you could cancel.
		if !canCancel(existing, caller) {
			panic("nsnft: a change of this kind is pending and you may not replace it")
		}
		chain.Emit("GovernanceDisplaced", "kind", existing.kind, "target", existing.target, "by", caller.String())
	}
	if byTheAdminAlone(caller) {
		if evicting(now) {
			panic("nsnft: recovery is replacing the admin; the admin proposes nothing until that lands or lapses")
		}
		if until := vetoedUntil(op.kind, now); until > 0 {
			panic("nsnft: recovery or the guardian vetoed a " + op.kind + " change; the admin may propose one again from unix " + itoa(until))
		}
	}
	op.proposer = caller
	op.at = now + delayFor(op.kind, caller)
	op.until = op.at + executeWindow
	pending.Set(op.kind, op)
	chain.Emit("GovernanceProposed",
		"kind", op.kind,
		"target", op.target,
		"executableAt", itoa(op.at),
		"expiresAt", itoa(op.until),
		"by", caller.String())
}

func proposeTrust(caller address, pkgPath string, now int64) {
	assertAdmin(caller)
	if !isRealmPath(pkgPath) {
		panic("nsnft: a registry must be a realm package path under " + runtime.ChainDomain() + "/r/")
	}
	a := chain.PackageAddress(pkgPath)
	if trusted.Has(a.String()) {
		panic("nsnft: that registry is already trusted")
	}
	setPending(caller, &pendingOp{kind: kindTrust, target: pkgPath, addr: a}, now)
}

func proposeRenderer(caller address, pkgPath string, now int64) {
	assertAdmin(caller)
	if !isRealmPath(pkgPath) {
		panic("nsnft: a renderer must be a realm package path under " + runtime.ChainDomain() + "/r/")
	}
	if pkgPath == rendererPath {
		panic("nsnft: that realm is already the approved renderer")
	}
	setPending(caller, &pendingOp{kind: kindRenderer, target: pkgPath}, now)
}

// proposeDelay bounds the value before anything is computed from it, so
// no input can wrap (nsdata audit L-3), and the proposal shows the value
// it would set, so a monitor can tell "to zero" from "up".
func proposeDelay(caller address, seconds int64, now int64) {
	assertAdmin(caller)
	if seconds < 0 || seconds > maxTimelock {
		panic("nsnft: timelock out of range (0 to " + itoa(maxTimelock) + " seconds)")
	}
	setPending(caller, &pendingOp{kind: kindDelay, target: itoa(seconds), secs: seconds}, now)
}

func proposeAdmin(caller, next address, now int64) {
	assertAdminOrRecovery(caller)
	if !next.IsValid() {
		panic("nsnft: invalid address")
	}
	if next == admin {
		panic("nsnft: that address is already the admin")
	}
	if next == recovery {
		panic("nsnft: admin and recovery must stay separate keys")
	}
	setPending(caller, &pendingOp{kind: kindAdmin, target: next.String(), addr: next}, now)
	if isRecovery(caller) && !isAdmin(caller) && admin.IsValid() {
		// The eviction drops the admin's plans now, not when it lands (see
		// the note at the top).
		dropProposalsOf(admin, "recovery is replacing the admin")
	}
}

func proposeRecovery(caller, next address, now int64) {
	assertAdminOrRecovery(caller)
	if !next.IsValid() {
		panic("nsnft: invalid address")
	}
	if next == recovery {
		panic("nsnft: that address is already recovery")
	}
	if next == admin {
		panic("nsnft: admin and recovery must stay separate keys")
	}
	setPending(caller, &pendingOp{kind: kindRecovery, target: next.String(), addr: next}, now)
}

func cancelPending(caller address, kind string, now int64) {
	op := liveOp(kind, now)
	if op == nil {
		if !isAdmin(caller) && !isRecovery(caller) && !isGuardian(caller) {
			panic("nsnft: admin, recovery or guardian only")
		}
		return // idempotent, so a batched sitting cannot be made to revert
	}
	if !canCancel(op, caller) {
		panic("nsnft: you may not cancel this change")
	}
	pending.Remove(kind)
	// A veto holds for one timelock (see the note at the top): what recovery
	// or the guardian cancelled, the admin cannot simply propose again in the
	// next block. The admin withdrawing its own proposal costs nothing.
	if byTheAdminAlone(op.proposer) && !isAdmin(caller) && timelockDelay > 0 {
		vetoes.Set(kind, &veto{until: now + timelockDelay, by: caller})
		chain.Emit("GovernanceVetoed", "kind", kind, "until", itoa(now+timelockDelay), "by", caller.String())
	}
	chain.Emit("GovernanceCancelled", "kind", kind, "target", op.target, "by", caller.String())
}

func executePending(caller address, kind string, now int64) {
	op := liveOp(kind, now)
	if op == nil {
		panic("nsnft: nothing pending of that kind")
	}
	if now < op.at {
		panic("nsnft: still in the timelock window")
	}
	// The eviction lands first, whoever picks the order (see the note at
	// the top): nothing the admin proposed runs while recovery is replacing
	// it, and the eviction then drops all of it.
	if kind != kindAdmin && byTheAdminAlone(op.proposer) && evicting(now) {
		panic("nsnft: recovery is replacing the admin; the admin's pending changes wait for that, and die with it")
	}
	pending.Remove(kind)
	prev := ""
	switch kind {
	case kindAdmin:
		if op.addr == recovery {
			panic("nsnft: admin and recovery must stay separate keys")
		}
		prev = admin.String()
		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 isRecovery(op.proposer) {
			vetoes = avl.Tree{}
		}
	case kindRecovery:
		if op.addr == admin {
			panic("nsnft: admin and recovery must stay separate keys")
		}
		prev = recovery.String()
		old := recovery
		recovery = op.addr
		// Recovery moving ITSELF keeps its eviction: it is handed to the new
		// key rather than orphaned. Only the eviction — recovery proposes
		// nothing else that could still be pending — so the new key never
		// inherits what an old deploy key proposed while it held both seats.
		// An admin replacing a lost recovery does not inherit that key's
		// eviction; it is dropped below with every other orphan.
		if op.proposer == old && old != admin {
			if e := liveOp(kindAdmin, now); e != nil && e.proposer == old {
				e.proposer = recovery
				chain.Emit("GovernanceHandedOver", "kind", kindAdmin, "target", e.target,
					"from", old.String(), "to", recovery.String())
			}
		}
	case kindTrust:
		trusted.Set(op.addr.String(), op.target)
		chain.Emit("RegistryTrusted", "addr", op.addr.String(), "path", op.target)
	case kindDelay:
		prev = itoa(timelockDelay)
		timelockDelay = op.secs
	case kindRenderer:
		// The approval moves; whatever the previous view registered stops
		// drawing, and wallets see the built-in card until the newly
		// approved realm registers itself.
		prev = rendererPath
		rendererPath = op.target
		renderer = nil
	default:
		panic("nsnft: unknown pending kind")
	}
	chain.Emit("GovernanceExecuted", "kind", kind, "target", op.target, "previous", prev, "by", caller.String())
	if kind == kindAdmin || kind == kindRecovery {
		dropOrphans()
	}
}

// dropOrphans removes every pending change whose proposer no longer
// holds a role. Called after each rotation; see the note at the top.
func dropOrphans() {
	var gone []string
	pending.Iterate("", "", func(k string, v any) bool {
		op := v.(*pendingOp)
		if op.proposer != admin && op.proposer != recovery {
			gone = append(gone, k)
		}
		return false
	})
	for _, k := range gone {
		op := pending.Get(k).(*pendingOp)
		pending.Remove(k)
		chain.Emit("GovernanceInvalidated", "kind", k, "target", op.target,
			"proposer", op.proposer.String(), "reason", "proposer no longer holds a role")
	}
}

func untrust(caller, registry address) {
	assertCanRevoke(caller)
	v := trusted.Get(registry.String())
	if v == nil {
		panic("nsnft: that registry is not trusted")
	}
	trusted.Remove(registry.String())
	chain.Emit("RegistryUntrusted", "addr", registry.String(), "path", v.(string), "by", caller.String())
}

/*
setGuardian takes recovery, to seat a guardian as much as to replace or
stand down a live one — otherwise the first move of a thief holding the
admin key would be to point the guardian at themselves, disarming the
emergency stop; and seating an EMPTY seat with its own bot left the thief a
key that outlived its eviction, untrusting the registry and vetoing the new
admin's grants, removable only by recovery (re-audit 2026-10-16, L-4). The
deploy seats it while its key still holds recovery. The address must be
real (nsdata audit I-4).
*/
func setGuardian(caller, g address) {
	if !g.IsValid() {
		panic("nsnft: invalid address")
	}
	if !isRecovery(caller) {
		if guardian.IsValid() {
			panic("nsnft: replacing a live guardian takes the recovery key")
		}
		panic("nsnft: seating a guardian takes the recovery key")
	}
	if guardian.IsValid() && guardian != g {
		dropVetoesBy(guardian)
	}
	guardian = g
	chain.Emit("GuardianSet", "addr", g.String(), "by", caller.String())
}

func clearGuardian(caller address) {
	if guardian.IsValid() {
		if !isRecovery(caller) {
			panic("nsnft: standing down a live guardian takes the recovery key")
		}
		dropVetoesBy(guardian)
	} else {
		assertAdminOrRecovery(caller)
	}
	guardian = ""
	chain.Emit("GuardianSet", "addr", "", "by", caller.String())
}

// -- entry points: each reads the caller and the clock, nothing more --

// ProposeTrust starts trusting a registry, by package path, after the
// timelock. Admin only.
func ProposeTrust(cur realm, pkgPath string) {
	assertNoSend(cur)
	proposeTrust(cur.Previous().Address(), pkgPath, time.Now().Unix())
}

// ProposeRenderer approves a view realm to draw the art, after the
// timelock. Admin only. The realm then registers itself (art.gno).
func ProposeRenderer(cur realm, pkgPath string) {
	assertNoSend(cur)
	proposeRenderer(cur.Previous().Address(), pkgPath, time.Now().Unix())
}

// ProposeTimelockDelay changes the timelock, after the current one.
// Admin only.
func ProposeTimelockDelay(cur realm, seconds int64) {
	assertNoSend(cur)
	proposeDelay(cur.Previous().Address(), seconds, time.Now().Unix())
}

// ProposeAdminTransfer rotates the admin after the timelock. Admin or
// recovery; when recovery proposes it, the admin cannot cancel it.
func ProposeAdminTransfer(cur realm, next address) {
	assertNoSend(cur)
	proposeAdmin(cur.Previous().Address(), next, time.Now().Unix())
}

// ProposeRecoveryTransfer rotates recovery after the timelock — twice the
// timelock when the admin proposes it. Admin or recovery; recovery can
// cancel either, so a stolen admin key cannot take it.
func ProposeRecoveryTransfer(cur realm, next address) {
	assertNoSend(cur)
	proposeRecovery(cur.Previous().Address(), next, time.Now().Unix())
}

func CancelPending(cur realm, kind string) {
	assertNoSend(cur)
	cancelPending(cur.Previous().Address(), kind, time.Now().Unix())
}

// ExecutePending applies a matured change. Anyone may call it.
func ExecutePending(cur realm, kind string) {
	assertNoSend(cur)
	executePending(cur.Previous().Address(), kind, time.Now().Unix())
}

// Untrust withdraws a registry's power to mint and burn, at once. Admin,
// recovery or guardian: removing a power is the safe direction, and a
// registry that has gone wrong must be stoppable in one transaction.
func Untrust(cur realm, registry address) {
	assertNoSend(cur)
	untrust(cur.Previous().Address(), registry)
}

func SetGuardian(cur realm, g address) {
	assertNoSend(cur)
	setGuardian(cur.Previous().Address(), g)
}

func ClearGuardian(cur realm) {
	assertNoSend(cur)
	clearGuardian(cur.Previous().Address())
}

// -- reads --

func Admin() address       { return admin }
func Recovery() address    { return recovery }
func Guardian() address    { return guardian }
func TimelockDelay() int64 { return timelockDelay }

// PendingAdmin is the address a pending admin rotation would install, or
// empty.
func PendingAdmin() address {
	if op := liveOp(kindAdmin, time.Now().Unix()); op != nil {
		return op.addr
	}
	return ""
}

// GetPending describes the live pending change of one kind: what it sets,
// when it becomes executable and when it lapses (unix seconds), and who
// proposed it. All empty when nothing is pending.
func GetPending(kind string) (target string, executableAt, expiresAt int64, proposer address) {
	op := liveOp(kind, time.Now().Unix())
	if op == nil {
		return "", 0, 0, ""
	}
	return op.target, op.at, op.until, op.proposer
}

// ListPending names the kinds with a live pending change, comma-separated.
func ListPending() string {
	now := time.Now().Unix()
	out := ""
	pending.Iterate("", "", func(k string, v any) bool {
		if now > v.(*pendingOp).until {
			return false
		}
		if out != "" {
			out += ","
		}
		out += k
		return false
	})
	return out
}

func IsTrusted(registry address) bool { return registry.IsValid() && trusted.Has(registry.String()) }

// Trusted lists every address that may mint or burn, comma-separated.
// nsdata compares this with its own address before adopting tokens, so
// the format is part of the contract: addresses only, no spaces.
func Trusted() string {
	out := ""
	trusted.Iterate("", "", func(a string, _ any) bool {
		if out != "" {
			out += ","
		}
		out += a
		return false
	})
	return out
}

// TrustedPath reports the package path a registry was trusted as, or "".
func TrustedPath(registry address) string {
	if v := trusted.Get(registry.String()); v != nil {
		return v.(string)
	}
	return ""
}

nsnft.gno

// Package nsnft is the token, and only the token.
//
// WHY THIS REALM EXISTS AT ALL.
//
// A name here is a GRC-721. An external marketplace that wants to list
// one has to hard-code an address, and whatever address that is becomes
// the thing we can never move. Until now the interface was split: the
// READS lived on nsdata, which is permanent, and the WRITES — Approve,
// SetApprovalForAll, TransferFrom — lived on nslogic, which changed
// address three times in a single day. So the half an integrator needs
// in order to settle a sale was the half that kept moving, and the reads
// kept answering while it did, which is the worst way for it to break.
//
// The fix is to pick ONE realm to freeze and make it the smallest, most
// boring one there is. That is this realm: an ownership ledger, the
// approval bookkeeping GRC-721 requires, the governance that decides who
// may mint, and nothing else. No prices, no expiry, no profiles, no
// policy — none of the things that will certainly need changing.
//
// Everything with an opinion in it stays in the registry, which becomes
// replaceable BECAUSE ownership no longer lives there. A migration then
// moves records, not tokens: nobody's holdings are stranded and no
// listing anywhere goes stale, because the token contract never moved.
//
// THE LEDGER IS THE CHAIN'S OWN gno.land/p/nt/grc721/v0, NOT A COPY.
//
// chain.Emit stamps the package whose code emits, and wallets and
// indexers (Adena, the Onbloc indexer) accept only Transfer and NewToken
// events stamped gno.land/p/nt/grc721/v0. The first version of this realm
// minted on a vendored GRC-721 deployed under our own p/ path, so every
// event it would ever have emitted carried OUR path, and no wallet would
// ever have listed a single name — permanently, because events cannot be
// re-emitted and this realm cannot be replaced. The ledger object lives
// here, created once in init; only this realm holds its PrivateLedger,
// and no Teller is ever handed out (see the note on holds below).
//
// THIS REALM HAS ITS OWN GOVERNANCE, AND THAT IS THE POINT.
//
// It would be shorter to ask nsdata who the admin is. It would also
// re-couple this realm to the exact thing it exists to let us replace —
// nsnft would then depend on one nsdata forever and we would have moved
// the problem rather than solved it. So roles, trust and the timelock are
// local (governance.gno), and nsdata is not imported.
//
// WHAT MAY BE CHANGED LATER AND WHAT MAY NOT.
//
// May, slowly: which registries are trusted, the roles, the timelock,
// and which view realm draws the art. May, instantly: withdrawing a
// registry's trust or the art, which only ever removes a power. Through a
// trusted registry only: the hold bits on a token. May not: anything
// else. If this realm ever needs a new function, the design has failed
// and the honest answer is that it was not small enough to freeze.
package nsnft

import (
	"chain"
	"chain/runtime/unsafe" // OriginSend only; this realm never moves coins
	"time"

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

const (
	collectionName   = "Meme Name Service"
	collectionSymbol = "MNS"

	/* THE REGISTRY AND THE VIEW THIS LEDGER IS BORN WITH.

	   Placeholders, exactly like an import path: the deploy tooling
	   (tools/deploy-gen.sh, tools/bundle-sources.py) rewrites every
	   quoted gno.land/r/demo/<realm> string to the generation's real path,
	   so the ledger is born trusting the one registry that is deployed
	   beside it — and no wallet is ever trusted, not even for the first
	   wiring. The previous version trusted the deployer's key at birth and
	   relied on somebody remembering to untrust it.

	   Fail-safe if the rewrite is ever skipped: nobody can deploy under
	   gno.land/r/demo on a public chain, so an unrewritten placeholder
	   trusts an address no transaction can come from. */
	genesisRegistry = "gno.land/r/nym-mnsrehearsal001/nsdata/v2"
	genesisView     = "gno.land/r/nym-mnsrehearsal001/nsview/v2"
)

var (
	// Created once, in init, by the chain's own GRC-721. token is the
	// read side; ledger is the write side and never leaves this realm.
	token  *grc721.Token
	ledger *grc721.PrivateLedger

	/* THE REGISTRIES PERMITTED TO MINT AND BURN: registry address -> the
	   package path it was trusted as. A set rather than a single value so
	   a migration can have the old and the new registry both live for the
	   window in which records are moving. An avl.Tree, so it is both a
	   lookup and an enumeration — whoever can mint names is the most
	   important fact about this contract, and it must be legible without
	   an indexer — and so a write touches one node rather than the whole
	   set. */
	trusted avl.Tree

	/* HOLDS, set by a trusted registry and never interpreted here.

	   A small bitmask per token (tid -> int). While any bit is set the
	   token cannot be approved or transferred — by its owner, by an
	   operator, by any marketplace — through any path in this realm.

	   WHY THE FROZEN REALM NEEDED THIS. The registry has two reasons to
	   hold a token in place: a free-tier name that has not been paid for
	   must not be sellable, and a name frozen by an admin during a
	   dispute must not be moved. Both used to be enforced in nslogic's
	   transfer wrappers — which only worked while nslogic was the only
	   way to transfer. The point of this realm is that it is NOT: any
	   GRC-721 marketplace calls TransferFrom here directly. A rule that
	   lives anywhere else is a rule an external marketplace skips.

	   WHY BITS AND NOT NAMED REASONS. What a bit MEANS is policy, and
	   policy changes; this realm cannot. So it stores numbers and the
	   registry owns the vocabulary. Separate bits, not one flag, so that
	   unfreezing a free-tier name cannot accidentally make it sellable.

	   Absent key = no hold. Burn clears it. */
	locks avl.Tree

	/* THE OWNERSHIP EPOCH (tid -> int64). Moves on every mint and every
	   transfer.

	   The registry stamps a name's profile data with the epoch it was
	   written in, and treats data from any other epoch as belonging to a
	   previous holder. That is how a sale that settles HERE — on a
	   marketplace the registry never hears from — still stops the
	   seller's payment addresses from answering for the buyer's name.

	   AN EPOCH, NOT AN OWNER ADDRESS, because a name can go A to B and
	   back to A. Compared by address, A's data from before the sale would
	   come back to life — including a pay address A may have abandoned.

	   Drawn from one global counter rather than counted per token, so a
	   token burned and minted again can never repeat an epoch it had in
	   a previous life.

	   avl.Tree and not a map: a Go map is persisted as ONE object, so
	   every mint and transfer re-wrote every token's epoch — measured at
	   ~784 gas per existing token per write, growing forever, in the one
	   realm that could never be fixed. A tree write touches a path. */
	epochs  avl.Tree
	lastSeq int64
)

// Bits a lock value may use. Eight is plenty for a registry and keeps a
// caller from storing arbitrary integers in a realm that cannot be
// patched to reject them later.
const maxLockBit = 7

// validLockBits is the range check, alone, so it can be tested directly.
func validLockBits(b int) bool { return b >= 0 && b < 1<<(maxLockBit+1) }

// validLockBit checks a bit INDEX, for SetLock. Separate from
// validLockBits, which checks a whole mask, because confusing the two is
// exactly the bug SetLock shipped with for one commit.
func validLockBit(bit int) bool { return bit >= 0 && bit <= maxLockBit }

func lockBitsOf(tid string) int {
	if v := locks.Get(tid); v != nil {
		return v.(int)
	}
	return 0
}

func bump(tid string) {
	lastSeq++
	epochs.Set(tid, lastSeq)
}

/*
THE HOLDS AND THE EPOCH LIVE IN THE LEDGER'S OWN HOOKS.

grc721/v0 calls an issuer-registered extension on every mint, transfer
and burn, after the ledger write and before the event, and a panic in a
hook aborts the movement. So the two rules this realm exists to keep are
enforced at the one place EVERY movement passes through — not in the
wrappers below, which merely repeat the hold check to give a clearer
error first.

Why that matters in a realm that never hands out a Teller: it makes the
rules a property of the ledger rather than of whichever entry point a
future reader adds or a marketplace finds. A transfer that reaches the
ledger by any route moves the epoch, and a held token does not move.
Approvals do not pass through a hook, so Approve checks the hold itself.

The type is unexported and the only instance is attached to the private
ledger, so no other realm can reach these methods.
*/
type holds struct{}

func (holds) ExtensionKind() string { return "nsnft/holds" }

func (holds) OnMint(to address, tid grc721.TokenID) {
	// A fresh token starts unheld; Mint applies the bits it was asked for
	// straight after. Burn already cleared any old hold, so this is the
	// belt to that brace.
	locks.Remove(string(tid))
	bump(string(tid))
}

func (holds) OnTransfer(from, to address, tid grc721.TokenID) {
	assertUnlocked(string(tid))
	bump(string(tid))
}

func (holds) OnBurn(tid grc721.TokenID) {
	// A hold on a token that no longer exists would silently apply to the
	// NEXT token minted with this id — a reclaimed name arriving frozen.
	locks.Remove(string(tid))
	// The epoch goes too. The next mint draws a fresh one from lastSeq,
	// which can never equal anything this token had before.
	epochs.Remove(string(tid))
}

func init(cur realm) {
	// Emits NewToken from gno.land/p/nt/grc721/v0; the collection id is
	// "<this realm's path>.MNS.0000000", the shape wallets parse.
	token, ledger = grc721.NewToken(collectionName, collectionSymbol, seqid.ID(0), cur)
	ledger.RegisterExtension(holds{})

	/* BOTH ROLES START ON THE DEPLOYER, AND ONLY IF IT IS REAL.

	   The deployer hands recovery to a cold key and admin to a multisig
	   as part of the deploy (tools/deploy-gen.sh), while the timelock is
	   still zero; then the timelock goes up. An invalid deployer cannot
	   happen on chain, and under `gno test` (which has none) it leaves
	   both roles empty — and every role check below refuses an empty
	   role, so nobody, not even a caller whose address stringifies to
	   nothing, can act as an absent admin. */
	if d := cur.Previous().Address(); d.IsValid() {
		admin = d
		recovery = d
	}

	reg := chain.PackageAddress(genesisRegistry)
	trusted.Set(reg.String(), genesisRegistry)
	chain.Emit("RegistryTrusted", "addr", reg.String(), "path", genesisRegistry)
	rendererPath = genesisView
	chain.Emit("RendererApproved", "path", genesisView)
}

/*
COINS SENT HERE ARE DESTROYED, SO REFUSE THEM.

This realm has no banker, no withdrawal and no sweep, and it can never
gain one — that is the whole premise of freezing it. Anything attached to
a call would sit at its address until the chain ends.

Checked only for a direct user call: when another realm calls in, any
coins the user attached went to THAT realm, not to this one, and
refusing them here would break legitimate registry calls.
*/
func assertNoSend(cur realm) {
	if !cur.Previous().IsUserCall() {
		return
	}
	if !unsafe.OriginSend().IsZero() {
		panic("nsnft: this realm takes no payment and cannot return it; do not attach coins")
	}
}

/*
assertTrusted is the whole security model for minting.

A caller that can mint can invent a name, and a name is the product. So
this is checked against the REALM address of the caller rather than an
address it hands us — a registry proves what it is by being it. Only
package paths can be trusted (governance.gno), so a wallet can never be
in this set.
*/
func assertTrusted(caller address) {
	if !caller.IsValid() || !trusted.Has(caller.String()) {
		panic("nsnft: only a trusted registry may do that")
	}
}

// ---------------------------------------------------------------------
// mint and burn — registry only
// ---------------------------------------------------------------------

/*
Mint creates a token, optionally already held in place.

`lockBits` is the hold it starts with — a free-tier name is minted locked
so there is never an instant in which it could be approved and sold
before the registry got round to locking it (nothing runs between the
ledger write and the line that sets the bits). Zero for an ordinary
paid name.
*/
func Mint(cur realm, to address, tid string, lockBits int) {
	assertNoSend(cur)
	assertTrusted(cur.Previous().Address())
	if !to.IsValid() {
		panic("nsnft: invalid recipient")
	}
	if tid == "" {
		panic("nsnft: empty token id")
	}
	if !validLockBits(lockBits) {
		panic("nsnft: lock bits out of range")
	}
	if err := ledger.Mint(to, grc721.TokenID(tid)); err != nil {
		panic("nsnft: " + err.Error())
	}
	if lockBits != 0 {
		locks.Set(tid, lockBits)
		chain.Emit("Locked", "tid", tid, "bits", itoa(int64(lockBits)))
	}
}

/*
Burn destroys a token. Reachable only by a trusted registry, which calls
it when a name lapses past its grace period and is reclaimed.

NOT reachable by the holder. A GRC-721 that lets an owner burn is
correct for collectibles and wrong here: the token is a lease on a name,
and destroying it would leave the registry holding a record for a name
whose token no longer exists. Letting go of a name is letting it expire.

The hold and the epoch are cleared by the burn hook (holds.OnBurn), the
per-token approval by the ledger itself.
*/
func Burn(cur realm, tid string) {
	assertNoSend(cur)
	assertTrusted(cur.Previous().Address())
	if err := ledger.Burn(grc721.TokenID(tid)); err != nil {
		panic("nsnft: " + err.Error())
	}
}

/*
SetLock turns one hold bit on or off. Trusted registry only.

The registry decides what a bit means; this realm only guarantees that
while any bit is set, nothing moves the token.
*/
func SetLock(cur realm, tid string, bit int, on bool) {
	assertNoSend(cur)
	assertTrusted(cur.Previous().Address())
	/* THE BIT IS RANGE-CHECKED BEFORE IT IS SHIFTED. An earlier check
	   tested 1<<bit, and an audit caught what that does: a bit of 64 or
	   more shifts to zero, passes, and the call quietly changes nothing
	   while still emitting LockChanged. Unacceptable in the one realm
	   that can never be patched. */
	if !validLockBit(bit) {
		panic("nsnft: lock bit out of range")
	}
	owner := OwnerOf(tid)
	if owner == "" {
		panic("nsnft: no such token")
	}
	v := lockBitsOf(tid)
	if on {
		v |= 1 << bit
	} else {
		v &^= 1 << bit
	}
	if v == 0 {
		locks.Remove(tid)
	} else {
		locks.Set(tid, v)
	}
	/* A NEW HOLD WITHDRAWS THE STANDING APPROVAL. A hold stops an
	   approval being USED, not the approval itself — so a name frozen
	   mid-dispute kept whatever approval it had, and it became live again
	   the moment the name was unfrozen. An audit caught it. The owner can
	   re-approve afterwards; nobody else's pre-dispute permission
	   survives. Operator grants are per owner, not per token, and are the
	   owner's to revoke. Approving the zero address is grc721/v0's
	   revoke, and it emits the standard Approval event. */
	if on && GetApproved(tid) != "" {
		if err := ledger.Approve(owner, "", grc721.TokenID(tid)); err != nil {
			panic("nsnft: " + err.Error())
		}
	}
	chain.Emit("LockChanged", "tid", tid, "bits", itoa(int64(v)))
}

func assertUnlocked(tid string) {
	if lockBitsOf(tid) != 0 {
		panic("nsnft: this token is held by the registry and cannot be approved or moved")
	}
}

// LockBits reports the current hold; 0 means free to move.
func LockBits(tid string) int { return lockBitsOf(tid) }

func IsLocked(tid string) bool { return lockBitsOf(tid) != 0 }

// Epoch reports the ownership epoch of a token, or 0 for one that does
// not exist. See epochs.
func Epoch(tid string) int64 {
	if v := epochs.Get(tid); v != nil {
		return v.(int64)
	}
	return 0
}

// ---------------------------------------------------------------------
// GRC-721, public — this is the surface the outside world holds
// ---------------------------------------------------------------------

// Approve grants (or, to the empty address, withdraws) the per-token
// approval. Refused while the token is held: approvals do not pass
// through a ledger hook, so this is the one place the hold is checked.
func Approve(cur realm, to address, tid string) {
	assertNoSend(cur)
	assertUnlocked(tid)
	if err := ledger.Approve(cur.Previous().Address(), to, grc721.TokenID(tid)); err != nil {
		panic("nsnft: " + err.Error())
	}
}

/*
RevokeApproval withdraws a token's per-token approval.

grc721/v0 revokes by approving the empty address; this keeps the named
entry point the site and tools already call, and allows it while the
token is held — withdrawing a permission is the safe direction. The
owner, or an operator acting for the owner, the same two callers Approve
accepts.
*/
func RevokeApproval(cur realm, tid string) {
	assertNoSend(cur)
	if OwnerOf(tid) == "" {
		panic("nsnft: no such token")
	}
	if err := ledger.Approve(cur.Previous().Address(), "", grc721.TokenID(tid)); err != nil {
		panic("nsnft: only the owner or an operator may revoke an approval: " + err.Error())
	}
}

func SetApprovalForAll(cur realm, operator address, approved bool) {
	assertNoSend(cur)
	if err := ledger.SetApprovalForAll(cur.Previous().Address(), operator, approved); err != nil {
		panic("nsnft: " + err.Error())
	}
}

/*
TransferFrom carries NO expiry check, and that is a deliberate reversal
of what nslogic once did.

Refusing to transfer an expired token is an anti-scam measure, and it
belongs in the REGISTRY, not here: this realm does not know what expiry
is and must not learn, because the moment it holds policy it stops being
the small frozen thing it exists to be. The registry keeps the rule by
refusing to RESOLVE an expired name. A buyer can still acquire a
worthless token from a careless seller, which is true of every NFT on
every chain, and the marketplace disclaimers say so.

The hold is checked here for a clear error and again by the ledger hook,
which also moves the epoch.
*/
func TransferFrom(cur realm, from, to address, tid string) {
	assertNoSend(cur)
	assertUnlocked(tid)
	if err := ledger.TransferFrom(cur.Previous().Address(), from, to, grc721.TokenID(tid)); err != nil {
		panic("nsnft: " + err.Error())
	}
}

// SafeTransferFrom is kept for the standard signature. grc721/v0 has no
// receiver hook (gno has no contract-receiver registry to check), so it
// is TransferFrom — as the vendored version effectively was, its
// receiver check being a stub that always said yes.
func SafeTransferFrom(cur realm, from, to address, tid string) {
	assertNoSend(cur)
	assertUnlocked(tid)
	if err := ledger.TransferFrom(cur.Previous().Address(), from, to, grc721.TokenID(tid)); err != nil {
		panic("nsnft: " + err.Error())
	}
}

// ---------------------------------------------------------------------
// reads
// ---------------------------------------------------------------------

/*
OwnerOf answers the zero address for a token that does not exist, rather
than panicking or returning an error.

The registry calls this on EVERY resolve — that is the whole design, one
truth rather than a cached copy that goes stale the moment a sale settles
somewhere we did not watch. A panic on an unknown id would make every
caller wrap it, and the wrapper that gets forgotten is the one that turns
a missing name into a broken page. (nsdata and nsmarket are written
against exactly this signature.)
*/
func OwnerOf(tid string) address {
	owner, err := token.OwnerOf(grc721.TokenID(tid))
	if err != nil {
		return ""
	}
	return owner
}

func Exists(tid string) bool { return OwnerOf(tid) != "" }

func BalanceOf(owner address) int64 {
	n, err := token.BalanceOf(owner)
	if err != nil {
		return 0
	}
	return n
}

// GetApproved answers totally: the zero address means nobody is approved
// or there is no such token.
func GetApproved(tid string) address {
	a, err := token.GetApproved(grc721.TokenID(tid))
	if err != nil {
		return ""
	}
	return a
}

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

func Name() string       { return token.GetName() }
func Symbol() string     { return token.GetSymbol() }
func GetName() string    { return token.GetName() }
func GetSymbol() string  { return token.GetSymbol() }
func TokenCount() int64  { return token.TotalSupply() }
func TotalSupply() int64 { return token.TotalSupply() }

// ID is the collection id wallets and indexers key on:
// "<this realm's path>.MNS.0000000".
func ID() string { return token.ID() }

/*
Render builds its string by concatenation rather than with ufmt.

NO DEPENDENCIES THIS REALM DOES NOT ABSOLUTELY NEED. It is meant to be
deployed once and never replaced, so every import is a permanent
commitment to somebody else's package. grc721/v0 (with avl and seqid,
which it already depends on) is here because it IS the thing this realm
is; a formatter, for one page of text, is not worth that.
*/
func Render(path string) string {
	out := "# Meme Name Service — tokens\n\n" +
		"This realm is the ownership ledger and nothing else. Prices, expiry,\n" +
		"profiles and every rule live in the registry.\n\n" +
		"- collection: `" + token.ID() + "`\n" +
		"- tokens: " + itoa(token.TotalSupply()) + "\n" +
		"- admin: `" + admin.String() + "`\n" +
		"- recovery: `" + recovery.String() + "`\n" +
		"- guardian: `" + guardian.String() + "`\n" +
		"- timelock: " + itoa(timelockDelay) + " s\n" +
		"- renderer: `" + rendererPath + "`"
	if renderer == nil {
		out += " (not registered: wallets see the built-in card)"
	}
	out += "\n\n## Trusted registries\n\n"
	trusted.Iterate("", "", func(a string, v any) bool {
		out += "- `" + v.(string) + "` (`" + a + "`)\n"
		return false
	})
	out += "\n## Pending governance\n\n"
	n := 0
	now := time.Now().Unix()
	pending.Iterate("", "", func(k string, v any) bool {
		op := v.(*pendingOp)
		if now > op.until {
			return false // void: lapsed unexecuted (re-audit 2026-10-16, I-6)
		}
		out += "- " + k + " -> `" + op.target + "`, executable " + itoa(op.at) +
			" to " + itoa(op.until) + ", by `" + op.proposer.String() + "`\n"
		n++
		return false
	})
	if n == 0 {
		out += "none\n"
	}
	out += "\nIntegrators: this address is stable. The registry behind it is not,\n" +
		"and is meant not to be.\n"
	return out
}

// itoa, because importing a package to print one number would outlast
// every reason we had for wanting it.
func itoa(n int64) string {
	if n == 0 {
		return "0"
	}
	neg := n < 0
	// Work in uint64 so the most negative int64 does not overflow when
	// its sign is flipped.
	u := uint64(n)
	if neg {
		u = uint64(-(n + 1)) + 1
	}
	var b []byte
	for u > 0 {
		b = append([]byte{byte('0' + u%10)}, b...)
		u /= 10
	}
	if neg {
		return "-" + string(b)
	}
	return string(b)
}