collections.gno
19.62 Kb · 568 lines
1package core
2
3import (
4 "chain"
5 "chain/runtime"
6
7 "gno.land/p/nt/grc721/royalty/v0"
8 "gno.land/p/nt/grc721/v0"
9 "gno.land/p/nt/seqid/v0"
10
11 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
12 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
13 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
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 if spec.Soulbound && spec.RoyaltyBps != 0 {
42 panic("a non-transferable collection has no secondary sales; royaltyBps must be 0")
43 }
44 primary := safe.ParsePayees("primaryPayees", spec.PrimaryPayees, MaxPayees)
45 royal := safe.ParsePayees("royaltyPayees", spec.RoyaltyPayees, MaxPayees)
46 next := itoa(collCount + 1)
47 assertPayees("primaryPayees", primary, next, spec.EngineID)
48 assertPayees("royaltyPayees", royal, next, spec.EngineID)
49
50 rec := mustEngine(spec.EngineID)
51 // I-19: claimed and live engine, creator allowed by its policy, params
52 // not another creator's; judged before any engine code runs.
53 g, why := createAccess(rec, creator, spec.Params)
54 if why != "" {
55 panic(why)
56 }
57 // I-16: the creator's own transaction runs the engine they chose.
58 if err := rec.impl.ValidateParams(spec.Params); err != nil {
59 panic("params rejected by engine: " + err.Error())
60 }
61 tts := collectionTraitTypes(rec, spec.Params)
62 // The engine's optional create gate gets the creator explicitly (no
63 // OriginCaller read in the engine; a realm creator works too, K-2).
64 if g, ok := rec.impl.(engine.CreateGate); ok {
65 err := g.GateCreate(engine.Collection{ID: next, Creator: creator, Params: spec.Params,
66 MaxSupply: spec.MaxSupply, Soulbound: spec.Soulbound})
67 if err != nil {
68 panic("create refused by engine: " + err.Error())
69 }
70 }
71
72 collCount++
73 cid := itoa(collCount)
74
75 // Each collection gets its own sub-realm identity, so Token.ID() and every
76 // grc721 event carry "…/core#c/<cid>" (design §2.3; verified by
77 // spike/subtoken and core tests on gno v1.7.0).
78 tok, led := grc721.NewToken(spec.Name, spec.Symbol, seqid.ID(uint64(collCount)), cur.Sub("c/"+cid))
79 st := &tokenState{soulbound: spec.Soulbound}
80 led.RegisterExtension(&lockExt{cid: cid, st: st})
81 roy, royLed := royalty.NewRoyalty(led, RoyaltyCapBps)
82 if spec.RoyaltyBps > 0 {
83 if err := royLed.SetDefaultRoyalty(royaltyAddress(cid), spec.RoyaltyBps); err != nil {
84 panic(err)
85 }
86 }
87
88 c := &collection{
89 id: cid,
90 name: spec.Name,
91 symbol: spec.Symbol,
92 description: spec.Description,
93 creator: creator,
94 engineID: spec.EngineID,
95 params: spec.Params,
96 traitTypes: tts,
97 soulbound: spec.Soulbound,
98 maxSupply: spec.MaxSupply,
99 nextTID: 1,
100 royaltyBps: spec.RoyaltyBps,
101 primaryPayees: primary,
102 royaltyPayees: royal,
103 minter: minter,
104 state: types.StateDraft,
105 createdHeight: height(),
106 access: g.access,
107 licenceFee: g.fee,
108 token: tok,
109 ledger: led,
110 roy: roy,
111 st: st,
112 }
113 collections.Set(collKey(cid), c)
114 byCreator.Set(creator.String()+":"+collKey(cid), cid)
115 byEngine.Set(spec.EngineID+":"+collKey(cid), cid)
116 rec.collections++
117 if g.key != "" && !g.reuse {
118 paramsTaken.Set(g.key, cid)
119 }
120 if g.lic != nil {
121 g.lic.used++
122 }
123
124 chain.Emit("CollectionCreated",
125 "cid", cid, "creator", creator.String(), "minter", minter,
126 "engine", spec.EngineID, "token", tok.ID(), "access", g.access, "soulbound", boolStr(spec.Soulbound))
127 return cid
128}
129
130// Launch freezes the configuration (I-6): sale window, reveal window and the
131// creator's commitment. The sale must start in the future so a beacon can
132// commit before the first mint.
133func Launch(cur realm, cid string, l types.LaunchSpec) {
134 c := mustCollection(cid)
135 assertBoundMinter(cur, c)
136 h := height()
137 if c.state != types.StateDraft {
138 panic("only a draft can be launched")
139 }
140 if l.StartHeight <= h {
141 panic("startHeight must be in the future")
142 }
143 if l.EndHeight < l.StartHeight || l.EndHeight-l.StartHeight > MaxSaleBlocks {
144 panic("sale window must be 0.." + itoa(MaxSaleBlocks) + " blocks")
145 }
146 if l.Mode == types.ModeOpen {
147 launchOpen(c, l)
148 return
149 }
150 if l.Mode != types.ModeReveal {
151 panic("mode must be \"\" (commit-reveal) or \"" + types.ModeOpen + "\"")
152 }
153 if l.RevealWindow < RevealWindowMin || l.RevealWindow > RevealWindowMax {
154 panic("revealWindow must be " + itoa(RevealWindowMin) + ".." + itoa(RevealWindowMax) + " blocks")
155 }
156 commit := safe.AssertHex("creatorCommit", l.CreatorCommit, 32)
157 // Commitments are domain-separated by chain, collection and role
158 // (safe.Commit), so only this collection's own history matters: a secret
159 // that went public here is never accepted again (SA-L1, RA M-5).
160 if isBurned(c, commit) {
161 panic("this commitment's secret was already revealed; derive a new secret")
162 }
163 source := l.BeaconSource
164 if l.UseBeacon {
165 if source == "" {
166 source = types.BeaconCommitted
167 }
168 if source == types.BeaconCommitted {
169 if beacon == "" {
170 panic("no beacon is configured; launch without useBeacon or with an approved randomness provider")
171 }
172 } else {
173 assertActiveProvider(source)
174 }
175 } else {
176 if source != "" {
177 panic("beaconSource needs useBeacon")
178 }
179 // SA-M2: without the beacon the creator alone knows the only secret
180 // and can grind the last mint for the map it wants. While the
181 // platform has a beacon or an approved randomness provider, nobody
182 // may opt out.
183 if beaconAvailable() {
184 panic("the platform beacon is configured; launch with useBeacon")
185 }
186 }
187
188 checkLaunch(c, types.ModeReveal)
189
190 c.prov = &provenance{creatorCommit: commit, acc: safe.InitialEntropy(runtime.ChainID(), c.id)}
191 c.startHeight, c.endHeight, c.revealWindow = l.StartHeight, l.EndHeight, l.RevealWindow
192 c.useBeacon = l.UseBeacon
193 c.beaconSource = source
194 c.mode = types.ModeReveal
195 schedule(c)
196}
197
198// launchOpen is Launch in open mode (I-17): no commitment, no beacon or
199// provider, no reveal window. The salt is public (openSalt) and anyone may
200// finalize once the sale is Closed.
201func launchOpen(c *collection, l types.LaunchSpec) {
202 if l.CreatorCommit != "" || l.UseBeacon || l.BeaconSource != "" {
203 panic("an open launch has no creatorCommit, useBeacon or beaconSource")
204 }
205 if l.RevealWindow != 0 {
206 panic("an open launch has revealWindow 0")
207 }
208 checkLaunch(c, types.ModeOpen)
209 c.prov = &provenance{acc: safe.InitialEntropy(runtime.ChainID(), c.id)}
210 c.startHeight, c.endHeight, c.revealWindow = l.StartHeight, l.EndHeight, 0
211 c.useBeacon, c.beaconSource = false, ""
212 c.mode = types.ModeOpen
213 schedule(c)
214}
215
216// checkLaunch refuses an engine that was deprecated or superseded after the
217// Draft was made (WP-J J-1: I-14's "no new sales" covers Launch and every
218// relaunch after AbortLaunch, not only CreateCollection; a collection that
219// is already Scheduled or later is not touched), then runs the engine's
220// launch gate (I-16: the creator's own tx; everything the engine needs is
221// passed in). An engine that implements engine.LaunchGate is then asked
222// again with the launch mode (e.g. an engine that only works in reveal
223// mode refuses an open launch).
224func checkLaunch(c *collection, mode string) {
225 rec := mustEngine(c.engineID)
226 assertEngineUsable(rec)
227 if err := rec.impl.CheckLaunch(c.id, c.params, c.maxSupply); err != nil {
228 panic("launch refused by engine: " + err.Error())
229 }
230 if g, ok := rec.impl.(engine.LaunchGate); ok {
231 err := g.GateLaunch(engine.Collection{ID: c.id, Creator: c.creator, Params: c.params,
232 MaxSupply: c.maxSupply, Mode: mode, Soulbound: c.soulbound})
233 if err != nil {
234 panic("launch refused by engine: " + err.Error())
235 }
236 }
237}
238
239// assertEngineUsable is the engine gate of Launch: claimed, not deprecated,
240// not superseded (CreateCollection's createAccess starts with the same
241// checks and texts). The access policy is not judged again (I-19).
242func assertEngineUsable(rec *engineRecord) {
243 if !rec.claimed {
244 panic("engine is not claimed by its author yet")
245 }
246 assertEngineNotRetired(rec)
247}
248
249// schedule snapshots the fees and moves c to Scheduled (both modes).
250func schedule(c *collection) {
251 c.primaryBps = fees.PrimaryBps
252 c.engineAuthor, c.engineBps = engineFeeQuote(c)
253 c.state = types.StateScheduled
254 commit := ""
255 if c.prov != nil {
256 commit = c.prov.creatorCommit
257 }
258 chain.Emit("CollectionScheduled",
259 "cid", c.id, "start", itoa(c.startHeight), "end", itoa(c.endHeight),
260 "revealWindow", itoa(c.revealWindow), "useBeacon", boolStr(c.useBeacon),
261 "beaconSource", c.beaconSource, "creatorCommit", commit,
262 "engineAuthor", c.engineAuthor.String(), "engineFeeBps", itoa(c.engineBps),
263 "mode", modeName(c.mode))
264}
265
266// modeName is the mode as shown in events and JSON ("reveal" or "open").
267func modeName(m string) string {
268 if m == types.ModeOpen {
269 return types.ModeOpen
270 }
271 return "reveal"
272}
273
274// collectionTraitTypes asks the engine for the collection's trait list
275// (I-16) and returns a core-owned copy, or nil when it equals the
276// manifest's (nothing extra stored).
277func collectionTraitTypes(rec *engineRecord, params string) []string {
278 tts := rec.impl.TraitTypes(params)
279 if err := engine.ValidateTraitTypes(tts); err != nil {
280 panic("trait types rejected: " + err.Error())
281 }
282 if sameList(tts, rec.manifest.TraitTypes) {
283 return nil
284 }
285 return append([]string{}, tts...)
286}
287
288func sameList(a, b []string) bool {
289 if len(a) != len(b) {
290 return false
291 }
292 for i := range a {
293 if a[i] != b[i] {
294 return false
295 }
296 }
297 return true
298}
299
300// traitTypesOf is c's effective trait list (shared; callers copy before
301// handing it out).
302func traitTypesOf(c *collection) []string {
303 if c.traitTypes != nil {
304 return c.traitTypes
305 }
306 return mustEngine(c.engineID).manifest.TraitTypes
307}
308
309// AbortLaunch returns a launched collection to Draft while nothing has been
310// minted — the way out when a beacon never commits. A commitment whose
311// secret was revealed is burned for this collection; unrevealed ones (the
312// beacon's deterministic one included) may be committed again (SA-L1).
313func AbortLaunch(cur realm, cid string) {
314 c := mustCollection(cid)
315 assertBoundMinter(cur, c)
316 refresh(c, height())
317 if c.state == types.StateDraft || c.state == types.StateFinal {
318 panic("only a launched, unfinished collection can be aborted")
319 }
320 if c.minted() > 0 {
321 panic("tokens were minted; the launch can no longer be aborted")
322 }
323 if c.prov.creatorRevealed {
324 c.burnedCommits = append(c.burnedCommits, c.prov.creatorCommit)
325 }
326 if c.prov.beaconRevealed {
327 c.burnedCommits = append(c.burnedCommits, c.prov.beaconCommit)
328 }
329 c.prov = nil
330 c.startHeight, c.endHeight, c.revealWindow, c.closeHeight = 0, 0, 0, 0
331 c.useBeacon, c.beaconSource, c.mode = false, "", types.ModeReveal
332 c.engineBps, c.engineAuthor = 0, ""
333 c.state = types.StateDraft
334 chain.Emit("CollectionState", "cid", c.id, "state", c.state.String())
335}
336
337// ReserveTo mints the creator's reserve before the sale starts. Reserve
338// mints feed the entropy like any mint, appear in Provenance, and do not
339// count toward wallet caps.
340func ReserveTo(cur realm, cid string, to address, n int64) (first, last int64) {
341 c := mustCollection(cid)
342 assertBoundMinter(cur, c)
343 assertNotPaused("mint")
344 h := height()
345 refresh(c, h)
346 if c.state != types.StateScheduled {
347 panic("reserve is only possible after launch and before the sale starts")
348 }
349 if c.mode == types.ModeOpen {
350 panic("an open collection has no creator reserve")
351 }
352 // SA-M2: a reserve is the creator's own allocation; it needs a map the
353 // creator cannot steer, i.e. the beacon.
354 if !c.useBeacon {
355 panic("a creator reserve needs a beacon launch")
356 }
357 // A reserve is a mint, and the beacon may only commit while nothing is
358 // minted: reserving first would leave the collection unmintable and
359 // unabortable (found on Onyx, collection 1). A randomness provider has
360 // nothing to commit: its value is drawn only after the reveal starts.
361 if awaitingBeaconCommit(c) {
362 panic("waiting for the beacon commitment; reserve after the beacon commits")
363 }
364 assertMintCount(c, n)
365 if c.reserved+n > c.maxSupply*MaxReserveBps/safe.BpsDenominator {
366 panic("reserve would exceed " + itoa(MaxReserveBps/100) + "% of supply")
367 }
368 first, last = mintBatchTo(c, to, n, h)
369 c.reserved += n
370 c.reservedTo.Set(to.String(), reservedTo(c, to)+n)
371 emitBatch("Reserved", c, to, first, last)
372 return first, last
373}
374
375// MintTo mints n tokens during the sale. The minter has already checked
376// phase, price, allowlist and wallet cap; core re-checks only what it owns:
377// state, supply and the beacon commitment (I-5). The lifetime counter of
378// I-9 is the grc721 balance itself (mintedBy).
379func MintTo(cur realm, cid string, to address, n int64) (first, last int64) {
380 c := mustCollection(cid)
381 assertBoundMinter(cur, c)
382 assertNotPaused("mint")
383 h := height()
384 refresh(c, h)
385 if c.state != types.StateMinting {
386 panic("collection is not minting (state " + c.state.String() + ")")
387 }
388 if awaitingBeaconCommit(c) {
389 panic("waiting for the beacon commitment; minting has not opened")
390 }
391 assertMintCount(c, n)
392 first, last = mintBatchTo(c, to, n, h)
393 if c.minted() == c.maxSupply {
394 c.closeHeight = h
395 c.state = types.StateClosed
396 chain.Emit("CollectionState", "cid", c.id, "state", c.state.String())
397 }
398 emitBatch("MintBatch", c, to, first, last)
399 return first, last
400}
401
402func assertMintCount(c *collection, n int64) {
403 if n <= 0 || n > MaxMintPerTx {
404 panic("count must be 1.." + itoa(MaxMintPerTx))
405 }
406 if c.minted()+n > c.maxSupply {
407 panic("only " + itoa(c.maxSupply-c.minted()) + " tokens left")
408 }
409}
410
411// mintBatchTo is the only place tokens come into existence.
412func mintBatchTo(c *collection, to address, n, h int64) (first, last int64) {
413 first = c.nextTID
414 last = first + n - 1
415 for tid := first; tid <= last; tid++ {
416 if err := c.ledger.Mint(to, grc721.TokenID(itoa(tid))); err != nil {
417 panic(err)
418 }
419 }
420 c.nextTID = last + 1
421 c.st.appendTokens(first, last, h)
422 c.st.appendOwners(first, last, to)
423 c.prov.acc = safe.MixEntropy(c.prov.acc, to, h, first, last)
424 return first, last
425}
426
427// mintedBy is addr's lifetime count of sale mints (I-9) while the
428// collection is not Final: before Final no token can move or burn (I-11,
429// lockExt) and tokens only come from mintBatchTo, so the grc721 balance is
430// exactly sale mints + reserves received. This replaces a stored counter
431// (~2 KB per new wallet, storage-cost-analysis P2). After Final the
432// balance moves freely and no minter needs the count any more: -1.
433func mintedBy(c *collection, addr address) int64 {
434 if c.st.final {
435 return -1
436 }
437 bal, err := c.token.BalanceOf(addr)
438 if err != nil {
439 return 0
440 }
441 return bal - reservedTo(c, addr)
442}
443
444func reservedTo(c *collection, addr address) int64 {
445 if v := c.reservedTo.Get(addr.String()); v != nil {
446 return v.(int64)
447 }
448 return 0
449}
450
451// awaitingBeaconCommit: a committed-beacon launch whose beacon has not
452// committed yet; nothing may be minted (or reserved) before it does.
453func awaitingBeaconCommit(c *collection) bool {
454 return c.useBeacon && c.beaconSource == types.BeaconCommitted && c.prov.beaconCommit == ""
455}
456
457// CloseMint materializes Closed once the sale window has passed. Anyone may
458// call it; reveals and Finalize work without it.
459func CloseMint(cur realm, cid string) {
460 assertNoDeposit(cur)
461 c := mustCollection(cid)
462 refresh(c, height())
463 if c.state != types.StateClosed {
464 panic("the sale is not over (state " + c.state.String() + ")")
465 }
466}
467
468// --- creator -----------------------------------------------------------------
469
470// TransferCreator starts a two-step handover (RA M-11).
471func TransferCreator(cur realm, cid string, to address) {
472 assertNoDeposit(cur)
473 c := mustCollection(cid)
474 assertCreator(cur, c)
475 if !to.IsValid() {
476 panic("invalid address")
477 }
478 c.pendingCreator = to
479 chain.Emit("CreatorTransferStarted", "cid", c.id, "from", c.creator.String(), "to", to.String())
480}
481
482func AcceptCreator(cur realm, cid string) {
483 assertNoDeposit(cur)
484 c := mustCollection(cid)
485 who := caller(cur)
486 if c.pendingCreator == "" || who != c.pendingCreator {
487 panic("no pending creator transfer to this address")
488 }
489 byCreator.Remove(c.creator.String() + ":" + collKey(c.id))
490 byCreator.Set(who.String()+":"+collKey(c.id), c.id)
491 chain.Emit("CreatorTransferred", "cid", c.id, "from", c.creator.String(), "to", who.String())
492 c.creator = who
493 c.pendingCreator = ""
494}
495
496// SetPayees changes the royalty split after Final. The primary-sale split is
497// frozen with the sale (I-6); the royalty receiver stays the collection's
498// sub-treasury, so third-party markets are unaffected. Royalties earned so
499// far are first paid to the current payees (SA-I4).
500func SetPayees(cur realm, cid, payees string) {
501 assertNoDeposit(cur)
502 c := mustCollection(cid)
503 assertCreator(cur, c)
504 if c.state != types.StateFinal {
505 panic("royalty payees can change only after the collection is final")
506 }
507 ps := safe.ParsePayees("royaltyPayees", payees, MaxPayees)
508 assertPayees("royaltyPayees", ps, c.id, c.engineID)
509 distribute(cur, c)
510 c.royaltyPayees = ps
511 chain.Emit("RoyaltyPayees", "cid", c.id, "payees", payees)
512}
513
514// assertPayees refuses payees that can never spend what they receive
515// (SA-L5): the platform's own realms and sub-addresses. cid is the
516// collection being configured, engineID its engine adapter.
517func assertPayees(field string, ps []types.Payee, cid, engineID string) {
518 for _, p := range ps {
519 assertSpendable(field, p.Addr, cid, engineID)
520 }
521}
522
523// assertSpendable panics for core, core's sub-addresses of collection cid
524// (token identity c/<cid>, royalty treasury roy/<cid>), the engine adapter,
525// and every address of the deny set: the static platform realms next to
526// core, every minter ever approved and every payee.deny realm (I-18). None
527// of them has a path that spends an incoming payment, so the coins would be
528// stranded (I-3).
529func assertSpendable(field string, addr address, cid, engineID string) {
530 bad := []address{chain.PackageAddress(selfPath)}
531 if cid != "" {
532 bad = append(bad, chain.DerivePkgSubAddr(selfPath, "c/"+cid), royaltyAddress(cid))
533 }
534 if engineID != "" {
535 bad = append(bad, chain.PackageAddress(engineID))
536 }
537 for _, b := range bad {
538 if addr == b {
539 panic(field + ": " + addr.String() + " is a platform realm address that cannot spend; use a wallet")
540 }
541 }
542 if v := deniedPayees.Get(addr.String()); v != nil {
543 d := v.(*deniedPayee)
544 if d.source == "minter" {
545 panic(field + ": " + addr.String() + " is the minter realm " + d.path + "; use a wallet")
546 }
547 panic(field + ": " + addr.String() + " is the platform realm " + d.path + " that cannot spend; use a wallet")
548 }
549}
550
551func assertCreator(cur realm, c *collection) {
552 if caller(cur) != c.creator {
553 panic("only the collection's creator can do this")
554 }
555}
556
557func assertBoundMinter(cur realm, c *collection) {
558 if cur.Previous().PkgPath() != c.minter {
559 panic("only the collection's bound minter (" + c.minter + ") can do this")
560 }
561}
562
563func boolStr(b bool) string {
564 if b {
565 return "true"
566 }
567 return "false"
568}