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.

collections.gno

14.99 Kb · 431 lines
  1package core
  2
  3import (
  4	"chain"
  5	"chain/runtime"
  6	"strings"
  7
  8	"gno.land/p/nt/grc721/royalty/v0"
  9	"gno.land/p/nt/grc721/v0"
 10	"gno.land/p/nt/seqid/v0"
 11
 12	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
 13	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/types/v1"
 14)
 15
 16// --- bound minter only -------------------------------------------------------
 17//
 18// A collection is created by an admin-approved minter realm and stays bound
 19// to it: only that realm can launch, abort, reserve and mint (I-5). The
 20// minter is trusted to pass the real creator; core trusts nothing else it
 21// is given and validates every field (I-13).
 22
 23// CreateCollection stores a Draft collection and returns its id. Nobody can
 24// mint a Draft, so a creator can configure phases across several messages
 25// without a race (OA B2).
 26func CreateCollection(cur realm, creator address, spec types.CollectionSpec) string {
 27	minter := cur.Previous().PkgPath()
 28	assertActiveMinter(minter)
 29	assertNotPaused("create")
 30	if !creator.IsValid() {
 31		panic("invalid creator address")
 32	}
 33	safe.AssertNonEmptyText("name", spec.Name, MaxNameLen)
 34	safe.AssertSymbol("symbol", spec.Symbol)
 35	safe.AssertText("description", spec.Description, MaxDescriptionLen)
 36	safe.AssertText("params", spec.Params, MaxParamsLen)
 37	if spec.MaxSupply <= 0 || spec.MaxSupply > MaxSupplyCap {
 38		panic("maxSupply must be 1.." + itoa(MaxSupplyCap))
 39	}
 40	safe.AssertBps("royaltyBps", spec.RoyaltyBps, RoyaltyCapBps)
 41	primary := safe.ParsePayees("primaryPayees", spec.PrimaryPayees, MaxPayees)
 42	royal := safe.ParsePayees("royaltyPayees", spec.RoyaltyPayees, MaxPayees)
 43	next := itoa(collCount + 1)
 44	assertPayees("primaryPayees", primary, next, spec.EngineID)
 45	assertPayees("royaltyPayees", royal, next, spec.EngineID)
 46
 47	rec := mustEngine(spec.EngineID)
 48	if !rec.claimed {
 49		panic("engine is not claimed by its author yet")
 50	}
 51	if rec.deprecated {
 52		panic("engine is deprecated")
 53	}
 54	// I-12 exception: the creator's own transaction runs the engine they chose.
 55	if err := rec.impl.ValidateParams(spec.Params); err != nil {
 56		panic("params rejected by engine: " + err.Error())
 57	}
 58
 59	collCount++
 60	cid := itoa(collCount)
 61
 62	// Each collection gets its own sub-realm identity, so Token.ID() and every
 63	// grc721 event carry "…/core#c/<cid>" (design §2.3; verified by
 64	// spike/subtoken and core tests on gno v1.7.0).
 65	tok, led := grc721.NewToken(spec.Name, spec.Symbol, seqid.ID(uint64(collCount)), cur.Sub("c/"+cid))
 66	st := &tokenState{}
 67	led.RegisterExtension(&lockExt{cid: cid, st: st})
 68	roy, royLed := royalty.NewRoyalty(led, RoyaltyCapBps)
 69	if spec.RoyaltyBps > 0 {
 70		if err := royLed.SetDefaultRoyalty(royaltyAddress(cid), spec.RoyaltyBps); err != nil {
 71			panic(err)
 72		}
 73	}
 74
 75	c := &collection{
 76		id:            cid,
 77		name:          spec.Name,
 78		symbol:        spec.Symbol,
 79		description:   spec.Description,
 80		creator:       creator,
 81		engineID:      spec.EngineID,
 82		params:        spec.Params,
 83		maxSupply:     spec.MaxSupply,
 84		nextTID:       1,
 85		royaltyBps:    spec.RoyaltyBps,
 86		primaryPayees: primary,
 87		royaltyPayees: royal,
 88		minter:        minter,
 89		state:         types.StateDraft,
 90		createdHeight: height(),
 91		token:         tok,
 92		ledger:        led,
 93		roy:           roy,
 94		st:            st,
 95	}
 96	collections.Set(collKey(cid), c)
 97	byCreator.Set(creator.String()+":"+collKey(cid), cid)
 98
 99	chain.Emit("CollectionCreated",
100		"cid", cid, "creator", creator.String(), "minter", minter,
101		"engine", spec.EngineID, "token", tok.ID())
102	return cid
103}
104
105// Launch freezes the configuration (I-6): sale window, reveal window and the
106// creator's commitment. The sale must start in the future so a beacon can
107// commit before the first mint.
108func Launch(cur realm, cid string, l types.LaunchSpec) {
109	c := mustCollection(cid)
110	assertBoundMinter(cur, c)
111	h := height()
112	if c.state != types.StateDraft {
113		panic("only a draft can be launched")
114	}
115	if l.StartHeight <= h {
116		panic("startHeight must be in the future")
117	}
118	if l.EndHeight < l.StartHeight || l.EndHeight-l.StartHeight > MaxSaleBlocks {
119		panic("sale window must be 0.." + itoa(MaxSaleBlocks) + " blocks")
120	}
121	if l.RevealWindow < RevealWindowMin || l.RevealWindow > RevealWindowMax {
122		panic("revealWindow must be " + itoa(RevealWindowMin) + ".." + itoa(RevealWindowMax) + " blocks")
123	}
124	commit := safe.AssertHex("creatorCommit", l.CreatorCommit, 32)
125	// Commitments are domain-separated by chain, collection and role
126	// (safe.Commit), so only this collection's own history matters: a secret
127	// that went public here is never accepted again (SA-L1, RA M-5).
128	if isBurned(c, commit) {
129		panic("this commitment's secret was already revealed; derive a new secret")
130	}
131	source := l.BeaconSource
132	if l.UseBeacon {
133		if source == "" {
134			source = types.BeaconCommitted
135		}
136		if source == types.BeaconCommitted {
137			if beacon == "" {
138				panic("no beacon is configured; launch without useBeacon or with an approved randomness provider")
139			}
140		} else {
141			assertActiveProvider(source)
142		}
143	} else {
144		if source != "" {
145			panic("beaconSource needs useBeacon")
146		}
147		// SA-M2: without the beacon the creator alone knows the only secret
148		// and can grind the last mint for the map it wants. While the
149		// platform has a beacon or an approved randomness provider, nobody
150		// may opt out.
151		if beaconAvailable() {
152			panic("the platform beacon is configured; launch with useBeacon")
153		}
154	}
155
156	c.prov = &provenance{creatorCommit: commit, acc: safe.InitialEntropy(runtime.ChainID(), cid)}
157	c.startHeight, c.endHeight, c.revealWindow = l.StartHeight, l.EndHeight, l.RevealWindow
158	c.useBeacon = l.UseBeacon
159	c.beaconSource = source
160	c.primaryBps = fees.PrimaryBps
161	c.engineAuthor, c.engineBps = engineFeeQuote(c)
162	c.state = types.StateScheduled
163
164	chain.Emit("CollectionScheduled",
165		"cid", cid, "start", itoa(c.startHeight), "end", itoa(c.endHeight),
166		"revealWindow", itoa(c.revealWindow), "useBeacon", boolStr(c.useBeacon),
167		"beaconSource", c.beaconSource, "creatorCommit", commit,
168		"engineAuthor", c.engineAuthor.String(), "engineFeeBps", itoa(c.engineBps))
169}
170
171// AbortLaunch returns a launched collection to Draft while nothing has been
172// minted — the way out when a beacon never commits. A commitment whose
173// secret was revealed is burned for this collection; unrevealed ones (the
174// beacon's deterministic one included) may be committed again (SA-L1).
175func AbortLaunch(cur realm, cid string) {
176	c := mustCollection(cid)
177	assertBoundMinter(cur, c)
178	refresh(c, height())
179	if c.state == types.StateDraft || c.state == types.StateFinal {
180		panic("only a launched, unfinished collection can be aborted")
181	}
182	if c.minted() > 0 {
183		panic("tokens were minted; the launch can no longer be aborted")
184	}
185	if c.prov.creatorRevealed {
186		c.burnedCommits = append(c.burnedCommits, c.prov.creatorCommit)
187	}
188	if c.prov.beaconRevealed {
189		c.burnedCommits = append(c.burnedCommits, c.prov.beaconCommit)
190	}
191	c.prov = nil
192	c.startHeight, c.endHeight, c.revealWindow, c.closeHeight = 0, 0, 0, 0
193	c.useBeacon, c.beaconSource = false, ""
194	c.engineBps, c.engineAuthor = 0, ""
195	c.state = types.StateDraft
196	chain.Emit("CollectionState", "cid", cid, "state", c.state.String())
197}
198
199// ReserveTo mints the creator's reserve before the sale starts. Reserve
200// mints feed the entropy like any mint, appear in Provenance, and do not
201// count toward wallet caps.
202func ReserveTo(cur realm, cid string, to address, n int64) (first, last int64) {
203	c := mustCollection(cid)
204	assertBoundMinter(cur, c)
205	assertNotPaused("mint")
206	h := height()
207	refresh(c, h)
208	if c.state != types.StateScheduled {
209		panic("reserve is only possible after launch and before the sale starts")
210	}
211	// SA-M2: a reserve is the creator's own allocation; it needs a map the
212	// creator cannot steer, i.e. the beacon.
213	if !c.useBeacon {
214		panic("a creator reserve needs a beacon launch")
215	}
216	// A reserve is a mint, and the beacon may only commit while nothing is
217	// minted: reserving first would leave the collection unmintable and
218	// unabortable (found on Onyx, collection 1). A randomness provider has
219	// nothing to commit: its value is drawn only after the reveal starts.
220	if awaitingBeaconCommit(c) {
221		panic("waiting for the beacon commitment; reserve after the beacon commits")
222	}
223	assertMintCount(c, n)
224	if c.reserved+n > c.maxSupply*MaxReserveBps/safe.BpsDenominator {
225		panic("reserve would exceed " + itoa(MaxReserveBps/100) + "% of supply")
226	}
227	first, last = mintBatchTo(c, to, n, h)
228	c.reserved += n
229	c.reservedTo.Set(to.String(), reservedTo(c, to)+n)
230	emitBatch("Reserved", c, to, first, last)
231	return first, last
232}
233
234// MintTo mints n tokens during the sale. The minter has already checked
235// phase, price, allowlist and wallet cap; core re-checks only what it owns:
236// state, supply and the beacon commitment (I-5). The lifetime counter of
237// I-9 is the grc721 balance itself (mintedBy).
238func MintTo(cur realm, cid string, to address, n int64) (first, last int64) {
239	c := mustCollection(cid)
240	assertBoundMinter(cur, c)
241	assertNotPaused("mint")
242	h := height()
243	refresh(c, h)
244	if c.state != types.StateMinting {
245		panic("collection is not minting (state " + c.state.String() + ")")
246	}
247	if awaitingBeaconCommit(c) {
248		panic("waiting for the beacon commitment; minting has not opened")
249	}
250	assertMintCount(c, n)
251	first, last = mintBatchTo(c, to, n, h)
252	if c.minted() == c.maxSupply {
253		c.closeHeight = h
254		c.state = types.StateClosed
255		chain.Emit("CollectionState", "cid", cid, "state", c.state.String())
256	}
257	emitBatch("MintBatch", c, to, first, last)
258	return first, last
259}
260
261func assertMintCount(c *collection, n int64) {
262	if n <= 0 || n > MaxMintPerTx {
263		panic("count must be 1.." + itoa(MaxMintPerTx))
264	}
265	if c.minted()+n > c.maxSupply {
266		panic("only " + itoa(c.maxSupply-c.minted()) + " tokens left")
267	}
268}
269
270// mintBatchTo is the only place tokens come into existence.
271func mintBatchTo(c *collection, to address, n, h int64) (first, last int64) {
272	first = c.nextTID
273	last = first + n - 1
274	for tid := first; tid <= last; tid++ {
275		if err := c.ledger.Mint(to, grc721.TokenID(itoa(tid))); err != nil {
276			panic(err)
277		}
278	}
279	c.nextTID = last + 1
280	c.st.appendTokens(first, last, h)
281	c.prov.acc = safe.MixEntropy(c.prov.acc, to, h, first, last)
282	return first, last
283}
284
285// mintedBy is addr's lifetime count of sale mints (I-9) while the
286// collection is not Final: before Final no token can move or burn (I-11,
287// lockExt) and tokens only come from mintBatchTo, so the grc721 balance is
288// exactly sale mints + reserves received. This replaces a stored counter
289// (~2 KB per new wallet, storage-cost-analysis P2). After Final the
290// balance moves freely and no minter needs the count any more: -1.
291func mintedBy(c *collection, addr address) int64 {
292	if c.st.final {
293		return -1
294	}
295	bal, err := c.token.BalanceOf(addr)
296	if err != nil {
297		return 0
298	}
299	return bal - reservedTo(c, addr)
300}
301
302func reservedTo(c *collection, addr address) int64 {
303	if v := c.reservedTo.Get(addr.String()); v != nil {
304		return v.(int64)
305	}
306	return 0
307}
308
309// awaitingBeaconCommit: a committed-beacon launch whose beacon has not
310// committed yet; nothing may be minted (or reserved) before it does.
311func awaitingBeaconCommit(c *collection) bool {
312	return c.useBeacon && c.beaconSource == types.BeaconCommitted && c.prov.beaconCommit == ""
313}
314
315// CloseMint materializes Closed once the sale window has passed. Anyone may
316// call it; reveals and Finalize work without it.
317func CloseMint(cur realm, cid string) {
318	assertNoDeposit(cur)
319	c := mustCollection(cid)
320	refresh(c, height())
321	if c.state != types.StateClosed {
322		panic("the sale is not over (state " + c.state.String() + ")")
323	}
324}
325
326// --- creator -----------------------------------------------------------------
327
328// TransferCreator starts a two-step handover (RA M-11).
329func TransferCreator(cur realm, cid string, to address) {
330	assertNoDeposit(cur)
331	c := mustCollection(cid)
332	assertCreator(cur, c)
333	if !to.IsValid() {
334		panic("invalid address")
335	}
336	c.pendingCreator = to
337	chain.Emit("CreatorTransferStarted", "cid", cid, "from", c.creator.String(), "to", to.String())
338}
339
340func AcceptCreator(cur realm, cid string) {
341	assertNoDeposit(cur)
342	c := mustCollection(cid)
343	who := caller(cur)
344	if c.pendingCreator == "" || who != c.pendingCreator {
345		panic("no pending creator transfer to this address")
346	}
347	byCreator.Remove(c.creator.String() + ":" + collKey(cid))
348	byCreator.Set(who.String()+":"+collKey(cid), cid)
349	chain.Emit("CreatorTransferred", "cid", cid, "from", c.creator.String(), "to", who.String())
350	c.creator = who
351	c.pendingCreator = ""
352}
353
354// SetPayees changes the royalty split after Final. The primary-sale split is
355// frozen with the sale (I-6); the royalty receiver stays the collection's
356// sub-treasury, so third-party markets are unaffected. Royalties earned so
357// far are first paid to the current payees (SA-I4).
358func SetPayees(cur realm, cid, payees string) {
359	assertNoDeposit(cur)
360	c := mustCollection(cid)
361	assertCreator(cur, c)
362	if c.state != types.StateFinal {
363		panic("royalty payees can change only after the collection is final")
364	}
365	ps := safe.ParsePayees("royaltyPayees", payees, MaxPayees)
366	assertPayees("royaltyPayees", ps, cid, c.engineID)
367	distribute(cur, c)
368	c.royaltyPayees = ps
369	chain.Emit("RoyaltyPayees", "cid", cid, "payees", payees)
370}
371
372// assertPayees refuses payees that can never spend what they receive
373// (SA-L5): the platform's own realms and sub-addresses. cid is the
374// collection being configured, engineID its engine adapter.
375func assertPayees(field string, ps []types.Payee, cid, engineID string) {
376	for _, p := range ps {
377		assertSpendable(field, p.Addr, cid, engineID)
378	}
379}
380
381// assertSpendable panics for core, core's sub-addresses of collection cid
382// (token identity c/<cid>, royalty treasury roy/<cid>), every minter ever
383// approved, the engine adapter, and the platform realms next to core
384// (market, reader, gallery, the genesis adapter). None of them has a path
385// that spends an incoming payment, so the coins would be stranded (I-3).
386func assertSpendable(field string, addr address, cid, engineID string) {
387	bad := []address{chain.PackageAddress(selfPath)}
388	if cid != "" {
389		bad = append(bad, chain.DerivePkgSubAddr(selfPath, "c/"+cid), royaltyAddress(cid))
390	}
391	if engineID != "" {
392		bad = append(bad, chain.PackageAddress(engineID))
393	}
394	base := strings.TrimSuffix(selfPath, "/core")
395	for _, sib := range platformRealms {
396		bad = append(bad, chain.PackageAddress(base+"/"+sib))
397	}
398	for _, b := range bad {
399		if addr == b {
400			panic(field + ": " + addr.String() + " is a platform realm address that cannot spend; use a wallet")
401		}
402	}
403	minters.Iterate("", "", func(path string, _ any) bool {
404		if addr == chain.PackageAddress(path) {
405			panic(field + ": " + addr.String() + " is the minter realm " + path + "; use a wallet")
406		}
407		return false
408	})
409}
410
411// platformRealms are the realm paths next to core (README package map).
412var platformRealms = []string{"mint/v1", "market/v1", "engines/genesis", "reader", "gallery"}
413
414func assertCreator(cur realm, c *collection) {
415	if caller(cur) != c.creator {
416		panic("only the collection's creator can do this")
417	}
418}
419
420func assertBoundMinter(cur realm, c *collection) {
421	if cur.Previous().PkgPath() != c.minter {
422		panic("only the collection's bound minter (" + c.minter + ") can do this")
423	}
424}
425
426func boolStr(b bool) string {
427	if b {
428		return "true"
429	}
430	return "false"
431}