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

access.gno

package core

import (
	"chain"

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

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
)

// Engine access policy (I-19, docs/mainnet/engine-access-policy.md).
//
// An engine's author decides who may open collections with it:
//
//   - closed   ("signature engine") only the author. Every registration
//     starts closed: nothing an author did not choose to share is usable
//     by others, and a squat copy stays useless to everyone else.
//   - licensed only the author and the creators the author licensed
//     (GrantLicence), each for a bounded number of collections and,
//     optionally, at a licence fee instead of the manifest's.
//   - open     ("tool engine") anyone.
//
// The policy is judged once, in CreateCollection, and never again: a
// policy change, a revoked or used-up licence leaves every collection
// already created (Drafts included) as it is. Only the claimed manifest
// author changes a policy or a licence; no admin op touches them (the
// admin's engine.deprecate still stops new collections for everyone).
//
// For every policy, a collection whose engine and params are byte-identical
// to an earlier collection's is refused unless its creator is that earlier
// collection's current creator (paramsTaken). Empty params (the engine's
// defaults) are exempt: an engine without params (genesis) would otherwise
// back one collection ever.

// Policies.
const (
	PolicyClosed   = "closed"
	PolicyLicensed = "licensed"
	PolicyOpen     = "open"
)

// How a collection's creator was allowed to use the engine (collection
// JSON "access", CollectionCreated.access).
const (
	AccessAuthor  = "author"
	AccessLicence = "licence"
	AccessOpen    = "open"
)

const (
	MaxLicencesPerEngine  = 1000 // live licences of one engine (GrantLicence of a new holder)
	MaxLicenceCollections = 1000 // collections one licence allows
	LicenceFeeDefault     = -1   // GrantLicence feeBps: the manifest's FeeBps applies
)

type licence struct {
	maxCollections int64
	used           int64 // collections created under this licence
	feeBps         int64 // LicenceFeeDefault or 0..EngineFeeCapBps, snapshotted into each collection
	grantedHeight  int64 // last GrantLicence of this holder
}

var (
	licences    avl.Tree // engine id + ":" + holder -> *licence
	paramsTaken avl.Tree // paramsKey(engine id, params) -> cid of the first collection with them
)

// SetEnginePolicy sets who may create collections with engine id: "closed",
// "licensed" or "open". The claimed manifest author only; refused for a
// deprecated or superseded engine (it backs no new collection anyway).
func SetEnginePolicy(cur realm, id, policy string) {
	assertNoDeposit(cur)
	rec := mustEngine(id)
	assertEngineAuthor(cur, rec, "set its policy")
	assertEngineNotRetired(rec)
	if policy != PolicyClosed && policy != PolicyLicensed && policy != PolicyOpen {
		panic("policy must be \"" + PolicyClosed + "\", \"" + PolicyLicensed + "\" or \"" + PolicyOpen + "\"")
	}
	rec.policy = policy
	chain.Emit("EnginePolicySet", "id", id, "policy", policy)
}

// GrantLicence lets holder create up to maxCollections (1..
// MaxLicenceCollections) collections with engine id while its policy is
// "licensed". feeBps is LicenceFeeDefault (-1, the manifest fee) or
// 0..EngineFeeCapBps: the engine-author fee of the holder's collections,
// snapshotted at their creation (a sale still pays at most the platform
// cap). Granting again to a holder updates maxCollections (not below the
// used count) and feeBps and keeps the used count. Claimed author only;
// not on a deprecated or superseded engine. A grant does not change the
// policy.
func GrantLicence(cur realm, id string, holder address, maxCollections, feeBps int64) {
	assertNoDeposit(cur)
	rec := mustEngine(id)
	assertEngineAuthor(cur, rec, "grant a licence")
	assertEngineNotRetired(rec)
	if !holder.IsValid() {
		panic("invalid licence holder address")
	}
	if holder == rec.manifest.Author {
		panic("the engine's author needs no licence")
	}
	if maxCollections < 1 || maxCollections > MaxLicenceCollections {
		panic("maxCollections must be 1.." + itoa(MaxLicenceCollections))
	}
	if feeBps != LicenceFeeDefault && (feeBps < 0 || feeBps > EngineFeeCapBps) {
		panic("licence feeBps must be -1 (the manifest fee) or 0.." + itoa(EngineFeeCapBps))
	}
	key := licenceKey(id, holder)
	l, _ := licences.Get(key).(*licence)
	if l == nil {
		if rec.licences >= MaxLicencesPerEngine {
			panic("engine has " + itoa(MaxLicencesPerEngine) + " licences; revoke one first")
		}
		l = &licence{}
		licences.Set(key, l)
		rec.licences++
	} else if maxCollections < l.used {
		panic("maxCollections must be at least the " + itoa(l.used) +
			" collections already created under this licence (revoke it to stop it)")
	}
	l.maxCollections, l.feeBps, l.grantedHeight = maxCollections, feeBps, height()
	chain.Emit("LicenceGranted", "id", id, "holder", holder.String(),
		"maxCollections", itoa(maxCollections), "feeBps", itoa(feeBps))
}

// RevokeLicence removes holder's licence on engine id. Collections already
// created under it are not affected. Claimed author only (also on a
// deprecated or superseded engine).
func RevokeLicence(cur realm, id string, holder address) {
	assertNoDeposit(cur)
	rec := mustEngine(id)
	assertEngineAuthor(cur, rec, "revoke a licence")
	key := licenceKey(id, holder)
	v := licences.Get(key)
	if v == nil {
		panic(holder.String() + " holds no licence on " + id)
	}
	licences.Remove(key)
	rec.licences--
	chain.Emit("LicenceRevoked", "id", id, "holder", holder.String(), "used", itoa(v.(*licence).used))
}

func assertEngineAuthor(cur realm, rec *engineRecord, what string) {
	if caller(cur) != rec.manifest.Author {
		panic("only the engine's author " + rec.manifest.Author.String() + " can " + what)
	}
	if !rec.claimed {
		panic("engine is not claimed by its author yet")
	}
}

func assertEngineNotRetired(rec *engineRecord) {
	if rec.deprecated {
		panic("engine is deprecated")
	}
	if rec.superseded {
		panic("engine is superseded by " + rec.supersededBy)
	}
}

func licenceKey(id string, holder address) string { return id + ":" + holder.String() }

// paramsKey identifies an (engine, params) pair in bounded space.
func paramsKey(id, params string) string {
	return safe.Sha256Hex(safe.Domain + "|params|v1|" + id + "|" + params)
}

// createGrant is what CreateCollection learned from the access gate.
type createGrant struct {
	access string
	lic    *licence // the licence used (AccessLicence), else nil
	fee    int64    // engine fee override snapshotted into the collection, or LicenceFeeDefault
	key    string   // paramsKey, "" for empty params
	reuse  bool     // key already held by this creator
}

// createAccess is the engine side of CreateCollection's gate: engine
// usable (claimed, live), creator allowed by the policy, params not held
// by another creator. It returns the refusal text ("" = allowed) and
// writes nothing; CreateCollection panics with that text and CreateRefusal
// returns it.
func createAccess(rec *engineRecord, creator address, params string) (createGrant, string) {
	g := createGrant{fee: LicenceFeeDefault}
	switch {
	case !rec.claimed:
		return g, "engine is not claimed by its author yet"
	case rec.deprecated:
		return g, "engine is deprecated"
	case rec.superseded:
		return g, "engine is superseded by " + rec.supersededBy
	}
	switch {
	case creator == rec.manifest.Author:
		g.access = AccessAuthor
	case rec.policy == PolicyOpen:
		g.access = AccessOpen
	case rec.policy == PolicyLicensed:
		l, _ := licences.Get(licenceKey(rec.id, creator)).(*licence)
		if l == nil {
			return g, "engine " + rec.id + " is licensed: " + creator.String() +
				" holds no licence from its author " + rec.manifest.Author.String()
		}
		if l.used >= l.maxCollections {
			return g, "the licence of " + creator.String() + " on " + rec.id + " is used up (" +
				itoa(l.used) + "/" + itoa(l.maxCollections) + " collections)"
		}
		g.access, g.lic, g.fee = AccessLicence, l, l.feeBps
	default:
		return g, "engine " + rec.id + " is closed: only its author " + rec.manifest.Author.String() +
			" creates collections with it"
	}
	if params == "" {
		return g, ""
	}
	g.key = paramsKey(rec.id, params)
	if v := paramsTaken.Get(g.key); v != nil {
		first := mustCollection(v.(string))
		if first.creator != creator {
			return g, "engine " + rec.id + " with these params already backs collection " + first.id +
				" of another creator; choose other params"
		}
		g.reuse = true
	}
	return g, ""
}

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

// EnginePolicy is engine id's policy: "closed", "licensed" or "open".
func EnginePolicy(id string) string { return mustEngine(id).policy }

// Licensed reports whether holder holds a licence on engine id with room
// for another collection (whatever the current policy).
func Licensed(id string, holder address) bool {
	mustEngine(id)
	l, _ := licences.Get(licenceKey(id, holder)).(*licence)
	return l != nil && l.used < l.maxCollections
}

// Licence is holder's licence on engine id as JSON
// {engine, holder, maxCollections, used, feeBps, grantedHeight}, or null.
func Licence(id string, holder address) string {
	mustEngine(id)
	v := licences.Get(licenceKey(id, holder))
	if v == nil {
		return "null"
	}
	w := &safe.JSONWriter{}
	writeLicence(w, id, holder.String(), v.(*licence))
	return w.String()
}

// Licences pages engine id's licences in holder-address order.
func Licences(id string, offset, limit int64) string {
	mustEngine(id)
	w := &safe.JSONWriter{}
	w.BeginArray()
	prefix := id + ":"
	skipped, written, want := int64(0), int64(0), clampLimit(limit)
	licences.Iterate(prefix, prefix+"\xff", func(k string, v any) bool {
		if skipped < offset {
			skipped++
			return false
		}
		writeLicence(w, id, k[len(prefix):], v.(*licence))
		written++
		return written >= want
	})
	w.EndArray()
	return w.String()
}

func writeLicence(w *safe.JSONWriter, id, holder string, l *licence) {
	w.BeginObject()
	w.StrField("engine", id)
	w.StrField("holder", holder)
	w.IntField("maxCollections", l.maxCollections)
	w.IntField("used", l.used)
	w.IntField("feeBps", l.feeBps)
	w.IntField("grantedHeight", l.grantedHeight)
	w.EndObject()
}

// ParamsTaken is the cid of the first collection created with engine id and
// exactly these params, or "" (always "" for empty params).
func ParamsTaken(id, params string) string {
	if params == "" {
		return ""
	}
	if v := paramsTaken.Get(paramsKey(id, params)); v != nil {
		return v.(string)
	}
	return ""
}

// CreateRefusal is why CreateCollection would refuse creator on engine id
// with params now, as core's own text, or "" when the engine gates pass:
// unknown engine, create paused, unclaimed/deprecated/superseded, the
// policy, a used-up licence, params of another creator. The engine's own
// ValidateParams and the spec's other fields are not judged here.
func CreateRefusal(id string, creator address, params string) string {
	v := engines.Get(id)
	if v == nil {
		return "unknown engine " + id
	}
	if Paused("create") {
		return "paused: create"
	}
	_, why := createAccess(v.(*engineRecord), creator, params)
	return why
}

admin.gno

package core

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

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

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
)

// 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.
//
// The initial admin and treasury come from config.gno (per chain; the
// admin is the bootstrap deployer and is handed to the 2/3 multisig with
// admin.transfer before minter.add, plan §5.7).
// SA-I6: CreateFee starts at 0 here so tests and bootstrap stay simple;
// the bootstrap sets fee.create (1 GNOT, decision §6-5).
var (
	admin        = initialAdmin
	pendingAdmin address
	fees         = types.Fees{
		PrimaryBps: 250, SecondaryBps: 250, EngineCapBps: EngineFeeCapBps,
		Treasury: initialTreasury,
	}
	beacon address
	// listingDeposit is the deposit return market/v1 pins into each new
	// listing at List and charges the buyer for the seller (CV-L2): the
	// listing's storage (4,077 B, measured) x the chain's storage price
	// (100 ugnot/B on Onyx and gnoland-1). Re-set with listing.deposit
	// (timelocked, <= ListingDepositCap) if the vm storage_price changes.
	listingDeposit int64    = 407_700
	minters        avl.Tree // minter pkgpath -> *minterRecord
	ops            avl.Tree // safe.PadInt(op id) -> *pendingOp
	opCount        int64
	pauses         avl.Tree // scope -> *pauseRecord

	// deniedPayees is every address refused as a payee or treasury beyond
	// core's own (SA-L5, M-17): the static platform realms (config.gno),
	// every minter ever approved, and payee.deny entries. It only grows
	// (I-18).
	deniedPayees avl.Tree // address -> *deniedPayee
	deniedOrder  avl.Tree // safe.PadInt(seq) -> address (DeniedPayees pages)
	deniedCount  int64
	deniedByOps  int64
)

type deniedPayee struct {
	path, source string // source: "static", "minter" or "op"
}

// 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
	OpListingDeposit  = "listing.deposit"      // ugnot, <= ListingDepositCap: market deposit return for new listings
	OpEngineDeprecate = "engine.deprecate"     // engine id: no new collections (proven re-wrap or squat, ENG-M1)
	OpPayeeDeny       = "payee.deny"           // realm pkgpath: refused as payee/treasury from now on (I-18: no op removes)
)

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 OpListingDeposit:
		if parseAmount(arg) > ListingDepositCap {
			panic("listing deposit above cap " + itoa(ListingDepositCap))
		}
	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 OpEngineDeprecate:
		if mustEngine(arg).deprecated {
			panic("engine is already deprecated")
		}
	case OpPayeeDeny:
		safe.AssertText("payee realm", arg, 256)
		if !strings.HasPrefix(arg, runtime.ChainDomain()+"/r/") || strings.Contains(arg, "#") {
			panic("payee.deny takes a realm path")
		}
		if deniedPayees.Has(chain.PackageAddress(arg).String()) {
			panic("realm is already denied as a payee")
		}
		if deniedByOps >= MaxDeniedPayees {
			panic("payee deny list is full (" + itoa(MaxDeniedPayees) + " entries)")
		}
	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 OpListingDeposit:
		listingDeposit = parseAmount(arg)
	case OpTreasury:
		fees.Treasury = address(arg)
	case OpBeacon:
		beacon = address(arg)
	case OpMinterAdd:
		minters.Set(arg, &minterRecord{})
		denyPayee(arg, "minter")
	case OpMinterDeprecate:
		minters.Get(arg).(*minterRecord).deprecated = true
	case OpEngineReview:
		mustEngine(arg).reviewed = true
	case OpEngineDeprecate:
		rec := mustEngine(arg)
		rec.deprecated, rec.deprecatedBy = true, "admin"
		chain.Emit("EngineDeprecated", "id", arg, "by", "admin")
	case OpPayeeDeny:
		denyPayee(arg, "op")
		deniedByOps++
		chain.Emit("PayeeDenied", "path", arg, "address", chain.PackageAddress(arg).String())
	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
}

// --- payee deny set (SA-L5, M-17, I-18) -----------------------------------------

// initDeniedPayees adds the static platform realms next to core.
func initDeniedPayees() {
	base := strings.TrimSuffix(selfPath, "/core")
	for _, sib := range staticDeniedRealms {
		denyPayee(base+"/"+sib, "static")
	}
}

// denyPayee adds path's package address to the deny set (idempotent).
func denyPayee(path, source string) {
	key := chain.PackageAddress(path).String()
	if deniedPayees.Has(key) {
		return
	}
	deniedPayees.Set(key, &deniedPayee{path: path, source: source})
	deniedCount++
	deniedOrder.Set(safe.PadInt(deniedCount, cidWidth), key)
}

// IsDeniedPayee reports whether addr is in the payee deny set (static
// platform realms, approved minters, payee.deny). Core's own addresses and
// a collection's sub-addresses and engine adapter are refused as well
// (assertSpendable) but are not listed here.
func IsDeniedPayee(addr address) bool { return deniedPayees.Has(addr.String()) }

// DeniedPayees pages the deny set as JSON: [{path, address, source}].
func DeniedPayees(offset, limit int64) string {
	w := &safe.JSONWriter{}
	w.BeginArray()
	deniedOrder.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
		key := v.(string)
		d := deniedPayees.Get(key).(*deniedPayee)
		w.BeginObject()
		w.StrField("path", d.path)
		w.StrField("address", key)
		w.StrField("source", d.source)
		w.EndObject()
		return false
	})
	w.EndArray()
	return w.String()
}

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/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
)

// --- 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)
	if spec.Soulbound && spec.RoyaltyBps != 0 {
		panic("a non-transferable collection has no secondary sales; royaltyBps must be 0")
	}
	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)
	// I-19: claimed and live engine, creator allowed by its policy, params
	// not another creator's; judged before any engine code runs.
	g, why := createAccess(rec, creator, spec.Params)
	if why != "" {
		panic(why)
	}
	// I-16: 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())
	}
	tts := collectionTraitTypes(rec, spec.Params)
	// The engine's optional create gate gets the creator explicitly (no
	// OriginCaller read in the engine; a realm creator works too, K-2).
	if g, ok := rec.impl.(engine.CreateGate); ok {
		err := g.GateCreate(engine.Collection{ID: next, Creator: creator, Params: spec.Params,
			MaxSupply: spec.MaxSupply, Soulbound: spec.Soulbound})
		if err != nil {
			panic("create refused 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{soulbound: spec.Soulbound}
	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,
		traitTypes:    tts,
		soulbound:     spec.Soulbound,
		maxSupply:     spec.MaxSupply,
		nextTID:       1,
		royaltyBps:    spec.RoyaltyBps,
		primaryPayees: primary,
		royaltyPayees: royal,
		minter:        minter,
		state:         types.StateDraft,
		createdHeight: height(),
		access:        g.access,
		licenceFee:    g.fee,
		token:         tok,
		ledger:        led,
		roy:           roy,
		st:            st,
	}
	collections.Set(collKey(cid), c)
	byCreator.Set(creator.String()+":"+collKey(cid), cid)
	byEngine.Set(spec.EngineID+":"+collKey(cid), cid)
	rec.collections++
	if g.key != "" && !g.reuse {
		paramsTaken.Set(g.key, cid)
	}
	if g.lic != nil {
		g.lic.used++
	}

	chain.Emit("CollectionCreated",
		"cid", cid, "creator", creator.String(), "minter", minter,
		"engine", spec.EngineID, "token", tok.ID(), "access", g.access, "soulbound", boolStr(spec.Soulbound))
	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.Mode == types.ModeOpen {
		launchOpen(c, l)
		return
	}
	if l.Mode != types.ModeReveal {
		panic("mode must be \"\" (commit-reveal) or \"" + types.ModeOpen + "\"")
	}
	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")
		}
	}

	checkLaunch(c, types.ModeReveal)

	c.prov = &provenance{creatorCommit: commit, acc: safe.InitialEntropy(runtime.ChainID(), c.id)}
	c.startHeight, c.endHeight, c.revealWindow = l.StartHeight, l.EndHeight, l.RevealWindow
	c.useBeacon = l.UseBeacon
	c.beaconSource = source
	c.mode = types.ModeReveal
	schedule(c)
}

// launchOpen is Launch in open mode (I-17): no commitment, no beacon or
// provider, no reveal window. The salt is public (openSalt) and anyone may
// finalize once the sale is Closed.
func launchOpen(c *collection, l types.LaunchSpec) {
	if l.CreatorCommit != "" || l.UseBeacon || l.BeaconSource != "" {
		panic("an open launch has no creatorCommit, useBeacon or beaconSource")
	}
	if l.RevealWindow != 0 {
		panic("an open launch has revealWindow 0")
	}
	checkLaunch(c, types.ModeOpen)
	c.prov = &provenance{acc: safe.InitialEntropy(runtime.ChainID(), c.id)}
	c.startHeight, c.endHeight, c.revealWindow = l.StartHeight, l.EndHeight, 0
	c.useBeacon, c.beaconSource = false, ""
	c.mode = types.ModeOpen
	schedule(c)
}

// checkLaunch refuses an engine that was deprecated or superseded after the
// Draft was made (WP-J J-1: I-14's "no new sales" covers Launch and every
// relaunch after AbortLaunch, not only CreateCollection; a collection that
// is already Scheduled or later is not touched), then runs the engine's
// launch gate (I-16: the creator's own tx; everything the engine needs is
// passed in). An engine that implements engine.LaunchGate is then asked
// again with the launch mode (e.g. an engine that only works in reveal
// mode refuses an open launch).
func checkLaunch(c *collection, mode string) {
	rec := mustEngine(c.engineID)
	assertEngineUsable(rec)
	if err := rec.impl.CheckLaunch(c.id, c.params, c.maxSupply); err != nil {
		panic("launch refused by engine: " + err.Error())
	}
	if g, ok := rec.impl.(engine.LaunchGate); ok {
		err := g.GateLaunch(engine.Collection{ID: c.id, Creator: c.creator, Params: c.params,
			MaxSupply: c.maxSupply, Mode: mode, Soulbound: c.soulbound})
		if err != nil {
			panic("launch refused by engine: " + err.Error())
		}
	}
}

// assertEngineUsable is the engine gate of Launch: claimed, not deprecated,
// not superseded (CreateCollection's createAccess starts with the same
// checks and texts). The access policy is not judged again (I-19).
func assertEngineUsable(rec *engineRecord) {
	if !rec.claimed {
		panic("engine is not claimed by its author yet")
	}
	assertEngineNotRetired(rec)
}

// schedule snapshots the fees and moves c to Scheduled (both modes).
func schedule(c *collection) {
	c.primaryBps = fees.PrimaryBps
	c.engineAuthor, c.engineBps = engineFeeQuote(c)
	c.state = types.StateScheduled
	commit := ""
	if c.prov != nil {
		commit = c.prov.creatorCommit
	}
	chain.Emit("CollectionScheduled",
		"cid", c.id, "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),
		"mode", modeName(c.mode))
}

// modeName is the mode as shown in events and JSON ("reveal" or "open").
func modeName(m string) string {
	if m == types.ModeOpen {
		return types.ModeOpen
	}
	return "reveal"
}

// collectionTraitTypes asks the engine for the collection's trait list
// (I-16) and returns a core-owned copy, or nil when it equals the
// manifest's (nothing extra stored).
func collectionTraitTypes(rec *engineRecord, params string) []string {
	tts := rec.impl.TraitTypes(params)
	if err := engine.ValidateTraitTypes(tts); err != nil {
		panic("trait types rejected: " + err.Error())
	}
	if sameList(tts, rec.manifest.TraitTypes) {
		return nil
	}
	return append([]string{}, tts...)
}

func sameList(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}

// traitTypesOf is c's effective trait list (shared; callers copy before
// handing it out).
func traitTypesOf(c *collection) []string {
	if c.traitTypes != nil {
		return c.traitTypes
	}
	return mustEngine(c.engineID).manifest.TraitTypes
}

// 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, c.mode = false, "", types.ModeReveal
	c.engineBps, c.engineAuthor = 0, ""
	c.state = types.StateDraft
	chain.Emit("CollectionState", "cid", c.id, "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")
	}
	if c.mode == types.ModeOpen {
		panic("an open collection has no creator reserve")
	}
	// 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", c.id, "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.st.appendOwners(first, last, to)
	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", c.id, "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(c.id))
	byCreator.Set(who.String()+":"+collKey(c.id), c.id)
	chain.Emit("CreatorTransferred", "cid", c.id, "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, c.id, c.engineID)
	distribute(cur, c)
	c.royaltyPayees = ps
	chain.Emit("RoyaltyPayees", "cid", c.id, "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>), the engine adapter,
// and every address of the deny set: the static platform realms next to
// core, every minter ever approved and every payee.deny realm (I-18). 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))
	}
	for _, b := range bad {
		if addr == b {
			panic(field + ": " + addr.String() + " is a platform realm address that cannot spend; use a wallet")
		}
	}
	if v := deniedPayees.Get(addr.String()); v != nil {
		d := v.(*deniedPayee)
		if d.source == "minter" {
			panic(field + ": " + addr.String() + " is the minter realm " + d.path + "; use a wallet")
		}
		panic(field + ": " + addr.String() + " is the platform realm " + d.path + " that cannot spend; use a wallet")
	}
}

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

config.gno

package core

// Deploy-time configuration (mainnet plan §2.4 M-27, §5.4). Everything that
// differs per chain lives in this file, so staging (WP-H,
// deploy/realms/<chain>.json) rewrites one file and its gate can refuse an
// Onyx address in a mainnet stage. The source carries the Onyx values.

// Roles are separate on purpose (S-8): the admin can only propose
// timelocked parameter changes and never holds funds (I-1); the treasury
// only receives fees; the platform engine author only claims and
// deprecates the platform engines and registers their reserved
// fingerprints. The admin here is the bootstrap admin (= the deployer):
// admin.transfer hands it to the 2/3 multisig before minter.add (§5.7).
var (
	initialAdmin    = address("g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06")
	initialTreasury = address("g1rq2g0fmd0e0v0myz677ju3t68g46kan3r96lls")
	platformAuthor  = address("g1nm8kd8hsmp6pr7mudj2c3y2hnmnl8awx7vcz4m")
)

// reservedFP is a platform engine whose art is public before its adapter
// registers (Onyx p/ packages, the TS twins in the site bundle). Its sample
// fingerprint exists in core from the enable tx, so nobody but its author
// can ever register it (ENG-M1, I-14).
type reservedFP struct {
	name, fingerprint string
	author            address
}

// reservedFingerprints: sha256(Render(engine.SampleInput())) of each
// platform engine, from docs/engines/README.md (2026-11-04; the v2 and new
// engines 2026-11-11, each checked against its art package in
// z_reserved_fp_filetest.gno); the upload
// card's is sha256 of the v2 card (engines/upload render.gno cardSVG =
// upload.CardFingerprint, WP-F 2026-11-10; it holds no path text, so it is
// the same on every chain).
var reservedFingerprints = []reservedFP{
	{"genesis", "a9eb40c4aef4fa3d80adcccc28db007ce93f0728a5b07c3805a42777fef4e8c9", platformAuthor},
	{"kilim", "a50693874cf408b5c24c306785bab1732af0d818952c9f8f892e19cc75bdebff", platformAuthor},
	{"strata", "6b96256a0111a9508048e8226c0ba87435be040aedbfe407485b3391d46b84af", platformAuthor},
	{"rubrica", "5565972025909a38ddc9e3e19dbcd1bbc7c1be3f8fe537ea98921b4f90650d04", platformAuthor},
	{"cantiere", "69902dba328df77cea56dc6635c1489f61bf386f108a6600df0eb8a0e08f8d76", platformAuthor},
	{"giornate", "44ec27ea29c5a7c38ac90e73de6be96ddd8d3a93e6741275719d5d9a68fa0e2e", platformAuthor},
	{"upload", "0e414b46db68c64891aadfb4e1fc18ef63d9711907538b659b61b41c7d34efd1", platformAuthor},
	// v2 engines and the new engines (2026-11-11, docs/engines/integration-2026-11.md)
	{"kilimv2", "13ef738418a6f8e586c48431f2e58d0963f7f6efabc98bc74f5400806e4449d6", platformAuthor},
	{"stratav2", "93c92a8bf12fcdb8ff28c1897c00c6a61806d489cbd48e81aa27ca76076f4f41", platformAuthor},
	{"rubricav2", "94976a6b2ff033d26c685fca5ad8a0feb1023b795a7af7cf84fd6c2d7733959f", platformAuthor},
	{"cantierev2", "4f16ecd23307b6f08a518d36adf908cb7d7999d1cb4d62c5cc68ce9b4d4a2c1c", platformAuthor},
	{"giornatev2", "d4e4e9e530cc25a7ecaba21bc44444cd7958b112d6981a7b094883257321f3b1", platformAuthor},
	{"sima", "bbc39e8daf3e8c4501ebb1130b7990d7151b52d4623e2ca3de9eaf2f6633f7cc", platformAuthor},
	{"cinar", "95d4922c9f9cdb02ab96e88c1628deb179ebb8d327054ab64d12040b38c00e83", platformAuthor},
	{"katman", "f8418846a3c0632a7e89b9728127effb4567ee3523067f265ee50d7c191345ef", platformAuthor},
	{"pafta", "ecba9be924f2f04fa5d4e05f9b87d32fb5547208b05d8ca36c0fa2ece9a0c4d7", platformAuthor},
	{"ebru", "bb69fb3b0400d4e15156f9feeb400ffa882c1143872e4278c7f4fc254699c6d8", platformAuthor},
}

// staticDeniedRealms are the platform realms next to core (paths relative
// to core's parent, README package map) that can never spend an incoming
// payment. They are refused as payees and treasury from deploy on (SA-L5,
// M-17); the admin adds others with payee.deny (I-18: additions only).
var staticDeniedRealms = []string{
	"mint/v1", "market/v1", "reader", "gallery",
	"engines/genesis", "engines/kilim", "engines/strata", "engines/rubrica", "engines/cantiere",
	"engines/giornate", "engines/upload",
	"assets/v1", "randomness/drand", "offers/v1", "mint/v2", "market/v2",
	"engines/kilimv2", "engines/stratav2", "engines/rubricav2", "engines/cantierev2", "engines/giornatev2",
	"engines/sima", "engines/cinar", "engines/katman", "engines/pafta", "engines/ebru",
}

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. With a randomness provider
//     Finalize may wait for the bound round, at most ProviderWaitBlocks
//     after the deadline or the binding (a Finalize after the deadline
//     binds), so anyone can end the lock by revealDeadline + 1 +
//     ProviderWaitBlocks + 1.
//   - I-12/I-16 engine code runs on a state-changing path only in the
//     engine user's own transaction: RegisterEngine (manifest, default
//     params, one sample render and its traits), CreateCollection
//     (ValidateParams, TraitTypes) and Launch (CheckLaunch). It never gets
//     core's cur. 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 RevealCreatorSecret,
//     RequestRandomness, FulfillRandomness and Finalize of collections
//     launched with it.
//   - I-13 every stored string passed safe.AssertText.
//   - I-14 a fingerprint reserved in source (config.gno) can only be
//     registered by its author; a commit-reveal reservation wins over any
//     later registration of the same art by another author; an unclaimed
//     record of another author blocks for at most UnclaimedHoldBlocks
//     (engines.gno).
//   - I-15 TokenURI is only ever core's placeholder, an allowlisted SVG, a
//     header-checked raster data URI of an allowlisted type, or an ipfs://
//     CIDv1 URI (tokens.gno, engine.CheckMedia).
//   - I-17 an open collection (LaunchSpec.Mode "open") never has a
//     reserve, a commitment or a beacon and is never a fair launch.
//   - I-18 the payee deny set only grows (admin.gno, payee.deny).
//   - I-20 a token of a non-transferable (soulbound) collection never
//     changes owner: core refuses every transfer of it (the lockExt hook,
//     so also through a RealmTeller) and every approval through core, the
//     market never lists it, and the flag is fixed at creation; its owner
//     may burn it once the collection is Final. Every token's first owner
//     (the address it was minted to) is recorded once and never changes
//     (tokens.gno, FirstOwner).
//   - I-19 a collection is created on an engine only by the engine's
//     manifest author, by anyone while the policy is open, or by a holder
//     of a licence with room while it is licensed — judged at creation
//     only, so a later policy or licence change never touches an existing
//     collection; a licence's used count never exceeds its maximum; a
//     non-empty (engine, params) pair is refused to anyone but the current
//     creator of the first collection with it; no admin op changes a
//     policy or a licence (access.gno).
//
// 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/sinopia4/engine/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
)

// 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)
	ProviderWaitBlocks = 24_400           // ~24 h: Finalize waits this long after the deadline (or the round's binding) for a provider's round before falling back (CV-M1)
	ListingDepositCap  = 5_000_000        // 5 GNOT: hard cap of the market's listing deposit return (op listing.deposit, CV-L2)

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

	// Engine registry (ENG-M1, I-14).
	ReservationTTLBlocks = 170_000 // ~7 days: a fingerprint reservation is usable this long
	UnclaimedHoldBlocks  = 24_400  // ~1 day: an unclaimed record stops blocking the same art after this
	MinReserveSaltLen    = 32
	MaxReserveSaltLen    = 256

	// MaxDeniedPayees bounds the payee.deny entries (each payee check
	// looks the address up once; the bound only caps admin-made growth).
	MaxDeniedPayees = 64
)

// CoreVersion tells indexers and frontends which core they read (M-26).
const CoreVersion = "sinopia-core/4"

// Provenance badges (design §4.3).
const (
	BadgeBoth        = "2/2"
	BadgeCreatorOnly = "creator-only"
	BadgeBeaconOnly  = "beacon-only"
	BadgeFallback    = "fallback"
	BadgeOpen        = "open" // open mode: no secrets, never a fair launch (I-17)
)

type collection struct {
	id, name, symbol, description string
	creator, pendingCreator       address
	engineID, params              string
	traitTypes                    []string // the collection's trait list when it differs from the manifest's (nil = manifest)
	mode                          string   // types.ModeReveal or types.ModeOpen, set at Launch
	soulbound                     bool     // non-transferable, fixed at creation (I-20)
	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
	access                        string   // AccessAuthor, AccessLicence or AccessOpen: how the creator could use the engine (I-19)
	licenceFee                    int64    // engine fee of the licence it was created under, or LicenceFeeDefault (manifest fee)
	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()
	initDeniedPayees()
}

// Version is CoreVersion (M-26).
func Version() string { return CoreVersion }

const cidWidth = 10

// collKey accepts a collection id as "<cid>" or as its token sub-path
// "c/<cid>" (the form a wallet derives from Token.ID(), "…/core#c/<cid>";
// K-1). Every function that takes a cid resolves it through
// mustCollection and then uses c.id only.
func collKey(cid string) string {
	if len(cid) > 2 && cid[0] == 'c' && cid[1] == '/' {
		cid = cid[2:]
	}
	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"
	"chain/runtime/unsafe"
	"strings"

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

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
)

// 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
	deprecatedBy     string // "author" or "admin" (engine.deprecate)
	superseded       bool   // a reserved registration of the same art won (I-14)
	supersededBy     string // engine id
	reviewed         bool
	registeredHeight int64
	reservation      string // reservationSource, reservationCommit or ""
	priority         int64  // 0 (in source), the reservation height, or registeredHeight
	collections      int64  // collections created on this engine (CollectionsByEngine)
	policy           string // PolicyClosed (at registration), PolicyLicensed or PolicyOpen (access.gno, I-19)
	licences         int64  // live licences (<= MaxLicencesPerEngine)
}

// Engine statuses (EngineStatus, engine JSON "status").
const (
	EngineUnclaimed  = "unclaimed"
	EngineUnverified = "unverified"
	EngineReviewed   = "reviewed"
	EngineDeprecated = "deprecated"
	EngineSuperseded = "superseded"
)

const (
	reservationSource = "source" // fingerprint reserved in config.gno
	reservationCommit = "commit" // backed by a ReserveFingerprint commitment
)

var (
	engines       avl.Tree // engine id -> *engineRecord
	engineOrder   avl.Tree // safe.PadInt(seq) -> engine id
	byFingerprint avl.Tree // fingerprint + ":" + engine id -> "" (CV-L3)
	byEngine      avl.Tree // engine id + ":" + padded cid -> cid (CollectionsByEngine, M-18)
	engineCount   int64

	// reservations: author + ":" + commit -> *fpReservation (ENG-M1). Keyed
	// by author so copying a pending commitment from the mempool only
	// creates a useless entry under the copier's own address.
	reservations avl.Tree
)

type fpReservation struct {
	height int64
}

// RegisterEngine stores the calling realm's engine (I-16: the manifest,
// default params and one sample render with its traits, in the engine's
// own registration transaction). The record is immutable afterwards except
// for the claim/deprecate/review/superseded flags, the collection count and
// the access policy (access.gno: every engine starts closed).
//
// salt is "" or the salt of a ReserveFingerprint commitment made by the
// manifest author (ENG-M1 rule 2). Fingerprint rules (I-14), with signer =
// OriginCaller:
//   - every registration must be signed by its manifest author (signer ==
//     Manifest.Author; WP-J J-2: otherwise a tx the author of a live engine
//     signs into a foreign realm could register a re-wrap of that art under
//     another author, since CV-L3 exempts the author's own versions);
//   - a fingerprint reserved in source (config.gno) registers only with
//     signer == Manifest.Author == its reserved author;
//   - a live record of the same art by another author (not deprecated, not
//     superseded) blocks the registration (CV-L3) unless this registration
//     is reserved in source, or backed by a reservation made before that
//     record's own priority (so the record was registered after the
//     reservation's commit; WP-J J-3), or the record is unclaimed and older
//     than UnclaimedHoldBlocks; such records are marked superseded instead.
func RegisterEngine(cur realm, e engine.Engine, salt string) 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())
	}

	fp := safe.Sha256Hex(sample)
	h := height()
	signer := unsafe.OriginCaller()
	kind, priority, resKey := registrationPriority(fp, m.Author, signer, salt, h)
	losers := conflicts(fp, m.Author, kind, priority, h)
	// every check passed: consume the reservation, then write
	if resKey != "" {
		reservations.Remove(resKey)
	}
	rec := &engineRecord{
		id:               id,
		impl:             e,
		manifest:         m,
		fingerprint:      fp,
		registeredHeight: h,
		reservation:      kind,
		priority:         priority,
		policy:           PolicyClosed,
	}
	engines.Set(id, rec)
	byFingerprint.Set(fp+":"+id, "")
	engineCount++
	engineOrder.Set(safe.PadInt(engineCount, cidWidth), id)
	chain.Emit("EngineRegistered", "id", id, "author", m.Author.String(), "feeBps", itoa(m.FeeBps),
		"fingerprint", rec.fingerprint, "kind", m.Kind, "reservation", kind)
	for _, l := range losers {
		l.superseded, l.supersededBy = true, id
		chain.Emit("EngineSuperseded", "id", l.id, "by", id)
	}
	return id
}

// registrationPriority applies the reservation rules and returns the
// registration's kind, priority (lower wins) and the reservation key it
// consumes ("" for none). It writes nothing.
func registrationPriority(fp string, author, signer address, salt string, h int64) (string, int64, string) {
	if reserved, ok := reservedAuthorOf(fp); ok {
		if signer != reserved || author != reserved {
			panic("fingerprint " + fp + " is reserved for " + reserved.String() +
				"; only that author may register it (signed by and named in the manifest)")
		}
		return reservationSource, 0, ""
	}
	if signer != author {
		panic("an engine registration must be signed by the manifest author " + author.String())
	}
	if salt == "" {
		return "", h, ""
	}
	if len(salt) < MinReserveSaltLen || len(salt) > MaxReserveSaltLen {
		panic("reservation salt must be " + itoa(MinReserveSaltLen) + ".." + itoa(MaxReserveSaltLen) + " bytes")
	}
	safe.AssertText("salt", salt, MaxReserveSaltLen)
	commit := ReservationCommit(runtime.ChainID(), fp, author, salt)
	key := author.String() + ":" + commit
	v := reservations.Get(key)
	if v == nil {
		panic("no fingerprint reservation of " + author.String() + " matches this engine and salt")
	}
	r := v.(*fpReservation)
	if h <= r.height {
		panic("the reservation is usable from height " + itoa(r.height+1))
	}
	if h > r.height+ReservationTTLBlocks {
		panic("the reservation expired at height " + itoa(r.height+ReservationTTLBlocks))
	}
	return reservationCommit, r.height, key
}

// conflicts returns the live records of the same art by other authors that
// this registration (by author, who signed it) supersedes, and panics on one
// that blocks it (CV-L3, I-14). A deprecated or superseded record never
// blocks.
//
// A commit reservation (priority = its ReserveFingerprint height) beats only
// a record with a later priority: a plain record registered after the
// commit height, or a record backed by a later reservation. A record
// registered at or before the commit height — claimed or not — is never
// superseded by it (WP-J J-3; rec.priority <= rec.registeredHeight, so a
// later priority implies a later registration). Unclaimed records still
// expire after UnclaimedHoldBlocks for every registration.
func conflicts(fp string, author address, kind string, priority, h int64) []*engineRecord {
	var losers []*engineRecord
	byFingerprint.Iterate(fp+":", fp+";", func(k string, _ any) bool {
		rec := mustEngine(k[len(fp)+1:])
		if rec.deprecated || rec.superseded || rec.manifest.Author == author {
			return false
		}
		switch {
		case kind == reservationSource:
		case !rec.claimed && h > rec.registeredHeight+UnclaimedHoldBlocks:
		case kind == reservationCommit && rec.priority > priority && rec.registeredHeight > priority:
		default:
			panic("engine renders the same art as " + rec.id + "; only its author " + rec.manifest.Author.String() +
				" may register another version (or deprecate it first)")
		}
		losers = append(losers, rec)
		return false
	})
	return losers
}

// reservedAuthorOf is fp's in-source reserved author (config.gno).
func reservedAuthorOf(fp string) (address, bool) {
	for _, r := range reservedFingerprints {
		if r.fingerprint == fp {
			return r.author, true
		}
	}
	return "", false
}

// ReserveFingerprint records a commitment to register an engine whose art
// is not public yet (ENG-M1 rule 2):
//
//	commit = ReservationCommit(chainId, fingerprint, author, salt)
//
// with salt 32..256 bytes. The caller (a wallet) is the author; the
// reservation is usable from the next block for ReservationTTLBlocks by a
// RegisterEngine(…, salt) signed by that author with that Manifest.Author.
// The commitment reveals nothing, so it cannot be front-run.
func ReserveFingerprint(cur realm, commitHex string) {
	assertNoDeposit(cur)
	if !cur.Previous().IsUserCall() {
		panic("reserve a fingerprint from the author's wallet")
	}
	author := caller(cur)
	commit := safe.AssertHex("commit", commitHex, 32)
	key := author.String() + ":" + commit
	h := height()
	if v := reservations.Get(key); v != nil && h <= v.(*fpReservation).height+ReservationTTLBlocks {
		panic("this commitment is already reserved until height " + itoa(v.(*fpReservation).height+ReservationTTLBlocks))
	}
	reservations.Set(key, &fpReservation{height: h})
	chain.Emit("FingerprintReserved", "author", author.String(), "commit", commit,
		"height", itoa(h), "expires", itoa(h+ReservationTTLBlocks))
}

// ReservationCommit is the commitment ReserveFingerprint takes:
// sha256("art|fpres|v1|" + chainID + "|" + fp + "|" + author + "|" + salt).
func ReservationCommit(chainID, fp string, author address, salt string) string {
	return safe.Sha256Hex(safe.Domain + "|fpres|v1|" + chainID + "|" + fp + "|" + author.String() + "|" + salt)
}

// Reservation is the reservation of author for commitHex as JSON
// {author, commit, height, validFrom, expires, active}, or null.
func Reservation(author address, commitHex string) string {
	v := reservations.Get(author.String() + ":" + commitHex)
	if v == nil {
		return "null"
	}
	r := v.(*fpReservation)
	h := height()
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.StrField("author", author.String())
	w.StrField("commit", commitHex)
	w.IntField("height", r.height)
	w.IntField("validFrom", r.height+1)
	w.IntField("expires", r.height+ReservationTTLBlocks)
	w.BoolField("active", h > r.height && h <= r.height+ReservationTTLBlocks)
	w.EndObject()
	return w.String()
}

// ReservedAuthor is fp's in-source reserved author, or "".
func ReservedAuthor(fp string) address {
	a, _ := reservedAuthorOf(fp)
	return a
}

// ReservedFingerprints is the in-source table as JSON [{name, fingerprint, author}].
func ReservedFingerprints() string {
	w := &safe.JSONWriter{}
	w.BeginArray()
	for _, r := range reservedFingerprints {
		w.BeginObject()
		w.StrField("name", r.name)
		w.StrField("fingerprint", r.fingerprint)
		w.StrField("author", r.author.String())
		w.EndObject()
	}
	w.EndArray()
	return w.String()
}

// 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, rec.deprecatedBy = true, "author"
	chain.Emit("EngineDeprecated", "id", id, "by", "author")
}

// --- 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
	}
	if c.licenceFee == LicenceFeeDefault {
		return author, engineFeeOf(rec)
	}
	if c.licenceFee < fees.EngineCapBps {
		return author, c.licenceFee
	}
	return author, fees.EngineCapBps
}

// 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. For a media engine it
// is the card.
func RenderWith(id, params, seed string) string {
	return renderChecked(mustEngine(id), studioInput(params, seed))
}

// RenderWithInput is RenderWith for a full Input, so living engines can be
// verified off chain and against their TS twins (M-24). CollectionID and
// TokenID are "0" and Salt "" as in every studio render; firstOwner is
// passed through as Input.FirstOwner ("" = none).
func RenderWithInput(id, params, seed string, mintHeight, lastMove, moves, h int64, firstOwner address) string {
	in := studioInput(params, seed)
	in.MintHeight, in.LastMoveHeight, in.Moves, in.Height = mintHeight, lastMove, moves, h
	in.FirstOwner = firstOwner
	return renderChecked(mustEngine(id), in)
}

func renderChecked(rec *engineRecord, in engine.Input) string {
	if err := rec.impl.ValidateParams(in.Params); err != nil {
		panic("params rejected by engine: " + err.Error())
	}
	svg := rec.impl.Render(in)
	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,
// checked against TraitTypes(params).
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())
	}
	tts := rec.impl.TraitTypes(params)
	if err := engine.ValidateTraitTypes(tts); err != nil {
		panic("trait types rejected: " + err.Error())
	}
	ts := rec.impl.Traits(studioInput(params, seed))
	if err := engine.ValidateTraitsFor(tts, 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", "deprecated" or
// "superseded".
func EngineStatus(id string) string { return engineStatus(mustEngine(id)) }

func engineStatus(rec *engineRecord) string {
	switch {
	case rec.deprecated:
		return EngineDeprecated
	case rec.superseded:
		return EngineSuperseded
	case !rec.claimed:
		return EngineUnclaimed
	case rec.reviewed:
		return EngineReviewed
	}
	return EngineUnverified
}

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

// EnginesByFingerprint pages every record with fingerprint fp, in path
// order (the deploy check's squat scan).
func EnginesByFingerprint(fp string, offset, limit int64) string {
	w := &safe.JSONWriter{}
	w.BeginArray()
	skipped, written, want := int64(0), int64(0), clampLimit(limit)
	byFingerprint.Iterate(fp+":", fp+";", func(k string, _ any) bool {
		if skipped < offset {
			skipped++
			return false
		}
		writeEngine(w, mustEngine(k[len(fp)+1:]))
		written++
		return written >= want
	})
	w.EndArray()
	return w.String()
}

// CollectionsByEngine pages the collections created on engine id, in
// creation order (M-18). The count is the engine JSON's "collections".
func CollectionsByEngine(id string, offset, limit int64) string {
	mustEngine(id)
	w := &safe.JSONWriter{}
	w.BeginArray()
	prefix := id + ":"
	skipped, written, want := int64(0), int64(0), clampLimit(limit)
	byEngine.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()
}

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")
	writeStrings(w, m.TraitTypes)
	w.BoolField("living", m.Living)
	w.IntField("maxSvgBytes", m.MaxSVGBytes)
	w.StrField("kind", m.Kind)
	w.IntField("maxMediaBytes", m.MaxMediaBytes)
	w.StrField("fingerprint", rec.fingerprint)
	w.StrField("status", engineStatus(rec))
	w.IntField("registeredHeight", rec.registeredHeight)
	w.StrField("reservation", rec.reservation)
	w.IntField("priority", rec.priority)
	w.StrField("supersededBy", rec.supersededBy)
	w.StrField("deprecatedBy", rec.deprecatedBy)
	w.IntField("collections", rec.collections)
	w.StrField("policy", rec.policy)
	w.IntField("licences", rec.licences)
	w.EndObject()
}

func writeStrings(w *safe.JSONWriter, list []string) {
	w.BeginArray()
	for _, t := range list {
		w.Str(t)
	}
	w.EndArray()
}

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/sinopia4/core"
gno = "0.9"

[addpkg]
  creator = "g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06"
  height = 1449962
  max_deposit = "50000000ugnot"

provenance.gno

package core

import (
	"chain"
	"chain/runtime"

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
)

// 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.
//
// The second secret sb comes from the committed beacon (below) or, when the
// collection was launched with a randomness provider, from the provider's
// round bound after the creator's turn (randomness.gno); the order rules and
// badges are the same.
//
// A collection launched without the beacon (only possible while no beacon
// or provider 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 (0 = none bound yet; randomness.gno)
	roundHeight                 int64 // height the round was bound at; its value is taken only later (CV-I6)
}

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", c.id, "commit", commit)
}

func RevealCreatorSecret(cur realm, cid, secret string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	assertCreator(cur, c)
	assertNotOpen(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", c.id, "secret", secret)
	if usesProvider(c) && c.prov.round == 0 {
		// CV-M1: the reveal binds the provider's round in the same tx, so
		// nobody can delay, time or skip the request afterwards. If the
		// provider cannot name a fresh round now, anyone binds one later
		// (RequestRandomness, Finalize); the creator's secret is public then.
		bindRound(c, h)
	}
	if revealsComplete(c) && c.minted() > 0 { // SEC-F1: 0 mints stays Closed (abortable)
		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.minted() == 0 { // SEC-F1 (SA-I9): a 0-mint sale stays abortable
		panic("nothing was minted; the creator may abort and relaunch instead")
	}
	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", c.id, "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).
// For a provider collection it first binds or consumes the provider's round
// (settleProvider) and falls back only when the provider failed to deliver.
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")
	}
	// CV-M1: a provider collection consumes its round whoever calls; the
	// fallback needs the provider to have failed for ProviderWaitBlocks.
	if usesProvider(c) && settleProvider(c, h) {
		return
	}
	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 {
	if c.mode == types.ModeOpen {
		return true // nothing to reveal: Finalize once Closed (I-17)
	}
	return c.prov.creatorRevealed && (!c.useBeacon || c.prov.beaconRevealed)
}

func assertNotOpen(c *collection) {
	if c.mode == types.ModeOpen {
		panic("an open collection has no secrets")
	}
}

// openSalt is an open collection's salt: public from Launch, so anyone can
// compute every token's art before minting (I-17).
func openSalt(cid string) string {
	return safe.Sha256Hex(safe.Domain + "|open|v1|" + runtime.ChainID() + "|" + cid)
}

// 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 c.mode == types.ModeOpen:
		p.salt = openSalt(c.id)
		p.badge = BadgeOpen
	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
	if c.mode == types.ModeOpen {
		return p.salt == openSalt(c.id)
	}
	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 when consumed (FulfillRandomness or
	// Finalize) 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 c.mode == types.ModeOpen || !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.StrField("mode", modeName(c.mode))
		w.BoolField("useBeacon", c.useBeacon)
		w.StrField("beaconSource", c.beaconSource)
		w.IntField("round", p.round)
		w.IntField("roundHeight", p.roundHeight)
		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()
}

// Salt is cid's final salt (hex), "" before Final (M-5: the upload adapter
// and other readers no longer parse Provenance JSON).
func Salt(cid string) string {
	c := mustCollection(cid)
	if c.state != types.StateFinal {
		return ""
	}
	return c.prov.salt
}

randomness.gno

package core

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

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

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
)

// 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 by the creator's
//     reveal (same transaction) or, for a silent creator, in the grace
//     period / at the deadline, and its value is then consumed by whoever
//     calls first (FulfillRandomness or Finalize): no caller can skip it.
//
// Before any provider is approved (randomness.add) a keeper must run that
// requests in the grace period for silent creators and fulfills bound
// rounds as soon as they are published (README "Randomness keeper").
//
// 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;
// CV-M1: the outcome never depends on who calls, or when):
//
//  1. the creator reveals until revealDeadline - BeaconGraceBlocks; the
//     reveal itself binds the collection to provider.Target() in the same
//     transaction, a round nobody knows yet (its secret is public now, so
//     nobody holding a choice learns anything new later);
//  2. a silent creator: RequestRandomness (anyone, a keeper) inside the
//     grace period, or the first Finalize after revealDeadline, binds the
//     round instead — the creator's window is closed by then;
//  3. once the provider has the bound round (and not in the binding
//     block, CV-I6), FulfillRandomness or Finalize (anyone, before or
//     after the deadline) takes its value as the beacon secret and the
//     collection is Final (2/2 after the creator, beacon-only otherwise).
//     After the deadline Finalize refuses to fall back while the bound
//     round may still arrive;
//  4. fallback (creator-only / fallback badge, never a FairLaunch) only
//     once the provider failed to deliver for ProviderWaitBlocks after the
//     deadline or the binding, whichever is later.
//
// A provider that panics aborts the calling transaction (a realm-boundary
// panic cannot be recovered); if an approved provider breaks, the admin
// deprecates it and, after the wait, Finalize stops calling it.
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 whose creator stayed
// silent to the provider's next unknowable round (a creator's reveal binds
// it itself). Permissionless and never paused (I-2); after the deadline the
// first Finalize binds instead.
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")
	}
	if c.minted() == 0 { // SEC-F1 (SA-I9): a 0-mint sale stays abortable
		panic("nothing was minted; the creator may abort and relaunch instead")
	}
	p := c.prov
	if p.round != 0 {
		panic("randomness already requested for round " + itoa(p.round))
	}
	if !p.creatorRevealed && h < revealDeadline(c)-BeaconGraceBlocks {
		panic("randomness is requested after the creator reveals, or in the window's last " +
			itoa(BeaconGraceBlocks) + " blocks")
	}
	if !bindRound(c, h) {
		panic("randomness provider returned an invalid or already published round; retry in a later block")
	}
	return p.round
}

// FulfillRandomness takes the bound 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); works before and
// after the deadline while the collection is Closed.
func FulfillRandomness(cur realm, cid string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	h := height()
	refresh(c, h)
	if c.state != types.StateClosed {
		panic("secrets are accepted only after the sale closed (state " + c.state.String() + ")")
	}
	if !usesProvider(c) {
		panic("this collection does not use a randomness provider")
	}
	if c.minted() == 0 { // SEC-F1 (SA-I9): a 0-mint sale stays abortable
		panic("nothing was minted; the creator may abort and relaunch instead")
	}
	p := c.prov
	if p.round == 0 {
		panic("randomness was not requested yet")
	}
	if h <= p.roundHeight {
		panic("round " + itoa(p.round) + " was bound in this block; fulfill it in a later one")
	}
	v := mustProvider(c.beaconSource).impl.Randomness(p.round)
	if v == "" {
		panic("round " + itoa(p.round) + " is not available from the provider yet")
	}
	consumeRound(c, safe.AssertHex("randomness", v, 32), h)
}

// bindRound fixes the collection's round to provider.Target() at height h.
// It refuses (false) a non-positive round or one whose value the provider
// already has: that value would be known before binding (CV-I6).
func bindRound(c *collection, h int64) bool {
	impl := mustProvider(c.beaconSource).impl
	round := impl.Target()
	if round <= 0 || isRandomness(impl.Randomness(round)) {
		return false
	}
	c.prov.round, c.prov.roundHeight = round, h
	chain.Emit("RandomnessRequested", "cid", c.id, "provider", c.beaconSource, "round", itoa(round))
	return true
}

func consumeRound(c *collection, v string, h int64) {
	p := c.prov
	p.beaconSecret = v
	p.beaconRevealed = true
	chain.Emit("BeaconRevealed", "cid", c.id, "provider", c.beaconSource, "round", itoa(p.round), "secret", v)
	finalize(c, h)
}

// providerWaitEnd is the last height at which Finalize still waits for the
// provider: ProviderWaitBlocks after the deadline or the binding.
func providerWaitEnd(c *collection) int64 {
	from := revealDeadline(c)
	if c.prov.roundHeight > from {
		from = c.prov.roundHeight
	}
	return from + ProviderWaitBlocks
}

// settleProvider is Finalize's provider step after the deadline (CV-M1).
// It returns true when Finalize is done: the round was bound now (a later
// Finalize or FulfillRandomness takes its value), or its value finalized
// the collection. It returns false only when the provider is provably
// unavailable — no usable value after providerWaitEnd — and Finalize falls
// back (creator-only / fallback, never a FairLaunch). While the bound round
// may still arrive it refuses, so nobody can pick the fallback by not
// fulfilling. After the wait a deprecated provider is not called at all
// (escape hatch for a provider whose code aborts every call).
func settleProvider(c *collection, h int64) bool {
	p := c.prov
	waited := h > providerWaitEnd(c)
	if waited && !mustProvider(c.beaconSource).active {
		return false
	}
	if p.round == 0 {
		if bindRound(c, h) {
			return true
		}
		if waited {
			return false
		}
		panic("the randomness provider cannot bind a round now; retry later (fallback after height " +
			itoa(providerWaitEnd(c)) + ")")
	}
	if h > p.roundHeight {
		if v := mustProvider(c.beaconSource).impl.Randomness(p.round); isRandomness(v) {
			consumeRound(c, safe.AssertHex("randomness", v, 32), h)
			return true
		}
	}
	if waited {
		return false
	}
	panic("waiting for randomness round " + itoa(p.round) + " (FulfillRandomness once it is published; fallback after height " +
		itoa(providerWaitEnd(c)) + ")")
}

// isRandomness: a provider value core accepts (64 hex characters).
func isRandomness(v string) bool {
	if len(v) != 64 {
		return false
	}
	for i := 0; i < len(v); i++ {
		c := v[i]
		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') {
			return false
		}
	}
	return true
}

// 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/sinopia4/safe/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
)

// 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,
		Soulbound:   c.soulbound,
	}
	info.TraitTypes = append([]string{}, traitTypesOf(c)...)
	if c.prov != nil {
		info.RevealDeadline = revealDeadline(c)
		info.Badge = c.prov.badge
		info.Mode = c.mode
		if c.state == types.StateFinal {
			info.Salt = c.prov.salt
		}
	}
	return info
}

// CollectionTraitTypes is the collection's trait list as JSON ["…"].
func CollectionTraitTypes(cid string) string {
	w := &safe.JSONWriter{}
	writeStrings(w, traitTypesOf(mustCollection(cid)))
	return w.String()
}

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

// ListingDeposit is the deposit return (ugnot) market/v1 pins into a new
// listing (CV-L2); 0..ListingDepositCap, admin op listing.deposit.
func ListingDeposit() int64 { return listingDeposit }

// 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.IntField("listingDeposit", listingDeposit)
	w.IntField("listingDepositCap", ListingDepositCap)
	w.EndObject()
	return w.String()
}

// PendingOps pages the timelock queue as JSON (M-25):
// [{id, op, arg, proposed, earliest}].
func PendingOps(offset, limit int64) string {
	w := &safe.JSONWriter{}
	w.BeginArray()
	ops.IterateByOffset(int(offset), int(clampLimit(limit)), 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)
	w.Key("traitTypes")
	writeStrings(w, traitTypesOf(c))
	w.StrField("access", c.access)
	w.BoolField("soulbound", c.soulbound)
	if c.prov != nil {
		w.StrField("mode", modeName(c.mode))
		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))
		salt := ""
		if c.state == types.StateFinal {
			salt = c.prov.salt
		}
		w.StrField("salt", salt)
	}
	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/sinopia4/safe/v2"
)

// 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 {
	return royaltyAddress(mustCollection(cid).id)
}

// 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/sinopia4/engine/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
)

// 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.
//
// First owners (I-20) are run-length records in a second tree with the
// same bucket keys: one record of ownerRec bytes (the token's slot in the
// bucket, then the 40-character address) for each run of consecutive
// tokens minted to one address. A mint batch adds at most one record per
// bucket it touches, and none when it continues the bucket's last run, so
// a batch of n costs 41 bytes, not 40 n; a bucket holds at most
// packSlots records. Neither a transfer nor an approval touches it.
type tokenState struct {
	final     bool
	soulbound bool     // non-transferable collection (I-20)
	pack      avl.Tree // safe.PadInt((tid-1)/packSlots, packKeyWidth) -> string of packed entries
	owners    avl.Tree // same key -> string of first-owner run records
}

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

	addrLen  = 40 // a bech32 "g1…" address of 20 bytes
	ownerRec = 1 + addrLen

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

// appendOwners records to as the first owner of first..last (appended in
// tid order, right after appendTokens of the same range).
func (st *tokenState) appendOwners(first, last int64, to address) {
	a := to.String()
	if len(a) != addrLen {
		panic("token state: unexpected address length")
	}
	for tid := first; tid <= last; {
		k := packKey(tid)
		v, _ := st.owners.Get(k).(string)
		if len(v) < ownerRec || v[len(v)-addrLen:] != a {
			st.owners.Set(k, v+string([]byte{byte((tid-1)%packSlots)})+a)
		}
		tid = (tid-1)/packSlots*packSlots + packSlots + 1 // first tid of the next bucket
	}
}

// firstOwner is the address token tid was minted to, or "" for a token
// that was never minted. Burned tokens keep theirs.
func (st *tokenState) firstOwner(tid int64) address {
	if tid <= 0 || st.field(tid, fieldMintHeight) == 0 {
		return ""
	}
	return st.ownerAt(tid)
}

// ownerAt is the first owner recorded for a minted token tid: the last run
// record at or before its slot (records are in slot order).
func (st *tokenState) ownerAt(tid int64) address {
	v, _ := st.owners.Get(packKey(tid)).(string)
	slot := byte((tid - 1) % packSlots)
	at := -1
	for off := 0; off+ownerRec <= len(v) && v[off] <= slot; off += ownerRec {
		at = off
	}
	if at < 0 {
		return ""
	}
	return address(v[at+1 : at+ownerRec])
}

// 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.soulbound {
		panic(errSoulbound)
	}
	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).
//
// Argument order follows grc721 with the collection first (K-1, Onbloc
// option A): Approve(cid, to, tid), TransferFrom(cid, from, to, tid).
func Approve(cur realm, cid string, to address, tid string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	assertTransferable(c)
	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)
	if approved {
		assertTransferable(c)
	}
	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 string, from, to address, tid string) {
	assertNoDeposit(cur)
	c := mustCollection(cid)
	assertTransferable(c)
	if err := c.ledger.TransferFrom(caller(cur), from, to, grc721.TokenID(tid)); err != nil {
		panic(err)
	}
}

const errSoulbound = "tokens of a non-transferable collection never move or get approved"

// assertTransferable refuses core's transfer and approval entry points for
// a non-transferable collection (I-20). The lockExt hook refuses every
// transfer anyway, also one through Token(cid).RealmTeller; this gives the
// same text before grc721's own approval checks. Revoking an
// approval-for-all stays possible.
func assertTransferable(c *collection) {
	if c.soulbound {
		panic(errSoulbound)
	}
}

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

// Name and Symbol are the collection's grc721 name and symbol (K-1: the
// grc721 read set a wallet needs, keyed by collection).
func Name(cid string) string { return mustCollection(cid).name }

func Symbol(cid string) string { return mustCollection(cid).symbol }

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

// FirstOwner is the address token tid was minted to (a sale mint or a
// creator reserve), whoever holds it now; burned tokens keep it. Panics
// for a token that was never minted.
func FirstOwner(cid, tid string) address {
	a := mustCollection(cid).st.firstOwner(tidNum(tid))
	if a == "" {
		panic(grc721.ErrInvalidTokenId)
	}
	return a
}

// 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, firstOwner} 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.StrField("firstOwner", in.FirstOwner.String())
	w.EndObject()
	return w.String()
}

// TokenURI is the token's art (I-15). Before Final every token shows
// core's neutral placeholder, never engine output (design §4.2). Then:
// an SVG engine's checked Render as an SVG data URI; a media engine's
// checked Media as a raster/SVG data URI or its ipfs:// CIDv1 URI, or —
// when the Media is empty or fails engine.CheckMedia — the checked card.
func TokenURI(cid, tid string) (string, error) {
	c := mustCollection(cid)
	if _, err := c.token.OwnerOf(grc721.TokenID(tid)); err != nil {
		return "", err
	}
	a := tokenArt(c, tid)
	return a.uri(), nil
}

// TokenCard is the token's checked SVG as a data URI: the art of an SVG
// engine, the card of a media engine, or the placeholder (gnoweb and
// SVG-only clients).
func TokenCard(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
}

// TokenMediaInfo describes what TokenURI returns without the payload:
// {"source":"placeholder"|"svg"|"card"|"data"|"ipfs","mime","sha256","uri","bytes"}
// (uri only for ipfs; bytes = the file size for data, else 0).
func TokenMediaInfo(cid, tid string) string {
	c := mustCollection(cid)
	if !exists(c, tid) {
		panic(grc721.ErrInvalidTokenId)
	}
	a := tokenArt(c, tid)
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.StrField("source", a.source)
	w.StrField("mime", a.mime)
	w.StrField("sha256", a.md.Sha256)
	uri := ""
	if a.source == artIPFS {
		uri = a.md.URI
	}
	w.StrField("uri", uri)
	w.IntField("bytes", int64(len(a.md.Data)))
	w.EndObject()
	return w.String()
}

// 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. "image" is TokenURI
// written without escaping (it only ever holds data-URI / ipfs characters,
// M-4); "image_mime" and "image_sha256" describe a checked media file.
func TokenMetadata(cid, tid string) string {
	c := mustCollection(cid)
	if !exists(c, tid) {
		panic(grc721.ErrInvalidTokenId)
	}
	a := tokenArt(c, tid)
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.StrField("name", c.name+" #"+tid)
	w.StrField("description", c.description)
	w.RawStrField("image", a.uri())
	if a.source == artData || a.source == artIPFS {
		w.StrField("image_mime", a.mime)
		if a.md.Sha256 != "" {
			w.StrField("image_sha256", a.md.Sha256)
		}
	}
	// attributes carry OpenSea's trait_type and Adena's traitType (K-1)
	w.Key("attributes")
	w.BeginArray()
	for _, tr := range tokenTraits(c, tid) {
		w.BeginObject()
		w.StrField("trait_type", tr.Type)
		w.StrField("traitType", tr.Type)
		w.StrField("value", tr.Value)
		w.EndObject()
	}
	w.EndArray()
	w.EndObject()
	return w.String()
}

// Art sources of a token (TokenMediaInfo "source").
const (
	artPlaceholder = "placeholder"
	artSVG         = "svg"
	artCard        = "card"
	artData        = "data"
	artIPFS        = "ipfs"
)

// art is a token's resolved, checked art.
type art struct {
	source string
	mime   string
	svg    string       // placeholder / svg / card
	md     engine.Media // data / ipfs (checked)
}

func (a art) uri() string {
	switch a.source {
	case artData:
		return "data:" + a.mime + ";base64," + base64.StdEncoding.EncodeToString([]byte(a.md.Data))
	case artIPFS:
		return a.md.URI
	}
	return dataURI(a.svg)
}

// tokenArt resolves a token's art under I-15; every engine output passes
// engine.CheckSVG or engine.CheckMedia first.
func tokenArt(c *collection, tid string) art {
	if !c.st.final {
		return art{source: artPlaceholder, mime: engine.MimeSVG, svg: placeholderSVG(c.name, "Unrevealed")}
	}
	rec := mustEngine(c.engineID)
	in := tokenInput(c, tid)
	if rec.manifest.Kind == engine.KindMedia {
		md := rec.impl.Media(in)
		if !md.IsZero() && engine.CheckMedia(rec.manifest, md) == nil {
			if md.Data != "" {
				return art{source: artData, mime: md.Mime, md: md}
			}
			return art{source: artIPFS, mime: md.Mime, md: md}
		}
		svg, ok := renderCheckedToken(c, rec, in)
		if ok {
			return art{source: artCard, mime: engine.MimeSVG, svg: svg}
		}
		return art{source: artPlaceholder, mime: engine.MimeSVG, svg: svg}
	}
	svg, ok := renderCheckedToken(c, rec, in)
	if ok {
		return art{source: artSVG, mime: engine.MimeSVG, svg: svg}
	}
	return art{source: artPlaceholder, mime: engine.MimeSVG, svg: svg}
}

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 mh > 0 {
		in.FirstOwner = c.st.ownerAt(n)
	}
	if c.st.final {
		in.Seed = safe.Seed(c.id, tid, c.prov.salt)
		in.Salt = 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, _ := renderCheckedToken(c, rec, tokenInput(c, tid))
	return svg
}

// renderCheckedToken is Render + CheckSVG; false (and the placeholder) when
// the output is rejected.
func renderCheckedToken(c *collection, rec *engineRecord, in engine.Input) (string, bool) {
	svg := rec.impl.Render(in)
	if err := engine.CheckSVG(rec.manifest, svg); err != nil {
		return placeholderSVG(c.name, "Engine output rejected"), false
	}
	return svg, true
}

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.ValidateTraitsFor(traitTypesOf(c), 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))
}