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 core

import (
	"chain"
	"chain/runtime"
	"strconv"
	"strings"

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

	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/safe/v1"
	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/types/v1"
)

// Admin (design §2.5.2, §7.5). The admin can only change the parameters
// listed in validateOp, each inside a hard cap, after a public timelock;
// it can pause new activity for a bounded time. It can never move, approve
// or burn a token, touch a collection's configuration, or receive funds
// (I-1). With no collection yet there is nothing to protect, so ops execute
// without delay — that is how the platform is configured after deploy.
//
// TODO(mainnet): the initial admin and treasury must be the 2/3 multisig.
var (
	admin        = address("g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w")
	pendingAdmin address
	fees         = types.Fees{PrimaryBps: 250, SecondaryBps: 250, Treasury: address("g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w")}
	beacon       address
	minters      avl.Tree // minter pkgpath -> *minterRecord
	ops          avl.Tree // safe.PadInt(op id) -> *pendingOp
	opCount      int64
	pausedUntil  avl.Tree // scope -> int64 height (exclusive)
)

type minterRecord struct {
	deprecated bool
}

type pendingOp struct {
	id       int64
	op, arg  string
	proposed int64
}

// Ops and their argument formats.
const (
	OpFeeCreate       = "fee.create"       // ugnot, <= CreateFeeCap
	OpFeePrimary      = "fee.primary"      // bps, <= ProtocolFeeCapBps
	OpFeeSecondary    = "fee.secondary"    // bps, <= ProtocolFeeCapBps
	OpTreasury        = "treasury"         // address
	OpBeacon          = "beacon"           // address, or "" to disable new beacon launches
	OpMinterAdd       = "minter.add"       // realm pkgpath
	OpMinterDeprecate = "minter.deprecate" // realm pkgpath: no new collections
	OpEngineReview    = "engine.review"    // engine id: reviewed badge (UI only)
	OpAdminTransfer   = "admin.transfer"   // address; the new admin must AcceptAdmin
)

var pauseScopes = []string{"create", "mint", "trade"}

func ProposeOp(cur realm, op, arg string) string {
	assertNoDeposit(cur)
	assertAdmin(cur)
	validateOp(op, arg)
	opCount++
	p := &pendingOp{id: opCount, op: op, arg: arg, proposed: height()}
	ops.Set(safe.PadInt(p.id, cidWidth), p)
	id := itoa(p.id)
	chain.Emit("OpProposed", "id", id, "op", op, "arg", arg, "earliest", itoa(earliestExecution(p)))
	return id
}

// ExecuteOp applies a proposed op once its timelock has passed. The delay is
// judged at execution, so an op proposed during bootstrap still waits the
// full timelock if a collection appeared in the meantime.
func ExecuteOp(cur realm, opID string) {
	assertNoDeposit(cur)
	assertAdmin(cur)
	p := mustOp(opID)
	if height() < earliestExecution(p) {
		panic("timelocked until height " + itoa(earliestExecution(p)))
	}
	validateOp(p.op, p.arg)
	applyOp(p.op, p.arg)
	ops.Remove(safe.PadInt(p.id, cidWidth))
	chain.Emit("OpExecuted", "id", opID, "op", p.op, "arg", p.arg)
}

func CancelOp(cur realm, opID string) {
	assertNoDeposit(cur)
	assertAdmin(cur)
	p := mustOp(opID)
	ops.Remove(safe.PadInt(p.id, cidWidth))
	chain.Emit("OpCancelled", "id", opID)
}

func AcceptAdmin(cur realm) {
	assertNoDeposit(cur)
	who := caller(cur)
	if pendingAdmin == "" || who != pendingAdmin {
		panic("no pending admin transfer to this address")
	}
	chain.Emit("AdminTransferred", "from", admin.String(), "to", who.String())
	admin = who
	pendingAdmin = ""
}

// Pause stops new activity in one scope for at most MaxPauseBlocks. It
// never blocks exits (I-2).
func Pause(cur realm, scope string) {
	assertNoDeposit(cur)
	assertAdmin(cur)
	assertScope(scope)
	until := height() + MaxPauseBlocks
	pausedUntil.Set(scope, until)
	chain.Emit("Paused", "scope", scope, "until", itoa(until))
}

func Unpause(cur realm, scope string) {
	assertNoDeposit(cur)
	assertAdmin(cur)
	assertScope(scope)
	pausedUntil.Remove(scope)
	chain.Emit("Unpaused", "scope", scope)
}

// Paused reports whether scope ("create", "mint", "trade") is paused now.
func Paused(scope string) bool {
	v := pausedUntil.Get(scope)
	return v != nil && height() < v.(int64)
}

func assertNotPaused(scope string) {
	if Paused(scope) {
		panic("paused: " + scope)
	}
}

func assertScope(scope string) {
	for _, s := range pauseScopes {
		if s == scope {
			return
		}
	}
	panic("pause scope must be one of " + strings.Join(pauseScopes, ", "))
}

func assertAdmin(cur realm) {
	if caller(cur) != admin {
		panic("admin only")
	}
}

func bootstrapping() bool { return collCount == 0 }

func earliestExecution(p *pendingOp) int64 {
	if bootstrapping() {
		return p.proposed
	}
	return p.proposed + TimelockBlocks
}

func mustOp(opID string) *pendingOp {
	v := ops.Get(safe.PadInt(safe.ParseID("opID", opID), cidWidth))
	if v == nil {
		panic("unknown op " + opID)
	}
	return v.(*pendingOp)
}

// validateOp is the closed list of admin powers (I-1).
func validateOp(op, arg string) {
	switch op {
	case OpFeeCreate:
		n := parseAmount(arg)
		if n > CreateFeeCap {
			panic("create fee above cap " + itoa(CreateFeeCap))
		}
	case OpFeePrimary, OpFeeSecondary:
		safe.AssertBps(op, parseAmount(arg), ProtocolFeeCapBps)
	case OpTreasury, OpAdminTransfer:
		if !address(arg).IsValid() {
			panic(op + ": invalid address")
		}
	case OpBeacon:
		if arg != "" && !address(arg).IsValid() {
			panic(op + ": invalid address")
		}
	case OpMinterAdd:
		safe.AssertText("minter", arg, 256)
		if !strings.HasPrefix(arg, runtime.ChainDomain()+"/r/") || strings.Contains(arg, "#") {
			panic("minter must be a realm path")
		}
		if minters.Has(arg) {
			panic("minter already added")
		}
	case OpMinterDeprecate:
		if !minters.Has(arg) {
			panic("unknown minter")
		}
	case OpEngineReview:
		mustEngine(arg)
	default:
		panic("unknown op " + strconv.Quote(op))
	}
}

func applyOp(op, arg string) {
	switch op {
	case OpFeeCreate:
		fees.CreateFee = parseAmount(arg)
	case OpFeePrimary:
		fees.PrimaryBps = parseAmount(arg)
	case OpFeeSecondary:
		fees.SecondaryBps = parseAmount(arg)
	case OpTreasury:
		fees.Treasury = address(arg)
	case OpBeacon:
		beacon = address(arg)
	case OpMinterAdd:
		minters.Set(arg, &minterRecord{})
	case OpMinterDeprecate:
		minters.Get(arg).(*minterRecord).deprecated = true
	case OpEngineReview:
		mustEngine(arg).reviewed = true
	case OpAdminTransfer:
		pendingAdmin = address(arg)
	}
}

func assertActiveMinter(path string) {
	v := minters.Get(path)
	if v == nil {
		panic("caller " + strconv.Quote(path) + " is not an approved minter")
	}
	if v.(*minterRecord).deprecated {
		panic("minter " + path + " is deprecated")
	}
}

func parseAmount(s string) int64 {
	n, err := strconv.ParseInt(s, 10, 64)
	if err != nil || n < 0 {
		panic("expected a non-negative integer, got " + strconv.Quote(s))
	}
	return n
}

collections.gno

package core

import (
	"chain"
	"chain/runtime"

	"gno.land/p/nt/grc721/royalty/v0"
	"gno.land/p/nt/grc721/v0"
	"gno.land/p/nt/seqid/v0"

	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/safe/v1"
	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/types/v1"
)

// --- bound minter only -------------------------------------------------------
//
// A collection is created by an admin-approved minter realm and stays bound
// to it: only that realm can launch, abort, reserve and mint (I-5). The
// minter is trusted to pass the real creator; core trusts nothing else it
// is given and validates every field (I-13).

// CreateCollection stores a Draft collection and returns its id. Nobody can
// mint a Draft, so a creator can configure phases across several messages
// without a race (OA B2).
func CreateCollection(cur realm, creator address, spec types.CollectionSpec) string {
	minter := cur.Previous().PkgPath()
	assertActiveMinter(minter)
	assertNotPaused("create")
	if !creator.IsValid() {
		panic("invalid creator address")
	}
	safe.AssertNonEmptyText("name", spec.Name, MaxNameLen)
	safe.AssertSymbol("symbol", spec.Symbol)
	safe.AssertText("description", spec.Description, MaxDescriptionLen)
	safe.AssertText("params", spec.Params, MaxParamsLen)
	if spec.MaxSupply <= 0 || spec.MaxSupply > MaxSupplyCap {
		panic("maxSupply must be 1.." + itoa(MaxSupplyCap))
	}
	safe.AssertBps("royaltyBps", spec.RoyaltyBps, RoyaltyCapBps)
	primary := safe.ParsePayees("primaryPayees", spec.PrimaryPayees, MaxPayees)
	royal := safe.ParsePayees("royaltyPayees", spec.RoyaltyPayees, MaxPayees)

	rec := mustEngine(spec.EngineID)
	if !rec.claimed {
		panic("engine is not claimed by its author yet")
	}
	if rec.deprecated {
		panic("engine is deprecated")
	}
	// I-12 exception: the creator's own transaction runs the engine they chose.
	if err := rec.impl.ValidateParams(spec.Params); err != nil {
		panic("params rejected by engine: " + err.Error())
	}

	collCount++
	cid := itoa(collCount)

	// Each collection gets its own sub-realm identity, so Token.ID() and every
	// grc721 event carry "…/core#c/<cid>" (design §2.3; verified by
	// spike/subtoken and core tests on gno v1.7.0).
	tok, led := grc721.NewToken(spec.Name, spec.Symbol, seqid.ID(uint64(collCount)), cur.Sub("c/"+cid))
	st := &tokenState{}
	led.RegisterExtension(&lockExt{cid: cid, st: st})
	roy, royLed := royalty.NewRoyalty(led, RoyaltyCapBps)
	if spec.RoyaltyBps > 0 {
		if err := royLed.SetDefaultRoyalty(royaltyAddress(cid), spec.RoyaltyBps); err != nil {
			panic(err)
		}
	}

	c := &collection{
		id:            cid,
		name:          spec.Name,
		symbol:        spec.Symbol,
		description:   spec.Description,
		creator:       creator,
		engineID:      spec.EngineID,
		params:        spec.Params,
		maxSupply:     spec.MaxSupply,
		nextTID:       1,
		royaltyBps:    spec.RoyaltyBps,
		primaryPayees: primary,
		royaltyPayees: royal,
		minter:        minter,
		state:         types.StateDraft,
		createdHeight: height(),
		token:         tok,
		ledger:        led,
		roy:           roy,
		st:            st,
	}
	collections.Set(collKey(cid), c)
	byCreator.Set(creator.String()+":"+collKey(cid), cid)

	chain.Emit("CollectionCreated",
		"cid", cid, "creator", creator.String(), "minter", minter,
		"engine", spec.EngineID, "token", tok.ID())
	return cid
}

// Launch freezes the configuration (I-6): sale window, reveal window and the
// creator's commitment. The sale must start in the future so a beacon can
// commit before the first mint.
func Launch(cur realm, cid string, l types.LaunchSpec) {
	c := mustCollection(cid)
	assertBoundMinter(cur, c)
	h := height()
	if c.state != types.StateDraft {
		panic("only a draft can be launched")
	}
	if l.StartHeight <= h {
		panic("startHeight must be in the future")
	}
	if l.EndHeight < l.StartHeight || l.EndHeight-l.StartHeight > MaxSaleBlocks {
		panic("sale window must be 0.." + itoa(MaxSaleBlocks) + " blocks")
	}
	if l.RevealWindow < RevealWindowMin || l.RevealWindow > RevealWindowMax {
		panic("revealWindow must be " + itoa(RevealWindowMin) + ".." + itoa(RevealWindowMax) + " blocks")
	}
	commit := safe.AssertHex("creatorCommit", l.CreatorCommit, 32)
	if usedCommits.Has(commit) {
		panic("this commitment was already used; derive a new secret")
	}
	if l.UseBeacon && beacon == "" {
		panic("no beacon is configured; launch without useBeacon")
	}

	usedCommits.Set(commit, cid)
	c.prov = &provenance{creatorCommit: commit, acc: safe.InitialEntropy(runtime.ChainID(), cid)}
	c.startHeight, c.endHeight, c.revealWindow = l.StartHeight, l.EndHeight, l.RevealWindow
	c.useBeacon = l.UseBeacon
	c.state = types.StateScheduled

	chain.Emit("CollectionScheduled",
		"cid", cid, "start", itoa(c.startHeight), "end", itoa(c.endHeight),
		"revealWindow", itoa(c.revealWindow), "useBeacon", boolStr(c.useBeacon),
		"creatorCommit", commit)
}

// AbortLaunch returns a launched collection to Draft while nothing has been
// minted — the way out when a beacon never commits. Used commitments stay
// used.
func AbortLaunch(cur realm, cid string) {
	c := mustCollection(cid)
	assertBoundMinter(cur, c)
	refresh(c, height())
	if c.state == types.StateDraft || c.state == types.StateFinal {
		panic("only a launched, unfinished collection can be aborted")
	}
	if c.minted() > 0 {
		panic("tokens were minted; the launch can no longer be aborted")
	}
	c.prov = nil
	c.startHeight, c.endHeight, c.revealWindow, c.closeHeight = 0, 0, 0, 0
	c.useBeacon = false
	c.state = types.StateDraft
	chain.Emit("CollectionState", "cid", cid, "state", c.state.String())
}

// ReserveTo mints the creator's reserve before the sale starts. Reserve
// mints feed the entropy like any mint, appear in Provenance, and do not
// count toward wallet caps.
func ReserveTo(cur realm, cid string, to address, n int64) (first, last int64) {
	c := mustCollection(cid)
	assertBoundMinter(cur, c)
	assertNotPaused("mint")
	h := height()
	refresh(c, h)
	if c.state != types.StateScheduled {
		panic("reserve is only possible after launch and before the sale starts")
	}
	// A reserve is a mint, and the beacon may only commit while nothing is
	// minted: reserving first would leave the collection unmintable and
	// unabortable (found on Onyx, collection 1).
	if c.useBeacon && c.prov.beaconCommit == "" {
		panic("waiting for the beacon commitment; reserve after the beacon commits")
	}
	assertMintCount(c, n)
	if c.reserved+n > c.maxSupply*MaxReserveBps/safe.BpsDenominator {
		panic("reserve would exceed " + itoa(MaxReserveBps/100) + "% of supply")
	}
	first, last = mintBatchTo(c, to, n, h)
	c.reserved += n
	emitBatch("Reserved", c, to, first, last)
	return first, last
}

// MintTo mints n tokens during the sale. The minter has already checked
// phase, price, allowlist and wallet cap; core re-checks only what it owns:
// state, supply, beacon commitment, and the lifetime counter (I-5, I-9).
func MintTo(cur realm, cid string, to address, n int64) (first, last int64) {
	c := mustCollection(cid)
	assertBoundMinter(cur, c)
	assertNotPaused("mint")
	h := height()
	refresh(c, h)
	if c.state != types.StateMinting {
		panic("collection is not minting (state " + c.state.String() + ")")
	}
	if c.useBeacon && c.prov.beaconCommit == "" {
		panic("waiting for the beacon commitment; minting has not opened")
	}
	assertMintCount(c, n)
	first, last = mintBatchTo(c, to, n, h)
	c.mintedBy.Set(to.String(), mintedBy(c, to)+n)
	if c.minted() == c.maxSupply {
		c.closeHeight = h
		c.state = types.StateClosed
		chain.Emit("CollectionState", "cid", cid, "state", c.state.String())
	}
	emitBatch("MintBatch", c, to, first, last)
	return first, last
}

func assertMintCount(c *collection, n int64) {
	if n <= 0 || n > MaxMintPerTx {
		panic("count must be 1.." + itoa(MaxMintPerTx))
	}
	if c.minted()+n > c.maxSupply {
		panic("only " + itoa(c.maxSupply-c.minted()) + " tokens left")
	}
}

// mintBatchTo is the only place tokens come into existence.
func mintBatchTo(c *collection, to address, n, h int64) (first, last int64) {
	first = c.nextTID
	last = first + n - 1
	for tid := first; tid <= last; tid++ {
		if err := c.ledger.Mint(to, grc721.TokenID(itoa(tid))); err != nil {
			panic(err)
		}
	}
	c.nextTID = last + 1
	c.st.addBatch(first, last, h)
	c.prov.acc = safe.MixEntropy(c.prov.acc, to, h, first, last)
	return first, last
}

func mintedBy(c *collection, addr address) int64 {
	if v := c.mintedBy.Get(addr.String()); v != nil {
		return v.(int64)
	}
	return 0
}

// CloseMint materializes Closed once the sale window has passed. Anyone may
// call it; reveals and Finalize work without it.
func CloseMint(cur realm, cid string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	refresh(c, height())
	if c.state != types.StateClosed {
		panic("the sale is not over (state " + c.state.String() + ")")
	}
}

// --- creator -----------------------------------------------------------------

// TransferCreator starts a two-step handover (RA M-11).
func TransferCreator(cur realm, cid string, to address) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	assertCreator(cur, c)
	if !to.IsValid() {
		panic("invalid address")
	}
	c.pendingCreator = to
	chain.Emit("CreatorTransferStarted", "cid", cid, "from", c.creator.String(), "to", to.String())
}

func AcceptCreator(cur realm, cid string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	who := caller(cur)
	if c.pendingCreator == "" || who != c.pendingCreator {
		panic("no pending creator transfer to this address")
	}
	byCreator.Remove(c.creator.String() + ":" + collKey(cid))
	byCreator.Set(who.String()+":"+collKey(cid), cid)
	chain.Emit("CreatorTransferred", "cid", cid, "from", c.creator.String(), "to", who.String())
	c.creator = who
	c.pendingCreator = ""
}

// SetPayees changes the royalty split after Final. The primary-sale split is
// frozen with the sale (I-6); the royalty receiver stays the collection's
// sub-treasury, so third-party markets are unaffected.
func SetPayees(cur realm, cid, payees string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	assertCreator(cur, c)
	if c.state != types.StateFinal {
		panic("royalty payees can change only after the collection is final")
	}
	c.royaltyPayees = safe.ParsePayees("royaltyPayees", payees, MaxPayees)
	chain.Emit("RoyaltyPayees", "cid", cid, "payees", payees)
}

func assertCreator(cur realm, c *collection) {
	if caller(cur) != c.creator {
		panic("only the collection's creator can do this")
	}
}

func assertBoundMinter(cur realm, c *collection) {
	if cur.Previous().PkgPath() != c.minter {
		panic("only the collection's bound minter (" + c.minter + ") can do this")
	}
}

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

core.gno

// Package core is the platform's immutable ledger (design §2.5.2): every
// collection, its official grc721 token and royalty, its provenance
// (commit–reveal v2), the engine registry, fees and the admin timelock.
//
// What core guarantees, whoever holds the admin key:
//
//   - I-1  admin cannot move, approve or burn a token, and holds no funds;
//     the op list is a closed set of parameters (admin.gno).
//   - I-2  pause only gates create, mint and trade. Transfer, burn,
//     finalize, distribute and every cancel stay open, and a pause expires
//     by itself after MaxPauseBlocks.
//   - I-5  supply only grows through the collection's bound minter, never
//     past maxSupply, and a token id is never minted twice.
//   - I-6  after Launch the engine, params, supply, payees, sale window and
//     commitments are frozen.
//   - I-10/11  a collection becomes Final at most once, only with both
//     reveals or after revealDeadline, and that deadline is bounded, so
//     the pre-reveal transfer lock always ends.
//   - I-12 engine code never runs on a state-changing path, except the
//     creator's own CreateCollection (ValidateParams) and the engine's own
//     RegisterEngine (one sample render). Every exported non-crossing
//     function is read-only, so an engine cannot call back into a mutator.
//   - I-13 every stored string passed safe.AssertText.
//
// core imports no mutable realm: minters and engines are known only by
// package path and interface value.
package core

import (
	"chain"
	"chain/runtime"
	"chain/runtime/unsafe"
	"strconv"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/grc721/royalty/v0"
	"gno.land/p/nt/grc721/v0"

	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/safe/v1"
	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/types/v1"
)

// Hard limits. They are constants on purpose: nobody, admin included, can
// raise them after deploy (block counts assume ~3.54 s blocks, RA M-1).
const (
	ProtocolFeeCapBps = 500           // 5% of any sale
	RoyaltyCapBps     = 1000          // 10% (RA M-3)
	CreateFeeCap      = 1_000_000_000 // 1,000 GNOT in ugnot
	MaxPayees         = 4
	MaxSupplyCap      = 10_000
	MaxMintPerTx      = 10    // hypothesis: measure n=10 gas/deposit on Onyx
	MaxReserveBps     = 1000  // creator reserve <= 10% of supply
	MaxSaleBlocks     = 732_000 // ~30 days
	RevealWindowMin   = 1_017   // ~1 hour
	RevealWindowMax   = 170_000 // ~7 days
	BeaconGraceBlocks = 254     // beacon may reveal first in the window's last ~15 min (< RevealWindowMin, so the creator always gets to go first)
	TimelockBlocks    = 48_800  // ~48 hours
	MaxPauseBlocks    = 195_000 // ~8 days

	MaxNameLen        = 64
	MaxDescriptionLen = 1024
	MaxParamsLen      = 1024
	MinSecretLen      = 32
	MaxSecretLen      = 256
	MaxPageSize       = 50
)

// Provenance badges (design §4.3).
const (
	BadgeBoth        = "2/2"
	BadgeCreatorOnly = "creator-only"
	BadgeBeaconOnly  = "beacon-only"
	BadgeFallback    = "fallback"
)

type collection struct {
	id, name, symbol, description string
	creator, pendingCreator       address
	engineID, params              string
	maxSupply                     int64
	nextTID                       int64 // next token id; minted so far = nextTID-1
	reserved                      int64
	royaltyBps                    int64
	primaryPayees, royaltyPayees  []types.Payee
	minter                        string
	state                         types.State
	startHeight, endHeight        int64
	revealWindow                  int64
	closeHeight                   int64 // sell-out height, or endHeight once time ran out
	useBeacon                     bool
	createdHeight                 int64
	prov                          *provenance
	token                         *grc721.Token
	ledger                        *grc721.PrivateLedger
	roy                           *royalty.Royalty
	st                            *tokenState
	mintedBy                      avl.Tree // address -> int64, lifetime, written on every mint (I-9)
}

func (c *collection) minted() int64 { return c.nextTID - 1 }

var (
	// selfPath is this realm's package path, captured once in init so read
	// functions can derive sub-addresses without a cur.
	selfPath string

	collections avl.Tree // safe.PadInt(cid) -> *collection
	byCreator   avl.Tree // creator + ":" + padded cid -> cid
	collCount   int64
	usedCommits avl.Tree // commit hex -> cid; a commitment is single-use platform-wide (RA M-5)
)

func init(cur realm) {
	selfPath = cur.PkgPath()
}

const cidWidth = 10

func collKey(cid string) string {
	return safe.PadInt(safe.ParseID("cid", cid), cidWidth)
}

func mustCollection(cid string) *collection {
	v := collections.Get(collKey(cid))
	if v == nil {
		panic("unknown collection " + strconv.Quote(cid))
	}
	return v.(*collection)
}

// stateAt is the effective state at height h; the stored state lags until
// the next write materializes it (refresh).
func stateAt(c *collection, h int64) types.State {
	switch c.state {
	case types.StateScheduled:
		if h > c.endHeight {
			return types.StateClosed
		}
		if h >= c.startHeight {
			return types.StateMinting
		}
	case types.StateMinting:
		if h > c.endHeight {
			return types.StateClosed
		}
	}
	return c.state
}

func refresh(c *collection, h int64) {
	s := stateAt(c, h)
	if s == c.state {
		return
	}
	if s == types.StateClosed && c.closeHeight == 0 {
		c.closeHeight = c.endHeight
	}
	c.state = s
	chain.Emit("CollectionState", "cid", c.id, "state", s.String())
}

// revealDeadline is when anyone may finalize without the missing secrets.
// It is at most endHeight + RevealWindowMax, which bounds the transfer
// lock (I-11).
func revealDeadline(c *collection) int64 {
	closed := c.closeHeight
	if closed == 0 {
		closed = c.endHeight
	}
	return closed + c.revealWindow
}

func caller(cur realm) address {
	return cur.Previous().Address()
}

// assertNoDeposit refuses coins on functions that take none, so nothing can
// get stuck in core (RA L-1). The origin-send envelope belongs to the first
// realm of the call; it is only ours to judge when a wallet called us.
func assertNoDeposit(cur realm) {
	if cur.Previous().IsUserCall() && !unsafe.OriginSend().IsZero() {
		panic("this function does not accept coins")
	}
}

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

func height() int64 { return runtime.ChainHeight() }

engines.gno

package core

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

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

	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/engine/v1"
	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/safe/v1"
)

// Engine registry ("art as code", design §5).
//
// An engine registers itself from its own /r/ adapter realm; its id is that
// realm's package path, so nobody can register in someone else's name. The
// stored interface value's methods are declared in the adapter, so every
// call runs with the adapter's authority, not core's (interrealm v2 borrow
// rule #1): engine code cannot write core state. It also cannot call back
// into a core mutator: all of core's state-changing functions are crossing
// and need a live cur the engine never has.
//
// Honest limits, surfaced to users rather than hidden:
//   - an adapter realm with state could change its art later; the sample
//     fingerprint (VerifyEngine) detects a change of the sample, and review
//     means reading the adapter for statelessness;
//   - a private (re-deployable) adapter cannot register: the VM aborts the
//     registration when core's state would retain the private realm's type
//     (spike A9, observed in gno v1.7.0 test mode; confirm on Onyx).
type engineRecord struct {
	id               string
	impl             engine.Engine
	manifest         engine.Manifest // core-owned copy
	fingerprint      string          // sha256 of Render(SampleInput())
	claimed          bool
	deprecated       bool
	reviewed         bool
	registeredHeight int64
}

var (
	engines     avl.Tree // engine id -> *engineRecord
	engineOrder avl.Tree // safe.PadInt(seq) -> engine id
	engineCount int64
)

// RegisterEngine stores the calling realm's engine (I-12 exception: one
// sample render in the engine's own registration transaction). The record
// is immutable afterwards except for the claim/deprecate/review flags.
func RegisterEngine(cur realm, e engine.Engine) string {
	id := cur.Previous().PkgPath()
	if !strings.HasPrefix(id, runtime.ChainDomain()+"/r/") || strings.Contains(id, "#") {
		panic("an engine registers from its own realm (an /r/ package, not a sub-realm or wallet)")
	}
	if e == nil {
		panic("nil engine")
	}
	if engines.Has(id) {
		panic("engine already registered: " + id + " (publish a new version under a new path)")
	}
	m := copyManifest(e.Manifest())
	if err := engine.ValidateManifest(m); err != nil {
		panic(err)
	}
	if err := e.ValidateParams(""); err != nil {
		panic("engine must accept empty params (its defaults): " + err.Error())
	}
	sample := e.Render(engine.SampleInput())
	if err := engine.CheckSVG(m, sample); err != nil {
		panic("sample render: " + err.Error())
	}
	if err := engine.ValidateTraits(m, e.Traits(engine.SampleInput())); err != nil {
		panic("sample traits: " + err.Error())
	}

	rec := &engineRecord{
		id:               id,
		impl:             e,
		manifest:         m,
		fingerprint:      safe.Sha256Hex(sample),
		registeredHeight: height(),
	}
	engines.Set(id, rec)
	engineCount++
	engineOrder.Set(safe.PadInt(engineCount, cidWidth), id)
	chain.Emit("EngineRegistered", "id", id, "author", m.Author.String(), "fingerprint", rec.fingerprint)
	return id
}

// ClaimEngine proves the manifest author controls that address. Unclaimed
// engines cannot back a collection.
func ClaimEngine(cur realm, id string) {
	assertNoDeposit(cur)
	rec := mustEngine(id)
	if caller(cur) != rec.manifest.Author {
		panic("only the manifest author " + rec.manifest.Author.String() + " can claim this engine")
	}
	rec.claimed = true
	chain.Emit("EngineClaimed", "id", id)
}

// DeprecateEngine stops new collections; existing ones keep rendering.
func DeprecateEngine(cur realm, id string) {
	assertNoDeposit(cur)
	rec := mustEngine(id)
	if !rec.claimed || caller(cur) != rec.manifest.Author {
		panic("only the engine's author can deprecate it")
	}
	rec.deprecated = true
	chain.Emit("EngineDeprecated", "id", id)
}

func mustEngine(id string) *engineRecord {
	v := engines.Get(id)
	if v == nil {
		panic("unknown engine " + id)
	}
	return v.(*engineRecord)
}

// copyManifest gives core its own copy: the engine's slice was allocated in
// the engine realm.
func copyManifest(m engine.Manifest) engine.Manifest {
	out := m
	out.TraitTypes = append([]string{}, m.TraitTypes...)
	return out
}

// --- engine reads (Studio, Verify) -------------------------------------------

// RenderWith renders any registered engine for arbitrary params and seed as
// a data URI — Studio previews and the Verify button.
func RenderWith(id, params, seed string) string {
	rec := mustEngine(id)
	if err := rec.impl.ValidateParams(params); err != nil {
		panic("params rejected by engine: " + err.Error())
	}
	svg := rec.impl.Render(studioInput(params, seed))
	if err := engine.CheckSVG(rec.manifest, svg); err != nil {
		return dataURI(placeholderSVG(rec.manifest.Name, "Engine output rejected"))
	}
	return dataURI(svg)
}

// EngineTraits returns a core-owned copy of the engine's traits for seed.
func EngineTraits(id, params, seed string) []engine.Trait {
	rec := mustEngine(id)
	if err := rec.impl.ValidateParams(params); err != nil {
		panic("params rejected by engine: " + err.Error())
	}
	ts := rec.impl.Traits(studioInput(params, seed))
	if err := engine.ValidateTraits(rec.manifest, ts); err != nil {
		panic("engine traits rejected: " + err.Error())
	}
	return append([]engine.Trait{}, ts...)
}

func TraitsWith(id, params, seed string) string {
	w := &safe.JSONWriter{}
	writeTraits(w, EngineTraits(id, params, seed))
	return w.String()
}

// VerifyEngine re-renders the sample and compares it with the fingerprint
// stored at registration.
func VerifyEngine(id string) bool {
	rec := mustEngine(id)
	return safe.Sha256Hex(rec.impl.Render(engine.SampleInput())) == rec.fingerprint
}

// EngineManifest is the typed read for other realms (gallery).
func EngineManifest(id string) engine.Manifest { return copyManifest(mustEngine(id).manifest) }

// EngineStatus is "unclaimed", "unverified", "reviewed" or "deprecated".
func EngineStatus(id string) string { return engineStatus(mustEngine(id)) }

func engineStatus(rec *engineRecord) string {
	switch {
	case rec.deprecated:
		return "deprecated"
	case !rec.claimed:
		return "unclaimed"
	case rec.reviewed:
		return "reviewed"
	}
	return "unverified"
}

// Engine is the record as JSON.
func Engine(id string) string {
	w := &safe.JSONWriter{}
	writeEngine(w, mustEngine(id))
	return w.String()
}

func Engines(offset, limit int64) string {
	w := &safe.JSONWriter{}
	w.BeginArray()
	engineOrder.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
		writeEngine(w, mustEngine(v.(string)))
		return false
	})
	w.EndArray()
	return w.String()
}

func writeEngine(w *safe.JSONWriter, rec *engineRecord) {
	m := rec.manifest
	w.BeginObject()
	w.StrField("id", rec.id)
	w.StrField("pkgPath", rec.id) // the adapter realm; read its source (and imports) with vm/qfile
	w.StrField("name", m.Name)
	w.StrField("version", m.Version)
	w.StrField("description", m.Description)
	w.StrField("license", m.License)
	w.StrField("author", m.Author.String())
	w.StrField("paramsSchema", m.ParamsSchema)
	w.Key("traitTypes")
	w.BeginArray()
	for _, t := range m.TraitTypes {
		w.Str(t)
	}
	w.EndArray()
	w.BoolField("living", m.Living)
	w.IntField("maxSvgBytes", m.MaxSVGBytes)
	w.StrField("fingerprint", rec.fingerprint)
	w.StrField("status", engineStatus(rec))
	w.IntField("registeredHeight", rec.registeredHeight)
	w.EndObject()
}

func studioInput(params, seed string) engine.Input {
	in := engine.SampleInput()
	in.Seed = seed
	in.Params = params
	in.Height = height()
	return in
}

gnomod.toml

module = "gno.land/r/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/core"
gno = "0.9"

[addpkg]
  creator = "g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w"
  height = 799270
  max_deposit = "100000000ugnot"

provenance.gno

package core

import (
	"chain"
	"chain/runtime"

	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/safe/v1"
	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/types/v1"
)

// Commit–reveal v2 (design §4.2–4.3, closes RA H-3, M-5, M-6).
//
// The map is fixed by three inputs: the creator's secret sc, the beacon's
// secret sb and the public mint-entropy accumulator acc. Neither committer
// knows the other's secret while minting is open, so neither can time the
// last mint for a good map. Order of reveals:
//
//  1. nothing is accepted before Closed (an early reveal informs the other
//     side);
//  2. the creator reveals first; the beacon follows, or reveals first
//     inside the last BeaconGraceBlocks of the window;
//  3. after revealDeadline anyone finalizes with whatever was revealed.
//
// What stays open, by design: the last revealer can still choose between
// revealing and not (one bit). The beacon is last, runs public code, and
// the badge shows the outcome. The transfer lock (tokens.gno) keeps anyone
// from trading on early knowledge until Final.
type provenance struct {
	creatorCommit, beaconCommit string
	acc                         string
	creatorSecret, beaconSecret string
	creatorRevealed             bool
	beaconRevealed              bool
	salt, badge                 string
	finalHeight                 int64
}

const (
	roleCreator = "creator"
	roleBeacon  = "beacon"
)

// BeaconCommit is the beacon's commitment, before any token exists.
func BeaconCommit(cur realm, cid, commitHex string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	if beacon == "" || caller(cur) != beacon {
		panic("only the configured beacon can commit")
	}
	if c.state == types.StateDraft || c.prov == nil || !c.useBeacon {
		panic("this collection is not waiting for a beacon")
	}
	if c.prov.beaconCommit != "" {
		panic("the beacon already committed")
	}
	if c.minted() > 0 {
		panic("too late: tokens were minted before the beacon committed")
	}
	commit := safe.AssertHex("commit", commitHex, 32)
	if usedCommits.Has(commit) {
		panic("this commitment was already used")
	}
	usedCommits.Set(commit, cid)
	c.prov.beaconCommit = commit
	chain.Emit("BeaconCommitted", "cid", cid, "commit", commit)
}

func RevealCreatorSecret(cur realm, cid, secret string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	assertCreator(cur, c)
	h := height()
	assertRevealOpen(c, h)
	if c.prov.creatorRevealed {
		panic("the creator secret is already revealed")
	}
	assertSecret(c, roleCreator, secret, c.prov.creatorCommit)
	c.prov.creatorSecret = secret
	c.prov.creatorRevealed = true
	chain.Emit("CreatorRevealed", "cid", cid, "secret", secret)
	if revealsComplete(c) {
		finalize(c, h)
	}
}

func RevealBeaconSecret(cur realm, cid, secret string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	if beacon == "" || caller(cur) != beacon {
		panic("only the configured beacon can reveal")
	}
	h := height()
	assertRevealOpen(c, h)
	if !c.useBeacon || c.prov.beaconCommit == "" {
		panic("this collection has no beacon commitment")
	}
	if c.prov.beaconRevealed {
		panic("the beacon secret is already revealed")
	}
	if !c.prov.creatorRevealed && h < revealDeadline(c)-BeaconGraceBlocks {
		panic("the beacon reveals after the creator, or in the window's last " + itoa(BeaconGraceBlocks) + " blocks")
	}
	assertSecret(c, roleBeacon, secret, c.prov.beaconCommit)
	c.prov.beaconSecret = secret
	c.prov.beaconRevealed = true
	chain.Emit("BeaconRevealed", "cid", cid, "secret", secret)
	if revealsComplete(c) {
		finalize(c, h)
	}
}

// Finalize is permissionless and never paused (I-2): immediately once every
// expected secret is revealed, otherwise after revealDeadline (fallback).
func Finalize(cur realm, cid string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	h := height()
	refresh(c, h)
	if c.state != types.StateClosed {
		panic("only a closed collection can be finalized (state " + c.state.String() + ")")
	}
	if !revealsComplete(c) && h <= revealDeadline(c) {
		panic("the reveal window is open until height " + itoa(revealDeadline(c)))
	}
	finalize(c, h)
}

func assertRevealOpen(c *collection, h int64) {
	refresh(c, h)
	if c.state != types.StateClosed {
		panic("secrets are accepted only after the sale closed (state " + c.state.String() + ")")
	}
	if h > revealDeadline(c) {
		panic("the reveal window closed; call Finalize")
	}
}

func assertSecret(c *collection, role, secret, commit string) {
	if len(secret) < MinSecretLen || len(secret) > MaxSecretLen {
		panic("secret must be " + itoa(MinSecretLen) + ".." + itoa(MaxSecretLen) + " bytes")
	}
	safe.AssertText("secret", secret, MaxSecretLen)
	if safe.Commit(runtime.ChainID(), c.id, role, secret) != commit {
		panic("secret does not match the " + role + " commitment")
	}
}

func revealsComplete(c *collection) bool {
	return c.prov.creatorRevealed && (!c.useBeacon || c.prov.beaconRevealed)
}

// finalize runs at most once per collection (I-10): every caller checks
// state Closed, and this sets Final.
func finalize(c *collection, h int64) {
	p := c.prov
	p.salt = safe.Salt(c.id, p.creatorSecret, p.beaconSecret, p.acc)
	switch {
	case p.creatorRevealed && p.beaconRevealed:
		p.badge = BadgeBoth
	case p.creatorRevealed:
		p.badge = BadgeCreatorOnly
	case p.beaconRevealed:
		p.badge = BadgeBeaconOnly
	default:
		p.badge = BadgeFallback
	}
	p.finalHeight = h
	c.state = types.StateFinal
	c.st.final = true
	chain.Emit("CollectionFinal", "cid", c.id, "salt", p.salt, "badge", p.badge)
}

// VerifyProvenance recomputes every commitment and the salt from public
// data. True only for a Final collection whose record is consistent.
func VerifyProvenance(cid string) bool {
	c := mustCollection(cid)
	if c.state != types.StateFinal {
		return false
	}
	p := c.prov
	chainID := runtime.ChainID()
	if p.creatorRevealed && safe.Commit(chainID, c.id, roleCreator, p.creatorSecret) != p.creatorCommit {
		return false
	}
	if p.beaconRevealed && safe.Commit(chainID, c.id, roleBeacon, p.beaconSecret) != p.beaconCommit {
		return false
	}
	return p.salt == safe.Salt(c.id, p.creatorSecret, p.beaconSecret, p.acc)
}

// Provenance is the whole record as JSON; secrets and salt stay "" until
// revealed / final.
func Provenance(cid string) string {
	c := mustCollection(cid)
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.StrField("cid", c.id)
	w.StrField("chainId", runtime.ChainID())
	w.StrField("state", stateAt(c, height()).String())
	w.IntField("minted", c.minted())
	w.IntField("reserved", c.reserved)
	if p := c.prov; p != nil {
		w.BoolField("useBeacon", c.useBeacon)
		w.StrField("creatorCommit", p.creatorCommit)
		w.StrField("beaconCommit", p.beaconCommit)
		w.StrField("entropy", p.acc)
		w.StrField("creatorSecret", p.creatorSecret)
		w.StrField("beaconSecret", p.beaconSecret)
		w.StrField("salt", p.salt)
		w.StrField("badge", p.badge)
		w.IntField("revealDeadline", revealDeadline(c))
		w.IntField("finalHeight", p.finalHeight)
		w.BoolField("verified", VerifyProvenance(cid))
	}
	w.EndObject()
	return w.String()
}

reads.gno

package core

import (
	"chain"
	"strings"

	"gno.land/p/nt/ufmt/v0"

	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/safe/v1"
	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/types/v1"
)

// Every function in this file is read-only (I-12: no exported non-crossing
// mutator). Lists are paginated with limit <= MaxPageSize (RA L-4).

// SelfAddress is core's package address, for the deploy-time cross-check
// against scripts/pkgaddr.py (RA H-5).
func SelfAddress() address { return chain.PackageAddress(selfPath) }

func CollectionCount() int64 { return collCount }

// MintedTotal counts every token ever minted, burned ones included (OA B4).
func MintedTotal(cid string) int64 { return mustCollection(cid).minted() }

// MintedBy is the lifetime mint counter of addr in cid (OA B3, I-9).
func MintedBy(cid string, addr address) int64 { return mintedBy(mustCollection(cid), addr) }

// Info is the typed collection view for other realms.
func Info(cid string) types.CollectionInfo {
	c := mustCollection(cid)
	info := types.CollectionInfo{
		ID:          c.id,
		Name:        c.name,
		Symbol:      c.symbol,
		Description: c.description,
		Creator:     c.creator,
		Minter:      c.minter,
		EngineID:    c.engineID,
		Params:      c.params,
		State:       stateAt(c, height()),
		MaxSupply:   c.maxSupply,
		Minted:      c.minted(),
		Reserved:    c.reserved,
		StartHeight: c.startHeight,
		EndHeight:   c.endHeight,
		RoyaltyBps:  c.royaltyBps,
	}
	if c.prov != nil {
		info.RevealDeadline = revealDeadline(c)
		info.Badge = c.prov.badge
	}
	return info
}

// PrimaryPayees returns a copy of the frozen primary-sale split.
func PrimaryPayees(cid string) []types.Payee {
	return append([]types.Payee{}, mustCollection(cid).primaryPayees...)
}

// FeeConfig is the typed fee view minters and markets settle with.
func FeeConfig() types.Fees { return fees }

func Beacon() address { return beacon }

func Admin() address { return admin }

func IsMinter(path string) bool {
	v := minters.Get(path)
	return v != nil && !v.(*minterRecord).deprecated
}

// Collection is the collection record as JSON.
func Collection(cid string) string {
	w := &safe.JSONWriter{}
	writeCollection(w, mustCollection(cid))
	return w.String()
}

func Collections(offset, limit int64) string {
	w := &safe.JSONWriter{}
	w.BeginArray()
	collections.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
		writeCollection(w, v.(*collection))
		return false
	})
	w.EndArray()
	return w.String()
}

func CollectionsByCreator(creator address, offset, limit int64) string {
	w := &safe.JSONWriter{}
	w.BeginArray()
	prefix := creator.String() + ":"
	skipped, written, want := int64(0), int64(0), clampLimit(limit)
	byCreator.Iterate(prefix, prefix+"\xff", func(_ string, v any) bool {
		if skipped < offset {
			skipped++
			return false
		}
		writeCollection(w, mustCollection(v.(string)))
		written++
		return written >= want
	})
	w.EndArray()
	return w.String()
}

// Fees is the fee configuration and its hard caps as JSON.
func Fees() string {
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.IntField("createFee", fees.CreateFee)
	w.IntField("primaryBps", fees.PrimaryBps)
	w.IntField("secondaryBps", fees.SecondaryBps)
	w.StrField("treasury", fees.Treasury.String())
	w.IntField("createFeeCap", CreateFeeCap)
	w.IntField("protocolFeeCapBps", ProtocolFeeCapBps)
	w.IntField("royaltyCapBps", RoyaltyCapBps)
	w.EndObject()
	return w.String()
}

// PendingOps is the timelock queue as JSON.
func PendingOps() string {
	w := &safe.JSONWriter{}
	w.BeginArray()
	ops.Iterate("", "", func(_ string, v any) bool {
		p := v.(*pendingOp)
		w.BeginObject()
		w.StrField("id", itoa(p.id))
		w.StrField("op", p.op)
		w.StrField("arg", p.arg)
		w.IntField("proposed", p.proposed)
		w.IntField("earliest", earliestExecution(p))
		w.EndObject()
		return false
	})
	w.EndArray()
	return w.String()
}

func writeCollection(w *safe.JSONWriter, c *collection) {
	h := height()
	w.BeginObject()
	w.StrField("cid", c.id)
	w.StrField("name", c.name)
	w.StrField("symbol", c.symbol)
	w.StrField("description", c.description)
	w.StrField("creator", c.creator.String())
	w.StrField("engine", c.engineID)
	w.StrField("params", c.params)
	w.StrField("minter", c.minter)
	w.StrField("state", stateAt(c, h).String())
	w.IntField("maxSupply", c.maxSupply)
	w.IntField("minted", c.minted())
	w.IntField("reserved", c.reserved)
	w.IntField("royaltyBps", c.royaltyBps)
	w.StrField("royaltyAddress", royaltyAddress(c.id).String())
	w.StrField("primaryPayees", safe.FormatPayees(c.primaryPayees))
	w.StrField("royaltyPayees", safe.FormatPayees(c.royaltyPayees))
	w.IntField("startHeight", c.startHeight)
	w.IntField("endHeight", c.endHeight)
	w.IntField("createdHeight", c.createdHeight)
	w.StrField("token", c.token.ID())
	if c.prov != nil {
		w.IntField("revealDeadline", revealDeadline(c))
		w.BoolField("useBeacon", c.useBeacon)
		w.StrField("badge", c.prov.badge)
	}
	w.EndObject()
}

func clampLimit(limit int64) int64 {
	if limit <= 0 || limit > MaxPageSize {
		return MaxPageSize
	}
	return limit
}

// Render stays minimal in the immutable realm; the browsable gallery is the
// private, re-deployable gallery realm (design §2.5.7).
func Render(path string) string {
	gallery := strings.TrimPrefix(strings.TrimSuffix(selfPath, "/core")+"/gallery", "gno.land")
	return ufmt.Sprintf("# Collections ledger\n\n%d collections, %d engines. Browse them in the [gallery](%s).\n",
		collCount, engineCount, gallery)
}

royalties.gno

package core

import (
	"chain"
	"chain/banker"

	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/safe/v1"
)

// Each collection's royalty receiver is its own sub-treasury
// DerivePkgSubAddr(core, "roy/<cid>"), written into the official royalty
// extension at creation. Any market can pay it through RoyaltyInfo; the
// creator can re-split it later (SetPayees) without touching the receiver.
// Only core can spend it: a banker for a sub-address needs core's live
// cur.Sub (interrealm v2 §5.5).

func royaltyAddress(cid string) address {
	return chain.DerivePkgSubAddr(selfPath, "roy/"+cid)
}

// RoyaltyAddress is the collection's royalty sub-treasury.
func RoyaltyAddress(cid string) address {
	mustCollection(cid)
	return royaltyAddress(cid)
}

// DistributeRoyalties pushes the whole sub-treasury balance to the royalty
// payees. Permissionless and never paused (I-2); market/v1 calls it after
// every sale. Returns the amount distributed. The sub-realm banker spend
// is verified by spike/subtoken, core and market tests on gno v1.7.0.
func DistributeRoyalties(cur realm, cid string) int64 {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	sub := cur.Sub("roy/" + cid)
	bal := banker.NewReadonlyBanker().GetCoin(sub.Address(), "ugnot")
	if bal <= 0 {
		return 0
	}
	shares := safe.SplitByBps(bal, c.royaltyPayees)
	bk := banker.NewBanker(banker.BankerTypeRealmSend, sub)
	for i, p := range c.royaltyPayees {
		if shares[i] > 0 {
			bk.SendCoins(sub.Address(), p.Addr, chain.NewCoins(chain.NewCoin("ugnot", shares[i])))
		}
	}
	chain.Emit("RoyaltiesDistributed", "cid", cid, "amount", itoa(bal))
	return bal
}

tokens.gno

package core

import (
	"chain"
	"encoding/base64"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/grc721/royalty/v0"
	"gno.land/p/nt/grc721/v0"

	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/engine/v1"
	"gno.land/p/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/safe/v1"
)

const tidWidth = 6

// tokenState is the per-collection data the transfer hook needs. It is
// shared by the collection and its lockExt, so neither points at the other.
type tokenState struct {
	final   bool
	batches avl.Tree // safe.PadInt(first) -> *mintBatch
	moves   avl.Tree // tid -> *moveRecord, created on a token's first transfer
}

// mintBatch records one mint call; mint height is derived per token from
// it, so a 10-token mint writes one record, not ten.
type mintBatch struct {
	first, last, height int64
}

type moveRecord struct {
	moves, lastMove int64
}

func (st *tokenState) addBatch(first, last, h int64) {
	st.batches.Set(safe.PadInt(first, tidWidth), &mintBatch{first: first, last: last, height: h})
}

func (st *tokenState) mintHeight(tid int64) int64 {
	var h int64
	st.batches.ReverseIterate("", safe.PadInt(tid, tidWidth), func(_ string, v any) bool {
		b := v.(*mintBatch)
		if tid <= b.last {
			h = b.height
		}
		return true
	})
	return h
}

func (st *tokenState) moveOf(tid string) (moves, lastMove int64) {
	if v := st.moves.Get(tid); v != nil {
		r := v.(*moveRecord)
		return r.moves, r.lastMove
	}
	return 0, 0
}

// lockExt is the grc721 Extension behind two invariants:
//
//   - I-11: before Final no token moves or burns (the reveal lock that
//     closes RA H-3's information-advantage branch). The veto is a panic,
//     which aborts the whole transaction — the documented Extension
//     semantics of p/nt/grc721/v0.
//   - H-2: every transfer bumps the token's move counter, so a market
//     listing taken at moves=N is dead after any transfer, even if the
//     token later comes back to the seller.
//
// It is declared in this realm, so the hooks write core state with core's
// authority even when another realm moves the token via RealmTeller.
type lockExt struct {
	cid string
	st  *tokenState
}

const lockKind = "art-lock"

func (e *lockExt) ExtensionKind() string { return lockKind }

// The hooks also emit the platform's per-token history events with the
// collection id ("Minted", "Transfer"); grc721's own Transfer event carries
// only the token's grc721 id.
func (e *lockExt) OnMint(to address, tid grc721.TokenID) {
	chain.Emit("Minted", "cid", e.cid, "tid", tid.String(), "to", to.String())
}

func (e *lockExt) OnTransfer(from, to address, tid grc721.TokenID) {
	if !e.st.final {
		panic("tokens are locked until the collection is final (reveal)")
	}
	key := tid.String()
	r, _ := e.st.moves.Get(key).(*moveRecord)
	if r == nil {
		r = &moveRecord{}
		e.st.moves.Set(key, r)
	}
	r.moves++
	r.lastMove = height()
	chain.Emit("Transfer", "cid", e.cid, "tid", key, "from", from.String(), "to", to.String())
}

func (e *lockExt) OnBurn(tid grc721.TokenID) {
	if !e.st.final {
		panic("tokens are locked until the collection is final (reveal)")
	}
	e.st.moves.Remove(tid.String())
}

// --- owner actions (I-2: never paused) ---------------------------------------
//
// The acting account is always the immediate caller (cur.Previous()), the
// same rule as grc721's CallerTeller: a realm a user merely calls cannot act
// for that user. Another realm moves tokens only after an Approve, through
// Token(cid).RealmTeller (market/v1 does exactly that).

func Approve(cur realm, cid, tid string, to address) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	if err := c.ledger.Approve(caller(cur), to, grc721.TokenID(tid)); err != nil {
		panic(err)
	}
}

func SetApprovalForAll(cur realm, cid string, operator address, approved bool) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	if err := c.ledger.SetApprovalForAll(caller(cur), operator, approved); err != nil {
		panic(err)
	}
}

func TransferFrom(cur realm, cid, tid string, from, to address) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	if err := c.ledger.TransferFrom(caller(cur), from, to, grc721.TokenID(tid)); err != nil {
		panic(err)
	}
}

// Burn is owner-only. The supply gate uses nextTID, so a burn never reopens
// a slot (I-5).
func Burn(cur realm, cid, tid string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	owner, err := c.token.OwnerOf(grc721.TokenID(tid))
	if err != nil {
		panic(err)
	}
	if owner != caller(cur) {
		panic("only the owner can burn a token")
	}
	if err := c.ledger.Burn(grc721.TokenID(tid)); err != nil {
		panic(err)
	}
}

// --- token reads ---------------------------------------------------------------

// Token publishes the collection's official *grc721.Token. Its exported
// methods are reads or teller factories that need the caller's live realm;
// the ledger itself is never published.
func Token(cid string) *grc721.Token { return mustCollection(cid).token }

// Royalty publishes the read-only royalty view (EIP-2981 RoyaltyInfo).
func Royalty(cid string) *royalty.Royalty { return mustCollection(cid).roy }

func OwnerOf(cid, tid string) (address, error) {
	return mustCollection(cid).token.OwnerOf(grc721.TokenID(tid))
}

func BalanceOf(cid string, owner address) (int64, error) {
	return mustCollection(cid).token.BalanceOf(owner)
}

// TokenMoves is the transfer counter market/v1 pins in a listing (H-2).
func TokenMoves(cid, tid string) int64 {
	n, _ := mustCollection(cid).st.moveOf(tid)
	return n
}

// TokenSeed is "" until the collection is Final: no read path can leak the
// rarity map early.
func TokenSeed(cid, tid string) string {
	c := mustCollection(cid)
	if !c.st.final || !exists(c, tid) {
		return ""
	}
	return safe.Seed(c.id, tid, c.prov.salt)
}

// TokenState is {mintHeight, lastMoveHeight, moves} as JSON.
func TokenState(cid, tid string) string {
	c := mustCollection(cid)
	if !exists(c, tid) {
		panic(grc721.ErrInvalidTokenId)
	}
	in := tokenInput(c, tid)
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.IntField("mintHeight", in.MintHeight)
	w.IntField("lastMoveHeight", in.LastMoveHeight)
	w.IntField("moves", in.Moves)
	w.EndObject()
	return w.String()
}

// TokenURI is a base64 SVG data URI. Before Final every token shows core's
// neutral placeholder, never engine output (design §4.2).
func TokenURI(cid, tid string) (string, error) {
	c := mustCollection(cid)
	if _, err := c.token.OwnerOf(grc721.TokenID(tid)); err != nil {
		return "", err
	}
	if !c.st.final {
		return dataURI(placeholderSVG(c.name, "Unrevealed")), nil
	}
	return dataURI(renderToken(c, tid)), nil
}

// TokenTraits is [{"trait_type":…,"value":…}] JSON.
func TokenTraits(cid, tid string) string {
	c := mustCollection(cid)
	w := &safe.JSONWriter{}
	writeTraits(w, tokenTraits(c, tid))
	return w.String()
}

// TokenTraitList is the typed form of TokenTraits for other realms (a copy).
func TokenTraitList(cid, tid string) []engine.Trait {
	return append([]engine.Trait{}, tokenTraits(mustCollection(cid), tid)...)
}

// TokenMetadata is OpenSea-style metadata JSON.
func TokenMetadata(cid, tid string) string {
	c := mustCollection(cid)
	uri, err := TokenURI(cid, tid)
	if err != nil {
		panic(err)
	}
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.StrField("name", c.name+" #"+tid)
	w.StrField("description", c.description)
	w.StrField("image", uri)
	w.Key("attributes")
	writeTraits(w, tokenTraits(c, tid))
	w.EndObject()
	return w.String()
}

func exists(c *collection, tid string) bool {
	_, err := c.token.OwnerOf(grc721.TokenID(tid))
	return err == nil
}

func tokenInput(c *collection, tid string) engine.Input {
	n := safe.ParseID("tid", tid)
	moves, lastMove := c.st.moveOf(tid)
	mh := c.st.mintHeight(n)
	if lastMove == 0 {
		lastMove = mh
	}
	in := engine.Input{
		Params:         c.params,
		CollectionID:   c.id,
		TokenID:        tid,
		MintHeight:     mh,
		LastMoveHeight: lastMove,
		Moves:          moves,
		Height:         height(),
	}
	if c.st.final {
		in.Seed = safe.Seed(c.id, tid, c.prov.salt)
	}
	return in
}

// renderToken runs the collection's engine on a read path. A bad output
// degrades to a placeholder; a panicking engine only fails reads of its own
// collections (interrealm v2 §9: cross-realm panics abort the query).
func renderToken(c *collection, tid string) string {
	rec := mustEngine(c.engineID)
	svg := rec.impl.Render(tokenInput(c, tid))
	if err := engine.CheckSVG(rec.manifest, svg); err != nil {
		return placeholderSVG(c.name, "Engine output rejected")
	}
	return svg
}

func tokenTraits(c *collection, tid string) []engine.Trait {
	if !exists(c, tid) {
		panic(grc721.ErrInvalidTokenId)
	}
	if !c.st.final {
		return []engine.Trait{{Type: "Status", Value: "Unrevealed"}}
	}
	rec := mustEngine(c.engineID)
	ts := rec.impl.Traits(tokenInput(c, tid))
	if err := engine.ValidateTraits(rec.manifest, ts); err != nil {
		return []engine.Trait{{Type: "Status", Value: "Engine output rejected"}}
	}
	return ts
}

func writeTraits(w *safe.JSONWriter, ts []engine.Trait) {
	w.BeginArray()
	for _, t := range ts {
		w.BeginObject()
		w.StrField("trait_type", t.Type)
		w.StrField("value", t.Value)
		w.EndObject()
	}
	w.EndArray()
}

// placeholderSVG is core's own neutral art: identical for every token of a
// collection, so it carries no rarity signal.
func placeholderSVG(name, label string) string {
	return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">` +
		`<rect width="512" height="512" fill="#111"/>` +
		`<text x="256" y="236" fill="#ddd" font-family="monospace" font-size="24" text-anchor="middle">` +
		safe.XMLEscape(name) + `</text>` +
		`<text x="256" y="286" fill="#888" font-family="monospace" font-size="18" text-anchor="middle">` +
		safe.XMLEscape(label) + `</text></svg>`
}

func dataURI(svg string) string {
	return "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(svg))
}

// emitBatch announces one MintTo ("MintBatch") or ReserveTo ("Reserved")
// call; each token also gets its own "Minted" event from lockExt.
func emitBatch(kind string, c *collection, to address, first, last int64) {
	chain.Emit(kind, "cid", c.id, "to", to.String(), "first", itoa(first), "last", itoa(last))
}