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/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/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.
// SA-I6: CreateFee starts at 0 here so tests and bootstrap stay simple;
// scripts/deploy-onyx.sh sets a non-zero fee.create during bootstrap.
var (
	admin        = address("g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06")
	pendingAdmin address
	fees         = types.Fees{
		PrimaryBps: 250, SecondaryBps: 250, EngineCapBps: EngineFeeCapBps,
		Treasury: address("g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06"),
	}
	beacon       address
	minters      avl.Tree // minter pkgpath -> *minterRecord
	ops          avl.Tree // safe.PadInt(op id) -> *pendingOp
	opCount      int64
	pauses       avl.Tree // scope -> *pauseRecord
)

// pauseRecord is one scope's pause and its budget (SA-L2): within a window
// of PauseWindowBlocks a scope can be paused for at most MaxPauseBlocks in
// total; a pause cannot be renewed while it runs. Worst case two budgets
// meet at a window boundary (<= 2 x MaxPauseBlocks in a row), never more.
type pauseRecord struct {
	windowStart int64
	used        int64 // blocks of budget charged in this window
	until       int64 // 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
	OpFeeEngine       = "fee.engine"       // bps, <= EngineFeeCapBps: platform cap on engine-author fees
	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
	OpRandomnessAdd   = "randomness.add"   // registered provider path: creators may launch with it
	OpRandomnessDepr  = "randomness.deprecate" // provider path: no new launches; running ones finish
)

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 the rest of its budget (at
// most MaxPauseBlocks per PauseWindowBlocks). It never blocks exits (I-2)
// and cannot be renewed while it runs (SA-L2).
func Pause(cur realm, scope string) {
	assertNoDeposit(cur)
	assertAdmin(cur)
	assertScope(scope)
	h := height()
	r := pauseOf(scope)
	if h < r.until {
		panic("already paused until height " + itoa(r.until) + "; a pause cannot be renewed")
	}
	if h >= r.windowStart+PauseWindowBlocks {
		r.windowStart, r.used = h, 0
	}
	left := MaxPauseBlocks - r.used
	if left <= 0 {
		panic("pause budget of " + scope + " is spent until height " + itoa(r.windowStart+PauseWindowBlocks))
	}
	r.used += left
	r.until = h + left
	pauses.Set(scope, r)
	chain.Emit("Paused", "scope", scope, "until", itoa(r.until))
}

// Unpause ends a pause early and gives the unused blocks back to the budget.
func Unpause(cur realm, scope string) {
	assertNoDeposit(cur)
	assertAdmin(cur)
	assertScope(scope)
	h := height()
	r := pauseOf(scope)
	if h < r.until {
		r.used -= r.until - h
	}
	r.until = 0
	chain.Emit("Unpaused", "scope", scope)
}

func pauseOf(scope string) *pauseRecord {
	if v := pauses.Get(scope); v != nil {
		return v.(*pauseRecord)
	}
	return &pauseRecord{windowStart: -PauseWindowBlocks}
}

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

// PauseBudget is the scope's pause record as JSON: {until, used,
// windowStart, windowEnd, left}.
func PauseBudget(scope string) string {
	assertScope(scope)
	r := pauseOf(scope)
	used := r.used
	if height() >= r.windowStart+PauseWindowBlocks && height() >= r.until {
		used = 0
	}
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.IntField("until", r.until)
	w.IntField("used", used)
	w.IntField("windowStart", r.windowStart)
	w.IntField("windowEnd", r.windowStart+PauseWindowBlocks)
	w.IntField("left", MaxPauseBlocks-used)
	w.EndObject()
	return w.String()
}

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 OpFeeEngine:
		safe.AssertBps(op, parseAmount(arg), EngineFeeCapBps)
	case OpTreasury, OpAdminTransfer:
		if !address(arg).IsValid() {
			panic(op + ": invalid address")
		}
		if op == OpTreasury {
			assertSpendable(op, address(arg), "", "") // SA-L5
		}
	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)
	case OpRandomnessAdd:
		if mustProvider(arg).active {
			panic("randomness provider already approved")
		}
	case OpRandomnessDepr:
		if !mustProvider(arg).active {
			panic("randomness provider is not approved")
		}
	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 OpFeeEngine:
		fees.EngineCapBps = 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)
	case OpRandomnessAdd:
		mustProvider(arg).active = true
		activeProviders++
	case OpRandomnessDepr:
		mustProvider(arg).active = false
		activeProviders--
	}
}

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"
	"strings"

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

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/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)
	next := itoa(collCount + 1)
	assertPayees("primaryPayees", primary, next, spec.EngineID)
	assertPayees("royaltyPayees", royal, next, spec.EngineID)

	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)
	// Commitments are domain-separated by chain, collection and role
	// (safe.Commit), so only this collection's own history matters: a secret
	// that went public here is never accepted again (SA-L1, RA M-5).
	if isBurned(c, commit) {
		panic("this commitment's secret was already revealed; derive a new secret")
	}
	source := l.BeaconSource
	if l.UseBeacon {
		if source == "" {
			source = types.BeaconCommitted
		}
		if source == types.BeaconCommitted {
			if beacon == "" {
				panic("no beacon is configured; launch without useBeacon or with an approved randomness provider")
			}
		} else {
			assertActiveProvider(source)
		}
	} else {
		if source != "" {
			panic("beaconSource needs useBeacon")
		}
		// SA-M2: without the beacon the creator alone knows the only secret
		// and can grind the last mint for the map it wants. While the
		// platform has a beacon or an approved randomness provider, nobody
		// may opt out.
		if beaconAvailable() {
			panic("the platform beacon is configured; launch with useBeacon")
		}
	}

	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.beaconSource = source
	c.primaryBps = fees.PrimaryBps
	c.engineAuthor, c.engineBps = engineFeeQuote(c)
	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),
		"beaconSource", c.beaconSource, "creatorCommit", commit,
		"engineAuthor", c.engineAuthor.String(), "engineFeeBps", itoa(c.engineBps))
}

// AbortLaunch returns a launched collection to Draft while nothing has been
// minted — the way out when a beacon never commits. A commitment whose
// secret was revealed is burned for this collection; unrevealed ones (the
// beacon's deterministic one included) may be committed again (SA-L1).
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")
	}
	if c.prov.creatorRevealed {
		c.burnedCommits = append(c.burnedCommits, c.prov.creatorCommit)
	}
	if c.prov.beaconRevealed {
		c.burnedCommits = append(c.burnedCommits, c.prov.beaconCommit)
	}
	c.prov = nil
	c.startHeight, c.endHeight, c.revealWindow, c.closeHeight = 0, 0, 0, 0
	c.useBeacon, c.beaconSource = false, ""
	c.engineBps, c.engineAuthor = 0, ""
	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")
	}
	// SA-M2: a reserve is the creator's own allocation; it needs a map the
	// creator cannot steer, i.e. the beacon.
	if !c.useBeacon {
		panic("a creator reserve needs a beacon launch")
	}
	// 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). A randomness provider has
	// nothing to commit: its value is drawn only after the reveal starts.
	if awaitingBeaconCommit(c) {
		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
	c.reservedTo.Set(to.String(), reservedTo(c, to)+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 and the beacon commitment (I-5). The lifetime counter of
// I-9 is the grc721 balance itself (mintedBy).
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 awaitingBeaconCommit(c) {
		panic("waiting for the beacon commitment; minting has not opened")
	}
	assertMintCount(c, n)
	first, last = mintBatchTo(c, to, n, h)
	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.appendTokens(first, last, h)
	c.prov.acc = safe.MixEntropy(c.prov.acc, to, h, first, last)
	return first, last
}

// mintedBy is addr's lifetime count of sale mints (I-9) while the
// collection is not Final: before Final no token can move or burn (I-11,
// lockExt) and tokens only come from mintBatchTo, so the grc721 balance is
// exactly sale mints + reserves received. This replaces a stored counter
// (~2 KB per new wallet, storage-cost-analysis P2). After Final the
// balance moves freely and no minter needs the count any more: -1.
func mintedBy(c *collection, addr address) int64 {
	if c.st.final {
		return -1
	}
	bal, err := c.token.BalanceOf(addr)
	if err != nil {
		return 0
	}
	return bal - reservedTo(c, addr)
}

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

// awaitingBeaconCommit: a committed-beacon launch whose beacon has not
// committed yet; nothing may be minted (or reserved) before it does.
func awaitingBeaconCommit(c *collection) bool {
	return c.useBeacon && c.beaconSource == types.BeaconCommitted && c.prov.beaconCommit == ""
}

// 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. Royalties earned so
// far are first paid to the current payees (SA-I4).
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")
	}
	ps := safe.ParsePayees("royaltyPayees", payees, MaxPayees)
	assertPayees("royaltyPayees", ps, cid, c.engineID)
	distribute(cur, c)
	c.royaltyPayees = ps
	chain.Emit("RoyaltyPayees", "cid", cid, "payees", payees)
}

// assertPayees refuses payees that can never spend what they receive
// (SA-L5): the platform's own realms and sub-addresses. cid is the
// collection being configured, engineID its engine adapter.
func assertPayees(field string, ps []types.Payee, cid, engineID string) {
	for _, p := range ps {
		assertSpendable(field, p.Addr, cid, engineID)
	}
}

// assertSpendable panics for core, core's sub-addresses of collection cid
// (token identity c/<cid>, royalty treasury roy/<cid>), every minter ever
// approved, the engine adapter, and the platform realms next to core
// (market, reader, gallery, the genesis adapter). None of them has a path
// that spends an incoming payment, so the coins would be stranded (I-3).
func assertSpendable(field string, addr address, cid, engineID string) {
	bad := []address{chain.PackageAddress(selfPath)}
	if cid != "" {
		bad = append(bad, chain.DerivePkgSubAddr(selfPath, "c/"+cid), royaltyAddress(cid))
	}
	if engineID != "" {
		bad = append(bad, chain.PackageAddress(engineID))
	}
	base := strings.TrimSuffix(selfPath, "/core")
	for _, sib := range platformRealms {
		bad = append(bad, chain.PackageAddress(base+"/"+sib))
	}
	for _, b := range bad {
		if addr == b {
			panic(field + ": " + addr.String() + " is a platform realm address that cannot spend; use a wallet")
		}
	}
	minters.Iterate("", "", func(path string, _ any) bool {
		if addr == chain.PackageAddress(path) {
			panic(field + ": " + addr.String() + " is the minter realm " + path + "; use a wallet")
		}
		return false
	})
}

// platformRealms are the realm paths next to core (README package map).
var platformRealms = []string{"mint/v1", "market/v1", "engines/genesis", "reader", "gallery"}

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. A pause expires by
//     itself, cannot be renewed while it runs, and each scope has a budget
//     of MaxPauseBlocks per PauseWindowBlocks (SA-L2).
//   - 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,
//     commitments, randomness source and fee snapshots are frozen.
//   - I-9  MintedBy(addr) is exact while a collection is not Final:
//     grc721 balance minus the reserves sent to addr. It needs I-11 (no
//     token moves or burns before Final); if that lock is ever relaxed the
//     counter must be stored again (TestRegress_P2_*).
//   - 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.
//     An admin-approved randomness provider (randomness.gno) runs only in
//     RequestRandomness/FulfillRandomness of collections launched with it.
//   - 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/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/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: pause budget per scope and window
	PauseWindowBlocks = 732_000 // ~30 days (SA-L2)
	EngineFeeCapBps   = engine.MaxFeeBps // 5%: hard cap of an engine author's fee (platform cap <= this)
	RequestMargin     = 127              // a randomness request leaves >= this many blocks before revealDeadline

	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
	beaconSource                  string // with useBeacon: types.BeaconCommitted or a randomness provider path
	createdHeight                 int64
	primaryBps                    int64    // protocol fee snapshot at Launch (SA-I5)
	engineBps                     int64    // engine-author fee snapshot at Launch (0 when creator == author)
	engineAuthor                  address  // who receives engineBps
	burnedCommits                 []string // commitments whose secret went public; never accepted again here (SA-L1)
	approvals                     avl.Tree // "o:"+owner+":"+operator -> int64 nonce (SA-L3; token nonces are packed in st)
	prov                          *provenance
	token                         *grc721.Token
	ledger                        *grc721.PrivateLedger
	roy                           *royalty.Royalty
	st                            *tokenState
	reservedTo                    avl.Tree // address -> int64 reserve tokens received (MintedBy = balance - this, 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
)

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/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/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(), "feeBps", itoa(m.FeeBps),
		"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)
}

// --- engine-author fee ---------------------------------------------------------
//
// An engine's author earns FeeBps (manifest, fixed at registration, <=
// EngineFeeCapBps) of every primary and secondary sale of a collection that
// uses the engine, capped by the platform's fees.EngineCapBps. A collection
// snapshots the fee at Launch (like the protocol fee, SA-I5) and later sales
// pay min(snapshot, current platform cap), so neither the author nor the
// admin can raise it on a running collection. No fee when the creator is
// the author: the creator's own payees already get the sale.

// engineFeeOf is the engine's fee under the current platform cap.
func engineFeeOf(rec *engineRecord) int64 {
	if rec.manifest.FeeBps < fees.EngineCapBps {
		return rec.manifest.FeeBps
	}
	return fees.EngineCapBps
}

// engineFeeQuote is what c would snapshot at a Launch now.
func engineFeeQuote(c *collection) (address, int64) {
	rec := mustEngine(c.engineID)
	author := rec.manifest.Author
	if author == c.creator {
		return author, 0
	}
	return author, engineFeeOf(rec)
}

// collectionEngineFee is the fee a sale of c pays now: the Launch snapshot
// bounded by the current cap; before Launch, the current quote.
func collectionEngineFee(c *collection) (address, int64) {
	if c.prov == nil {
		return engineFeeQuote(c)
	}
	if c.engineBps < fees.EngineCapBps {
		return c.engineAuthor, c.engineBps
	}
	return c.engineAuthor, fees.EngineCapBps
}

// EngineFee is the engine-author share of cid's sales: the author and the
// bps a sale pays now (0 when the creator is the author). mint/v1 and
// market/v1 pay safe.BpsOf(amount, bps) to author.
func EngineFee(cid string) (author address, bps int64) {
	return collectionEngineFee(mustCollection(cid))
}

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.IntField("feeBps", m.FeeBps)
	w.IntField("effectiveFeeBps", engineFeeOf(rec))
	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/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia2/core"
gno = "0.9"

[addpkg]
  creator = "g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06"
  height = 829911
  max_deposit = "100000000ugnot"

provenance.gno

package core

import (
	"chain"
	"chain/runtime"

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/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 may reveal until revealDeadline - BeaconGraceBlocks; the
//     beacon follows at any time before the deadline;
//  3. inside the last BeaconGraceBlocks only the beacon may reveal. If the
//     creator stayed silent, the beacon's reveal finalizes at once
//     ("beacon-only"), so the creator never sees sb while it can still
//     choose (SA-M1; this also closes the mempool race of a creator
//     front-running the beacon's grace reveal);
//  4. after revealDeadline anyone finalizes with whatever was revealed.
//
// What stays open, by design: the beacon, as last revealer after the
// creator, can still choose between revealing and not (one bit). It runs
// public code and the badge shows the outcome. The transfer lock
// (tokens.gno) keeps anyone from trading on early knowledge until Final.
//
// A collection launched without the beacon (only possible while no beacon
// is configured, SA-M2) gives the creator the whole choice of the map; it
// can have no creator reserve and is never reported as a fair launch
// (FairLaunch, Provenance "fair").
type provenance struct {
	creatorCommit, beaconCommit string
	acc                         string
	creatorSecret, beaconSecret string
	creatorRevealed             bool
	beaconRevealed              bool
	salt, badge                 string
	finalHeight                 int64
	round                       int64 // randomness provider round bound by RequestRandomness (0 = none)
}

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 || usesProvider(c) {
		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 isBurned(c, commit) {
		panic("this commitment's secret was already revealed for this collection")
	}
	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")
	}
	if c.useBeacon {
		// SA-M1: once the grace period starts only the beacon may reveal, so
		// the creator can never reveal after seeing sb.
		if c.prov.beaconRevealed {
			panic("the beacon revealed first; the outcome is fixed")
		}
		if h >= revealDeadline(c)-BeaconGraceBlocks {
			panic("the creator's reveal window ended at height " + itoa(revealDeadline(c)-BeaconGraceBlocks-1) +
				"; only the beacon may reveal now")
		}
	}
	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 || usesProvider(c) || 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)
	// After the creator: both secrets are in (2/2). First, in the grace
	// period: the creator can no longer reveal, so the map is fixed now
	// (beacon-only) — nobody is left holding a choice (SA-M1).
	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)))
	}
	// SA-I9: a sale that minted nothing stays Closed, so its creator can
	// still abort and relaunch; nobody else can lock it into Final.
	if c.minted() == 0 {
		panic("nothing was minted; the creator may abort and relaunch instead")
	}
	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 && !usesProvider(c) && safe.Commit(chainID, c.id, roleBeacon, p.beaconSecret) != p.beaconCommit {
		return false
	}
	// A provider's value was checked by FulfillRandomness against the
	// provider's verified round (p.round); it is recomputable off chain
	// from the provider's public source (e.g. the drand round).
	return p.salt == safe.Salt(c.id, p.creatorSecret, p.beaconSecret, p.acc)
}

// FairLaunch is true only for a Final, consistent collection whose map no
// single party could choose: launched with the beacon and finalized with
// both secrets or with the beacon's alone (after the creator stayed
// silent). Creator-only collections (no beacon: the creator alone knew the
// only secret and could steer the last mint, SA-M2) and fallbacks are not
// fair launches, even when VerifyProvenance is true.
func FairLaunch(cid string) bool {
	c := mustCollection(cid)
	if !VerifyProvenance(cid) || !c.useBeacon {
		return false
	}
	return c.prov.badge == BadgeBoth || c.prov.badge == BadgeBeaconOnly
}

func isBurned(c *collection, commit string) bool {
	for _, b := range c.burnedCommits {
		if b == commit {
			return true
		}
	}
	return false
}

// 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("beaconSource", c.beaconSource)
		w.IntField("round", p.round)
		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.BoolField("fair", FairLaunch(cid))
	}
	w.EndObject()
	return w.String()
}

randomness.gno

package core

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

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

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

// Pluggable randomness sources (beacon v2).
//
// A collection launched with useBeacon picks its second entropy source at
// Launch (LaunchSpec.BeaconSource, frozen by I-6):
//
//   - types.BeaconCommitted: the platform beacon's commit-reveal
//     (provenance.gno; BeaconCommit before the first mint,
//     RevealBeaconSecret after the creator).
//   - the package path of a randomness provider realm: a public random
//     value nobody can know in advance, e.g. a drand round relayed and
//     BLS-verified on chain (gnolang/gno#6268 p/drand + r/drand). Nothing
//     is committed before the sale; the round is fixed only once the
//     creator can no longer choose (RequestRandomness), then anyone pulls
//     its value (FulfillRandomness).
//
// A provider realm registers itself (its id is its package path, as for
// engines) and is usable only after the admin approves it through the
// timelocked op randomness.add; randomness.deprecate stops new launches,
// running collections finish with it. So a drand provider plugs in without
// a core redeploy. Its methods are declared in its own realm, so core
// calling them runs the provider with the provider's authority (interrealm
// v2 borrow rule #1): it cannot write core state, and with no cur it cannot
// call a core mutator.
//
// Order with a provider (same guarantees as the committed beacon, SA-M1):
//
//  1. the creator reveals until revealDeadline - BeaconGraceBlocks;
//  2. RequestRandomness (anyone) after the creator revealed, or inside the
//     grace period when it stayed silent, and no later than revealDeadline
//     - RequestMargin: binds the collection to provider.Target(), a round
//     whose value nobody knows yet — not the creator, whose secret is
//     public or whose window is closed, not the minters, whose sale is over;
//  3. FulfillRandomness (anyone) once the provider has that round: the
//     value becomes the beacon secret and the collection is Final at once
//     (2/2 after the creator, beacon-only in grace);
//  4. after revealDeadline Finalize works as before (creator-only /
//     fallback if the provider never delivered).
type RandomnessProvider interface {
	// Name is a short label for UIs, e.g. "drand quicknet".
	Name() string
	// Target is the round a request made in the current block is bound
	// to. Its value must be unknowable to anyone at this block (a round
	// published strictly in the future). Read-only.
	Target() int64
	// Randomness is round's verified value as 64 lowercase hex characters
	// (32 bytes), or "" while it is not available. Read-only.
	Randomness(round int64) string
}

type providerRecord struct {
	id               string
	name             string
	impl             RandomnessProvider
	active           bool // approved by the admin and not deprecated
	registeredHeight int64
}

var (
	providers       avl.Tree // provider pkgpath -> *providerRecord
	activeProviders int64
)

const MaxProviderNameLen = 64

// RegisterRandomnessProvider stores the calling realm's provider. It is
// inert until the admin approves it (randomness.add, timelocked).
func RegisterRandomnessProvider(cur realm, p RandomnessProvider) string {
	assertNoDeposit(cur)
	id := cur.Previous().PkgPath()
	if !strings.HasPrefix(id, runtime.ChainDomain()+"/r/") || strings.Contains(id, "#") {
		panic("a randomness provider registers from its own realm (an /r/ package, not a sub-realm or wallet)")
	}
	if p == nil {
		panic("nil provider")
	}
	if providers.Has(id) {
		panic("randomness provider already registered: " + id)
	}
	name := p.Name()
	safe.AssertNonEmptyText("provider name", name, MaxProviderNameLen)
	providers.Set(id, &providerRecord{id: id, name: name, impl: p, registeredHeight: height()})
	chain.Emit("RandomnessProviderRegistered", "id", id, "name", name)
	return id
}

func mustProvider(id string) *providerRecord {
	v := providers.Get(id)
	if v == nil {
		panic("unknown randomness provider " + id)
	}
	return v.(*providerRecord)
}

func assertActiveProvider(id string) {
	if !mustProvider(id).active {
		panic("randomness provider " + id + " is not approved")
	}
}

// beaconAvailable: some unpredictable second source exists, so no launch
// may opt out of it (SA-M2).
func beaconAvailable() bool { return beacon != "" || activeProviders > 0 }

func usesProvider(c *collection) bool {
	return c.useBeacon && c.beaconSource != types.BeaconCommitted
}

// RequestRandomness binds a provider-backed collection to the provider's
// next unknowable round. Permissionless and never paused (I-2).
func RequestRandomness(cur realm, cid string) int64 {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	h := height()
	assertRevealOpen(c, h)
	if !usesProvider(c) {
		panic("this collection does not use a randomness provider")
	}
	p := c.prov
	if p.round != 0 {
		panic("randomness already requested for round " + itoa(p.round))
	}
	dl := revealDeadline(c)
	if !p.creatorRevealed && h < dl-BeaconGraceBlocks {
		panic("randomness is requested after the creator reveals, or in the window's last " +
			itoa(BeaconGraceBlocks) + " blocks")
	}
	if h > dl-RequestMargin {
		panic("too late to request randomness (last height " + itoa(dl-RequestMargin) + "); call Finalize after the deadline")
	}
	round := mustProvider(c.beaconSource).impl.Target()
	if round <= 0 {
		panic("randomness provider returned an invalid round")
	}
	p.round = round
	chain.Emit("RandomnessRequested", "cid", cid, "provider", c.beaconSource, "round", itoa(round))
	return round
}

// FulfillRandomness takes the requested round's value from the provider as
// the beacon secret and finalizes (2/2 after the creator, beacon-only when
// it stayed silent). Permissionless and never paused (I-2).
func FulfillRandomness(cur realm, cid string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	h := height()
	assertRevealOpen(c, h)
	if !usesProvider(c) {
		panic("this collection does not use a randomness provider")
	}
	p := c.prov
	if p.round == 0 {
		panic("randomness was not requested yet")
	}
	v := mustProvider(c.beaconSource).impl.Randomness(p.round)
	if v == "" {
		panic("round " + itoa(p.round) + " is not available from the provider yet")
	}
	v = safe.AssertHex("randomness", v, 32)
	p.beaconSecret = v
	p.beaconRevealed = true
	chain.Emit("BeaconRevealed", "cid", cid, "provider", c.beaconSource, "round", itoa(p.round), "secret", v)
	finalize(c, h)
}

// RandomnessProviders lists registered providers (by path) as JSON:
// [{id, name, active, registeredHeight}]. Registration is open, so only
// "active" ones (admin-approved) can be chosen at Launch.
func RandomnessProviders(offset, limit int64) string {
	w := &safe.JSONWriter{}
	w.BeginArray()
	providers.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
		r := v.(*providerRecord)
		w.BeginObject()
		w.StrField("id", r.id)
		w.StrField("name", r.name)
		w.BoolField("active", r.active)
		w.IntField("registeredHeight", r.registeredHeight)
		w.EndObject()
		return false
	})
	w.EndArray()
	return w.String()
}

reads.gno

package core

import (
	"chain"
	"strings"

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

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/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 addr's lifetime count of sale mints in cid (OA B3, I-9),
// reserves excluded. Exact until the collection is Final, -1 afterwards
// (derived from the locked grc721 balance; see mintedBy).
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 }

// PrimaryFeeBps is the protocol fee on cid's primary sale: the fee at
// Launch, or the current one if the admin lowered it since (SA-I5: a fee
// cannot rise during a sale).
func PrimaryFeeBps(cid string) int64 {
	c := mustCollection(cid)
	if c.prov != nil && c.primaryBps < fees.PrimaryBps {
		return c.primaryBps
	}
	return fees.PrimaryBps
}

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.IntField("engineCapBps", fees.EngineCapBps)
	w.IntField("engineFeeCapBps", EngineFeeCapBps)
	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())
	author, bps := collectionEngineFee(c)
	w.StrField("engineAuthor", author.String())
	w.IntField("engineFeeBps", bps)
	if c.prov != nil {
		w.IntField("revealDeadline", revealDeadline(c))
		w.BoolField("useBeacon", c.useBeacon)
		w.StrField("beaconSource", c.beaconSource)
		w.StrField("badge", c.prov.badge)
		w.BoolField("fair", FairLaunch(c.id))
	}
	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/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/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)
	return distribute(cur, mustCollection(cid))
}

func distribute(cur realm, c *collection) int64 {
	cid := c.id
	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/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
)

// 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.
//
// Per-token state is packed (storage-cost-analysis P1+P3): one fixed-width
// entry of packEntry bytes per token, packSlots tokens per avl key. Entry =
// four big-endian uint32 fields: mint height, transfer count (H-2), height
// of the last transfer, and the token's approval nonce (SA-L3). A mint
// appends entries in tid order (a new key every packSlots tokens, ~2 KB the
// minter of that bucket's first token pays); a transfer or an Approve only
// rewrites bytes in place, so neither creates a storage object.
type tokenState struct {
	final bool
	pack  avl.Tree // safe.PadInt((tid-1)/packSlots, packKeyWidth) -> string of packed entries
}

const (
	packSlots    = 128
	packFields   = 4
	packEntry    = packFields * 4
	packKeyWidth = 3 // MaxSupplyCap/packSlots < 1000

	fieldMintHeight = 0
	fieldMoves      = 1
	fieldLastMove   = 2
	fieldNonce      = 3
)

func packKey(tid int64) string { return safe.PadInt((tid-1)/packSlots, packKeyWidth) }

// u32 encodes v as 4 big-endian bytes. Heights stay below 2^32 for ~470
// years of 3.5 s blocks; 2^32 transfers or approvals of one token cannot
// happen, so overflow is a hard error rather than a wrap.
func u32(v int64) string {
	if v < 0 || v > 0xFFFFFFFF {
		panic("token state: value out of uint32 range")
	}
	return string([]byte{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)})
}

// appendTokens adds zeroed entries (mint height h) for first..last, which
// must directly follow the last stored token.
func (st *tokenState) appendTokens(first, last, h int64) {
	entry := u32(h) + u32(0) + u32(0) + u32(0)
	for tid := first; tid <= last; {
		k := packKey(tid)
		v, _ := st.pack.Get(k).(string)
		if int64(len(v)) != ((tid-1)%packSlots)*packEntry {
			panic("token state: tokens must be appended in order")
		}
		for ; tid <= last && packKey(tid) == k; tid++ {
			v += entry
		}
		st.pack.Set(k, v)
	}
}

// field reads one field of token tid; 0 for a token that was never minted.
func (st *tokenState) field(tid int64, f int) int64 {
	if tid <= 0 {
		return 0
	}
	v, _ := st.pack.Get(packKey(tid)).(string)
	off := int((tid-1)%packSlots)*packEntry + f*4
	if off+4 > len(v) {
		return 0
	}
	return int64(v[off])<<24 | int64(v[off+1])<<16 | int64(v[off+2])<<8 | int64(v[off+3])
}

// setFields rewrites one or two fields of token tid in place (one avl
// update; f2 < 0 means none).
func (st *tokenState) setFields(tid int64, f1 int, v1 int64, f2 int, v2 int64) {
	k := packKey(tid)
	v, _ := st.pack.Get(k).(string)
	base := int((tid-1)%packSlots) * packEntry
	if tid <= 0 || base+packEntry > len(v) {
		panic("token state: unknown token")
	}
	o1 := base + f1*4
	v = v[:o1] + u32(v1) + v[o1+4:]
	if f2 >= 0 {
		o2 := base + f2*4
		v = v[:o2] + u32(v2) + v[o2+4:]
	}
	st.pack.Set(k, v)
}

func (st *tokenState) mintHeight(tid int64) int64 { return st.field(tid, fieldMintHeight) }

func (st *tokenState) moveOf(tid string) (moves, lastMove int64) {
	n := tidNum(tid)
	return st.field(n, fieldMoves), st.field(n, fieldLastMove)
}

// tidNum is the numeric token id, or 0 for anything that is not a
// canonical positive decimal (no such token exists).
func tidNum(tid string) int64 {
	if len(tid) == 0 || len(tid) > 12 || tid[0] == '0' {
		return 0
	}
	var n int64
	for i := 0; i < len(tid); i++ {
		c := tid[i]
		if c < '0' || c > '9' {
			return 0
		}
		n = n*10 + int64(c-'0')
	}
	return n
}

// 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()
	n := tidNum(key)
	e.st.setFields(n, fieldMoves, e.st.field(n, fieldMoves)+1, fieldLastMove, 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)")
	}
	// the packed entry stays: a burned id is never minted again (I-5)
}

// --- 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).

// Every Approve of a token and every SetApprovalForAll of an (owner,
// operator) pair bumps a nonce. A market pins the nonces at listing time,
// so revoking an approval kills a listing for good: approving again later
// starts a new nonce and never revives the old listing (SA-L3).
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)
	}
	n := tidNum(tid)
	c.st.setFields(n, fieldNonce, c.st.field(n, fieldNonce)+1, -1, 0)
}

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

// ApprovalNonces returns the token's approval nonce and the (owner,
// operator) approval-for-all nonce. Approvals made directly through
// Token(cid).RealmTeller by a realm acting for itself do not bump them.
func ApprovalNonces(cid, tid string, owner, operator address) (tokenNonce, operatorNonce int64) {
	c := mustCollection(cid)
	return c.st.field(tidNum(tid), fieldNonce), nonceOf(c, "o:"+owner.String()+":"+operator.String())
}

func bumpNonce(c *collection, key string) {
	c.approvals.Set(key, nonceOf(c, key)+1)
}

func nonceOf(c *collection, key string) int64 {
	if v := c.approvals.Get(key); v != nil {
		return v.(int64)
	}
	return 0
}

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))
}