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

admin.gno

package nslogic

import (
	"strconv"
	"strings"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// assertIsAdmin reads nsdata.GetAdmin() fresh every call — correct even
// immediately after a TransferAdmin, and correct for a freshly-deployed
// logic realm with no local state of its own to go stale.
//
// Note: admin authority to swap WHICH realm is trustedLogic, or to
// transfer admin itself, is deliberately NOT exposed here — those live
// only in nsdata's own admin.gno, callable solely by a direct wallet
// call from the current admin address, never proxied through logic.
// That's the one part of the system a compromised or buggy logic realm
// cannot touch.
func assertIsAdmin(cur realm) {
	if cur.Previous().Address() != nsdata.GetAdmin() {
		panic("nslogic: restricted to project admin")
	}
}

// SetLabelPattern no longer changes anything, and refuses anything but
// the rule this realm actually implements.
//
// It used to compile an arbitrary regex and store it, with validateLabel
// reading it back. That flexibility cost 15 GNOT of permanent storage
// per deploy — see the measurements in validate.gno — for a rule that
// has never changed and should not change casually.
//
// It is kept rather than deleted so that an admin who reaches for it
// gets told what happened instead of a "function not found". And it
// refuses a different pattern rather than accepting one it will not
// enforce: a stored string describing rules the code does not apply is
// the exact silent divergence the caching version was written to avoid.
func SetLabelPattern(cur realm, pattern string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetLabelPattern", "pattern", pattern)
	if pattern != labelRule {
		panic("nslogic: the label rule is fixed in this realm (" + labelRule +
			"). Changing it means deploying a new logic realm — which is deliberate, " +
			"because a stored pattern the code does not enforce is worse than no setting at all.")
	}
	nsdata.SetLabelPatternRecord(cross(cur), pattern)
}

func SetLabelLengthLimits(cur realm, minLen, maxLen int) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetLabelLengthLimits", "min", fmtI(minLen), "max", fmtI(maxLen))
	if minLen < 1 || maxLen < minLen {
		panic("nslogic: invalid length bounds")
	}
	nsdata.SetLabelLengthRecord(cross(cur), minLen, maxLen)
}

// SetDefaultNamePrice sets the fallback price in micro-USD, used by any
// domain that has not set its own base. BOUNDED (timelock.gno): a raise up
// to four times every ten minutes, a cut up to 25% once an hour, or a
// timelocked proposal for anything else.
func SetDefaultNamePrice(cur realm, microUsd int64) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetDefaultNamePrice", "microUsd", fmtInt(microUsd))
	if microUsd < 0 || microUsd > maxPriceUSD {
		panic("nslogic: a price is 0.." + strconv.FormatInt(maxPriceUSD, 10) + " micro-USD")
	}
	v := strconv.FormatInt(microUsd, 10)
	old := DefaultPriceUSD()
	authorizeTweak(cur, keyDefaultPrice, old, microUsd, microUsd > old, actionID("SetDefaultNamePrice", v))
	setGlobal(cur, keyDefaultPrice, v)
}

// SetUsdRate records how many ugnot one USD buys — the bridge between
// the USD price list and settlement on this chain.
//
// It is a MANUAL rate, not a market feed: it sits where it was last
// written. A stale rate during a sharp move sells names at the wrong
// price, and no amount of contract logic fixes that — keeping it current
// is an operational duty. Isolated as one global so a future logic realm
// can swap in a real oracle without touching the vault or restating a
// single price.
//
// BOUNDED (timelock.gno): a rate of 1 ugnot to the dollar used to be one
// call away from selling every name for dust. ASYMMETRIC (Ely,
// 2026-10-16): a higher rate — GNOT fell, names cost more GNOT — moves up
// to four times every ten minutes, so a 75% crash is followed in one
// update; a lower rate — the direction that sells names cheap — moves at
// most 25%, once an hour. Anything larger is a timelocked proposal.
//
// THE KEEPER may call this too (keeper.gno), and nothing else: the same
// bound and the same hourly slot, never the timelock, and KeeperAction on
// every move. Anybody who is neither gets the admin refusal, as before.
func SetUsdRate(cur realm, ugnotPerUsd int64) {
	assertNoSend(cur)
	if cur.Previous().Address() != nsdata.GetAdmin() {
		keeperSetRate(cur, ugnotPerUsd)
		return
	}
	assertIsAdmin(cur)
	emitAdmin(cur, "SetUsdRate", "ugnotPerUsd", fmtInt(ugnotPerUsd))
	if ugnotPerUsd <= 0 || ugnotPerUsd > maxRate {
		panic("nslogic: a rate is 1.." + strconv.FormatInt(maxRate, 10) + " ugnot per USD")
	}
	v := strconv.FormatInt(ugnotPerUsd, 10)
	old := RateUgnotPerUsd()
	authorizeTweak(cur, keyRate, old, ugnotPerUsd, ugnotPerUsd > old, actionID("SetUsdRate", v))
	setGlobal(cur, keyRate, v)
}

// SetTermLength / SetGracePeriod retune the lifecycle itself. Both were
// hardcoded constants in the vault until 2026-08-21 — meaning the 1-year
// term and 90-day grace could never have been changed, on a realm that
// is never redeployed. There was no reason to accept that.
// maxLifecycleDays bounds both setters. time.Duration is int64
// NANOSECONDS, so `days * 24h` overflows above ~106,751 days and wraps to
// a NEGATIVE duration — which would install a negative term and brick
// every registration and renewal in the registry. Guarding the input is
// what keeps the multiplication in range.
const maxLifecycleDays = 36500 // 100 years

// BOTH ARE TIMELOCKED (timelock.gno). A grace period of zero made every
// name in grace reclaimable by anybody on the spot — owners who could
// still have renewed lost their names to whoever registered first — and a
// term change reprices every renewal and moves every holder's tenure.
func SetTermLength(cur realm, days int64) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetTermLength", "days", fmtInt(days))
	if days <= 0 || days > maxLifecycleDays {
		panic("nslogic: term out of range (1..36500 days)")
	}
	term := days * 24 * 60 * 60
	// Keep gracePeriod <= termLength. Anchoring a renewal to the previous
	// due date is only coherent while a renewal cannot happen more than
	// one full term after it; the vault clamps forward defensively, but
	// the combination should not be reachable in the first place.
	if nsdata.GetGracePeriod() > term {
		panic("nslogic: term must be at least the current grace period")
	}
	requireAction(cur, actionID("SetTermLength", strconv.FormatInt(days, 10)))
	nsdata.SetTermLengthRecord(cross(cur), term)
}

func SetGracePeriod(cur realm, days int64) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetGracePeriod", "days", fmtInt(days))
	if days < 0 || days > maxLifecycleDays {
		panic("nslogic: grace period out of range (0..36500 days)")
	}
	grace := days * 24 * 60 * 60
	if grace > nsdata.GetTermLength() {
		panic("nslogic: grace period may not exceed the term length")
	}
	requireAction(cur, actionID("SetGracePeriod", strconv.FormatInt(days, 10)))
	nsdata.SetGracePeriodRecord(cross(cur), grace)
}

// SetTokenURIBase re-points TokenURI at a different renderer, so the NFT
// artwork can be replaced without touching the vault.
func SetTokenURIBase(cur realm, base string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetTokenURIBase", "base", base)
	nsdata.SetTokenURIBaseRecord(cross(cur), base)
}

func SetExtraLimits(cur realm, keyLen, valueLen, entries int) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetExtraLimits", "keyLen", fmtI(keyLen), "valueLen", fmtI(valueLen), "entries", fmtI(entries))
	// NEVER BELOW WHAT THIS REALM ITSELF WRITES: the vault's own defaults
	// (32-byte keys, 512-byte values, 24 entries). One instant call to a
	// tiny limit used to make every later global write revert, the keeper's
	// rate and the instant revocations among them (re-audit L-2).
	if keyLen < minExtraKeyLen || valueLen < minExtraValueLen || entries < minExtraEntries {
		panic("nslogic: extra limits are at least " + fmtI(minExtraKeyLen) + " / " + fmtI(minExtraValueLen) +
			" / " + fmtI(minExtraEntries) + ", the sizes this realm writes")
	}
	nsdata.SetExtraLimitsRecord(cross(cur), keyLen, valueLen, entries)
}

const (
	minExtraKeyLen   = 32
	minExtraValueLen = 512
	minExtraEntries  = 24
)

// SetGlobalEntryLimit sets how many keys the vault's globals may hold —
// its own cap now, apart from the per-record extras SetExtraLimits bounds.
func SetGlobalEntryLimit(cur realm, entries int) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetGlobalEntryLimit", "entries", fmtI(entries))
	if entries < 1 || entries > 1024 {
		panic("nslogic: the globals cap must be 1-1024")
	}
	nsdata.SetGlobalEntryLimitRecord(cross(cur), entries)
}

// SetAccountLimits bounds the vault's per-address store: field name,
// value, and fields per address. Small numbers, because whoever's
// transaction writes a field pays for it.
func SetAccountLimits(cur realm, keyLen, valueLen, entries int) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetAccountLimits", "keyLen", fmtI(keyLen), "valueLen", fmtI(valueLen), "entries", fmtI(entries))
	// Never below what this realm writes (the vault's defaults, 16/128/8):
	// a tiny limit refused every later grant, redemption and referral
	// count, deletes included — L-2's bug on the per-address store
	// (review follow-up).
	if keyLen < 16 || keyLen > 64 || valueLen < 128 || valueLen > 1024 || entries < 8 || entries > 64 {
		panic("nslogic: account limits must be 16-64 / 128-1024 / 8-64")
	}
	nsdata.SetAccountLimitsRecord(cross(cur), keyLen, valueLen, entries)
}

/*
SetMarketFee is nsmarket's fee control, living here because this is the
realm the vault trusts.

nsmarket.SetFee could never work: it wrote through nsdata.SetGlobalRecord
from a realm deliberately outside the trusted set, so it passed its own
admin check and then panicked inside the vault for every caller. Rather
than grant nsmarket vault privileges — which would surrender the property
that realm is built around — the setter moved to the realm that already
has the grant, and the validation moved with it.

The spec grammar is nsmarket's, restated here rather than imported so
this realm does not take a dependency on the marketplace to set a number:
an amount in ugnot ("1000000"), or a percentage ("%2.5"); "0" for none,
because "" removes the key and nsmarket then charges its default of one
GNOT. A malformed spec would otherwise be read on every sale and resolve
silently to zero.

A CHANGE THAT COULD RAISE THE FEE IS TIMELOCKED. The fee is read at sale
time, so a raise lands on listings sellers made under the old one — up to
half of their sale, moved to the treasury, with no notice. A timelocked
raise is the notice: sellers see ActionProposed and may unlist. Lowering
it, or switching it off, stays instant.
*/
func SetMarketFee(cur realm, spec string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetMarketFee", "spec", spec)
	assertValidFeeSpec(spec)
	spec = strings.TrimSpace(spec)
	if feeCouldRise(nsdata.GetGlobal(keyMarketFee), spec) {
		requireAction(cur, actionID("SetMarketFee", spec))
	}
	setGlobal(cur, keyMarketFee, spec)
}

const (
	keyMarketFee = "marketfee"
	// nsmarket's fee when the global is unset: one GNOT, flat. Restated
	// rather than imported, like the grammar, so this realm takes no
	// dependency on the marketplace to set a number.
	defaultMarketFee = "1000000"
)

// feeCouldRise reports whether moving from the stored spec `old` to `next`
// could raise the fee on any sale. Both are read the way nsmarket reads
// them: unset means the default. A move to zero never rises; a change of
// kind — flat to percentage or back — rises on some price, so it counts.
func feeCouldRise(old, next string) bool {
	of, ob := feeParts(old)
	nf, nb := feeParts(next)
	switch {
	case nf == 0 && nb == 0:
		return false
	case of == 0 && ob == 0:
		return true
	case ob == 0 && nb == 0:
		return nf > of
	case of == 0 && nf == 0:
		return nb > ob
	}
	return true
}

// feeParts splits a spec into (flat ugnot, basis points), the way
// nsmarket.parseFee does; unset is the default fee, and an unreadable spec
// is zero — which is also how nsmarket charges it.
func feeParts(spec string) (flat, bps int64) {
	spec = strings.TrimSpace(spec)
	if spec == "" {
		spec = defaultMarketFee
	}
	if !strings.HasPrefix(spec, "%") {
		n, err := strconv.ParseInt(spec, 10, 64)
		if err != nil || n < 0 {
			return 0, 0
		}
		return n, 0
	}
	body := spec[1:]
	whole, frac := body, ""
	if dot := strings.Index(body, "."); dot >= 0 {
		whole, frac = body[:dot], body[dot+1:]
	}
	w, err := strconv.ParseInt("0"+whole, 10, 64)
	if err != nil {
		return 0, 0
	}
	bps = w * 100
	if frac != "" {
		f, err := strconv.ParseInt("0"+frac, 10, 64)
		if err != nil || len(frac) > 1 {
			return 0, 0
		}
		bps += f * 10
	}
	return 0, bps
}

// assertValidFeeSpec mirrors nsmarket.parseFee. Percentages are carried
// as basis points so a fee is expressible without floating point
// anywhere near money.
func assertValidFeeSpec(spec string) {
	spec = strings.TrimSpace(spec)
	if spec == "" {
		return
	}
	if !strings.HasPrefix(spec, "%") {
		n, err := strconv.ParseInt(spec, 10, 64)
		if err != nil || n < 0 {
			panic("nslogic: a fee is an amount in ugnot or a percentage like %2.5 — got " + spec)
		}
		return
	}
	body := spec[1:]
	whole, frac := body, ""
	if dot := strings.Index(body, "."); dot >= 0 {
		whole, frac = body[:dot], body[dot+1:]
	}
	// ONE decimal, matching nsmarket.parseFee exactly. I wrote two here
	// first, which made this validator MORE permissive than the parser
	// that has to read the value back — and a spec nsmarket refuses is
	// read as a zero fee on every sale, silently, forever. A validator
	// looser than its consumer is worse than no validator: it converts a
	// rejected input into a silent revenue leak.
	if len(frac) > 1 {
		panic("nslogic: a fee percentage carries at most one decimal — got " + spec)
	}
	for _, part := range []string{whole, frac} {
		for i := 0; i < len(part); i++ {
			if part[i] < '0' || part[i] > '9' {
				panic("nslogic: a fee percentage must be digits — got " + spec)
			}
		}
	}
	if whole == "" && frac == "" {
		panic("nslogic: a fee percentage needs a number — got " + spec)
	}
	// Basis points the same way parseFee computes them: whole*100 plus
	// one tenth-digit worth ten. Not two digits, and not a 100% ceiling
	// — nsmarket caps at maxFeeBps, which is 50%.
	w, _ := strconv.ParseInt("0"+whole, 10, 64)
	bp := w * 100
	if frac != "" {
		f, _ := strconv.ParseInt("0"+frac, 10, 64)
		bp += f * 10
	}
	if bp <= 0 || bp > 5000 {
		panic("nslogic: a fee percentage must be above zero and at most 50 — got " + spec)
	}
}

// SetGlobal writes an arbitrary project-wide key into the vault's
// package-level extension slot — the escape hatch for global state that
// does not exist yet, and for keys other realms read (cardfx). It refuses
// every key a setter here owns: the escape hatch used to walk round every
// bound and timelock on them. See managedGlobal.
func SetGlobal(cur realm, key, value string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetGlobal", "key", key, "value", value)
	if managedGlobal(key) {
		panic("nslogic: " + key + " has its own setter, with its own rules; use that")
	}
	setGlobal(cur, key, value)
}

func setGlobal(cur realm, key, value string) {
	/* THE RESTORE SEAL IS NOT AN ORDINARY GLOBAL.
	   restore.gno says sealing is "IRREVERSIBLE… There is no argument
	   that unseals it". One admin call writing key "restore" used to
	   reopen it. The vault now refuses both keys through its general
	   setter and refuses to change a seal through its reserved one, so a
	   logic swap cannot drop the guard; this check stays so the refusal
	   names the right door. */
	if key == keyRestore || key == keyRestoredCount {
		panic("nslogic: " + key + " is written by the restore machinery, not by SetGlobal")
	}
	if err := nsdata.SetGlobalRecord(cross(cur), key, value); err != nil {
		panic(err)
	}
}

// SetTreasury moves the revenue-receiving role — independent of
// nsdata's TransferAdmin, same reasoning as the original build's
// admin/treasury separation.
//
// TIMELOCKED. It took effect at once and said nothing, so a stolen admin
// key redirected every later sale — names, renewals, skins, market fees —
// in one call (audit M4). Now it is announced and waits, and recovery can
// cancel it.
func SetTreasury(cur realm, newTreasury address) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetTreasury", "addr", newTreasury.String())
	if !newTreasury.IsValid() {
		panic("nslogic: invalid treasury address")
	}
	requireAction(cur, actionID("SetTreasury", newTreasury.String()))
	nsdata.SetTreasuryRecord(cross(cur), newTreasury)
}

// SelfAddress reports this deployed realm's own address — needed once,
// at wiring time, so admin knows what to pass to
// nsdata.ProposeTrustedLogicGrant.
func SelfAddress(cur realm) address {
	return cur.Address()
}

blocked.gno

package nslogic

import (
	"strings"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

/*
THE BLOCK LIST: labels nobody may hold, at any price.

This is NOT the reserved list, and confusing the two would undo both.

	reserved (collections/reserved-labels.json, 232 labels) says
	"blocked from the free tier, buyable at list price like anything
	else". admin*meme being purchasable is deliberate: the harm it
	guards against is handing a phishing address out for nothing, not
	the existence of the name. That list is enforced by the issuer,
	which is the only place that decides what is free.

	THIS list says "not available, full stop". It is the small set where
	the answer does not change when somebody offers money: names that
	impersonate the registry itself, and the registry's own names.

WHY IT LIVES IN THE VAULT'S GLOBALS RATHER THAN IN THIS FILE.

Baking it in would mean a logic deploy to block a word, and the words
worth blocking are exactly the ones discovered after launch — the label
somebody tried yesterday that nobody thought of. Globals are writable by
the admin, survive a logic swap because they belong to the vault, and
cost storage only for what is actually stored.

Chunked because a global value is capped at 512 bytes. Eight chunks is
about four kilobytes, or several hundred labels, which is far more than
this list should ever need — if it grows past that, the thing being
built is a content policy and it belongs off chain where it can be
updated without a transaction.

FAILS OPEN, and that is the uncomfortable choice, so it is written down.
An unreadable chunk blocks nothing rather than blocking everything.
Failing closed here would mean one malformed global takes the whole
registry offline — every registration, for everyone, until an admin
notices. The harm from a blocked label slipping through is one bad name
that an admin can freeze; the harm from failing closed is total. The
list is also not the only defence: the issuer holds the reserved list,
and FreezeName exists for anything that gets past both.
*/

const (
	blockChunks   = 8
	blockKeyStem  = "block"
	blockChunkMax = 512
)

// blockKey is the global name for one chunk: block0 … block7.
func blockKey(i int) string {
	return blockKeyStem + string(rune('0'+i))
}

/*
BlockedLabel reports whether a label may not be registered at all.

Compares against the label as the registry stores it — lowercase, already
validated — so a caller cannot slip past with different casing. Every
comparison is exact: this list holds whole labels, not substrings,
because "contains" matching turns a list of a dozen words into an
unpredictable filter that refuses names nobody meant to refuse.
*/
func BlockedLabel(label string) bool {
	if label == "" {
		return false
	}
	want := strings.ToLower(label)
	for i := 0; i < blockChunks; i++ {
		v := nsdata.GetGlobal(blockKey(i))
		if v == "" {
			continue
		}
		for _, e := range strings.Split(v, ",") {
			if strings.ToLower(strings.TrimSpace(e)) == want {
				return true
			}
		}
	}
	return false
}

// BlockList returns one chunk, so the panel can show and edit what is
// actually stored rather than what somebody believes is stored.
func BlockList(i int) string {
	if i < 0 || i >= blockChunks {
		return ""
	}
	return nsdata.GetGlobal(blockKey(i))
}

// BlockChunks is the number of chunks, so the panel does not hard-code a
// constant that this file might later change.
func BlockChunks() int { return blockChunks }

/*
SetBlockList replaces one chunk. Admin only.

Replaces rather than appends: an append-only list has no way to correct a
mistake, and a mistake here refuses somebody a name for reasons nobody
can see. The panel reads the chunk, edits it, and writes it back whole.
*/
func SetBlockList(cur realm, i int, csv string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetBlockList", "chunk", fmtI(i), "csv", csv)
	if i < 0 || i >= blockChunks {
		panic("nslogic: chunk out of range")
	}
	if len(csv) > blockChunkMax {
		panic("nslogic: that chunk is longer than a global may be")
	}
	// Normalised on the way in, so the comparison above never has to
	// account for whatever spacing somebody typed into a form.
	parts := strings.Split(csv, ",")
	out := []string{}
	for _, p := range parts {
		p = strings.ToLower(strings.TrimSpace(p))
		if p != "" {
			out = append(out, p)
		}
	}
	setGlobal(cur, blockKey(i), strings.Join(out, ","))
}

// assertNotBlocked is the gate both doors pass through — the paid
// registration and the free grant. One function, called twice, because
// a block that only covers one route is not a block.
func assertNotBlocked(label string) {
	if BlockedLabel(label) {
		panic("nslogic: " + label + " is not available")
	}
}

credits.gno

package nslogic

import (
	"chain"
	"strconv"
	"strings"
	"time"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

/*
CREDITS: a free registration, granted to an address ahead of time.

WHY. Two plans need it (MAINNET.md §0):
  - the migration grant: every wallet that registered a name on testnet
    gets one free name on mainnet, of its own choosing;
  - onboarding: somebody who holds no GNOT at all is given a name, and
    the project registers it FOR them.

WHERE IT LIVES. In the vault's per-address store, never in this realm, so
a logic swap neither loses nor repeats anybody's credit — and not in
globals, which cannot hold an address-sized key at all.

THE RECORD is one field, "cr", holding "granted,used,expires,held,at":

	granted  credits issued in total. A grant SETS this number, it never
	         adds to it, so re-running a grant batch after people have
	         redeemed cannot hand anybody a second name;
	used     credits redeemed;
	expires  the unix second they lapse, 0 for none (the claim window
	         still bounds every credit);
	held     1: the name is minted with the free-tier hold — usable and
	         renewable, not sellable until upgraded at list price. Only a
	         grant made with sellable=false writes 1;
	at       the unix second of the grant (re-audit 2026-10-16, M-2), so
	         recovery can void what a stolen admin key granted
	         (nsdata.VoidGrantsSince) and the honest admin can grant again
	         what was legitimate. A record written before this field reads
	         as granted at 0.

AN INCIDENT CAN UNDO A GRANT. What a thief granted used to outlive its
eviction: the credits live in the vault, and nothing could touch them while
the logic was revoked and the registry paused, so the thief's wallets
redeemed in the block that unpaused it. Now the vault's incident switches
(nsdata incident.gno) hold: no credit is spent while the registry is
paused, while recovery's quarantine runs, or once recovery has voided the
time it was granted in; and the guardian's Disarm shuts the claim window.

SELLABLE BY DEFAULT (Ely, 2026-10-16). A credit buys a real name, minted
like a paid one and free to sell, unless the grant says otherwise: the
per-grant flag is `sellable`, and every caller passes true unless it means
to hand out a held name. The record keeps the hold bit, so its stored form
did not change; the API speaks in the direction the default runs.

WHO PAYS THE STORAGE DEPOSIT. Whoever SIGNS, and nobody else can. The
chain charges a call's storage deposit and its gas to the transaction's
signer (gno.land/pkg/sdk/vm keeper.go, lockStorageDeposit(ctx, caller,
...)); a realm cannot pay either on somebody's behalf, and this one holds
no coins to try. So there are two doors, and both spend the holder's
credit:

	RedeemCredit  the holder signs. The name costs nothing; the holder
	              pays the storage deposit (about 0.57 GNOT) and gas.
	RegisterFor   the admin or the granter signs and the project pays
	              both; the name goes to the holder. This is the only
	              path for a holder with no GNOT, who cannot sign at all.

WHAT A CREDIT BUYS. One ordinary registration at no price: any open
domain, any label the ordinary rules allow, up to a list price cap
(ClaimMaxPriceUSD) — the on-chain answer to MAINNET.md's "do premium names
count?", left settable rather than decided here. UNSET, THE CAP COVERS
NOTHING and no credit redeems (re-audit 2026-10-16, H-1): it used to fall
back to the default name price, and the default rises fast. The deploy
sets it explicitly (tools/deploy-gen.sh, CLAIMMAX).

GRANTED BY THE ADMIN, AND NOT TIMELOCKED, deliberately. A credit can only
create a registration of a name nobody holds: it never touches an
existing holder, moves no money, works only inside the claim window and
only under the price cap. A stolen admin key can gift itself cheap names
until it is rotated out — the same order of harm as the free tier, and
far smaller than anything the timelock guards. A 48-hour wait on every
grant would make "register it for them now" impossible.
*/

const (
	keyCredit   = "cr"       // account field: the record above
	keyClaimEnd = "claimend" // global: unix second the claim window closes; unset means closed
	keyClaimMax = "claimmax" // global: highest list price, micro-USD, a credit covers

	maxCreditsPerAddress = 100
	maxGrantBatch        = 100
	maxClaimWindowDays   = 730 // one setting cannot promise more than two years
)

type credit struct {
	granted, used, expires int64
	held                   bool
	at                     int64 // when granted; 0 for a record from before the field
}

// parseCredit FAILS CLOSED: anything it cannot read is no credit at all.
// A malformed record must never be read as a free name. Four fields is the
// record before the grant time existed; five carries it.
func parseCredit(v string) credit {
	if v == "" {
		return credit{}
	}
	f := strings.Split(v, ",")
	if (len(f) != 4 && len(f) != 5) || (f[3] != "0" && f[3] != "1") {
		return credit{}
	}
	g, e1 := strconv.ParseInt(f[0], 10, 64)
	u, e2 := strconv.ParseInt(f[1], 10, 64)
	x, e3 := strconv.ParseInt(f[2], 10, 64)
	if e1 != nil || e2 != nil || e3 != nil || g < 0 || u < 0 || x < 0 {
		return credit{}
	}
	c := credit{granted: g, used: u, expires: x, held: f[3] == "1"}
	if len(f) == 5 {
		at, e4 := strconv.ParseInt(f[4], 10, 64)
		if e4 != nil || at < 0 {
			return credit{}
		}
		c.at = at
	}
	return c
}

func (c credit) encode() string {
	h := "0"
	if c.held {
		h = "1"
	}
	return strconv.FormatInt(c.granted, 10) + "," + strconv.FormatInt(c.used, 10) + "," +
		strconv.FormatInt(c.expires, 10) + "," + h + "," + strconv.FormatInt(c.at, 10)
}

// voided reports whether recovery voided the time this credit was granted.
func (c credit) voided() bool { return c.granted > c.used && nsdata.GrantVoided(c.at) }

// available is how many may be redeemed at `now`.
func (c credit) available(now int64) int64 {
	if c.expires != 0 && now >= c.expires {
		return 0
	}
	if c.used >= c.granted {
		return 0
	}
	return c.granted - c.used
}

func readCredit(owner address) credit { return parseCredit(nsdata.GetAccount(owner, keyCredit)) }

func writeCredit(cur realm, owner address, c credit) {
	v := c.encode()
	// Nothing granted and nothing used is no record: free the storage.
	// A record with redemptions stays, because `used` is what stops a
	// repeated grant from handing out a second name.
	if c.granted == 0 && c.used == 0 {
		v = ""
	}
	if err := nsdata.SetAccountRecord(cross(cur), owner, keyCredit, v); err != nil {
		panic("nslogic: " + err.Error())
	}
}

// CreditsOf reports an address's credits: how many it may redeem right
// now, and the record behind that answer. `sellable` is whether the names
// they buy come without the free-tier hold — true unless the grant said not.
// Credits recovery voided are not available; the window, a pause and a
// quarantine are the registry's state, reported by CreditRefusal.
func CreditsOf(owner address) (available, granted, used, expires int64, sellable bool) {
	c := readCredit(owner)
	a := c.available(time.Now().Unix())
	if c.voided() {
		a = 0
	}
	return a, c.granted, c.used, c.expires, !c.held
}

// CreditGrantedAt is when an address's credits were last granted (unix
// seconds; 0 for none, or for a record from before the field existed).
func CreditGrantedAt(owner address) int64 { return readCredit(owner).at }

// -- the window and the cap --

// ClaimWindowEnd is the unix second redemption closes, or 0 when no
// window is set — which means CLOSED. An entitlement nobody bounded is a
// liability that never ends, so the default is no window at all.
func ClaimWindowEnd() int64 {
	v := nsdata.GetGlobal(keyClaimEnd)
	if v == "" {
		return 0
	}
	end, err := strconv.ParseInt(v, 10, 64)
	if err != nil || end < 0 {
		return 0
	}
	return end
}

func ClaimWindowOpen() bool { return readClaimWindow(nsdata.GetGlobal(keyClaimEnd), time.Now().Unix()) }

// readClaimWindow fails closed on anything it cannot read, the same rule
// the free tier's window follows: a mistyped setting must not give names away.
func readClaimWindow(v string, now int64) bool {
	if v == "" {
		return false
	}
	end, err := strconv.ParseInt(v, 10, 64)
	if err != nil {
		return false
	}
	return now < end
}

// SetClaimWindow opens redemption until `end` (unix seconds), at most two
// years ahead, or closes it with 0. Closing is the one call to reach for
// on a Sunday when something about the grants looks wrong.
func SetClaimWindow(cur realm, end int64) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetClaimWindow", "end", fmtInt(end))
	if end == 0 {
		setGlobal(cur, keyClaimEnd, "")
		return
	}
	now := time.Now().Unix()
	if end <= now || end > now+maxClaimWindowDays*86400 {
		panic("nslogic: a claim window ends in the future and at most " +
			strconv.Itoa(maxClaimWindowDays) + " days ahead; 0 closes it")
	}
	setGlobal(cur, keyClaimEnd, strconv.FormatInt(end, 10))
}

/*
ClaimMaxPriceUSD is the highest list price, in micro-USD, a credit can be
spent on, or 0 while no cap is set — and while none is set no credit
redeems at all (ClaimCapSet).

IT NEVER FOLLOWS THE DEFAULT PRICE (re-audit 2026-10-16, H-1). It used to
fall back to DefaultPriceUSD while unset, which is how a registry is born.
The default moves fast in its "dearer" direction — four times, every ten
minutes, instantly — and premium prices do not move with it, so each
dearer step on the default carried the cap past another tier of premium
names: a stolen admin key took the $300 x*doge with a free credit in forty
minutes, never touching SetClaimMaxPrice, whose raise is meant to be the
slow step. So the cap stands on its own now, an unset or unreadable one
covers nothing, and the first cap is a decision (SetClaimMaxPrice).
*/
func ClaimMaxPriceUSD() int64 {
	p, _ := claimCap()
	return p
}

// ClaimCapSet reports whether a cap is set at all. Unset — or unreadable,
// which is read the same way — no credit can be spent on anything.
func ClaimCapSet() bool {
	_, ok := claimCap()
	return ok
}

func claimCap() (int64, bool) {
	v := nsdata.GetGlobal(keyClaimMax)
	if v == "" {
		return 0, false
	}
	p, err := strconv.ParseInt(v, 10, 64)
	if err != nil || p < 0 {
		return 0, false
	}
	return p, true
}

// SetClaimMaxPrice is BOUNDED like a price (timelock.gno), with the
// direction turned round: RAISING the cap is what makes names cheaper — a
// credit then covers pricier names, premium ones in the end — so a raise is
// the slow step (25%, once an hour) and a cut the fast one (down to a
// quarter, every ten minutes). Anything else is a timelocked proposal.
//
// THE FIRST CAP IS NOT A STEP. From no cap there is nothing to step from,
// so setting one is always the timelocked proposal: instant at a fresh
// vault's delay of zero, which is when the deploy sets it, and recovery's
// to veto once the delay is raised.
func SetClaimMaxPrice(cur realm, microUsd int64) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetClaimMaxPrice", "microUsd", fmtInt(microUsd))
	if microUsd < 0 || microUsd > maxPriceUSD {
		panic("nslogic: the claim cap must be 0.." + strconv.FormatInt(maxPriceUSD, 10) + " micro-USD")
	}
	v := strconv.FormatInt(microUsd, 10)
	id := actionID("SetClaimMaxPrice", v)
	old, set := claimCap()
	if !set {
		requireAction(cur, id)
		// A cap from nothing is the cheaper direction for claimants: the
		// next raise waits the cheap clock's hour like any other.
		lastTweak.Set(clockKey(keyClaimMax, false), time.Now().Unix())
	} else {
		authorizeTweak(cur, keyClaimMax, old, microUsd, microUsd < old, id)
	}
	setGlobal(cur, keyClaimMax, v)
}

// -- granting --

// GrantCredits SETS how many free registrations `to` is entitled to in
// total, with an optional expiry (0 for none) and whether the names they
// buy are SELLABLE — true is the default to pass; false mints them with
// the free-tier hold. 0 revokes whatever is unredeemed. See the note at
// the top of this file on why a grant sets rather than adds.
func GrantCredits(cur realm, to address, n, expires int64, sellable bool) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "GrantCredits", "to", to.String(), "n", fmtInt(n), "expires", fmtInt(expires), "sellable", fmtBool(sellable))
	grantCredits(cur, to, n, expires, sellable, time.Now().Unix())
}

// GrantCreditsBatch is GrantCredits for a comma-separated list of
// addresses, up to 100 a call — the migration grant is one entry per
// testnet wallet. Returns how many were written. One bad address fails
// the whole batch, so a typo cannot silently leave somebody out.
func GrantCreditsBatch(cur realm, addrs string, n, expires int64, sellable bool) int {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "GrantCreditsBatch", "addrs", addrs, "n", fmtInt(n), "expires", fmtInt(expires), "sellable", fmtBool(sellable))
	parts := strings.Split(addrs, ",")
	if len(parts) > maxGrantBatch {
		panic("nslogic: at most " + strconv.Itoa(maxGrantBatch) + " addresses per batch")
	}
	now := time.Now().Unix()
	done := 0
	for _, p := range parts {
		p = strings.TrimSpace(p)
		if p == "" {
			continue
		}
		grantCredits(cur, address(p), n, expires, sellable, now)
		done++
	}
	return done
}

func grantCredits(cur realm, to address, n, expires int64, sellable bool, now int64) {
	if !to.IsValid() {
		panic("nslogic: not an address: " + to.String())
	}
	if n < 0 || n > maxCreditsPerAddress {
		panic("nslogic: a grant is 0.." + strconv.Itoa(maxCreditsPerAddress) + " credits")
	}
	if expires != 0 && expires <= now {
		panic("nslogic: credits that have already expired are not a grant; pass 0 for no expiry")
	}
	c := readCredit(to)
	c.granted, c.expires, c.held, c.at = n, expires, !sellable, now
	writeCredit(cur, to, c)
}

// -- redeeming --

// RedeemCredit registers label*domain to the caller and spends one of the
// caller's credits. The caller signs, so the caller pays the storage
// deposit and gas; the name itself costs nothing.
func RedeemCredit(cur realm, label, domainLabel string) {
	assertNoSend(cur)
	redeemCredit(cur, cur.Previous().Address(), label, domainLabel)
}

// RegisterFor registers label*domain to `owner` and spends one of
// OWNER'S credits — the project signs and pays the storage and gas, which
// is the only way a holder with no GNOT can get a name at all. Admin or
// granter: the same machine that issues free names relays these, and it
// can spend only credits the admin granted, only into the holder's own
// wallet.
func RegisterFor(cur realm, owner address, label, domainLabel string) {
	assertNoSend(cur)
	assertMayGrant(cur)
	emitAdmin(cur, "RegisterFor", "owner", owner.String(), "label", label, "domain", domainLabel)
	if !owner.IsValid() {
		panic("nslogic: a registration needs a recipient")
	}
	redeemCredit(cur, owner, label, domainLabel)
}

// CreditRefusal is why `owner` could not spend a credit on label*domain
// right now, or "" when nothing about the credit stands in the way. For
// the site, before anybody signs; the label rules are checked separately.
func CreditRefusal(owner address, label, domainLabel string) string {
	return creditRefusal(owner, label, domainLabel, time.Now().Unix())
}

func creditRefusal(owner address, label, domainLabel string, now int64) string {
	if nsdata.IsPaused() {
		return "the registry is paused"
	}
	if q := nsdata.QuarantineUntil(); now < q {
		return "recovery has quarantined giveaways until unix " + strconv.FormatInt(q, 10)
	}
	if !readClaimWindow(nsdata.GetGlobal(keyClaimEnd), now) {
		return "the claim window is closed"
	}
	c := readCredit(owner)
	if c.available(now) <= 0 {
		if c.granted > c.used && c.expires != 0 && now >= c.expires {
			return "this address's credits have expired"
		}
		return "this address has no credit to spend"
	}
	if c.voided() {
		return "recovery voided the credits granted to this address at unix " + strconv.FormatInt(c.at, 10) +
			"; the admin may grant them again"
	}
	most, set := claimCap()
	if !set {
		return "credits are off: no claim cap is set, and an unset cap covers nothing"
	}
	if p := NamePriceUSD(domainLabel, label); p > most {
		return "a credit covers names listed at up to " + strconv.FormatInt(most, 10) +
			" micro-USD, and this one lists at " + strconv.FormatInt(p, 10)
	}
	return ""
}

/*
redeemCredit is both doors. Every check runs before anything is written,
the registration lands before the credit is spent, and either failing
reverts the other: the credit cannot be spent on a name that did not
arrive, and a name cannot arrive without its credit being spent.
*/
func redeemCredit(cur realm, owner address, label, domainLabel string) {
	assertNotRestoring()
	validateLabel(label)
	assertNotBlocked(label)
	if !DomainOpen(domainLabel) {
		panic("nslogic: this domain is not accepting new names")
	}
	now := time.Now().Unix()
	if r := creditRefusal(owner, label, domainLabel, now); r != "" {
		panic("nslogic: " + r)
	}
	c := readCredit(owner)
	if err := nsdata.RegisterNameRecord(cross(cur), label, domainLabel, owner, now, !c.held); err != nil {
		panic(err)
	}
	c.used++
	writeCredit(cur, owner, c)
	chain.Emit("CreditRedeemed", "tid", label+"*"+domainLabel, "owner", owner.String(),
		"by", cur.Previous().Address().String())
}

domain.gno

package nslogic

import (
	"strconv"
	"strings"
	"time"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// RegisterDomain mints a new `*domain` — ADMIN-ONLY (2026-08-15 policy:
// domains are never sold or owned by third parties). No payment: the
// project isn't paying itself. Domains are also permanently
// non-transferable by users (see nft.gno's TransferFrom).
func RegisterDomain(cur realm, label string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "RegisterDomain", "label", label)
	validateLabel(label)
	caller := cur.Previous().Address()
	if err := nsdata.RegisterDomainRecord(cross(cur), label, caller, time.Now().Unix()); err != nil {
		panic(err)
	}
}

// RenewDomain extends a domain's expiry by exactly one year from its
// PREVIOUS due date, not from the payment date. No payment — domains are
// always project-owned, so this is self-service upkeep, not a sale.
// Deliberately does not call validateLabel — a tightened pattern only
// gates new registrations, never renewals of what's already registered.
func RenewDomain(cur realm, label string) {
	assertNoSend(cur)
	caller := cur.Previous().Address()
	if err := nsdata.RenewDomainRecord(cross(cur), label, caller, time.Now().Unix()); err != nil {
		panic(err)
	}
}

// ReassignDomain moves a domain record to a new owner. ADMIN-ONLY, and
// the deliberate exception to "domains are non-transferable".
//
// It exists because domain ownership is snapshotted into the record at
// registration time, while `admin` is a rotatable role. After the
// planned EOA-to-multisig rotation, the incoming admin could not renew
// or reprice any domain the outgoing key had registered — and if the
// rotation happened *because* the old key was compromised, the attacker
// could still reprice those domains afterwards. This is the recovery
// lever for exactly that situation.
//
// Not a loophole in the non-transferability policy: that policy exists
// to stop domains reaching third parties as tradeable assets, and this
// path is reachable only by the current admin, moving a project domain
// between project-controlled addresses.
//
// TIMELOCKED (timelock.gno): a stolen admin key could otherwise move every
// project domain to itself in one block. Genesis domains run ten years, so
// the honest recovery this exists for loses nothing by waiting.
func ReassignDomain(cur realm, label string, newOwner address) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "ReassignDomain", "label", label, "to", newOwner.String())
	if !newOwner.IsValid() {
		panic("nslogic: invalid owner address")
	}
	requireAction(cur, actionID("ReassignDomain", label, newOwner.String()))
	/* THE STOPGAP IS GONE. This used to read the domain's settings back
	   and rewrite them around a token transfer, because that transfer
	   wiped them. Domains are records now, and nsdata moves the owner
	   without touching price, len, nm, open or maxterm. */
	if err := nsdata.ReassignDomainRecord(cross(cur), label, newOwner); err != nil {
		panic(err)
	}
}

// -- pricing controls (admin) --
//
// Every amount here is MICRO-USD (1 USD = 1_000_000). Nothing is priced
// in the chain token; ugnot is derived at payment time from the stored
// rate, so a second settlement token later is a second rate rather than
// a second price list.

// SetDomainOpen enables or disables registration of new names under a
// domain. Existing names are untouched: closing a domain stops new
// mints, it does not seize anything already held.
func SetDomainOpen(cur realm, label string, open bool) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetDomainOpen", "label", label, "open", fmtBool(open))
	v := "1"
	if !open {
		v = "0"
	}
	setDomainExtra(cur, label, keyOpen, v)
}

// SetDomainBasePrice sets the domain's base price in micro-USD. Every
// "%N" rule under the domain is relative to this, so one call reprices
// the whole domain. BOUNDED (timelock.gno): a raise up to four times every
// ten minutes, a cut up to 25% once an hour; a move to or from free, or
// anything larger, is a timelocked proposal.
func SetDomainBasePrice(cur realm, label string, microUsd int64) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetDomainBasePrice", "label", label, "microUsd", fmtInt(microUsd))
	if microUsd < 0 || microUsd > maxPriceUSD {
		panic("nslogic: a price is 0.." + strconv.FormatInt(maxPriceUSD, 10) + " micro-USD")
	}
	v := strconv.FormatInt(microUsd, 10)
	old := DomainBasePriceUSD(label)
	own := keyPrice + ":" + label
	clocks := []string{own}
	if nsdata.GetDomainExtra(label, keyPrice) == "" {
		// Still on the default: its first own price is a move of the
		// default's too, on the default's clocks (timelock.gno, re-audit L-1),
		// and the domain takes the default's clocks with it — or a first
		// price EQUAL to the default, which moves nothing and stamps nothing,
		// left a fresh clock for the next cut (review follow-up).
		inheritClocks(own, keyDefaultPrice)
		clocks = append(clocks, keyDefaultPrice)
	}
	authorizeTweakOn(cur, clocks, old, microUsd, microUsd > old,
		actionID("SetDomainBasePrice", label, v))
	setDomainExtra(cur, label, keyPrice, v)
}

// SetDomainLengthRules prices by label length: "3:2000000,4:%150,5:0"
// means 3-char names cost $2.00, 4-char names cost 150% of the domain
// base, and 5-char names are free.
//
// TIMELOCKED, with the price rules below: one rule can make any length
// free ("3:0"), so a rule set is not a tweak whatever it says. Propose the
// NORMALISED form, which the refusal prints.
func SetDomainLengthRules(cur realm, label, rules string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetDomainLengthRules", "label", label, "rules", rules)
	norm := normalizeRules(rules, true)
	requireAction(cur, actionID("SetDomainLengthRules", label, norm))
	setDomainExtra(cur, label, keyLens, norm)
}

// SetDomainNameOverrides prices specific labels: "420:5000000,gm:%500".
// Highest precedence — this beats length rules and the base. TIMELOCKED,
// like the length rules: "premiumname:0" was a one-call way to take one.
func SetDomainNameOverrides(cur realm, label, rules string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetDomainNameOverrides", "label", label, "rules", rules)
	norm := normalizeRules(rules, false)
	requireAction(cur, actionID("SetDomainNameOverrides", label, norm))
	setDomainExtra(cur, label, keyNames, norm)
}

// SetDomainField writes an arbitrary key on a domain, for whatever a
// future feature needs without a vault change — the domain's art among
// them. It refuses the keys this realm's own setters own, which it used
// to write straight past ("price" to zero, with no bound).
func SetDomainField(cur realm, label, key, value string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetDomainField", "label", label, "key", key, "value", value)
	if strings.HasPrefix(key, "_") {
		panic("nslogic: keys beginning with '_' are reserved")
	}
	if managedDomainKey(key) {
		panic("nslogic: " + key + " has its own setter, with its own rules; use that")
	}
	setDomainExtra(cur, label, key, value)
}

func setDomainExtra(cur realm, label, key, value string) {
	if err := nsdata.SetDomainExtraRecord(cross(cur), label, key, value); err != nil {
		panic(err)
	}
}

// FreezeDomain / UnfreezeDomain: project-only power to permanently block
// re-registration of a domain even after its grace period lapses.
// DeleteDomain destroys a domain and every name beneath it.
//
// THE VAULT PRIMITIVE EXISTED BEFORE THIS DID, AND THAT MADE IT
// UNREACHABLE. nsdata.DeleteDomainRecord gates on assertIsTrustedLogic,
// so the only way to reach it is a function in this realm — and there
// was not one. The capability shipped in the vault and could not be
// used, which is worse than not shipping it, because it reads as
// present.
//
// Bounded by the vault at maxDeletePerCall names per call. It returns
// how many it removed and whether it finished, so a large domain is
// several calls rather than a transaction that cannot fit in a block.
// Repeat until done is true; calling it on a domain that is already gone
// reports done rather than panicking, so a loop terminates cleanly.
//
// ADMIN ONLY, and deliberately not owner-callable: domains are
// project-owned (SPEC.md §17b) and this destroys other people's names.
//
// TIMELOCKED (timelock.gno). It burned every live name under a domain at
// once — and paid the deleter the holders' storage deposits, about 57 GNOT
// per hundred names. One proposal, "DeleteDomain <label>", covers every
// call of a multi-call deletion while it stays matured, and is spent by
// the call that finishes; recovery can cancel it between calls.
func DeleteDomain(cur realm, label string) (removed int64, done bool) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "DeleteDomain", "label", label)
	id := actionID("DeleteDomain", label)
	assertActionReady(id)
	removed, done = nsdata.DeleteDomainRecord(cross(cur), label)
	if done {
		nsdata.ConsumeAction(cross(cur), id)
	}
	return removed, done
}

// SetDomainTTL sets how long a resolver may cache answers about this
// domain, in seconds, where 0 means never cache — the ENS rule. Admin
// only, since domains are project-owned.
func SetDomainTTL(cur realm, label string, seconds int64) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetDomainTTL", "label", label, "seconds", fmtInt(seconds))
	if seconds < 0 || seconds > maxTTL {
		panic("nslogic: a ttl is 0.." + fmtInt(maxTTL) + " seconds")
	}
	if err := nsdata.SetDomainTTLRecord(cross(cur), label, seconds); err != nil {
		panic(err)
	}
}

func FreezeDomain(cur realm, label string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "FreezeDomain", "label", label)
	nsdata.SetDomainFrozen(cross(cur), label, true)
}

func UnfreezeDomain(cur realm, label string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "UnfreezeDomain", "label", label)
	nsdata.SetDomainFrozen(cross(cur), label, false)
}

events.gno

package nslogic

import (
	"strconv"

	"chain"
)

/*
EVERY ADMIN ACTION EMITS AdminAction, with the signer and the call.

There was no event anywhere in this realm, so a stolen admin key's
treasury change, rate change or deletion was invisible until its effects
showed up somewhere else (audit M-4/M-6). The vault now says what changed
(nsdata/events.gno); this says who asked, through which call, with which
arguments — the line a monitor alerts on. A failed call emits nothing:
an aborted transaction keeps no events.

One event type, "AdminAction", with "fn" naming the call, so a monitor
subscribes once and a new admin call is covered without anybody updating
a list. Profile values replayed by a restore are not repeated here, only
their keys, for the reason given in nsdata/events.gno.
*/
func emitAdmin(cur realm, fn string, kv ...string) {
	attrs := []string{"fn", fn, "by", cur.Previous().Address().String()}
	chain.Emit("AdminAction", append(attrs, kv...)...)
}

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

func fmtI(n int) string { return strconv.Itoa(n) }

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

freetier.gno

package nslogic

import (
	"strconv"
	"time"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

/*
THE FREE TIER: a name somebody can hold without ever owning a wallet.

The vault has supported this since it was written — RegisterNameRecord
takes mintNFT=false and stores a record with no GRC-721 token, and
UpgradeFreeRecord is described there as "the paid free-tier upgrade".
Nothing in the logic realm ever reached either. This is that wiring.

WHY A RECORD WITHOUT A TOKEN IS THE RIGHT SHAPE, and not a compromise:

	IT IS A REAL NAME. Owned, resolvable, renewable, on chain, visible
	to anyone. Not a promise, not a queue position, not a row in our
	database. Everything the paid tier does except be sold.

	IT CANNOT BE SOLD, and that is what makes giving it away safe.
	nsmarket escrows a TOKEN, and there is no token — so a squatter who
	farms a thousand of these has farmed a thousand things nobody can
	buy from them. The anti-abuse property falls out of the data model
	rather than out of a rule somebody has to enforce.

	IT BECOMES SELLABLE BY BECOMING PAID. UpgradeFreeName takes the full
	list price and mints the token. So the same name costs nothing and
	costs full price, and which one depends entirely on whether you want
	to sell it.

WHY THE PROJECT PAYS. The whole point is somebody with no GNOT, and
possibly no wallet, who is going to put this name in front of an
audience. Measured on Pearl: a registration is about 0.04 GNOT of fee
plus a small storage deposit, and a free-tier record is smaller than a
paid one because there is no token and no ledger entry. That is a
marketing cost per name, bounded by a daily cap we apply off chain,
where it can be changed without a deploy.

WHAT IS DELIBERATELY NOT HERE. No wordlist: storage is 100 ugnot a byte,
so a ten-thousand-word dictionary is about 57 GNOT paid forever to
encode a marketing decision that will change. The contract carries the
structural rules in reserved.gno and nothing else; the lists live off
chain with the issuer, which is us, because the free path is granted
rather than bought. See tools/gen-reserved.py.
*/

const (
	keyFreeDomain = "free"     // per-domain: "1" means the free tier is open here
	keyGrantEnd   = "grantend" // global: unix seconds, or "never"
	keyGranter    = "granter"  // global: the address allowed to issue grants
)

/*
THE GRANTER IS NOT THE ADMIN, and that separation is the point.

Free names are issued by a machine — something has to sign the grant
after a person proves an X account, and that key has to sit somewhere
warm. If that key were the admin key, a compromise of the issuing
machine would be a compromise of the registry: DeleteDomain destroys
every name under a domain and burns their tokens, instantly, with no
timelock.

So there is a second role that can do exactly one kind of thing: give
names away on the project's behalf — free-tier grants and renewals, and
RegisterFor, which spends a holder's own credit into the holder's own
wallet (credits.gno). Worst case for a stolen granter key is that
somebody gives away free names, or spends people's credits on names they
did not pick, until we notice and clear the role — a bounded, reversible,
embarrassing loss rather than an unbounded one.

Stored in the vault's globals rather than in this realm, so it survives
a logic redeploy. Unset means nobody but the admin may grant, which is
the right default for a role that exists to be delegated deliberately.
*/
func Granter() address {
	return address(nsdata.GetGlobal(keyGranter))
}

// SetGranter delegates grant issuance, or withdraws it. Passing the
// empty address is the revocation, and it is the first thing to reach
// for if the issuing machine is ever in doubt — instant, always.
//
// NAMING a granter is TIMELOCKED (timelock.gno): a stolen admin key would
// otherwise hand itself a second, quieter key that gives names away and
// spends people's credits, and keep it after the admin key is rotated out.
func SetGranter(cur realm, a address) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetGranter", "addr", a.String())
	if a != "" && !a.IsValid() {
		panic("nslogic: not an address")
	}
	if a != "" {
		requireAction(cur, actionID("SetGranter", a.String()))
	}
	setGlobal(cur, keyGranter, a.String())
}

/*
SetFreeLengths tunes which lengths the free tier will issue.

In the panel rather than in a redeploy: nslogic is about 22 GNOT to
deploy, and "should four-character names be free this month" is a
marketing question that should cost a signature, not a deployment.

IT DOES NOT REACH BACKWARDS. Raising the minimum stops NEW issuance of
short names; every one already granted stays granted and keeps renewing
free. FreeLabelAllowed is called by GrantFreeName and by nothing else,
which is what makes that true — see the note on it in reserved.gno.
*/
func SetFreeLengths(cur realm, min, max int) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetFreeLengths", "min", fmtI(min), "max", fmtI(max))
	if min < 1 || max > 63 || min > max {
		panic("nslogic: a free-tier length range must sit inside 1..63 and be the right way round")
	}
	setGlobal(cur, keyFreeMin, strconv.Itoa(min))
	setGlobal(cur, keyFreeMax, strconv.Itoa(max))
}

func assertMayGrant(cur realm) {
	caller := cur.Previous().Address()
	if caller == nsdata.GetAdmin() {
		return
	}
	g := Granter()
	if g == "" || caller != g {
		panic("nslogic: only the admin or the granter may issue free names")
	}
}

// DomainFree reports whether a domain accepts free-tier registrations.
// Off by default, and per-domain on purpose: the free tier is a
// promotion aimed at a few domains, not a property of the registry.
func DomainFree(domainLabel string) bool {
	return nsdata.GetDomainExtra(domainLabel, keyFreeDomain) == "1"
}

// SetDomainFree opens or closes the free tier for one domain.
func SetDomainFree(cur realm, domainLabel string, on bool) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetDomainFree", "label", domainLabel, "on", fmtBool(on))
	if !nsdata.DomainExists(domainLabel) {
		panic("nslogic: no such domain")
	}
	v := ""
	if on {
		v = "1"
	}
	if err := nsdata.SetDomainExtraRecord(cross(cur), domainLabel, keyFreeDomain, v); err != nil {
		panic(err)
	}
}

/*
GrantWindowOpen reports whether free grants are being issued at all.

A single global switch that closes everything at once, because the
failure this guards against is not a clever attack — it is noticing on a
Sunday that something is wrong and wanting one call that stops it. An
unset value means open; "never" means open with no end date, which is
what the admin panel already writes.
*/
func GrantWindowOpen() bool {
	return readGrantWindow(nsdata.GetGlobal(keyGrantEnd), time.Now().Unix())
}

// readGrantWindow is GrantWindowOpen with the clock and the stored value
// handed in, so the reading can be tested without a chain.
func readGrantWindow(v string, now int64) bool {
	if v == "" || v == "never" {
		return true
	}
	end, err := strconv.ParseInt(v, 10, 64)
	if err != nil {
		// An unparseable window is a misconfiguration, and the safe
		// reading of a misconfigured gate is "closed". Giving names away
		// because a setting was mistyped is the wrong way to fail.
		return false
	}
	return now < end
}

/*
GrantFreeName registers a free-tier record to somebody else.

ADMIN OR GRANTER, and that is the whole trust model: the eligibility rules —
which Twitter account, how old, how many followers, whether the label is
a dictionary word — live off chain with the issuer. Putting them here
would freeze a marketing policy into a realm and cost storage to do it.
What the chain enforces is the part that must not depend on our
correctness: the label is structurally allowed, the domain opted in, and
the window is open.

`owner` may be an address the recipient generated in their browser
seconds ago and has never funded. That is the point.
*/
func GrantFreeName(cur realm, label, domainLabel string, owner address) {
	assertNoSend(cur)
	assertMayGrant(cur)
	emitAdmin(cur, "GrantFreeName", "label", label, "domain", domainLabel, "owner", owner.String())
	assertNotRestoring()

	if !GrantWindowOpen() {
		panic("nslogic: free grants are closed")
	}
	// Recovery's quarantine holds every giveaway shut, whatever the window
	// says (nsdata incident.gno, re-audit 2026-10-16, M-2).
	if q := nsdata.QuarantineUntil(); time.Now().Unix() < q {
		panic("nslogic: recovery has quarantined giveaways until unix " + strconv.FormatInt(q, 10))
	}
	if !DomainFree(domainLabel) {
		panic("nslogic: *" + domainLabel + " does not offer free names")
	}
	if !DomainOpen(domainLabel) {
		panic("nslogic: this domain is not accepting new names")
	}
	validateLabel(label)
	assertNotBlocked(label)
	// The structural backstop. The issuer has already applied the full
	// policy; this is what stops a bug there giving away a four-letter
	// name or a pure-numeric one.
	if !FreeLabelAllowed(label) {
		panic("nslogic: " + label + " is not available on the free tier")
	}
	if !owner.IsValid() {
		panic("nslogic: a grant needs a recipient")
	}

	// paid=false — a token minted with the free-tier hold already on it,
	// so it can never be approved or sold until UpgradeFreeName lifts it.
	if err := nsdata.RegisterNameRecord(cross(cur), label, domainLabel, owner,
		time.Now().Unix(), false); err != nil {
		panic(err)
	}
}

/*
UpgradeFreeName mints the token for a free-tier record, at full price.

This is the only way a free name becomes sellable, and the price is the
ordinary list price with no referral discount — a discount is for
bringing somebody new, and this person is already here.

`newOwner` exists because the common case is somebody who has decided to
sell and, in the same moment, wants the name in a wallet they actually
control rather than the browser key they were given. The vault handles
that move inside UpgradeFreeRecord.

Callable by the record's current owner only. Anyone may PAY for
somebody else's upgrade in the sense that they can hand over the money,
but they cannot perform it — a stranger promoting your name into a token
and choosing where it lands is a theft with a receipt.
*/
func UpgradeFreeName(cur realm, label, domainLabel string, newOwner address) {
	// Not during a restore window: the price rules may not be back yet, and
	// the name would be made sellable at the genesis price (restore.gno).
	assertNotRestoring()
	caller := cur.Previous().Address()
	if nsdata.GetNameOwner(label, domainLabel) != caller {
		panic("nslogic: restricted to name owner")
	}
	if !nsdata.IsNameValid(label, domainLabel) {
		panic("nslogic: this name has expired")
	}
	if newOwner == "" {
		newOwner = caller
	}
	if !newOwner.IsValid() {
		panic("nslogic: invalid destination address")
	}

	// Full list price, resolved now rather than at grant time — the
	// name's worth is what it is worth today, and a free name held for a
	// year should not be upgradable at last year's rate.
	takePaymentSplit(cur, NamePrice(domainLabel, label), "", 0)

	if err := nsdata.UpgradeFreeRecord(cross(cur), label, domainLabel, newOwner); err != nil {
		panic(err)
	}
}

/*
GrantFreeRenewal extends a free-tier name at no charge.

THE DEAL IS THE DISPLAY, and it is checked off chain: the issuer signs
somebody in on X, reads their display name, and finds the name in it.
That single act proves both halves at once — that a real account still
exists, and that it is still carrying the name — which is why renewal is
one click a year rather than a form.

FREE-TIER RECORDS ONLY. A paid name renewed for nothing is revenue given
away by accident, and the two are told apart by whether a token was ever
minted — now, whether the token still carries the free-tier hold. The
hold is the registry's flag, read through GetNameInfo's `paid`.

NO OWNERSHIP PROOF IS ASKED FOR, and that is deliberate rather than
missing. Renewing somebody else's name is a GIFT — it takes nothing,
moves nothing, and grants the caller no power over it. The only cost of
allowing it is ours, and the vault's renewal cap already bounds how far
any single name can be pushed. A proof requirement here would buy
nothing and would cost the one-click renewal that makes the deal work.

RenewNameRecord insists the caller is the owner, so the owner is looked
up and passed. That is not a bypass: this realm is the trusted logic,
and what it is asserting is exactly true — this renewal is on that
owner's behalf.
*/
func GrantFreeRenewal(cur realm, label, domainLabel string) {
	assertNoSend(cur)
	assertMayGrant(cur)
	emitAdmin(cur, "GrantFreeRenewal", "label", label, "domain", domainLabel)
	// A free renewal is a giveaway too: not during a restore window, and not
	// while recovery's quarantine holds (review follow-up).
	assertNotRestoring()
	if q := nsdata.QuarantineUntil(); time.Now().Unix() < q {
		panic("nslogic: recovery has quarantined giveaways until unix " + strconv.FormatInt(q, 10))
	}

	if !nsdata.NameExists(label, domainLabel) {
		panic("nslogic: no such name")
	}
	owner, _, _, _, _, paid := nsdata.GetNameInfo(label, domainLabel)
	if paid {
		panic("nslogic: " + label + "*" + domainLabel +
			" is a paid name — free renewal is for free-tier records")
	}
	if RenewalsLeft(label, domainLabel) <= 0 {
		panic("nslogic: this name is already paid as far ahead as a name may run")
	}
	if err := nsdata.RenewNameRecord(cross(cur), label, domainLabel, owner,
		time.Now().Unix()); err != nil {
		panic(err)
	}
}

// IsFreeTier reports whether a name is a record without a token — the
// free tier. Exported because the site and the issuer both need to ask
// before offering a free renewal, and neither should infer it.
func IsFreeTier(label, domainLabel string) bool {
	if !nsdata.NameExists(label, domainLabel) {
		return false
	}
	_, _, _, _, _, paid := nsdata.GetNameInfo(label, domainLabel)
	return !paid
}

gnomod.toml

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

[addpkg]
  creator = "g1lh4rrf9pq9k9tvka9p6vwhyv70e4h09szap6zu"
  height = 453069
  max_deposit = "40000000ugnot"

holdings.gno

package nslogic

import (
	"strings"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// Answering "what does this address hold" in ONE read.
//
// The site used to ask the chain for every name in the REGISTRY and then
// throw away the ones that did not match — one HTTP round trip per name
// in the world to draw one person's collection. Six names took three
// seconds, and it gets linearly worse for everybody every time anybody
// else registers anything.
//
// The scan itself is unavoidable: nsdata keys names by domain*label and
// has no index by owner, and nsdata is the permanent vault so no index
// can be added to it now. But the scan does not have to happen across
// the network. nslogic is swappable and can walk the same records inside
// a single query, which turns N round trips into one.
//
// Nothing is cached and nothing is trusted from the caller: every row is
// read from the vault at the moment of the query, exactly as before.
//
// Paged, because a query has a gas ceiling of its own and a registry
// with fifty thousand names in it must not become one enormous read that
// nobody can complete. `after` is the vault's own cursor, so paging here
// is the same paging ExportNames already does.
const maxHoldingsPage = 200

// NamesOwnedBy returns rows of `label*domain,registered,expires,streak,frozen`
// separated by ";", plus the cursor to continue from. Labels are
// restricted to [a-z0-9-] so neither separator can appear inside a field.
//
// `next` is empty when the scan has reached the end of the registry. It
// is NOT empty merely because this page found no matches: a page of two
// hundred names belonging to other people returns no rows and a cursor,
// and the caller keeps going.
func NamesOwnedBy(owner address, after string, limit int) (rows, next string) {
	if limit <= 0 || limit > maxHoldingsPage {
		limit = maxHoldingsPage
	}
	keys, nxt := nsdata.ExportNames("", after, limit)

	var b strings.Builder
	for _, key := range strings.Split(keys, ",") {
		if key == "" {
			continue
		}
		// The tree key is domain*label; the token ID is label*domain.
		at := strings.Index(key, "*")
		if at < 0 {
			continue
		}
		domainLabel, label := key[:at], key[at+1:]

		o, registered, expires, streak, frozen, _ := nsdata.GetNameInfo(label, domainLabel)
		if o != owner {
			continue
		}
		if b.Len() > 0 {
			b.WriteString(";")
		}
		b.WriteString(ufmt.Sprintf("%s*%s,%d,%d,%d,%t",
			label, domainLabel, registered, expires, streak, frozen))
	}
	return b.String(), nxt
}

// CountNamesOwnedBy is the same walk without the strings, for a header
// that wants a number before the list has finished arriving.
func CountNamesOwnedBy(owner address, after string, limit int) (n int, next string) {
	if limit <= 0 || limit > maxHoldingsPage {
		limit = maxHoldingsPage
	}
	keys, nxt := nsdata.ExportNames("", after, limit)
	for _, key := range strings.Split(keys, ",") {
		if key == "" {
			continue
		}
		at := strings.Index(key, "*")
		if at < 0 {
			continue
		}
		if nsdata.GetNameOwner(key[at+1:], key[:at]) == owner {
			n++
		}
	}
	return n, nxt
}

// Everything the profile page draws, in ONE read.
//
// It was making seventeen queries: three to establish that the name
// exists and when it expires, then fourteen more — one per extension
// slot — that could not start until the first three had come back. Two
// waves, and the node serves only a few at a time, so a profile took
// seconds to assemble out of values that all live in the same record.
//
// Values come back in the ORDER THE KEYS WERE ASKED FOR rather than as
// key=value pairs. An extension key is allowed to contain "=" (only
// commas and newlines are forbidden), so a pair encoding would have an
// ambiguous split; positional has none.
//
// Line 0 is the record: owner, registered, expires, streak, frozen, and
// the grace period, which is global but is one more query the page would
// otherwise have to make on its own.
//
// An empty return means the name is not registered. That is a real
// answer rather than an error: asking about a name nobody owns is the
// normal case on a profile URL somebody typed.
func ProfileOf(label, domainLabel, keys string) string {
	if !nsdata.NameExists(label, domainLabel) {
		return ""
	}
	owner, registered, expires, streak, frozen, _ := nsdata.GetNameInfo(label, domainLabel)

	var b strings.Builder
	b.WriteString(ufmt.Sprintf("%s,%d,%d,%d,%t,%d",
		owner.String(), registered, expires, streak, frozen, nsdata.GetGracePeriod()))

	for _, k := range strings.Split(keys, ",") {
		b.WriteString("\n")
		if k == "" {
			continue
		}
		v := nsdata.GetNameExtra(label, domainLabel, k)

		// THE GNO.LAND ADDRESS ANSWERS EVEN WHEN NOBODY SAVED ONE.
		//
		// A name is an NFT held by an address, so the owner is already
		// public — it is the first field of the record above. Returning
		// it here as well costs no storage and means a name can be paid
		// without its holder ever having opened a profile editor, which
		// is most of them, and without a transaction to back-fill the
		// ones registered before this existed.
		//
		// Doing it in the realm rather than in the website is the whole
		// point: any client asking this realm for the gno key gets the
		// same answer our pages do. A front end that derived it locally
		// would leave every other reader with nothing.
		//
		// "off" is the opt-out, and it has to be a sentinel. An empty
		// value is indistinguishable from never having set one, so an
		// empty gno field would simply hand the derived address back on
		// the next read.
		if k == "gno" {
			if v == "off" {
				v = ""
			} else if v == "" {
				v = owner.String()
			}
		}
		b.WriteString(escapeValue(v))
	}
	return b.String()
}

// Extension VALUES are free text — a bio can hold anything a person can
// type, newlines included — so they cannot be newline-separated raw.
// Escaping is done here rather than stripping, because silently eating a
// line break out of somebody's bio is data loss on a read path.
func escapeValue(s string) string {
	s = strings.ReplaceAll(s, `\`, `\\`)
	s = strings.ReplaceAll(s, "\n", `\n`)
	return strings.ReplaceAll(s, "\r", `\r`)
}

// RecentNames answers "what has just been registered" in one read.
//
// The site used to build this by listing every key and then reading each
// record one at a time — the same shape NamesOwnedBy replaced for a
// wallet's holdings, and the same problem: fine at thirteen names, one
// query per name forever after. A feed that gets slower every time
// somebody registers is a feed that eventually stops loading on the busy
// day you most wanted it.
//
// Returns rows of "label*domain,registered,expires,owner", newest first,
// and a cursor. Sorting happens across a PAGE, not the whole registry:
// the vault stores names alphabetically and there is no index by date,
// so a caller that wants the true newest reads every page and merges.
// That is one query per 200 names instead of one per name — enough of a
// difference to stop mattering, without pretending the vault has an
// index it does not have.
func RecentNames(after string, limit int) (rows, next string) {
	if limit <= 0 || limit > maxHoldingsPage {
		limit = maxHoldingsPage
	}
	keys, nxt := nsdata.ExportNames("", after, limit)

	type row struct {
		text string
		at   int64
	}
	var found []row
	for _, key := range strings.Split(keys, ",") {
		if key == "" {
			continue
		}
		// The tree key is domain*label; the token ID is label*domain.
		at := strings.Index(key, "*")
		if at < 1 {
			continue
		}
		domainLabel, label := key[:at], key[at+1:]
		owner, registered, expires, _, _, _ := nsdata.GetNameInfo(label, domainLabel)
		found = append(found, row{
			text: ufmt.Sprintf("%s*%s,%d,%d,%s", label, domainLabel, registered, expires, owner.String()),
			at:   registered,
		})
	}

	// Insertion sort, newest first. The page is at most 200 entries and
	// gno has no sort in scope here; anything cleverer would be more code
	// than the problem deserves.
	for i := 1; i < len(found); i++ {
		v := found[i]
		j := i - 1
		for j >= 0 && found[j].at < v.at {
			found[j+1] = found[j]
			j--
		}
		found[j+1] = v
	}

	var b strings.Builder
	for _, r := range found {
		if b.Len() > 0 {
			b.WriteString(";")
		}
		b.WriteString(r.text)
	}
	return b.String(), nxt
}

keeper.gno

package nslogic

import (
	"chain"
	"strconv"
	"time"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

/*
THE KEEPER: a hot key that moves the GNOT/USD rate and nothing else
(Ely, 2026-10-16).

WHY A ROLE. The rate is MANUAL (pricing.gno, SetUsdRate): it sits where it
was last written, and a stale rate during a sharp move sells names at the
wrong price. Keeping it current is a job for a bot, and a bot lives on a
server. The admin key must not, so the bot gets a key of its own that can
do exactly one thing.

WHAT IT CAN DO. Call SetUsdRate inside the bounds every instant change
obeys (timelock.gno): a higher rate — GNOT fell — up to four times at once,
every ten minutes, so a crash is followed at once; a lower rate — the
direction that sells names cheap — at most 25%, once an hour. The clocks
are the SAME ones the admin's instant moves use, so the two keys together
still cheapen names one step an hour. Never through the timelock: a
matured proposal belongs to the admin, and the keeper's call refuses an
out-of-bound value even while one is waiting. Every other function refuses
it, because every other function asks for the admin; the admin keeps
SetUsdRate as before.

WHAT ITS THEFT COSTS. Names a quarter cheaper each hour, in public — each
move emits KeeperAction — until the admin, recovery or the guardian calls
ClearKeeper, which is instant; or names made too dear to buy, an outage.
Bounded in size, in rate and in time, and it never touches a name or a
coin directly.

NAMED THROUGH THE TIMELOCK, CLEARED AT ONCE. SetKeeper waits out the vault's
action delay ("SetKeeper <addr>" through nsdata.ProposeAction), like naming
a granter: otherwise a stolen admin key installs a second key that survives
its own rotation. Clearing is the safe direction and is open to all three
governance roles. An admin rotation does not clear the keeper by itself;
the incident runbook does (MAINNET.md §1b).

NEVER THE ADMIN, NEVER RECOVERY. A keeper on the admin's address adds
nothing, and one on recovery's puts the cold key's address on a server.
Both are refused when it is named, and recovery is refused again at call
time, in case a later rotation moved recovery onto the keeper's address.

Stored in the vault's globals like the granter, so a logic swap keeps it,
and listed in managedGlobal, so SetGlobal cannot write round the timelock.
*/

const keyKeeper = "keeper" // global: the address that may move the rate

// Keeper is the address allowed to move the rate, or "" for none.
func Keeper() address { return address(nsdata.GetGlobal(keyKeeper)) }

// SetKeeper names the keeper. Admin only, and TIMELOCKED: propose exactly
// "SetKeeper <addr>" with nsdata.ProposeAction, then call once it matures.
// ClearKeeper removes the role.
func SetKeeper(cur realm, a address) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetKeeper", "addr", a.String())
	if !a.IsValid() {
		panic("nslogic: not an address; ClearKeeper removes the keeper")
	}
	if a == nsdata.GetAdmin() || a == nsdata.GetRecovery() {
		panic("nslogic: the keeper is a key of its own, never the admin or the recovery key")
	}
	requireAction(cur, actionID("SetKeeper", a.String()))
	setGlobal(cur, keyKeeper, a.String())
}

// ClearKeeper removes the keeper at once. Admin, recovery or guardian —
// the guardian bot's answer to a KeeperAction it did not expect. Clearing
// when there is no keeper does nothing and still succeeds, so a bot may
// call it without reading first.
func ClearKeeper(cur realm) {
	assertNoSend(cur)
	caller := cur.Previous().Address()
	if !isGovernor(caller) {
		panic("nslogic: only the admin, recovery or the guardian may clear the keeper")
	}
	chain.Emit("KeeperCleared", "keeper", Keeper().String(), "by", caller.String())
	setGlobal(cur, keyKeeper, "")
}

// isGovernor is the vault's three roles, read fresh. An unset role matches
// nobody.
func isGovernor(a address) bool {
	if a == "" {
		return false
	}
	return a == nsdata.GetAdmin() || a == nsdata.GetRecovery() || a == nsdata.GetGuardian()
}

// assertIsKeeper lets the keeper through and nobody else, with the refusal
// a stranger has always had from an admin call.
func assertIsKeeper(caller address) {
	k := Keeper()
	if k == "" || caller != k {
		panic("nslogic: restricted to project admin")
	}
	if k == nsdata.GetRecovery() {
		panic("nslogic: the keeper's address is now the recovery key's; name a new keeper")
	}
}

/*
keeperSetRate is SetUsdRate for the keeper: the same range check, the
bound and the shared hourly slot, and no door into the timelock. Every
move emits KeeperAction, with the value it replaced.
*/
func keeperSetRate(cur realm, ugnotPerUsd int64) {
	caller := cur.Previous().Address()
	assertIsKeeper(caller)
	old := RateUgnotPerUsd()
	chain.Emit("KeeperAction", "fn", "SetUsdRate", "by", caller.String(),
		"ugnotPerUsd", fmtInt(ugnotPerUsd), "was", fmtInt(old))
	if ugnotPerUsd <= 0 || ugnotPerUsd > maxRate {
		panic("nslogic: a rate is 1.." + strconv.FormatInt(maxRate, 10) + " ugnot per USD")
	}
	keeperStep(keyRate, old, ugnotPerUsd)
	setGlobal(cur, keyRate, strconv.FormatInt(ugnotPerUsd, 10))
}

// keeperStep is authorizeTweak with the timelock door bricked up: an
// instant step inside its direction's bound, after that direction's rest,
// or a refusal. It writes the same clocks, so the admin's next instant
// move in that direction waits the same time.
func keeperStep(setting string, old, next int64) {
	if next == old {
		return
	}
	dearer := next > old // the rate: higher means names cost more GNOT
	if !withinStep(old, next, dearer) {
		panic("nslogic: for the keeper, " + stepRefusal(setting, old, next, dearer) +
			"; a larger move is the admin's, through the vault timelock")
	}
	now := time.Now().Unix()
	if !clockRested(setting, dearer, now) {
		panic("nslogic: " + restRefusal(setting, dearer) + "; the keeper waits for the next step")
	}
	lastTweak.Set(clockKey(setting, dearer), now)
}

name.gno

package nslogic

import (
	"chain"
	"strings"
	"time"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// Profile field names inside a name's extension slot. The vault stores
// them as opaque strings and bounds their size; what they MEAN is this
// realm's convention, so new profile fields need no vault change.
const (
	keyDisplayName = "displayName"
	keyBio         = "bio"
	keyWebsite     = "website"
	keyAvatar      = "avatar"
)

// RegisterName mints `label*domain` under an existing domain. Anyone may
// call this. Minting still works while the parent domain is past its own
// due date, as long as its grace period hasn't fully lapsed and it isn't
// frozen — nsdata's RegisterNameRecord enforces that.
func RegisterName(cur realm, label, domainLabel string) {
	registerName(cur, label, domainLabel, "")
}

// RegisterNameRef is RegisterName with a referral code — the NAME of
// whoever sent the buyer here, as it appears in the link.
//
// It is a second entry point rather than a third argument on the first
// one because the first one is already deployed and already being called
// by wallets and by the site. Changing its arity would break every one
// of those callers at the same instant, which is exactly the failure the
// voting realm produced last time; adding a function breaks nothing and
// lets the front end pick whichever the deployed realm actually has.
//
// A code that does not earn — misspelt, lapsed, the buyer's own name, a
// free-tier name, or one not yet held for thirty days (referral.gno) — is
// IGNORED, not rejected. The registration goes through at list price.
// Refusing to sell somebody a name because they mistyped somebody else's
// would be an absurd way to lose a sale.
func RegisterNameRef(cur realm, label, domainLabel, refName string) {
	registerName(cur, label, domainLabel, refName)
}

func registerName(cur realm, label, domainLabel, refName string) {
	assertNotRestoring()
	validateLabel(label)
	assertNotBlocked(label)
	if !DomainOpen(domainLabel) {
		panic("nslogic: this domain is not accepting new names")
	}
	caller := cur.Previous().Address()

	// Resolved BEFORE anything is written, so the code is judged in the
	// world the buyer was quoted in.
	ref := resolveReferrer(refName, caller)
	price := NamePrice(domainLabel, label)
	if ref != "" {
		if _, pct := RefRates(); pct > 0 {
			price -= price * pct / 100
		}
	}
	payTo, cut := referralCut(ref, price)
	takePaymentSplit(cur, price, payTo, cut)

	if err := nsdata.RegisterNameRecord(cross(cur), label, domainLabel, caller, time.Now().Unix(), true); err != nil {
		panic(err)
	}

	// Written after the record exists, because the extension slot is
	// created by registration. Only recorded when the cut was actually
	// paid: the record says who brought this buyer, and a referrer who
	// earned nothing did not.
	if ref != "" && cut > 0 {
		setExtra(cur, label, domainLabel, keyRef, ref.String())
		creditReferral(cur, ref)
		// Money left the treasury's share: say so, so a monitor can add up
		// what referral rules are costing without reading every tx.
		chain.Emit("ReferralPaid", "tid", label+"*"+domainLabel, "referrer", ref.String(),
			"amount", fmtInt(cut), "price", fmtInt(price))
	}
}

// RenewName — same anchoring rule as RenewDomain: extends from the
// previous due date, not from the payment date. Deliberately does not
// call validateLabel — an already-registered name must keep renewing
// under whatever pattern was in force when it was minted.
func RenewName(cur realm, label, domainLabel string) {
	// Not while a restore window is open: the prices may not be back yet
	// (restore.gno, assertNotRestoring; review follow-up).
	assertNotRestoring()
	// FIRST YEAR ONLY (referral.gno): a renewal pays the full price, all
	// of it to the treasury, and nobody's cut. Renewals used to pay the
	// referrer for as long as the name survived, which made a second
	// wallet's code a permanent discount on its owner's own renewals.
	assertRoomToRenew(label, domainLabel)
	takePayment(cur, NamePrice(domainLabel, label))

	caller := cur.Previous().Address()
	if err := nsdata.RenewNameRecord(cross(cur), label, domainLabel, caller, time.Now().Unix()); err != nil {
		panic(err)
	}
}

// SetProfile writes the four conventional profile fields. Each lands in
// the name's extension slot, where the vault enforces size bounds.
func SetProfile(cur realm, label, domainLabel, displayName, bio, website, avatar string) {
	assertNoSend(cur)
	assertNameOwner(cur, label, domainLabel)
	setExtra(cur, label, domainLabel, keyDisplayName, displayName)
	setExtra(cur, label, domainLabel, keyBio, bio)
	setExtra(cur, label, domainLabel, keyWebsite, website)
	setExtra(cur, label, domainLabel, keyAvatar, avatar)
}

// SetNameField writes a single arbitrary key — cross-chain addresses and
// anything else a future feature needs, with no vault change required.
// Keys used by this realm's own machinery are reserved.
func SetNameField(cur realm, label, domainLabel, key, value string) {
	assertNoSend(cur)
	assertNameOwner(cur, label, domainLabel)
	if strings.HasPrefix(key, "_") {
		panic("nslogic: keys beginning with '_' are reserved")
	}
	// `ref` decides who gets paid out of every renewal of this name. A
	// holder who could write it would set it to an address they control
	// and take a permanent cut of their own renewals out of the
	// treasury — so the one key that moves money is the one key its
	// owner may not touch.
	if key == keyRef {
		panic("nslogic: '" + keyRef + "' is set at registration and cannot be edited")
	}
	setExtra(cur, label, domainLabel, key, value)
}

func setExtra(cur realm, label, domainLabel, key, value string) {
	if err := nsdata.SetNameExtraRecord(cross(cur), label, domainLabel, key, value); err != nil {
		panic(err)
	}
}

func assertNameOwner(cur realm, label, domainLabel string) {
	if nsdata.GetNameOwner(label, domainLabel) != cur.Previous().Address() {
		panic("nslogic: restricted to name owner")
	}
}

// SetPrimaryName lets a wallet explicitly choose (and later change) which
// of its names is used for reverse resolution.
func SetPrimaryName(cur realm, label, domainLabel string) {
	assertNoSend(cur)
	caller := cur.Previous().Address()
	if nsdata.GetNameOwner(label, domainLabel) != caller {
		panic("nslogic: restricted to name owner")
	}
	if err := nsdata.SetPrimaryRecord(cross(cur), caller, label, domainLabel); err != nil {
		panic(err)
	}
}

/*
ClearPrimaryName switches reverse resolution OFF for the caller.

WHY THIS HAS TO EXIST, and it is a hole rather than a feature request.

nsdata sets the reverse pointer AUTOMATICALLY on a wallet's first
registration — RegisterNameRecord does it, and nothing asked the person
first. From that moment their address answers with their name, so anybody
who sees that address anywhere can find the persona attached to it, and
every transaction it has ever made becomes attributable. Retroactively:
the chain is permanent and indexers keep copies.

And until now there was NO WAY OUT. ClearPrimaryRecord is gated to
trusted logic, and no logic realm exposed it, so the one person the
pointer is about could not remove it. A name service is a bridge between
a persona and a wallet; publishing that bridge without consent and
without an exit is the worst version of it.

This is the exit. It takes no arguments on purpose: a wallet has exactly
one reverse pointer, and the only address it can clear is its own, so
there is nothing to pass and nothing to get wrong.

WHAT IT DOES NOT DO, said plainly because a promise we cannot keep would
be worse than the hole: clearing stops FUTURE lookups. It does not
unpublish what was already visible, and it cannot — the history is on
chain and other people have copies. The honest sequence is to choose
before publishing, which is why the site now shows what the link exposes
before it offers to make it.
*/
func ClearPrimaryName(cur realm) {
	assertNoSend(cur)
	nsdata.ClearPrimaryRecord(cross(cur), cur.Previous().Address())
}

// maxTTL caps a cache policy, a name's or a domain's: 2^31-1 seconds,
// about 68 years, the ceiling DNS itself uses (RFC 2181). Anything longer
// reads as forever to every resolver, and an unbounded value did not
// survive a snapshot (restore.gno, ttlSecs).
const maxTTL = int64(1<<31 - 1)

// SetNameTTL is the owner's cache policy for their own name, in
// seconds, where 0 MEANS NEVER CACHE — copied from the ENS registry so
// integrators need not read anything of ours to handle it.
//
// The owner sets it rather than the registry because only they know the
// risk: a name being used to receive payments wants 0, since a cached
// answer after a sale pays the previous owner; a name used as a display
// handle can safely be cached for a long time. At most maxTTL.
func SetNameTTL(cur realm, label, domainLabel string, seconds int64) {
	assertNoSend(cur)
	assertNameOwner(cur, label, domainLabel)
	if seconds < 0 || seconds > maxTTL {
		panic("nslogic: a ttl is 0.." + fmtInt(maxTTL) + " seconds")
	}
	if err := nsdata.SetNameTTLRecord(cross(cur), label, domainLabel, seconds); err != nil {
		panic(err)
	}
}

func FreezeName(cur realm, label, domainLabel string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "FreezeName", "label", label, "domain", domainLabel)
	nsdata.SetNameFrozen(cross(cur), label, domainLabel, true)
}

// UnfreezeName is TIMELOCKED (timelock.gno); freezing stays instant. A
// freeze is the takedown and dispute lever — a disputed or stolen name is
// held while it is sorted out — so releasing one instantly would let a
// stolen admin key free a name and move it in the same transaction.
func UnfreezeName(cur realm, label, domainLabel string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "UnfreezeName", "label", label, "domain", domainLabel)
	requireAction(cur, actionID("UnfreezeName", label, domainLabel))
	nsdata.SetNameFrozen(cross(cur), label, domainLabel, false)
}

// UnfreezeNames releases several names behind ONE timelocked action:
// propose exactly "UnfreezeNames a*meme,b*doge,…" (token ids, comma-
// separated, at most maxUnfreezeBatch). A stolen key freezes names one call
// each and instantly, about a thousand a block; releasing them one action
// each, with at most 32 actions pending, took ⌈N/32⌉ timelocks (re-audit
// 2026-10-16, L-3). One unknown or malformed name refuses the whole call.
const maxUnfreezeBatch = 64

func UnfreezeNames(cur realm, tids string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "UnfreezeNames", "tids", tids)
	list := strings.Split(tids, ",")
	if tids == "" || len(list) > maxUnfreezeBatch {
		panic("nslogic: 1.." + fmtI(maxUnfreezeBatch) + " token ids, comma-separated")
	}
	type ref struct{ label, domain string }
	refs := make([]ref, 0, len(list))
	for _, tid := range list {
		label, domainLabel := splitTokenID(tid)
		if label == "" || domainLabel == "" || !nsdata.NameExists(label, domainLabel) {
			panic("nslogic: not a registered name: " + tid)
		}
		refs = append(refs, ref{label, domainLabel})
	}
	requireAction(cur, actionID("UnfreezeNames", tids))
	for _, r := range refs {
		nsdata.SetNameFrozen(cross(cur), r.label, r.domain, false)
	}
}

// -- resolution --

func ResolveName(label, domainLabel string) address {
	if !nsdata.IsNameValid(label, domainLabel) {
		panic("nslogic: name is expired")
	}
	return nsdata.GetNameOwner(label, domainLabel)
}

// ResolveAddress performs reverse resolution: address -> name.
//
// It must verify the ownership it is asserting, not merely that the
// pointed-at name exists and is unexpired. nsdata's `primary` tree is a
// record of what an address last SELECTED, not proof of what it still
// owns — and although nsdata now clears the pointer on transfer and
// reclaim, this check is the half that lives in the swappable realm and
// therefore stays correct even against pointers written by an older
// version of the logic. Without it, an address that sold or lost a name
// kept reverse-resolving to it, impersonating the new owner.
func ResolveAddress(addr address) string {
	tid := nsdata.GetPrimary(addr)
	if tid == "" {
		return ""
	}
	label, domainLabel := splitTokenID(tid)
	if !nsdata.IsNameValid(label, domainLabel) {
		return ""
	}
	if nsdata.GetNameOwner(label, domainLabel) != addr {
		return ""
	}
	return tid
}

// splitTokenID splits a `label*domain` token ID.
func splitTokenID(tid string) (label, domainLabel string) {
	for i := 0; i < len(tid); i++ {
		if tid[i] == '*' {
			return tid[:i], tid[i+1:]
		}
	}
	return tid, ""
}

nft.gno

package nslogic

import (
	"strings"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// This realm only exposes the WRITE side of the GRC-721 surface. Reads
// (BalanceOf, OwnerOf, TokenURI, GetApproved, IsApprovedForAll, and
// every listing/status/profile query) have no authorization check to
// perform and are served directly by nsdata — no reason to duplicate
// them here.

func isDomainToken(tid string) bool {
	return strings.HasPrefix(tid, "*")
}

// isTokenValid checks the underlying domain/name's expiry via nsdata's
// own validity reads — the anti-scam pattern (an expired name must not
// be sellable) enforced at the transfer boundary, not just at read time.
func isTokenValid(tid string) bool {
	if isDomainToken(tid) {
		return nsdata.IsDomainValid(tid[1:])
	}
	label, domainLabel := splitTokenID(tid)
	return nsdata.IsNameValid(label, domainLabel)
}

// assertNotFrozen is the check that made freezing mean something.
//
// FreezeName set a bit that only ever gated RE-REGISTRATION after a
// lapse. Transfer, approval, listing and sale all ignored it, so the one
// manual lever the takedown process relies on did nothing about the case
// it exists for: a disputed or stolen name could be approved to a fresh
// wallet, listed and sold while the interface showed it as frozen.
//
// The bit was already stored and already readable — GetNameInfo returns
// it — so this needs no change to the permanent vault, only the read
// that was never performed.
func assertNotFrozen(tid string) {
	label, domainLabel := splitTokenID(tid)
	_, _, _, _, frozen, _ := nsdata.GetNameInfo(label, domainLabel)
	if frozen {
		panic("nslogic: this name is frozen and cannot be transferred or approved")
	}
}

/*
THERE ARE NO TRANSFER OR APPROVAL FUNCTIONS HERE ANY MORE.

Approve, SetApprovalForAll, TransferFrom and SafeTransferFrom lived in this
realm, and they could only work while this realm was the one place a
transfer could happen. In this generation ownership is in nsnft, and nsnft
sees whoever calls it as the caller — so a logic realm calling in on a
user's behalf would be refused as not approved, correctly. A logic realm
that COULD move people's tokens would be a logic realm that could steal
them.

So: holders approve and transfer on nsnft directly, and marketplaces —
ours included — settle as approved operators there.

The two policies these wrappers enforced moved to where they bind every
path, not just ours:
  - frozen names: a hold bit on the token in nsnft (nsdata.SetNameFrozen)
  - free-tier names: a hold bit set at mint (nsdata.RegisterNameRecord)
Expired names are refused by our marketplace and never resolve; an
external marketplace can move an expired token, as with any NFT. See
MIGRATION.md, second attempt, rule 6.

The helpers above stay because the marketplace-facing reads use them.
*/

payment.gno

package nslogic

import (
	"chain"
	"chain/banker"
	"chain/runtime/unsafe"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// takePayment verifies the attached send-envelope covers `price` ugnot,
// forwards the price to the treasury, and refunds any overpayment to the
// caller in the same transaction. Nothing is ever retained: every ugnot
// that arrives leaves again, as either payment or refund.
//
// It used to take a `beneficiary` and split the price fee/remainder,
// routing the remainder to treasury only while `beneficiary == admin`.
// That comparison was a proxy for "is this a project-owned domain", and
// it silently broke the moment `admin` rotated — the planned EOA-to-
// multisig step — because a domain's owner is frozen into its record at
// registration time. After a rotation, every registration's remainder
// would have been paid to the retired key instead of the treasury, with
// no error and no log line.
//
// The heuristic is gone rather than patched. Domains are admin-only to
// create and permanently non-transferable, so every domain is
// project-owned by construction and 100% of every payment belongs to the
// treasury. `platformFeeBps` stays in nsdata's config for a future logic
// realm that reintroduces third-party domain ownership; reinstating the
// split is then a logic-realm swap, not a migration.
func takePayment(cur realm, price int64) {
	takePaymentSplit(cur, price, "", 0)
}

// takePaymentSplit is takePayment with a referrer's cut carved out of the
// same price. The buyer pays exactly what they were quoted; the cut is
// not added on top, it is a share of what the treasury would otherwise
// have received.
//
// All three legs settle inside the buyer's own transaction — treasury,
// referrer, refund — so this realm's balance is the same after the call
// as before it. That is not a stylistic preference: holding a referrer's
// cut until they claim it would make this an account you can have a
// balance in, and that is a different kind of thing to operate, subject
// to a different set of rules, run by people with licences. The cut is
// paid now or it is not paid.
func takePaymentSplit(cur realm, price int64, cutTo address, cut int64) {
	if !cur.Previous().IsUserCall() {
		panic("nslogic: only direct wallet calls may attach payment")
	}
	caller := cur.Previous().Address()
	sent := unsafe.OriginSend()
	assertOnlyUgnot(sent)

	paid := sent.AmountOf(ugnot)
	if paid < price {
		panic(ufmt.Sprintf("nslogic: insufficient payment: need %d ugnot, got %d", price, paid))
	}
	excess := paid - price

	// Belt and braces. referralCut already caps the percentage, but this
	// is the line where the arithmetic becomes money leaving an address,
	// and a bug upstream must not be able to pay out more than came in.
	if cut < 0 || cut > price || cutTo == "" {
		cut = 0
	}

	b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	pkgAddr := cur.Address()
	if cut > 0 {
		b.SendCoins(pkgAddr, cutTo, chain.Coins{chain.NewCoin(ugnot, cut)})
	}
	if price-cut > 0 {
		b.SendCoins(pkgAddr, nsdata.GetTreasury(), chain.Coins{chain.NewCoin(ugnot, price-cut)})
	}
	if excess > 0 {
		b.SendCoins(pkgAddr, caller, chain.Coins{chain.NewCoin(ugnot, excess)})
	}
}

// assertOnlyUgnot rejects any other denomination outright. Only the
// ugnot amount was ever accounted for, and neither realm has a
// withdrawal path, so a foreign coin sent alongside a payment would have
// been stranded in this realm's address permanently. Refusing the whole
// transaction is simpler than sweeping it back and keeps the
// "this realm never retains funds" invariant absolute.
func assertOnlyUgnot(sent chain.Coins) {
	for _, c := range sent {
		if c.Denom != ugnot {
			panic("nslogic: only ugnot is accepted, got: " + c.Denom)
		}
	}
}

// assertNoSend guards every entry point that has no price. Without it,
// coins attached to a free call (a renewal of a project domain, a
// profile edit, an admin setter) would land in this realm's address with
// no way back out.
//
// IT APPLIES TO DIRECT WALLET CALLS ONLY, and that qualification is not
// a loosening — it is the guard finally matching its own reason.
//
// OriginSend() reports what the TRANSACTION carried, not what this call
// received. Measured on sapphire-1 with a pair of probe realms: a user
// attaches 500000ugnot to realm A, A calls realm B, and B's OriginSend()
// reads 500000ugnot even though every one of those coins is sitting in
// A's address. B never saw them and cannot strand them.
//
// So for a realm-to-realm call this was rejecting a payment this realm
// never received. It is the reason a marketplace could not transfer a
// name inside the same transaction that pays for it — the transfer is a
// free call, the transaction is not, and the two are unrelated. A
// two-transaction sale is the alternative, and that means somebody's
// money or somebody's name sitting somewhere in between. Not here.
func assertNoSend(cur realm) {
	if !cur.Previous().IsUserCall() {
		return // the coins went to whoever called us, not to us
	}
	if !unsafe.OriginSend().IsZero() {
		panic("nslogic: this function takes no payment; do not attach coins")
	}
}

premium.gno

package nslogic

import (
	"strconv"
	"strings"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// Global pricing layers that sit ACROSS every domain rather than inside
// one — see SPEC.md §27.
//
// Two of them, and they work at different points:
//
//	GLOBAL LENGTH RULES are a FLOOR beneath each domain's own length
//	rules, consulted only when the domain has nothing to say about that
//	length. "three-character names cost $5 everywhere" becomes one entry
//	instead of an edit to all twenty-seven domains, and a domain that
//	wants its own answer still overrides it.
//
//	GLOBAL NAME PREMIUMS are an ADJUSTMENT applied after the price has
//	already resolved. Making `og` premium is one entry covering
//	`og*degen`, `og*meme` and every domain invented later. Deliberately
//	not the per-name override, which REPLACES a price outright: "this
//	name costs exactly X here" and "this name is worth more everywhere"
//	are different tools and both are worth having.
//
// Full order, most specific first:
//
//  1. per-name override      (domain "nm")
//  2. per-domain length rule (domain "len")
//  3. global length rule     (global "glen")
//  4. domain base price      (domain "price")
//  5. global default         (global "defaultPrice")
//     then the global name premium modifies the result,
//     then any referral discount comes off what is left.
const (
	keyGlobalLens = "glen"    // global length rules
	keyPremium    = "premium" // premium1, premium2, ... see below

	// The vault caps an extension value at maxExtraValueLen (512 bytes),
	// which is roughly 40-60 premium entries. The list is therefore split
	// across numbered keys rather than pretending one will do; a list
	// that silently truncated at the 512th byte would drop exactly the
	// entries nobody checked.
	maxPremiumKeys = 8
)

// GlobalLengthRule returns the global rule for a label length, if any.
func GlobalLengthRule(n int) (string, bool) {
	return lookupRule(nsdata.GetGlobal(keyGlobalLens), strconv.Itoa(n))
}

// PremiumFor returns the raw modifier for a name across all premium
// keys, or "" when the name is not premium anywhere.
func PremiumFor(label string) string {
	for i := 1; i <= maxPremiumKeys; i++ {
		csv := nsdata.GetGlobal(keyPremium + strconv.Itoa(i))
		if csv == "" {
			continue
		}
		if v, ok := lookupRule(csv, label); ok {
			return v
		}
	}
	return ""
}

// applyPremium adjusts an already-resolved price.
//
// ZERO ALWAYS STAYS ZERO. A fixed "+$2.00" would otherwise silently undo
// a giveaway tier set months earlier, and a free tier that quietly stops
// being free is worse than never having offered one. This is decided
// explicitly rather than inherited from the percentage case happening to
// work out at zero.
//
// Forms: "%5" / "+%5" five percent more · "-%10" ten percent less ·
// "2.00" two dollars more · "-0.25" twenty-five cents less ·
// "=5.00" exactly five dollars, ignoring everything resolved above.
func applyPremium(mod string, price int64) int64 {
	mod = strings.TrimSpace(mod)
	if mod == "" || price <= 0 {
		return price
	}

	// "=X" replaces outright. Checked before the sign handling because
	// an exact price is not a delta and has no direction.
	if strings.HasPrefix(mod, "=") {
		v, ok := parseUSD(mod[1:])
		if !ok || v < 0 {
			return price
		}
		return v
	}

	neg := false
	switch {
	case strings.HasPrefix(mod, "-"):
		neg, mod = true, mod[1:]
	case strings.HasPrefix(mod, "+"):
		mod = mod[1:]
	}

	var delta int64
	if strings.HasPrefix(mod, "%") {
		pct, err := strconv.ParseInt(mod[1:], 10, 64)
		// Out of range reads as malformed (see applyRule): an unbounded
		// percentage would wrap into a wrong price rather than a high one.
		if err != nil || pct < 0 || pct > maxRulePct || price > maxPriceUSD {
			return price
		}
		delta = price * pct / 100
	} else {
		v, ok := parseUSD(mod)
		if !ok || v < 0 {
			return price
		}
		delta = v
	}

	if neg {
		// A discount may take a name to free, but never below it: a
		// negative price would be a payout, and this realm never pays
		// anybody to register.
		if delta >= price {
			return 0
		}
		return price - delta
	}
	return price + delta
}

// parseUSD reads a human dollar figure — "2", "2.5", "2.50", "0.069" —
// into micro-USD. Written by hand rather than with floats: a float would
// make "0.07" cost a different number of micro-dollars depending on the
// platform, and prices must be exact.
func parseUSD(s string) (int64, bool) {
	s = strings.TrimSpace(s)
	if s == "" {
		return 0, false
	}
	whole, frac := s, ""
	if i := strings.IndexByte(s, '.'); i >= 0 {
		whole, frac = s[:i], s[i+1:]
	}
	if whole == "" {
		whole = "0"
	}
	w, err := strconv.ParseInt(whole, 10, 64)
	// Capped at maxPriceUSD, so w*microUSD below cannot wrap.
	if err != nil || w < 0 || w > maxPriceUSD/microUSD {
		return 0, false
	}
	// Pad or truncate the fraction to exactly six digits of micro-USD.
	if len(frac) > 6 {
		frac = frac[:6]
	}
	for len(frac) < 6 {
		frac += "0"
	}
	var f int64
	if frac != "" {
		f, err = strconv.ParseInt(frac, 10, 64)
		if err != nil || f < 0 {
			return 0, false
		}
	}
	return w*microUSD + f, true
}

// SetGlobalLengthRules writes the project-wide length rules:
// "1:300000000,2:150000000,3:60000000" prices one, two and three
// character names everywhere a domain has not said otherwise.
//
// IT HAD NO SETTER UNTIL NOW, which meant the only way to write it was
// the generic SetGlobal escape hatch — straight past normalizeRules, so
// a typo stored fine and then vanished at lookup time, because
// lookupRule skips a malformed pair in silence. A pricing layer whose
// only writer cannot validate is a pricing layer that fails open.
//
// TIMELOCKED (timelock.gno), like every price rule set: "3:0" here makes
// short names free on every domain that has no rule of its own.
func SetGlobalLengthRules(cur realm, rules string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetGlobalLengthRules", "rules", rules)
	norm := normalizeRules(rules, true)
	requireAction(cur, actionID("SetGlobalLengthRules", norm))
	setGlobal(cur, keyGlobalLens, norm)
}

// SetPremiumNames writes one page of the premium keyword list, 1-based.
// The list is paged because the vault caps an extension value at 512
// bytes; see maxPremiumKeys.
//
// Same gap as above: normalizePremiums existed and nothing exported
// called it.
func SetPremiumNames(cur realm, page int, csv string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetPremiumNames", "page", fmtI(page), "csv", csv)
	if page < 1 || page > maxPremiumKeys {
		panic("nslogic: premium page must be 1-" + strconv.Itoa(maxPremiumKeys))
	}
	v := normalizePremiums(csv)
	if len(v) > 512 {
		panic("nslogic: premium page " + strconv.Itoa(page) +
			" is " + strconv.Itoa(len(v)) + " bytes; the vault caps a value at 512. Split it across pages.")
	}
	// TIMELOCKED: a premium of "=0" or "-%100" makes a name free everywhere.
	requireAction(cur, actionID("SetPremiumNames", strconv.Itoa(page), v))
	setGlobal(cur, keyPremium+strconv.Itoa(page), v)
}

// PremiumNames reads one page back, so the admin panel can show what is
// stored rather than what it last sent.
func PremiumNames(page int) string {
	if page < 1 || page > maxPremiumKeys {
		return ""
	}
	return nsdata.GetGlobal(keyPremium + strconv.Itoa(page))
}

// GlobalLengthRules returns the whole rule string, for the same reason.
func GlobalLengthRules() string { return nsdata.GetGlobal(keyGlobalLens) }

// normalizePremiums validates a premium list before storage. Same
// reasoning as normalizeRules: a malformed entry must never reach the
// vault, because every later lookup would carry it.
func normalizePremiums(csv string) string {
	if strings.TrimSpace(csv) == "" {
		return ""
	}
	var out []string
	seen := map[string]bool{}
	for _, pair := range strings.Split(csv, ",") {
		pair = strings.TrimSpace(pair)
		if pair == "" {
			continue
		}
		parts := strings.SplitN(pair, ":", 2)
		if len(parts) != 2 {
			panic("nslogic: bad premium, want name:modifier — got " + pair)
		}
		k, v := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
		if k == "" || strings.ContainsAny(k, "*, \t\n") {
			panic("nslogic: invalid name in premium — " + k)
		}
		if seen[k] {
			panic("nslogic: duplicate premium name — " + k)
		}
		if !validPremiumValue(v) {
			panic("nslogic: bad premium modifier for " + k + " — " + v)
		}
		seen[k] = true
		out = append(out, k+":"+v)
	}
	return strings.Join(out, ",")
}

func validPremiumValue(v string) bool {
	if v == "" {
		return false
	}
	if strings.HasPrefix(v, "=") {
		_, ok := parseUSD(v[1:])
		return ok
	}
	if strings.HasPrefix(v, "-") || strings.HasPrefix(v, "+") {
		v = v[1:]
	}
	if strings.HasPrefix(v, "%") {
		p, err := strconv.ParseInt(v[1:], 10, 64)
		return err == nil && p >= 0 && p <= maxRulePct
	}
	_, ok := parseUSD(v)
	return ok
}

pricing.gno

package nslogic

import (
	"math"
	"strconv"
	"strings"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// Pricing lives here, not in the vault. The vault stores numbers as
// opaque strings and has no opinion about what they mean, so the whole
// model can be replaced by swapping this realm.
//
// PRICES ARE DENOMINATED IN USD, held as MICRO-USD (1 USD = 1_000_000)
// so fractions of a cent are expressible — a name that costs about a
// gumball needs that. Nothing is stored in ugnot: the chain's token is
// just the settlement rail, converted at payment time from a stored
// rate. Accepting a second token later is then only a second rate, not
// a second price list.
//
// PRECEDENCE — most specific wins:
//
//  1. per-name override      (keyNames: "420:5000000,gm:%500")
//  2. per-length rule        (keyLens:  "3:2000000,4:%150,5:0")
//  3. GLOBAL length rule     (global keyGlobalLens — see premium.gno)
//  4. domain base price      (keyPrice: "500000"  = $0.50)
//  5. global default         (global keyDefaultPrice)
//
// then the GLOBAL NAME PREMIUM adjusts the result, and a referral
// discount comes off last. Both live in premium.gno.
//
// A rule value is either an absolute micro-USD amount or "%N", meaning N
// percent of that domain's base — so repricing a domain once carries
// every relative rule under it. "0" means free, which is how giveaway
// tiers are expressed: "all five-character names under *pleb are free"
// is just a length rule resolving to zero.
//
// Rules are stored as CSV in ONE key each rather than one key per rule.
// The vault caps extension keys at 32 bytes and 24 entries per record; a
// key like "nm:somelongname" breaks the first and a few dozen premium
// names break the second. Two CSV keys sidestep both.
const (
	keyPrice        = "price" // domain base, micro-USD
	keyLens         = "len"   // length rules
	keyNames        = "nm"    // per-name overrides
	keyOpen         = "open"  // "0" closes the domain to new names
	keyDefaultPrice = "defaultPrice"
	keyRate         = "rateUgnotPerUsd" // ugnot equal to 1 USD

	microUSD         = int64(1_000_000)
	fallbackPriceUSD = int64(500_000) // $0.50
	// TESTNET PEG: $0.069 per GNOT, so 1 USD = 1/0.069 GNOT = 14.492753
	// GNOT = 14_492_753 ugnot. Deliberately a fixed number while we are on
	// a testnet whose token has no market price at all -- a "real" rate
	// there would be fiction dressed as precision. Replaced with a genuine
	// conversion before mainnet; tracked in MAINNET.md.
	fallbackRate = int64(14_492_753)
	maxRules     = 64

	// The most any single USD price setting may say: one million dollars.
	// Far above any name this registry will list, and low enough that the
	// arithmetic on it stays far from overflow (see NamePrice).
	maxPriceUSD = int64(1_000_000) * microUSD

	// The largest "%N" a price rule or premium may carry: a hundredfold.
	maxRulePct = 10_000
)

// DomainOpen reports whether names may currently be registered under a
// domain. An absent key means open — a domain created before this
// existed must not silently close.
func DomainOpen(domainLabel string) bool {
	return nsdata.GetDomainExtra(domainLabel, keyOpen) != "0"
}

// -- USD side --

func DefaultPriceUSD() int64 {
	if v := nsdata.GetGlobal(keyDefaultPrice); v != "" {
		if p, err := strconv.ParseInt(v, 10, 64); err == nil && p >= 0 {
			return p
		}
	}
	return fallbackPriceUSD
}

func DomainBasePriceUSD(domainLabel string) int64 {
	if v := nsdata.GetDomainExtra(domainLabel, keyPrice); v != "" {
		if p, err := strconv.ParseInt(v, 10, 64); err == nil && p >= 0 {
			return p
		}
	}
	return DefaultPriceUSD()
}

// NamePriceUSD resolves the four inputs in precedence order and returns
// micro-USD. This is the authoritative price; ugnot is derived from it.
func NamePriceUSD(domainLabel, label string) int64 {
	return applyPremium(PremiumFor(label), resolveBeforePremium(domainLabel, label))
}

// resolveBeforePremium runs steps 1-5. Separated from NamePriceUSD so
// the admin panel can show WHY a price is what it is: the figure before
// the premium and the figure after are both meaningful, and a single
// function returning only the total makes a wrong price impossible to
// diagnose.
func resolveBeforePremium(domainLabel, label string) int64 {
	base := DomainBasePriceUSD(domainLabel)
	if v, ok := lookupRule(nsdata.GetDomainExtra(domainLabel, keyNames), label); ok {
		return applyRule(v, base)
	}
	if v, ok := lookupRule(nsdata.GetDomainExtra(domainLabel, keyLens), strconv.Itoa(len(label))); ok {
		return applyRule(v, base)
	}
	// The global length rule is a floor, not a replacement: it applies
	// only where the domain itself had nothing to say about this length.
	if v, ok := GlobalLengthRule(len(label)); ok {
		return applyRule(v, base)
	}
	return base
}

// ExplainPriceUSD returns each stage of the resolution, so the control
// panel can show the arithmetic rather than assert a total. Returns the
// price before any premium, the premium modifier that applied (empty if
// none), and the final price.
func ExplainPriceUSD(domainLabel, label string) (beforePremium int64, modifier string, final int64) {
	before := resolveBeforePremium(domainLabel, label)
	mod := PremiumFor(label)
	return before, mod, applyPremium(mod, before)
}

// -- settlement side --

// RateUgnotPerUsd is how many ugnot one USD buys.
//
// This is a MANUALLY MAINTAINED rate, not a market oracle: an admin
// writes it and it sits there until rewritten. That is a real
// operational hazard — a stale rate during a sharp move sells names at
// the wrong price in whichever direction hurts — and the mitigation is
// keeping it fresh, not anything this code can do. Kept as one global so
// a future logic realm can swap in a real oracle without touching the
// vault or restating a single price.
func RateUgnotPerUsd() int64 {
	if v := nsdata.GetGlobal(keyRate); v != "" {
		if r, err := strconv.ParseInt(v, 10, 64); err == nil && r > 0 {
			return r
		}
	}
	return fallbackRate
}

// NamePrice converts the USD price to ugnot for settlement. Rounds UP,
// so rounding never sells a name below its listed price; a free name
// stays exactly free.
//
// IT REFUSES TO OVERFLOW. usd*rate is int64 arithmetic, which wraps
// silently, and a wrapped product is a price of millions of GNOT or a
// negative one — and a negative price made takePaymentSplit refund more
// than was paid (audit L5). A price that cannot be computed is refused,
// which fails closed: no sale, never a wrong one.
func NamePrice(domainLabel, label string) int64 {
	usd := NamePriceUSD(domainLabel, label)
	if usd <= 0 {
		return 0
	}
	rate := RateUgnotPerUsd()
	if usd > (math.MaxInt64-microUSD)/rate {
		panic("nslogic: this name's price does not fit in a ugnot amount; the price list needs fixing")
	}
	return (usd*rate + microUSD - 1) / microUSD
}

// -- rule plumbing --

// applyRule reads a stored rule. An out-of-range one is treated like a
// malformed one — the base applies — because stored values can arrive by
// the restore window, unvalidated, and an unbounded percentage would wrap
// the multiplication into a small, wrong, price.
func applyRule(v string, base int64) int64 {
	if strings.HasPrefix(v, "%") {
		pct, err := strconv.ParseInt(v[1:], 10, 64)
		if err != nil || pct < 0 || pct > maxRulePct || base > maxPriceUSD {
			return base
		}
		return base * pct / 100
	}
	n, err := strconv.ParseInt(v, 10, 64)
	if err != nil || n < 0 || n > maxPriceUSD {
		return base
	}
	return n
}

func lookupRule(csv, want string) (string, bool) {
	if csv == "" {
		return "", false
	}
	for _, pair := range strings.Split(csv, ",") {
		parts := strings.SplitN(strings.TrimSpace(pair), ":", 2)
		if len(parts) != 2 {
			continue
		}
		if strings.TrimSpace(parts[0]) == want {
			return strings.TrimSpace(parts[1]), true
		}
	}
	return "", false
}

// normalizeRules validates and canonicalises a rule string before it is
// stored, so a malformed entry can never reach storage and poison every
// later lookup.
func normalizeRules(csv string, numericKeys bool) string {
	if strings.TrimSpace(csv) == "" {
		return ""
	}
	var out []string
	seen := map[string]bool{}
	for _, pair := range strings.Split(csv, ",") {
		pair = strings.TrimSpace(pair)
		if pair == "" {
			continue
		}
		parts := strings.SplitN(pair, ":", 2)
		if len(parts) != 2 {
			panic("nslogic: bad rule, want key:value — got " + pair)
		}
		k, v := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
		if k == "" {
			panic("nslogic: empty rule key")
		}
		if numericKeys {
			if n, err := strconv.Atoi(k); err != nil || n <= 0 {
				panic("nslogic: length must be a positive number — got " + k)
			}
		} else if strings.ContainsAny(k, "*, \t\n") {
			panic("nslogic: invalid name in rule — " + k)
		}
		// Bounded as well as well-formed: an amount above maxPriceUSD or a
		// percentage above maxRulePct is a typo, and an unbounded one could
		// overflow the price arithmetic downstream.
		if strings.HasPrefix(v, "%") {
			if p, err := strconv.ParseInt(v[1:], 10, 64); err != nil || p < 0 || p > maxRulePct {
				panic("nslogic: bad percentage (0-" + strconv.Itoa(maxRulePct) + ") — " + v)
			}
		} else if n, err := strconv.ParseInt(v, 10, 64); err != nil || n < 0 || n > maxPriceUSD {
			panic("nslogic: bad amount — " + v)
		}
		if seen[k] {
			panic("nslogic: duplicate rule key — " + k)
		}
		seen[k] = true
		out = append(out, k+":"+v)
		if len(out) > maxRules {
			panic("nslogic: too many rules (max 64)")
		}
	}
	return strings.Join(out, ",")
}

referral.gno

package nslogic

import (
	"strconv"
	"strings"
	"time"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// The referral programme.
//
// THE RULES, decided by the owner on 2026-10-16 and bounded in code:
//
//	ONE FLAT TIER. A referrer's cut and a buyer's discount are two fixed
//	percentages. Nothing escalates with how old a name is or how long
//	its holder has been here: tenure could be bought (an old name keeps
//	its registration date through a sale), and an escalating table was
//	the reason a second wallet's code was worth up to 37% off.
//
//	AT MOST 10% TOGETHER. Cut plus discount never exceeds maxRefPercent,
//	whatever an admin stores; SetReferralRules refuses more, and the
//	reader clamps anything stored before. An admin can lower it, never
//	raise it.
//
//	FIRST YEAR ONLY. The cut and the discount apply to the registration,
//	which buys the first term. Renewals pay full price and pay nobody.
//
//	A CODE MUST HAVE BEEN HELD. A code earns only when it names a PAID
//	(not free-tier) name that its holder has kept for refHoldDays, by
//	the registry's own holding clock (nsdata.GetNameHeldSince). A wallet
//	made this morning, with a name bought this morning, is no referrer.
//
// What that does to the second-wallet trick: a buyer who quotes the code
// of a second wallet they control saves the discount and recovers the cut
// — at most 10% of the price, after waiting thirty days with a paid name
// in that wallet. TestASecondWalletEarnsAtMostTenPercent pins the number.
//
// SINGLE LEVEL, ALWAYS. One buyer, one referrer, one cut, taken out of
// an actual sale. There is no downline, no override on somebody else's
// referrals, and no bonus for recruiting other referrers — and there is
// no code here that could be extended into one without being obvious
// about it. That is the line between an affiliate programme and the
// other thing, and this realm stays on the near side of it.
//
// WHERE THE LINK LIVES. The referrer is recorded on the REFERRED NAME,
// in its extension slot, at the moment it is registered — a record of
// who brought the buyer, nothing that pays out any more. The vault
// destroys a name's extras when a lapsed name is re-registered and hides
// them the moment it changes hands, so a name that lapses or is sold
// forgets its referrer with no code here to make it so.
//
// WHO GETS PAID. The referrer's own address, fixed, at the moment of the
// sale (see PayoutFor). Nothing accrues and nothing is owed later: the
// cut is paid inside the registration or not at all.
//
// SELF-REFERRAL IS REFUSED. Otherwise the informed apply their own code
// and the cut becomes a silent discount for people who read the source.
//
// EVERYTHING SETTLES IN ONE TRANSACTION. Buyer pays, treasury is paid,
// referrer is paid, overpayment goes back — all inside the message the
// buyer signed. No escrow, no float, not for a block.
const (
	keyRef      = "ref"     // on a NAME: the referrer's address
	keyRefCut   = "refcut"  // global: the referrer's percentage, stored "0:N"
	keyRefDisc  = "refdisc" // global: the buyer's discount, stored "0:N"
	keyRefCount = "rc"      // ACCOUNT field (nsdata's per-address store): how many referred
	keyRefWin   = "refwin"  // global: days a captured code stays valid

	maxRefPercent = 10 // cut plus discount, together; an admin may lower it, never exceed it
	refHoldDays   = 30 // a code earns only once its holder has kept a paid name this long
)

// -- the rates --

// tierPercent reads a stored rate. The canonical form is a one-tier table
// at year zero, "0:N", which every reader of the old escalating tables —
// the site among them — reads as N at any tenure. A legacy multi-tier
// table counts only at year zero (RefRates asks for nothing else), so a
// table that once escalated cannot escalate now. Junk entries are
// skipped, not fatal, so one bad character cannot stop every sale; a
// percentage above the cap is clamped.
func tierPercent(spec string, years int64) int64 {
	best := int64(0)
	bestAt := int64(-1) // the threshold of the tier `best` came from
	for _, part := range strings.Split(spec, ",") {
		kv := strings.SplitN(strings.TrimSpace(part), ":", 2)
		if len(kv) != 2 {
			continue
		}
		at, err1 := strconv.ParseInt(strings.TrimSpace(kv[0]), 10, 64)
		pct, err2 := strconv.ParseInt(strings.TrimSpace(kv[1]), 10, 64)
		if err1 != nil || err2 != nil || at < 0 || pct < 0 {
			continue
		}
		if pct > maxRefPercent {
			pct = maxRefPercent
		}
		// The highest tier that applies, not the biggest number in the
		// table, so a table that tapers means what it reads as.
		if years >= at && at >= bestAt {
			bestAt = at
			best = pct
		}
	}
	return best
}

// RefRates is the flat cut and discount in force, in percent, clamped so
// that together they never exceed maxRefPercent whatever is stored. The
// discount is kept and the cut gives way: what a buyer was quoted is the
// promise, the cut is the treasury's to shrink.
func RefRates() (cutPct, discountPct int64) {
	return clampRates(tierPercent(RefCutRules(), 0), tierPercent(RefDiscountRules(), 0))
}

// clampRates is the 10% ceiling on its own, so it can be tested without a
// vault: negative inputs are zero, the discount is capped first, and the
// cut takes whatever room is left.
func clampRates(cut, disc int64) (int64, int64) {
	if cut < 0 {
		cut = 0
	}
	if disc < 0 {
		disc = 0
	}
	if disc > maxRefPercent {
		disc = maxRefPercent
	}
	if cut > maxRefPercent-disc {
		cut = maxRefPercent - disc
	}
	return cut, disc
}

// THE PRESET THE PROJECT LAUNCHES WITH: five percent to the referrer, five
// off for the buyer — the whole 10% the owner allowed, split evenly.
// Written here rather than typed into the admin panel at launch because a
// number that exists only in somebody's memory of a conversation gets set
// wrong once and noticed a month later. It is a DEFAULT, not a policy:
// SetReferralRules overwrites it, and empty rates switch the programme off.
const (
	defaultRefCut      = "0:5"
	defaultRefDiscount = "0:5"
)

// DefaultReferralRules lets the site show the presets before anybody
// commits them.
func DefaultReferralRules() (cut, discount string) {
	return defaultRefCut, defaultRefDiscount
}

// SeedReferralRules writes the presets, and ONLY into empty rates. Not an
// init(): at init a fresh logic realm is not yet trusted by the vault.
// Refusing to overwrite makes it safe to call twice and safe to call by
// mistake.
func SeedReferralRules(cur realm) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	if nsdata.GetGlobal(keyRefCut) != "" || nsdata.GetGlobal(keyRefDisc) != "" {
		panic("nslogic: referral rules are already set; use SetReferralRules to change them")
	}
	SetReferralRules(cur, defaultRefCut, defaultRefDiscount)
}

func RefCutRules() string      { return nsdata.GetGlobal(keyRefCut) }
func RefDiscountRules() string { return nsdata.GetGlobal(keyRefDisc) }

// RefWindowDays is how long a clicked link keeps counting for. It is
// enforced by the browser that captured the code, not by this realm —
// the chain never sees the click, only the registration that quotes a
// code — so it is stored here purely to be ONE number rather than a
// constant baked separately into the site, the FAQ and the rules page.
// Zero means the default; the site treats an absent value the same way.
func RefWindowDays() int64 {
	d := parseInt64(nsdata.GetGlobal(keyRefWin))
	if d <= 0 {
		return 30
	}
	return d
}

func SetReferralWindow(cur realm, days int64) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetReferralWindow", "days", fmtInt(days))
	if days < 0 || days > 3650 {
		panic("nslogic: window must be 0-3650 days")
	}
	setGlobal(cur, keyRefWin, strconv.FormatInt(days, 10))
}

// ReferralQuote is what a code is worth, answered before anybody signs
// anything. One call rather than four, because the site needs all of it
// at once to show a price.
//
// A referrer of "" means the code does not earn — it did not resolve, it
// is the buyer's own, it names a free-tier name, or its holder has not
// kept it for refHoldDays — and both percentages are then zero. `tenure`
// is the referrer's years held, for display only: it no longer moves
// either percentage.
func ReferralQuote(refName string, buyer address) (referrer address, tenure, discountPct, cutPct int64) {
	ref := resolveReferrer(refName, buyer)
	if ref == "" {
		return "", 0, 0, 0
	}
	cut, disc := RefRates()
	return ref, TenureYears(ref), disc, cut
}

// SetReferralRules sets both rates at once, because setting one without
// the other is how a cut ends up larger than the margin. Each is "N" or
// "0:N" (percent), or empty for none; two empties switch the programme
// off. Together they may not exceed maxRefPercent. A multi-tier table is
// refused: the programme has one tier.
func SetReferralRules(cur realm, cutSpec, discountSpec string) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetReferralRules", "cut", cutSpec, "discount", discountSpec)
	cut, cutPct := normalizeRate(cutSpec)
	disc, discPct := normalizeRate(discountSpec)
	if cutPct+discPct > maxRefPercent {
		panic("nslogic: a referrer's cut plus a buyer's discount may be at most " +
			strconv.Itoa(maxRefPercent) + "% — got " + strconv.FormatInt(cutPct+discPct, 10) + "%")
	}
	setGlobal(cur, keyRefCut, cut)
	setGlobal(cur, keyRefDisc, disc)
}

// normalizeRate reads one rate as an admin types it — "5", "0:5", or ""
// — and returns its stored form, "0:5" or "" for none, and the percent.
// Anything else panics before it can reach storage.
func normalizeRate(spec string) (stored string, pct int64) {
	s := strings.TrimSpace(spec)
	if s == "" {
		return "", 0
	}
	if kv := strings.SplitN(s, ":", 2); len(kv) == 2 {
		if strings.TrimSpace(kv[0]) != "0" {
			panic("nslogic: the referral programme has one flat tier; write N or 0:N — got " + spec)
		}
		s = strings.TrimSpace(kv[1])
	}
	p, err := strconv.ParseInt(s, 10, 64)
	if err != nil || p < 0 || p > maxRefPercent {
		panic("nslogic: a referral rate is a whole percent, 0-" + strconv.Itoa(maxRefPercent) + " — got " + spec)
	}
	if p == 0 {
		return "", 0
	}
	return "0:" + strconv.FormatInt(p, 10), p
}

// -- tenure, for display --

// TenureYears is how long a wallet counts as having been here, measured
// from its PRIMARY name. It used to pick the referral tier; it moves no
// money now, and stays because the referral page shows it.
//
// A lapsed or missing primary is zero years, not an error.
func TenureYears(who address) int64 {
	/* RESOLVED, NOT READ RAW. GetPrimary reports what an address last
	   SELECTED, not what it still holds — and a sale on the token ledger
	   no longer clears the seller's pointer. ResolveAddress re-checks the
	   owner and the expiry. */
	tid := ResolveAddress(who)
	at := strings.Index(tid, "*")
	if at < 1 {
		return 0
	}
	_, _, _, streak, _, _ := nsdata.GetNameInfo(tid[:at], tid[at+1:])
	return streak
}

// -- where it gets paid --

// Commissions go to the referring wallet. There is no way to redirect
// them, and that is a decision rather than an omission.
//
// There WAS a redirect — SetReferralPayout, "a forwarding address, not a
// transferable right". It does not survive the obvious question: how
// would this realm tell somebody moving money between their own two
// wallets from somebody who has sold the stream to a stranger? It
// cannot. Nothing on chain distinguishes those, and a rule that cannot
// be enforced is not a rule, it is a sentence in a document.
//
// So the destination is the referrer's own address, fixed. Selling the
// entitlement now means handing over private keys, which is a deterrent
// no contract clause could match.
func PayoutFor(who address) address { return who }

// -- the record on a name --

// ReferrerOf reads the wallet credited with a name, or the empty address.
func ReferrerOf(label, domainLabel string) address {
	v := nsdata.GetNameExtra(label, domainLabel, keyRef)
	if a := address(v); v != "" && a.IsValid() {
		return a
	}
	return ""
}

/*
resolveReferrer turns a claimed referring NAME into the wallet to credit,
or the empty address if the claim does not stand up. Every rejection is
silent on purpose: a mistyped code should not fail somebody's
registration, it should simply earn nobody anything.

THE CODE ITSELF must qualify: a paid name, live, held by its current
holder for refHoldDays. Checking the code rather than "any name the
referrer has" is one lookup instead of a registry walk, and the site
builds a holder's link from a name that qualifies.
*/
func resolveReferrer(refName string, buyer address) address {
	at := strings.Index(refName, "*")
	if refName == "" || at < 1 || at == len(refName)-1 {
		return ""
	}
	label, domainLabel := refName[:at], refName[at+1:]
	if !nsdata.NameExists(label, domainLabel) || !nsdata.IsNameValid(label, domainLabel) {
		return "" // a lapsed name is not a working code
	}
	owner := nsdata.GetNameOwner(label, domainLabel)
	if owner == buyer {
		return "" // no referring yourself
	}
	if !nsdata.IsNamePaid(label, domainLabel) {
		return "" // a free-tier name is not a code
	}
	if !heldLongEnough(nsdata.GetNameHeldSince(label, domainLabel), time.Now().Unix()) {
		return "" // not held long enough, or bought and not yet seen by the registry
	}
	return owner
}

// heldLongEnough is the thirty-day rule on its own. A zero `since` means
// the registry has not seen the current holder yet — never long enough.
func heldLongEnough(since, now int64) bool {
	return since > 0 && now >= since && now-since >= refHoldDays*86400
}

/*
StartReferralClock starts the holding clock on a name the caller BOUGHT,
so that thirty days later it can be a referral code.

A sale that settles on the token ledger never calls the registry, so the
registry first sees a buyer at their first write to the name. A buyer who
never edits a profile would otherwise never qualify. This is that first
write, with nothing in it: it clears the seller's stale data, which every
read already hides, and stamps the clock. Names you registered yourself
start their clock at registration and need nothing.
*/
func StartReferralClock(cur realm, label, domainLabel string) {
	assertNoSend(cur)
	assertNameOwner(cur, label, domainLabel)
	if err := nsdata.FreshenNameRecord(cross(cur), label, domainLabel); err != nil {
		panic("nslogic: " + err.Error())
	}
}

// -- the money --

// PriceWithReferral is what a buyer actually pays given the code they
// arrived with. Exported so the site can display the number the chain
// will charge instead of computing its own and hoping they agree.
func PriceWithReferral(domainLabel, label, refName string, buyer address) int64 {
	price := NamePrice(domainLabel, label)
	if price <= 0 {
		return 0 // free is free, and a percentage of nothing is nothing
	}
	if resolveReferrer(refName, buyer) == "" {
		return price
	}
	_, disc := RefRates()
	return price - price*disc/100
}

// referralCut is what leaves for a qualifying referrer out of a
// registration's payment of `price` (already discounted). Returns the
// destination and the amount; the caller pays it in the same call that
// pays the treasury. Registration only: renewals pay nobody.
func referralCut(ref address, price int64) (address, int64) {
	if ref == "" || price <= 0 {
		return "", 0
	}
	cutPct, _ := RefRates()
	cut := price * cutPct / 100
	if cut <= 0 {
		return "", 0
	}
	return PayoutFor(ref), cut
}

// -- the scoreboard --

// creditReferral records one paid referral against a wallet.
//
// The COUNT and nothing else. There was a running total of micro-USD
// beside it, and it is gone, because a number stored in the vault is a
// number anyone with an RPC endpoint can read — there is no such thing
// as an admin-only global on a public chain, and building the site as
// though there were would be the kind of privacy that works right up
// until somebody checks.
//
// Not storing it is the only real reduction available. The payments are
// still in the block history and always will be, so anyone determined
// can add them up; what we can decline to do is publish a convenient
// running total ourselves. tools/referrals.py reconstructs it from the
// chain when we want it, which costs no storage and publishes nothing.
//
// The registrant's transaction pays for this entry: one small field,
// written once per referrer and overwritten after — the price of the
// discount they just received.
//
// IT LIVES IN THE VAULT'S PER-ADDRESS STORE, and until it did, no referred
// registration ever succeeded. It was the global "ref:" + address, 44
// bytes against a 32-byte cap on global keys; the vault refused it, this
// panicked, and the whole purchase reverted after the price was taken —
// on every chain the programme ran on. A key that short would only have
// moved the failure: globals held at most 24 entries, shared with the
// price list, so it would have broken again at about the twenty-first
// referrer. An address is a key there now, and each wallet's fields are
// bounded on their own.
func creditReferral(cur realm, ref address) {
	if ref == "" {
		return
	}
	if err := nsdata.SetAccountRecord(cross(cur), ref, keyRefCount,
		strconv.FormatInt(ReferralCount(ref)+1, 10)); err != nil {
		panic("nslogic: " + err.Error())
	}
}

// ReferralCount is how many paid registrations a wallet has been
// credited with. Public, like everything in the vault.
func ReferralCount(who address) int64 {
	return parseInt64(nsdata.GetAccount(who, keyRefCount))
}

func parseInt64(s string) int64 {
	v, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
	if err != nil {
		return 0
	}
	return v
}

// How many vault pages one ReferralBoard call may scan.
const refBoardPages = 5

// ReferralBoard pages through every credited wallet for the
// leaderboard: one "address,count" row per line.
//
// It walks the vault's per-address store, where other fields (credits)
// sit beside the counters, so a page can scan more keys than it returns.
// `next` is an opaque cursor — pass it back as `after` — and is non-empty
// whenever the walk stopped before the end, including when it stopped on
// its scanning budget with fewer rows than asked for. A caller keeps
// going until `next` is empty.
func ReferralBoard(after string, limit int) (rows, next string) {
	if limit <= 0 || limit > 200 {
		limit = 200
	}
	var out []string
	from := after
	for page := 0; page < refBoardPages; page++ {
		keys, more := nsdata.ExportAccounts(from, 200)
		if keys == "" {
			return strings.Join(out, "\n"), ""
		}
		for _, k := range strings.Split(keys, ",") {
			from = k
			at := strings.Index(k, ":")
			if at < 0 || k[at+1:] != keyRefCount {
				continue
			}
			addr := k[:at]
			n := ReferralCount(address(addr))
			if n <= 0 {
				continue
			}
			out = append(out, addr+","+strconv.FormatInt(n, 10))
			if len(out) >= limit {
				return strings.Join(out, "\n"), k
			}
		}
		if more == "" {
			return strings.Join(out, "\n"), ""
		}
	}
	return strings.Join(out, "\n"), from
}

reserved.gno

package nslogic

import (
	"strconv"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// GENERATED BY tools/gen-reserved.py FROM collections/reserved-labels.json.
// Do not edit by hand: the site reads the same source, and a change made
// in one place only is a label the site offers and the chain refuses.
//
// STRUCTURAL RULES ONLY. The wordlists live off chain, in that JSON,
// because storage is 100 ugnot per byte and a ten-thousand-word
// dictionary is about 57 GNOT paid forever to encode a marketing
// decision that will change. This is the backstop against a bug in the
// issuer, not the place the policy lives.
//
// THE NUMBERS ARE SETTABLE, the shape is not. A minimum length is a
// promotion knob and belongs in the panel — redeploying this realm to
// change a 5 to a 4 costs about 22 GNOT. So the lengths read from the
// vault's globals and fall back to the values generated here; the
// pattern rules are structural facts about what a handle looks like and
// stay in code.

const (
	defaultFreeMinLength = 5
	defaultFreeMaxLength = 63

	keyFreeMin = "freemin"
	keyFreeMax = "freemax"
)

// FreeMinLength is the shortest label the free tier will issue. Settable
// from the panel, because which lengths are worth money is a commercial
// judgement that moves.
func FreeMinLength() int {
	if v := nsdata.GetGlobal(keyFreeMin); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 63 {
			return n
		}
	}
	return defaultFreeMinLength
}

func FreeMaxLength() int {
	if v := nsdata.GetGlobal(keyFreeMax); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 63 {
			return n
		}
	}
	return defaultFreeMaxLength
}

/*
FreeLabelAllowed reports whether a label may be ISSUED on the free tier.

ISSUED, and never renewed. This is called by GrantFreeName and by
nothing else, deliberately: if the minimum length rises from three to
five, somebody who already holds a three-character free name keeps it
and keeps renewing it free. Tightening a rule must not reach backwards
and take away what was already given — that is the single fastest way to
make a giveaway cost more trust than it ever bought.

A name that LAPSES and is registered again is a new issuance, and gets
whatever the rules say that day. That is not retroactive; it is a
different name event.
*/
func FreeLabelAllowed(label string) bool {
	n := len(label)
	if n < FreeMinLength() || n > FreeMaxLength() {
		return false
	}
	// Pure digits: 1337, 420, years. Collectible, and no handle is one.
	digits := true
	for i := 0; i < n; i++ {
		if label[i] < '0' || label[i] > '9' {
			digits = false
			break
		}
	}
	if digits {
		return false
	}
	// aaaa — every character the same.
	same := true
	for i := 1; i < n; i++ {
		if label[i] != label[0] {
			same = false
			break
		}
	}
	if same {
		return false
	}
	// abab — a two-character cycle. Also collectible, also not a handle.
	if n >= 4 {
		cycle := true
		for i := 2; i < n; i++ {
			if label[i] != label[i-2] {
				cycle = false
				break
			}
		}
		if cycle {
			return false
		}
	}
	return true
}

restore.gno

package nslogic

import (
	"chain"
	"strconv"
	"strings"
	"time"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

/*
REBUILDING THE REGISTRY ON A NEW CHAIN.

WHY THIS EXISTS. gno.land replaces testnets rather than preserving them:
topaz-1 was superseded by sapphire-1 on twenty-four hours' notice and
every name registered on it went to zero. tools/snapshot.js keeps a
complete off-chain copy of the vault for exactly that morning. This is
the other half — the path that turns a snapshot back into a live
registry, so that people who paid for a name get that name back rather
than an apology.

THIS IS A BACKDOOR, AND IT IS TREATED AS ONE.

A function that can mint any name, to any address, with any registration
date, is precisely the thing that would make every name here worthless
if it could be reached whenever the admin felt like it. Ownership means
nothing if history is editable on demand. So the capability is not
merely admin-gated — admin-gated is what everything else here already
is, and it is not enough for this. It is a ONE-SHOT:

  - it starts closed, and on a chain where nothing needs restoring it is
    sealed immediately and can never be used at all;
  - opening it is a deliberate, separate, announced act with a deadline
    attached, so forgetting to close it is not the same as leaving it
    open forever;
  - sealing is IRREVERSIBLE. Sealed cannot be reopened. There is no
    argument that unseals it, including a good one;
  - it refuses to touch a name that already exists. It fills gaps in an
    empty registry; it cannot rewrite a live one.

WHERE THE SEAL LIVES, AND WHY IT IS NOT HERE. This realm holds no state
at all — that is the whole reason prices and names survive a logic
upgrade untouched. If the seal lived in this realm's variables it would
reset to "never opened" the moment a new generation was deployed, which
would make "irreversible" a lie with a two-hour shelf life. It lives in
the vault's global slot instead, so a new logic generation inherits a
seal it cannot talk its way out of.

WHAT THAT DOES AND DOES NOT GUARANTEE. It is a real barrier against
every accident and against this realm being reached later for something
it was not built for. It is not a barrier against the admin themselves,
who can deploy a further logic realm and have the vault trust it — but
that is already total control by definition, and no flag in a realm the
admin can replace was ever going to change it. What the seal gives is
the thing that actually matters in practice: the state is public, it is
checkable by anybody at any time through RestoreStatus, and moving it
backwards leaves a permanent trace on chain.

WHAT IT DELIBERATELY DOES NOT RESTORE. Marketplace listings and open
votes. Those live in their own realms, are intentions rather than facts,
and are re-creatable by the people who made them in one transaction
each. Re-materialising somebody's month-old asking price as though they
had just set it would be inventing a decision on their behalf.
*/

// The vault key holding the state of this whole mechanism.
const keyRestore = "restore"

// Restore states, stored as a string in the vault's global slot.
const (
	restoreNever  = ""       // never opened; the normal state forever
	restoreSealed = "sealed" // closed permanently; cannot be reopened
	restoreOpen   = "open:"  // followed by the unix second it lapses
)

// The longest a restore window may be left open. A restore is a day of
// work, not a season, and an unbounded window is just "open forever"
// spelled differently — the failure here is nobody remembering to seal
// it, so the deadline seals it for them.
const maxRestoreDays = 30

// RestoreStatus reports the state of the restore mechanism in a form a
// person can read, and is deliberately PUBLIC AND UNAUTHENTICATED.
// Anybody at all can check whether this registry currently has a door in
// it, without asking us and without trusting the answer we would give.
//
// Returns the state ("never", "open", "expired" or "sealed"), the unix
// second an open window lapses (0 otherwise), and how many records have
// been restored in the lifetime of this vault.
func RestoreStatus() (state string, deadline int64, restored int64) {
	st, d := readRestoreState(nsdata.GetGlobal(keyRestore), time.Now().Unix())
	return st, d, restoredCount()
}

// readRestoreState is the state machine on its own, with the clock passed
// in. Split out so the one piece of logic that decides whether the door
// is open can be tested exhaustively without a chain under it.
func readRestoreState(raw string, now int64) (state string, deadline int64) {
	switch {
	case raw == restoreSealed:
		return "sealed", 0
	case strings.HasPrefix(raw, restoreOpen):
		d, err := strconv.ParseInt(raw[len(restoreOpen):], 10, 64)
		if err != nil || d <= 0 {
			// An unparseable deadline is read as NO permission. The safe
			// reading of a door whose lock is broken is "shut" — a corrupt
			// value must never widen what somebody is allowed to do.
			return "sealed", 0
		}
		if now >= d {
			return "expired", d
		}
		return "open", d
	}
	return "never", 0
}

const keyRestoredCount = "restored"

func restoredCount() int64 {
	if v := nsdata.GetGlobal(keyRestoredCount); v != "" {
		if n, err := strconv.ParseInt(v, 10, 64); err == nil {
			return n
		}
	}
	return 0
}

/*
THE RESTORE KEYS GO THROUGH THE VAULT'S RESERVED DOOR, and every refusal
panics.

They used to go through SetGlobalRecord, written for the first vault,
which had no reserved keys. This vault refuses "restore" and "restored"
there — and the three call sites threw the error away. So SealRestore
returned success and sealed nothing, OpenRestore returned success and
opened nothing (every Restore* call then said "never been opened", in the
middle of a paused migration), and the counter never moved. A returned
error in gno does not revert anything; ignoring one is how a control
reads as live while doing nothing.

SetReservedGlobalRecord is the machinery's own door, and the vault now
refuses to change a seal through it as well: a sealed restore stays
sealed whatever any logic realm asks, so a future logic generation
cannot talk its way out of it either.
*/
func setRestoreKey(cur realm, key, value string) {
	if err := nsdata.SetReservedGlobalRecord(cross(cur), key, value); err != nil {
		panic("nslogic: " + err.Error())
	}
}

func bumpRestored(cur realm, n int64) {
	setRestoreKey(cur, keyRestoredCount, strconv.FormatInt(restoredCount()+n, 10))
}

/*
assertNotRestoring CLOSES REGISTRATION WHILE A RESTORE WINDOW IS OPEN
(re-audit 2026-10-16, M-4). The window opens on an empty registry, and the
snapshots it replays are committed to the repository, so the list of who
held what is public: anybody could register a holder's name before its
batch arrived — at the genesis price, before the price rules were back —
and the holder never got it back, while the batch holding it reverted and
stopped the run. Every door that creates a name, or makes a free one
sellable, passes this: RegisterName and RegisterNameRef, RedeemCredit and
RegisterFor, GrantFreeName, UpgradeFreeName (and the lab's RegisterLabName).
Sealed, or lapsed, the registry sells again.
*/
func assertNotRestoring() {
	if st, _ := readRestoreState(nsdata.GetGlobal(keyRestore), time.Now().Unix()); st == "open" {
		panic("nslogic: the registry is being restored; registration reopens once the restore is sealed")
	}
}

// assertRestoring is the gate every Restore* function passes through.
func assertRestoring(cur realm) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	state, _, _ := RestoreStatus()
	switch state {
	case "open":
		return
	case "sealed":
		panic("nslogic: restore was sealed and cannot be reopened. This is " +
			"not recoverable by design — a registry whose history can be " +
			"rewritten on request does not have owners, it has guests.")
	case "expired":
		panic("nslogic: the restore window has lapsed. Deploy a fresh vault " +
			"and open a new window there; an expired one does not reopen.")
	}
	panic("nslogic: restore has never been opened. Call OpenRestore first, " +
		"and mean it.")
}

// OpenRestore opens the window, once, for a bounded number of days.
//
// Only ever valid on a chain where the registry is EMPTY because the
// previous chain was retired. It cannot be called on a vault that has
// been sealed, and it cannot be called twice.
func OpenRestore(cur realm, days int64) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "OpenRestore", "days", fmtInt(days))

	state, _, _ := RestoreStatus()
	if state != "never" {
		panic("nslogic: restore may be opened exactly once per vault; this " +
			"one is already " + state + ". A door that reopens is a door.")
	}
	if days < 1 || days > maxRestoreDays {
		panic("nslogic: a restore window must be between 1 and " +
			strconv.Itoa(maxRestoreDays) + " days")
	}
	/* THE PRECONDITION THE COMMENT ABOVE ALREADY CLAIMS.
	   "Only ever valid on a chain where the registry is EMPTY" was a
	   statement of intent that nothing enforced, so the window was
	   openable on a populated vault. The record restorers all refuse an
	   existing record, but RestoreNameField does not — it writes any
	   extension key on any EXISTING name, which includes the payment
	   addresses the site renders on a name's pay page. That is a way to
	   redirect somebody else's incoming money using only the admin key,
	   without the timelock and public event that granting a fresh logic
	   realm would cost. Now it is what it said it was. */
	/* NAMES ONLY, not domains. A registry is now born with its domains
	   (genesis), so "no domains" can never be true again and the guard
	   would have made disaster recovery impossible on every new chain.
	   The hazard it exists for is RestoreNameField writing onto EXISTING
	   NAMES — somebody's pay address — and only names carry that. */
	if _, n, _, _ := nsdata.Sizes(); n != 0 {
		panic("nslogic: restore is for a registry holding no names yet; " +
			"this one already holds records")
	}
	// TIMELOCKED (timelock.gno). This is the door that mints any name to
	// anybody with any date; on a fresh registry, before the first name and
	// before SealRestore, a stolen admin key could otherwise open it at once.
	requireAction(cur, actionID("OpenRestore", strconv.FormatInt(days, 10)))
	deadline := time.Now().Unix() + days*86400
	setRestoreKey(cur, keyRestore, restoreOpen+strconv.FormatInt(deadline, 10))
}

// SealRestore closes the door permanently. Valid from any state,
// including "never" — which is how it should be called on a chain that
// has nothing to restore, so that the capability is provably dead rather
// than merely unused.
//
// There is no matching unseal, and adding one later would defeat every
// word written at the top of this file.
func SealRestore(cur realm) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SealRestore")
	setRestoreKey(cur, keyRestore, restoreSealed)
	// Read back, not assumed: this call used to report success while the
	// state stayed "never".
	if st, _, _ := RestoreStatus(); st != "sealed" {
		panic("nslogic: the seal did not land; restore reads " + st)
	}
}

/*
RestoreDomain re-creates one domain with its original dates.

ORDER MATTERS: domains before their names. The vault refuses to register
a name under a domain that does not exist or had lapsed at the moment
the name claims to have been registered, which is correct behaviour and
also exactly the order a snapshot should be replayed in.

The vault's own registration path sets `registered` to whatever instant
it is handed and derives the expiry from the term length, so the
registration date is restored by passing the ORIGINAL one, and the
expiry is then corrected to the recorded value rather than a computed
one. Anything else would quietly hand everybody a fresh term.
*/
func RestoreDomain(cur realm, label string, owner address, registered, expires, ttl int64, frozen bool) {
	assertRestoring(cur)
	emitAdmin(cur, "RestoreDomain", "label", label, "owner", owner.String())
	if nsdata.DomainExists(label) {
		panic("nslogic: " + label + " already exists; restore fills an empty " +
			"registry and never overwrites a live record")
	}
	if registered <= 0 || expires <= 0 {
		panic("nslogic: a restored record needs its original dates")
	}
	if err := nsdata.RegisterDomainRecord(cross(cur), label, owner, registered); err != nil {
		panic("nslogic: " + err.Error())
	}
	nsdata.SetDomainExpiryRecord(cross(cur), label, expires)
	ttl = clampTTL(ttl)
	if ttl != 0 {
		if err := nsdata.SetDomainTTLRecord(cross(cur), label, ttl); err != nil {
			panic("nslogic: " + err.Error())
		}
	}
	if frozen {
		nsdata.SetDomainFrozen(cross(cur), label, true)
	}
	bumpRestored(cur, 1)
}

// RestoreName re-creates one name. See RestoreDomain on ordering and on
// why the dates are passed rather than computed.
//
// isNFT is carried across under its old name so snapshot blobs stay
// readable, and now means PAID: false restores a free-tier name with the
// hold on its token, so a restore can never quietly make a free name
// sellable.
func RestoreName(cur realm, label, domainLabel string, owner address, registered, expires, ttl int64, frozen, isNFT bool) {
	assertRestoring(cur)
	emitAdmin(cur, "RestoreName", "label", label, "domain", domainLabel, "owner", owner.String())
	if nsdata.NameExists(label, domainLabel) {
		panic("nslogic: " + label + "*" + domainLabel + " already exists; " +
			"restore fills an empty registry and never overwrites a live record")
	}
	if registered <= 0 || expires <= 0 {
		panic("nslogic: a restored record needs its original dates")
	}
	// RestoreNameRecord, not RegisterNameRecord: it ADOPTS a token the
	// ledger already holds, which is the whole point of a migration —
	// records move, tokens do not. If the ledger's holder is not the
	// snapshot's owner, the record is written for the holder and the
	// snapshot's profile is not replayed onto it.
	if err := nsdata.RestoreNameRecord(cross(cur), label, domainLabel, owner, registered, isNFT); err != nil {
		panic("nslogic: " + err.Error())
	}
	nsdata.SetNameExpiryRecord(cross(cur), label, domainLabel, expires)
	ttl = clampTTL(ttl)
	if ttl != 0 {
		if err := nsdata.SetNameTTLRecord(cross(cur), label, domainLabel, ttl); err != nil {
			panic("nslogic: " + err.Error())
		}
	}
	if frozen {
		nsdata.SetNameFrozen(cross(cur), label, domainLabel, true)
	}
	bumpRestored(cur, 1)
}

/*
RestoreNames replays many names in ONE transaction.

WHY A BLOB AND NOT A LOOP OF CALLS. A restore is done in one sitting
against a clock: the window is bounded and the people whose names are
missing are watching. One transaction per name is one signature per
name, and at a few hundred names that is an afternoon of clicking during
which a single mistimed refresh loses the thread. The compact form here
is unpleasant to read and it is the difference between a restore that
gets finished and one that gets abandoned half way.

The format is records separated by "|", fields separated by ",":

	label,domain,owner,registered,expires,ttl,frozen,isNFT

Neither a label nor a domain may contain "," or "|" — the character set
is enforced at registration — and an address contains neither, so the
split is unambiguous. tools/snapshot.js writes the JSON this is built
from; see tools/restore-blob.js for the conversion.

It stops at the first bad record and panics, taking the whole
transaction with it. That is deliberate: a partial batch that silently
skipped four names would leave four people without theirs and nothing
anywhere saying which four.
*/
func RestoreNames(cur realm, blob string) int {
	assertRestoring(cur)
	emitAdmin(cur, "RestoreNames", "bytes", fmtI(len(blob)))
	if blob == "" {
		panic("nslogic: nothing to restore")
	}
	recs := strings.Split(blob, "|")
	if len(recs) > 50 {
		panic("nslogic: at most 50 records per call, or the transaction " +
			"runs out of gas half way and it is unclear what landed")
	}
	done := 0
	for i, rec := range recs {
		if rec == "" {
			continue
		}
		r := parseRestoreRecord(rec, i)
		if nsdata.NameExists(r.label, r.domain) {
			panic("nslogic: record " + strconv.Itoa(i) + " (" + r.label + "*" + r.domain +
				") already exists; restore never overwrites a live record")
		}
		if err := nsdata.RestoreNameRecord(cross(cur), r.label, r.domain, r.owner, r.registered, r.isNFT); err != nil {
			panic("nslogic: record " + strconv.Itoa(i) + ": " + err.Error())
		}
		nsdata.SetNameExpiryRecord(cross(cur), r.label, r.domain, r.expires)
		if r.ttl != 0 {
			if err := nsdata.SetNameTTLRecord(cross(cur), r.label, r.domain, r.ttl); err != nil {
				panic("nslogic: record " + strconv.Itoa(i) + ": " + err.Error())
			}
		}
		if r.frozen {
			nsdata.SetNameFrozen(cross(cur), r.label, r.domain, true)
		}
		done++
	}
	bumpRestored(cur, int64(done))
	return done
}

// restoreRec is one parsed line of the blob.
type restoreRec struct {
	label, domain string
	owner         address
	registered    int64
	expires, ttl  int64
	frozen, isNFT bool
}

/*
parseRestoreRecord reads one record and refuses anything it is not sure
about.

EVERY CHECK HERE IS A PANIC AND NOT A SKIP. The blob is machine-written
from a snapshot, so a malformed record does not mean "this one name is
odd", it means the file is not what it was believed to be — and the
worst outcome available is a restore that appears to succeed while
quietly dropping the records it could not read. Somebody would find out
months later when one person asked where their name went.
*/
func parseRestoreRecord(rec string, i int) restoreRec {
	f := strings.Split(rec, ",")
	if len(f) != 8 {
		panic("nslogic: record " + strconv.Itoa(i) + " has " +
			strconv.Itoa(len(f)) + " fields, expected 8 " +
			"(label,domain,owner,registered,expires,ttl,frozen,isNFT)")
	}
	if f[0] == "" || f[1] == "" {
		panic("nslogic: record " + strconv.Itoa(i) + " has no name")
	}
	out := restoreRec{
		label:      f[0],
		domain:     f[1],
		owner:      address(f[2]),
		registered: mustSecs(f[3], i, "registered"),
		expires:    mustSecs(f[4], i, "expires"),
		ttl:        ttlSecs(f[5], i),
		frozen:     f[6] == "1",
		isNFT:      f[7] == "1",
	}
	if !out.owner.IsValid() {
		panic("nslogic: record " + strconv.Itoa(i) + " has an invalid owner address")
	}
	if out.registered <= 0 || out.expires <= 0 {
		panic("nslogic: record " + strconv.Itoa(i) + " is missing its original dates")
	}
	// An expiry before the registration is not a record, it is a
	// corruption, and restoring it would create a name that was already
	// reclaimable the day it was bought.
	if out.expires < out.registered {
		panic("nslogic: record " + strconv.Itoa(i) + " expires before it was registered")
	}
	return out
}

func mustSecs(s string, i int, what string) int64 {
	v, err := strconv.ParseInt(s, 10, 64)
	if err != nil || v < 0 {
		panic("nslogic: record " + strconv.Itoa(i) + " has a bad " + what)
	}
	return v
}

/*
ttlSecs reads a TTL and caps it at maxTTL (name.gno). A holder may have set
any non-negative int64 before the cap existed, and a snapshot written by
JavaScript rounded such a value above 2^53 — MaxInt64 came back as
9223372036854776000, which no int64 holds — so the whole batch of fifty
reverted (re-audit 2026-10-16, M-3). A run of digits too large to parse is
read as the longest a TTL may be; anything else malformed still refuses
the record.
*/
func ttlSecs(s string, i int) int64 {
	if v, err := strconv.ParseInt(s, 10, 64); err == nil && v >= 0 {
		return clampTTL(v)
	}
	if s != "" && len(s) <= 40 && strings.Trim(s, "0123456789") == "" {
		return maxTTL
	}
	panic("nslogic: record " + strconv.Itoa(i) + " has a bad ttl")
}

func clampTTL(v int64) int64 {
	if v > maxTTL {
		return maxTTL
	}
	return v
}

// RestoreNameField and RestoreDomainField put back a record's extension
// keys — profiles, cross-chain addresses, tier markers, and a domain's
// pricing rules. Separate calls because the extension slot has no fixed
// shape by design, which is the same reason the snapshot captures it by
// enumeration rather than by schema.
func RestoreNameField(cur realm, label, domainLabel, key, value string) {
	assertRestoring(cur)
	emitAdmin(cur, "RestoreNameField", "label", label, "domain", domainLabel, "key", key)
	/* ONLY ONTO A RECORD A RESTORE WROTE, AND ONLY FOR ITS HOLDER.

	   Profile fields include pay addresses, so replaying one is replaying
	   where money goes. Two audit findings meet here: a name sold between
	   the snapshot and the restore would have had the seller's addresses
	   written onto the buyer's name, and a name a user registered DURING
	   the restore window could have had its pay fields rewritten with the
	   admin key alone. RestoredFor is set only by RestoreNameRecord, and
	   only when the ledger's holder matched the snapshot.

	   Skipped rather than panicked, deliberately: a blob of fields rides in
	   one transaction, and one sold name must not abort everybody else's
	   restore. tools/restore-blob.js reads the fields back afterwards. */
	rf := nsdata.RestoredFor(label, domainLabel)
	if rf == "" || nsdata.GetNameOwner(label, domainLabel) != rf {
		return
	}
	if err := nsdata.SetNameExtraRecord(cross(cur), label, domainLabel, key, value); err != nil {
		panic("nslogic: " + err.Error())
	}
}

func RestoreDomainField(cur realm, label, key, value string) {
	assertRestoring(cur)
	emitAdmin(cur, "RestoreDomainField", "label", label, "key", key, "value", value)
	if err := nsdata.SetDomainExtraRecord(cross(cur), label, key, value); err != nil {
		panic("nslogic: " + err.Error())
	}
}

// RestoreGlobal puts back the vault's global slot — where the default
// price, the referral tiers and the seasonal card effects live.
//
// It refuses to write the restore keys themselves. Without that, a
// snapshot taken while a window was open would, on being replayed,
// cheerfully restore the open window along with everything else — and a
// seal that a backup file can undo is not a seal.
func RestoreGlobal(cur realm, key, value string) {
	assertRestoring(cur)
	emitAdmin(cur, "RestoreGlobal", "key", key, "value", value)
	if key == keyRestore || key == keyRestoredCount {
		panic("nslogic: the restore mechanism does not restore itself")
	}
	// NOR A ROLE, the rule genesis keeps (nsdata refusedInGenesis): the
	// granter, the keeper, the lab nomination or anything address-valued
	// is a power, set deliberately on the chain it belongs to, never by a
	// backup file round the timelock (re-audit 2026-10-16, L-7). SKIPPED,
	// not refused, like a stale reverse pointer: globals travel fifty to a
	// transaction, and one sandbox's lab nomination must not stop the whole
	// restore (review follow-up). The AdminAction above says it was asked.
	if key == keyGranter || key == keyKeeper || key == "labdomain" || looksLikeAddress(value) {
		chain.Emit("RestoreSkipped", "key", key, "why", "a role or an address; name it again through its own setter")
		return
	}
	if err := nsdata.SetGlobalRecord(cross(cur), key, value); err != nil {
		panic("nslogic: " + err.Error())
	}
}

// RestoreAccountField puts back one field of the per-address store —
// credits and their redemptions, referral counts. Without it a rebuilt
// registry would forget who had already spent their free name, and the
// migration grant could be claimed twice.
func RestoreAccountField(cur realm, owner address, key, value string) {
	assertRestoring(cur)
	emitAdmin(cur, "RestoreAccountField", "owner", owner.String(), "key", key, "value", value)
	// A credit's grant time is never in the future: one written through
	// this door would escape every void recovery could ever declare.
	if key == keyCredit && value != "" {
		if c := parseCredit(value); c.granted > 0 || c.used > 0 {
			if now := time.Now().Unix(); c.at > now {
				c.at = now
			}
			value = c.encode()
		}
	}
	if err := nsdata.SetAccountRecord(cross(cur), owner, key, value); err != nil {
		panic("nslogic: " + err.Error())
	}
}

// RestorePrimary puts back reverse resolution — which name an address
// answers to. Registration already sets this for an owner who had none,
// so this exists for the owners who had chosen a different one.
//
// SKIPPED, NOT REFUSED, when the vault would refuse it — the name is not
// there, or the ledger says somebody else holds it (a sale leaves the
// seller's pointer behind): pointers travel fifty to a transaction, and one
// stale pointer must not revert everybody else's (re-audit 2026-10-16, M-3).
func RestorePrimary(cur realm, owner address, label, domainLabel string) {
	assertRestoring(cur)
	emitAdmin(cur, "RestorePrimary", "owner", owner.String(), "label", label, "domain", domainLabel)
	if !nsdata.NameExists(label, domainLabel) || nsdata.GetNameOwner(label, domainLabel) != owner {
		return
	}
	if err := nsdata.SetPrimaryRecord(cross(cur), owner, label, domainLabel); err != nil {
		panic("nslogic: " + err.Error())
	}
}

term.gno

package nslogic

import (
	"strconv"
	"time"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// How far ahead a name may be paid.
//
// Renewal was unbounded. RenewNameRecord adds one term to the previous
// due date and asks no further questions, so a holder pressing renew
// seven times bought seven years of runway, and nothing anywhere said
// that was not intended. It is a bug in two directions at once:
//
//   - Free domains have a base price of zero. Renewal is free too, so a
//     script could take every good name under *gnoland and hold it for a
//     century for the cost of gas. There is no economic brake on a free
//     name at all; the term limit IS the brake.
//   - A paid name held fifty years ahead is fifty years of a promise we
//     have made against a rate written by hand and a testnet that will
//     be replaced. Selling that is easy and honouring it is not.
//
// The limit is RUNWAY, not total lifetime: at most N years may be
// outstanding at any moment. Nobody is stopped from holding a name
// forever — they renew as the runway burns down, which is the same
// arrangement every domain registrar has always used and the one people
// already understand.
//
// Per domain first, then a project-wide default, so a free domain can be
// capped at one year without capping anything else.
const (
	keyMaxTerm      = "maxterm" // domain extra AND global: years of runway
	defaultMaxTerm  = int64(5)
	maxMaxTermYears = int64(100)
)

// MaxTermYears is the cap that applies to names under this domain.
func MaxTermYears(domainLabel string) int64 {
	if v := nsdata.GetDomainExtra(domainLabel, keyMaxTerm); v != "" {
		if y, err := strconv.ParseInt(v, 10, 64); err == nil && y > 0 {
			return y
		}
	}
	if v := nsdata.GetGlobal(keyMaxTerm); v != "" {
		if y, err := strconv.ParseInt(v, 10, 64); err == nil && y > 0 {
			return y
		}
	}
	return defaultMaxTerm
}

// SetMaxTerm caps a single domain, or the whole project when the domain
// label is empty. A domain's own cap always wins, so tightening one free
// domain does not disturb the rest.
func SetMaxTerm(cur realm, domainLabel string, years int64) {
	assertNoSend(cur)
	assertIsAdmin(cur)
	emitAdmin(cur, "SetMaxTerm", "domain", domainLabel, "years", fmtInt(years))
	if years < 1 || years > maxMaxTermYears {
		panic("nslogic: term cap must be 1-100 years")
	}
	v := strconv.FormatInt(years, 10)
	if domainLabel == "" {
		setGlobal(cur, keyMaxTerm, v)
		return
	}
	if !nsdata.DomainExists(domainLabel) {
		panic("nslogic: unknown domain")
	}
	if err := nsdata.SetDomainExtraRecord(cross(cur), domainLabel, keyMaxTerm, v); err != nil {
		panic(err)
	}
}

// RenewalsLeft is how many more years may be added to a name right now.
// Zero means the renew button should be off, and the site reads this
// rather than doing the arithmetic itself — the cap can be per domain,
// and a page that guesses it will guess wrong on exactly the domains
// where it matters.
//
// An unregistered name reports the full allowance: nothing is holding
// runway yet.
func RenewalsLeft(label, domainLabel string) int64 {
	maxYears := MaxTermYears(domainLabel)
	if !nsdata.NameExists(label, domainLabel) {
		return maxYears
	}
	term := nsdata.GetTermLength()
	if term <= 0 {
		return 0
	}
	_, _, expires, _, _, _ := nsdata.GetNameInfo(label, domainLabel)
	return renewalsLeft(expires, time.Now().Unix(), term, maxYears)
}

// renewalsLeft is the arithmetic on its own, so it can be tested without
// a chain under it.
//
// Runway is measured from NOW, not from the registration date, so a name
// deep in its grace period counts as zero rather than as a negative that
// would then read as extra room. Years already bought round UP: a name
// with thirteen months left is holding two of its five, because the
// alternative lets somebody sit permanently at four-years-and-eleven-
// months and renew every month forever.
func renewalsLeft(expires, now, term, maxYears int64) int64 {
	if term <= 0 {
		return 0
	}
	runway := expires - now
	if runway < 0 {
		runway = 0
	}
	left := maxYears - (runway+term-1)/term
	if left < 0 {
		return 0
	}
	return left
}

// assertRoomToRenew is the enforcement. It runs before payment is taken,
// so a rejected renewal costs gas and nothing else — taking the money
// first and reverting would work too, but only because a panic reverts,
// and depending on that for a refund is a habit that eventually meets a
// path where it is not true.
func assertRoomToRenew(label, domainLabel string) {
	if RenewalsLeft(label, domainLabel) > 0 {
		return
	}
	panic(ufmt.Sprintf(
		"nslogic: %s*%s is already paid %d years ahead, which is the limit. Renew again when it has run down.",
		label, domainLabel, MaxTermYears(domainLabel)))
}

timelock.gno

package nslogic

import (
	"math"
	"strconv"
	"strings"
	"time"

	"gno.land/p/nt/avl/v0"
	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

/*
THE ADMIN KEY IS NOT THE REGISTRY ANY MORE.

Until this file, every admin call here was instant, and an audit used them
to take a paid name from its holder, make every name in grace reclaimable,
delete live names and redirect all revenue — in one transaction, with a
48-hour timelock in force and nothing ever proposed (audit H-1). The
vault's timelock guarded only the trust set and the roles.

So the calls are now in three classes:

	TIMELOCKED — anything that destroys or moves names or money, or
	rewrites pricing rules a single edit could zero: DeleteDomain,
	SetTermLength, SetGracePeriod, SetTreasury, ReassignDomain,
	UnfreezeName and UnfreezeNames (up to 64 names behind one action),
	SetGranter and SetKeeper (naming one; removing stays
	instant), SetDomainLengthRules, SetDomainNameOverrides,
	SetGlobalLengthRules, SetPremiumNames, OpenRestore, and SetMarketFee
	whenever the change could raise a fee. The admin proposes the exact call in the vault —
	nsdata.ProposeAction("<Function> <arg> <arg>…") — waits out the
	vault's delay, during which recovery can cancel it, and then makes
	the call, which spends the proposal. A refusal names the exact id to
	propose.

	BOUNDED — the price levers that must move day to day: SetUsdRate,
	SetDefaultNamePrice, SetDomainBasePrice, SetClaimMaxPrice. Instant
	inside a bound that depends on WHICH WAY the change moves a name's
	cost (Ely, 2026-10-16); anything bigger, or sooner, goes through the
	timelock the same way.

	  CHEAPER — the direction a thief needs: the rate down, a price cut,
	  the credit cap raised. At most cheapMaxPct of the current value at
	  once, at most once per cheapCooldown (an hour). A stolen key can
	  move each lever a quarter an hour, in public — the rate and a base
	  price compound, so a name's price can fall by about 44% in the first
	  hour (0.75 x 0.75), and to 0.5625^h of list after h hours — rather
	  than take every name for dust in one block. Two levers per name, not
	  three: an unpriced domain's first own price shares the default's
	  clocks (authorizeTweakOn).

	  DEARER — the rate up after GNOT crashes, a price raised, the credit
	  cap cut. Up to dearMaxFactor at once (four times: GNOT falling 75%
	  is followed in ONE update), at most once per dearCooldown (ten
	  minutes). Its theft costs an outage — names too dear to buy — never
	  a name or a coin. Which is only true while no lever is tied to
	  another: the credit cap used to fall back to the default price, so a
	  dearer default walked the cap the cheap way, four times every ten
	  minutes (re-audit 2026-10-16, H-1). It stands alone now, and unset it
	  covers nothing (credits.gno).

	Each direction keeps its own clock, so a dearer step in between does
	not reopen the cheaper hour. The guardian bot revoking the logic realm
	on the first AdminAction it did not expect is what keeps that hour
	short. The KEEPER (keeper.gno) moves the rate inside the same bounds,
	on the same clocks as the admin, and never through the timelock.

	INSTANT — everything that cannot take anything from anybody: freezing
	(the protective direction), opening and closing domains, the block
	list, free-tier and credit grants, limits, TTLs, art, and ClearKeeper.

THE CLOCK IS THE VAULT'S, deliberately: a new logic realm cannot shorten a
delay it does not hold, and the delay itself only changes through the
vault's own timelock.
*/

// actionID is the canonical name of one call: the function and its
// arguments, separated by single spaces, an empty argument written "".
// It is what the admin proposes and what the call spends, so a proposal
// authorizes exactly one change with exactly those arguments.
func actionID(fn string, args ...string) string {
	id := fn
	for _, a := range args {
		if a == "" {
			a = `""`
		}
		if strings.ContainsAny(a, " \t\n\r") {
			panic("nslogic: an argument to a timelocked call may not contain spaces: " + a)
		}
		id += " " + a
	}
	return id
}

// assertActionReady explains, before anything is written, why a
// timelocked call cannot run yet. The vault's ConsumeAction is the
// authority; this only makes the refusal say what to do.
func assertActionReady(id string) {
	if nsdata.EvictionPending() {
		panic("nslogic: recovery is replacing the admin; timelocked changes wait until that lands, and the admin's proposals die with it")
	}
	at, expires, _ := nsdata.GetAction(id)
	now := time.Now().Unix()
	switch {
	case at == 0:
		panic("nslogic: this change waits out the vault timelock. Propose exactly `" + id +
			"` with nsdata.ProposeAction from the admin key, then call again once it matures; recovery may cancel it until then")
	case now < at:
		panic("nslogic: `" + id + "` is proposed and matures at unix " + strconv.FormatInt(at, 10))
	case now >= expires:
		panic("nslogic: `" + id + "` expired at unix " + strconv.FormatInt(expires, 10) + "; propose it again")
	}
	if !nsdata.ActionReady(id) {
		panic("nslogic: `" + id + "` was proposed by a previous admin; propose it again")
	}
}

// requireAction lets a timelocked call through only on a matured proposal
// for exactly this call, and spends it.
func requireAction(cur realm, id string) {
	assertActionReady(id)
	nsdata.ConsumeAction(cross(cur), id)
}

// -- bounded instant changes --

const (
	// A move that makes names CHEAPER (the rate down, a price cut, the
	// credit cap raised) is at most this much of the current value, and a
	// setting moves that way instantly at most once per cheapCooldown.
	cheapMaxPct   = 25
	cheapCooldown = 60 * 60

	// A move that makes names DEARER may go up to dearMaxFactor times (or
	// down to 1/dearMaxFactor, for the credit cap) at once — four: GNOT
	// falling 75% is followed in one update — at most once per dearCooldown.
	dearMaxFactor = 4
	dearCooldown  = 10 * 60

	// The highest rate SetUsdRate accepts: a million GNOT to the dollar.
	// Like maxPriceUSD, a ceiling no real market reaches, low enough that
	// price times rate cannot overflow unnoticed (see NamePrice).
	maxRate = int64(1_000_000_000_000)
)

/*
lastTweak is the ONE piece of state this realm keeps: when each bounded
setting last moved, one clock per direction. Not a record — losing it
costs nothing but one early tweak — so it lives here rather than in the
vault, and a logic swap simply starts it empty.
*/
var lastTweak avl.Tree

func clockKey(setting string, dearer bool) string {
	if dearer {
		return setting + ":dear"
	}
	return setting + ":cheap"
}

/*
authorizeTweak lets a bounded setting move from `old` to `next` instantly
when the move stays inside its direction's bound and that direction's clock
has rested; otherwise it needs a matured proposal of `id`, which it spends.
`dearer` says whether the move makes names dearer — for the rate and the
prices that is a rise, for the credit cap a fall — and the caller, which
knows what its setting means, decides it. A move to or from zero is never
an instant step: a free domain, or a price restored from free, is a
decision.
*/
func authorizeTweak(cur realm, setting string, old, next int64, dearer bool, id string) {
	authorizeTweakOn(cur, []string{setting}, old, next, dearer, id)
}

/*
authorizeTweakOn is authorizeTweak for a move that rides more than one
clock: every clock named must have rested, and all of them are stamped.

An unpriced domain's base price IS the default, so its first price of its
own is measured against the default — after the default has already been
cut, on a clock of its own. Rate, default and domain then each took 25% in
one block: 0.75^3 of the price, 58% off, not the two levers (about 44%)
this file promises (re-audit 2026-10-16, L-1). So that first own price
rides the default's clocks too (domain.gno): in any hour, either the
default or an unpriced domain's first own price moves, never both.
*/
func authorizeTweakOn(cur realm, settings []string, old, next int64, dearer bool, id string) {
	if next == old {
		return
	}
	now := time.Now().Unix()
	if nsdata.ActionReady(id) {
		nsdata.ConsumeAction(cross(cur), id)
		for _, st := range settings {
			lastTweak.Set(clockKey(st, dearer), now)
		}
		return
	}
	setting := settings[0]
	if !withinStep(old, next, dearer) {
		panic("nslogic: " + stepRefusal(setting, old, next, dearer) +
			"; anything larger waits out the vault timelock: propose `" + id +
			"` with nsdata.ProposeAction and call again once it matures")
	}
	for _, st := range settings {
		if !clockRested(st, dearer, now) {
			panic("nslogic: " + restRefusal(st, dearer) +
				"; wait, or put this through the vault timelock: propose `" + id + "` with nsdata.ProposeAction")
		}
	}
	for _, st := range settings {
		lastTweak.Set(clockKey(st, dearer), now)
	}
}

// withinStep is the bound on its own. New values are capped (maxPriceUSD,
// maxRate); an old value stored before the caps, or by a restore, is not,
// so anything too large to multiply safely is simply not an instant step.
func withinStep(old, next int64, dearer bool) bool {
	if old <= 0 || next <= 0 || old > math.MaxInt64/100 || next > math.MaxInt64/100 {
		return false
	}
	if dearer {
		hi, lo := next, old
		if lo > hi {
			hi, lo = lo, hi
		}
		return hi <= lo*dearMaxFactor
	}
	d := next - old
	if d < 0 {
		d = -d
	}
	return d*100 <= old*cheapMaxPct
}

// inheritClocks gives `to` every last-move time of `from` that is later
// than its own, in both directions: a setting that starts out as another
// one's value starts on that one's clocks.
func inheritClocks(to, from string) {
	for _, dearer := range []bool{true, false} {
		f := lastTweak.Get(clockKey(from, dearer))
		if f == nil {
			continue
		}
		if t := lastTweak.Get(clockKey(to, dearer)); t == nil || t.(int64) < f.(int64) {
			lastTweak.Set(clockKey(to, dearer), f.(int64))
		}
	}
}

func clockRested(setting string, dearer bool, now int64) bool {
	rest := int64(cheapCooldown)
	if dearer {
		rest = dearCooldown
	}
	v := lastTweak.Get(clockKey(setting, dearer))
	return v == nil || now-v.(int64) >= rest
}

func stepRefusal(setting string, old, next int64, dearer bool) string {
	span := strconv.FormatInt(old, 10) + " to " + strconv.FormatInt(next, 10)
	if dearer {
		return setting + " may make names dearer by at most " + strconv.Itoa(dearMaxFactor) + "x at once (" + span + ")"
	}
	return setting + " may make names cheaper by at most " + strconv.Itoa(cheapMaxPct) + "% at once (" + span + ")"
}

func restRefusal(setting string, dearer bool) string {
	if dearer {
		return setting + " made names dearer less than ten minutes ago"
	}
	return setting + " made names cheaper less than an hour ago"
}

// LastTweak reports when a bounded setting last moved instantly in each
// direction (unix seconds, 0 for never), so the panel can say when the
// next step each way is due: dearer after ten minutes, cheaper after an hour.
func LastTweak(setting string) (dearer, cheaper int64) {
	if v := lastTweak.Get(clockKey(setting, true)); v != nil {
		dearer = v.(int64)
	}
	if v := lastTweak.Get(clockKey(setting, false)); v != nil {
		cheaper = v.(int64)
	}
	return dearer, cheaper
}

// -- keys only their own setters may write --

/*
managedGlobal reports whether SetGlobal must refuse a key, because a
setter in this realm owns it — bounded, timelocked or validated. The
escape hatch wrote any key, so it walked straight round every one of those
rules: SetGlobal("rateUgnotPerUsd", "1") was a one-call way to sell every
name for dust.
*/
func managedGlobal(key string) bool {
	switch key {
	case keyDefaultPrice, keyRate, keyMarketFee, keyGranter, keyKeeper, keyGlobalLens,
		keyRefCut, keyRefDisc, keyRefWin, keyMaxTerm, keyFreeMin, keyFreeMax,
		keyClaimEnd, keyClaimMax, keyRestore, keyRestoredCount, "labdomain":
		return true
	}
	return strings.HasPrefix(key, keyPremium) || strings.HasPrefix(key, blockKeyStem)
}

// managedDomainKey is the same rule for SetDomainField.
func managedDomainKey(key string) bool {
	switch key {
	case keyPrice, keyLens, keyNames, keyOpen, keyFreeDomain, keyMaxTerm:
		return true
	}
	return false
}

types.gno

// Package nslogic is the swappable "business rules" half of the split
// (NOTES.md §9t). It holds every piece of policy that might reasonably
// change — pricing, character validation, payment/refund, freeze rules,
// transfer restrictions — and no persistent records of its own. (One
// throttle, not a record: when each bounded price setting last moved,
// timelock.gno's lastTweak. A logic swap starts it empty and loses
// nothing.)
//
// Every mutation here ends by calling into nsdata's narrow Record/Raw
// API via cross(cur). nsdata trusts whichever address is currently wired
// up as trustedLogic to have done its own authorization checks
// correctly, so THIS realm is where "is the caller allowed to do this"
// actually lives. If a bug is found here, admin deploys a fixed nslogic
// and re-points the vault at it (ProposeTrustedLogicGrant, then
// ExecutePending after the timelock) — no data migration,
// records and config untouched.
//
// Deliberately reads config fresh from nsdata on every call rather than
// caching it. The one thing that cannot be read fresh is a COMPILED
// regex — avl trees store the pattern string, not the compiled object —
// so that one value is cached, and the cache is validated against
// nsdata on every use.
package nslogic

const (
	ugnot    = "ugnot"
	bpsDenom = 10_000
)

validate.gno

package nslogic

import (
	"strings"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)

// THE LABEL RULE IS WRITTEN OUT, NOT COMPILED.
//
// It used to be a regexp, and that regexp was the single most expensive
// thing in this realm — by a wide margin, and not by a little. Measured
// on sapphire-1 with vm/qstorage against purpose-built probe realms:
//
//	a realm with code and no package-level state      2,711 bytes
//	the same realm plus ONE compiled regexp         154,877 bytes
//
// A compiled regexp is an object graph, and gno charges 100 ugnot for
// every byte of it, forever. That one variable was 15.2 GNOT of the
// 22.5 GNOT it costs to deploy this realm — about 68% of the bill, to
// enforce a rule that fits in thirty lines.
//
// The second regexp was worse, because it was compiled LAZILY and cached
// in a package-level var. That does not avoid the cost, it MOVES it: the
// first person to register a name after a fresh deploy would have had
// their transaction grow this realm's storage by 150KB and been charged
// ~15 GNOT of deposit for it. Confirmed by probe, not inferred — a realm
// deployed at 2,711 bytes went to 154,149 the moment one call compiled
// and cached a regexp, billed to the caller. Somebody buying a ten-cent
// name would have been asked for fifteen GNOT.
//
// The hand-written version is also 6x cheaper in gas on every call
// (1.06M against 6.67M), so there is no axis on which the regexp was
// the better choice. It read better. That was the whole of its case.
//
// WHAT THIS COSTS US. The pattern is no longer admin-tunable at runtime:
// changing the rule now means redeploying this realm. That is a fair
// trade at 7 GNOT a deploy, it was never a rule that should change
// casually, and SetLabelPattern refuses anything but the implemented
// pattern so the stored string can never describe rules the code does
// not enforce.

// labelRule is the pattern this realm implements, kept as a string so
// nsdata, the error messages and the site all quote the same thing.
const labelRule = `^[a-z0-9]+(-[a-z0-9]+)*$`

// matchesLabelRule is that pattern, by hand: lowercase letters and
// digits, single hyphens between them, none at either end.
func matchesLabelRule(s string) bool {
	if s == "" {
		return false
	}
	prevHyphen := true // a leading hyphen is not allowed
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch {
		case c >= 'a' && c <= 'z', c >= '0' && c <= '9':
			prevHyphen = false
		case c == '-':
			if prevHyphen {
				return false // leading, or two in a row
			}
			prevHyphen = true
		default:
			return false
		}
	}
	return !prevHyphen // nor a trailing one
}

// looksLikeAddress was `^g1[a-z0-9]{20,38}$`. Anything shaped like a real
// gno.land address is refused as a label, so a name can never be mistaken
// for a raw wallet address in a UI.
func looksLikeAddress(s string) bool {
	if len(s) < 22 || len(s) > 40 || !strings.HasPrefix(s, "g1") {
		return false
	}
	for i := 2; i < len(s); i++ {
		c := s[i]
		if !(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') {
			return false
		}
	}
	return true
}

// validateLabel — same policy as the original single-realm build (see
// NOTES.md for the ENS/Starname/r/sys/users research behind it). The
// length bounds are still read from nsdata, so they survive a swap of
// this realm; the character rule is now this realm's own.
//
// Call sites, and why: RegisterName/RegisterDomain only (both the
// first-ever mint AND reclaiming a past-grace slot — a reclaim is a
// genuine new mint with a new owner). RenewName/RenewDomain deliberately
// do NOT call this — an already-registered name must keep renewing under
// whatever rule was in force when it was minted.
func validateLabel(label string) {
	minLen, maxLen := nsdata.GetLabelLength()
	if len(label) < minLen || len(label) > maxLen {
		panic(ufmt.Sprintf("nslogic: label must be %d-%d characters", minLen, maxLen))
	}
	// Structural invariant, enforced regardless of what the pattern
	// happens to allow: "*" is the separator in both the token ID
	// (label*domain) and nsdata's storage key (domain*label). A label or
	// domain containing one would make those encodings ambiguous and let
	// two different names collide onto a single record.
	if strings.Contains(label, "*") {
		panic("nslogic: label may not contain '*'")
	}
	if !matchesLabelRule(label) {
		panic("nslogic: a name is lowercase letters, digits and single hyphens between them — " + labelRule)
	}
	if looksLikeAddress(label) {
		panic("nslogic: label looks like a wallet address, not allowed")
	}
}