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.

reads.gno

16.95 Kb · 579 lines
  1package upload
  2
  3import (
  4	"errors"
  5	"strconv"
  6	"strings"
  7
  8	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
  9	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/media/v1"
 10	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
 11	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/types/v1"
 12	assets "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/assets/v1"
 13	"gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/core"
 14)
 15
 16// Every function in this file is read-only. Every token read returns core's
 17// placeholder / "Unrevealed" before the collection is Final (T5).
 18
 19// Readiness reasons (Status.reason).
 20const (
 21	ReasonNotUpload      = "not-upload"
 22	ReasonNoStore        = "no-store"
 23	ReasonNotSealed      = "store-not-sealed"
 24	ReasonBoundElsewhere = "bound-elsewhere"
 25	ReasonSupply         = "supply-mismatch"
 26	ReasonUnbound        = "unbound"
 27	ReasonReady          = "ready"
 28)
 29
 30type col struct {
 31	cid     string
 32	info    types.CollectionInfo
 33	upload  bool
 34	store   string // params store id ("" if none or unknown)
 35	si      media.StoreInfo
 36	b       *binding // this collection's binding (nil if unbound)
 37	boundTo string   // collection the store is bound to ("" if none)
 38}
 39
 40func loadCol(cid string) col {
 41	c := col{cid: cid, info: core.Info(cid)}
 42	c.upload = c.info.EngineID == selfPath
 43	if !c.upload {
 44		return c
 45	}
 46	if id, ok := parseParams(c.info.Params); ok && storeExists(id) {
 47		c.store = id
 48		c.si = assets.Info(id)
 49		if v := bound.Get(id); v != nil {
 50			c.boundTo = v.(string)
 51		}
 52	}
 53	if v := byCID.Get(cid); v != nil {
 54		c.b = v.(*binding)
 55	}
 56	return c
 57}
 58
 59// status: ready = bound ∧ store sealed ∧ supply match (§6).
 60func (c *col) status() (bool, string) {
 61	switch {
 62	case !c.upload:
 63		return false, ReasonNotUpload
 64	case c.store == "":
 65		return false, ReasonNoStore
 66	case !c.si.Sealed:
 67		return false, ReasonNotSealed
 68	case c.boundTo != "" && c.boundTo != c.cid:
 69		return false, ReasonBoundElsewhere
 70	case c.info.MaxSupply != c.si.Slots:
 71		return false, ReasonSupply
 72	case c.b == nil || c.b.store != c.store:
 73		return false, ReasonUnbound
 74	}
 75	return true, ReasonReady
 76}
 77
 78func (c *col) badge() string {
 79	if !c.upload {
 80		return "computed"
 81	}
 82	if ok, _ := c.status(); !ok {
 83		return "unbound"
 84	}
 85	return media.Badge(c.si.OnchainN, c.si.IPFSN)
 86}
 87
 88func mustUpload(cid string) col {
 89	c := loadCol(cid)
 90	if !c.upload {
 91		panic("collection " + cid + " does not use the upload engine")
 92	}
 93	return c
 94}
 95
 96// IsUpload reports whether cid's engine is this adapter.
 97func IsUpload(cid string) bool { return core.Info(cid).EngineID == selfPath }
 98
 99// StoreOf is the store named by cid's params ("" if none).
100func StoreOf(cid string) string { return loadCol(cid).store }
101
102// Readiness is the typed Status for other realms.
103func Readiness(cid string) (ready bool, reason, store, badge string) {
104	c := loadCol(cid)
105	ready, reason = c.status()
106	return ready, reason, c.store, c.badge()
107}
108
109// Status is {cid, upload, state, store, bound, ready, reason, badge, settled,
110// maxSupply, slots}. The frontend shows the mint UI only when ready (T14).
111func Status(cid string) string {
112	c := loadCol(cid)
113	ready, reason := c.status()
114	w := &safe.JSONWriter{}
115	w.BeginObject()
116	w.StrField("cid", cid)
117	w.BoolField("upload", c.upload)
118	w.StrField("state", c.info.State.String())
119	w.StrField("store", c.store)
120	w.BoolField("bound", c.b != nil)
121	w.BoolField("ready", ready)
122	w.StrField("reason", reason)
123	w.StrField("badge", c.badge())
124	w.BoolField("settled", c.b != nil && c.b.key != "")
125	w.IntField("maxSupply", c.info.MaxSupply)
126	w.IntField("slots", c.si.Slots)
127	w.EndObject()
128	return w.String()
129}
130
131// StorageBadge is "computed" (any other engine), "onchain", "ipfs",
132// "mixed", or "unbound" for an upload collection that is not ready (§9).
133func StorageBadge(cid string) string {
134	c := loadCol(cid)
135	return c.badge()
136}
137
138// SetComposition is {collection, store, ready, reason, set}, set =
139// assets.Composition of the collection's store: slots per tier and per
140// trait value over the planned set (public and fixed before the sale, D8).
141func SetComposition(cid string) string {
142	c := mustUpload(cid)
143	if c.store == "" {
144		panic("collection " + cid + " names no store")
145	}
146	ready, reason := c.status()
147	w := &safe.JSONWriter{}
148	w.BeginObject()
149	w.StrField("collection", cid)
150	w.StrField("store", c.store)
151	w.BoolField("ready", ready)
152	w.StrField("reason", reason)
153	w.Key("set")
154	w.Raw(assets.Composition(c.store))
155	w.EndObject()
156	return w.String()
157}
158
159const (
160	stHidden   = 0 // not Final: placeholder
161	stNotReady = 1 // Final but not bound/ready: no art
162	stResolved = 2
163)
164
165func readToken(cid, tid string) (col, resolved, int, error) {
166	c := mustUpload(cid)
167	if _, err := core.OwnerOf(cid, tid); err != nil {
168		return c, resolved{}, stHidden, err
169	}
170	if c.info.State != types.StateFinal {
171		return c, resolved{}, stHidden, nil
172	}
173	if ok, _ := c.status(); !ok {
174		return c, resolved{}, stNotReady, nil
175	}
176	salt := saltOf(cid, c.b)
177	if salt == "" {
178		return c, resolved{}, stNotReady, nil
179	}
180	n := tidNum(tid)
181	r := assign(cid, tid, n, c.info, c.store, c.si, keyOf(cid, c.b, salt), nil)
182	return c, r, stResolved, nil
183}
184
185func mustReadToken(cid, tid string) (col, resolved, int) {
186	c, r, st, err := readToken(cid, tid)
187	if err != nil {
188		panic(err)
189	}
190	return c, r, st
191}
192
193// TokenURI is the canonical art URI: "data:<mime>;base64,…" for on-chain
194// art, "ipfs://<cidv1>" for IPFS art; core's placeholder before Final and
195// core's TokenURI (the generic card) for a collection that is not ready.
196func TokenURI(cid, tid string) (string, error) {
197	if !IsUpload(cid) {
198		return "", errors.New("collection " + cid + " does not use the upload engine")
199	}
200	_, r, st, err := readToken(cid, tid)
201	if err != nil {
202		return "", err
203	}
204	if st != stResolved {
205		return core.TokenURI(cid, tid)
206	}
207	return artURI(r), nil
208}
209
210func artURI(r resolved) string {
211	if r.art.Kind == media.KindChain {
212		return assets.ArtworkDataURI(r.store, r.art.Index)
213	}
214	return "ipfs://" + r.art.CID
215}
216
217// TokenImage is the inline image: a data URI for on-chain art, "" for IPFS
218// art (never a remote URL); core's placeholder before Final.
219func TokenImage(cid, tid string) string {
220	_, r, st := mustReadToken(cid, tid)
221	if st != stResolved {
222		uri, _ := core.TokenURI(cid, tid)
223		return uri
224	}
225	if r.art.Kind != media.KindChain {
226		return ""
227	}
228	return assets.ArtworkDataURI(r.store, r.art.Index)
229}
230
231// Assignment is the typed TokenArtwork for other realms (gallery): ready is
232// false before Final or when the collection is not ready; a is a copy.
233func Assignment(cid, tid string) (ready bool, slot, edition int64, a media.Artwork) {
234	_, r, st := mustReadToken(cid, tid)
235	if st != stResolved {
236		return false, 0, 0, media.Artwork{}
237	}
238	return true, r.slot, r.edition, r.art
239}
240
241// TokenArtwork is the token's assignment as JSON:
242// {collection, tid, revealed, ready, reason} and, once revealed and ready,
243// {store, artwork, slot, edition, editions, assignment, kind, mime, mimeType,
244// size, sha256, digest, cid, uri, tier, tierSource, title, traits}.
245// uri is "ipfs://<cid>" for IPFS art and "" for on-chain art (read its bytes
246// with TokenImage / TokenURI: base64 of up to 256 KiB is not free).
247func TokenArtwork(cid, tid string) string {
248	c, r, st := mustReadToken(cid, tid)
249	_, reason := c.status()
250	w := &safe.JSONWriter{}
251	w.BeginObject()
252	w.StrField("collection", cid)
253	w.StrField("tid", tid)
254	w.BoolField("revealed", c.info.State == types.StateFinal)
255	w.BoolField("ready", st == stResolved)
256	w.StrField("reason", reason)
257	if st == stResolved {
258		a := r.art
259		w.StrField("store", r.store)
260		w.IntField("artwork", a.Index)
261		w.IntField("slot", r.slot)
262		w.IntField("edition", r.edition)
263		w.IntField("editions", a.Editions)
264		w.StrField("assignment", assignmentMode(r.si))
265		w.StrField("kind", media.KindName(a.Kind))
266		w.StrField("mime", media.MimeName(a.Mime))
267		w.StrField("mimeType", media.MimeType(a.Mime))
268		w.IntField("size", a.Size)
269		w.StrField("sha256", a.SHA256)
270		w.StrField("digest", a.Digest)
271		w.StrField("cid", a.CID)
272		if a.Kind == media.KindChain {
273			w.StrField("uri", "")
274		} else {
275			w.StrField("uri", "ipfs://"+a.CID)
276		}
277		w.StrField("tier", a.Tier)
278		w.StrField("tierSource", "creator")
279		w.StrField("title", a.Title)
280		w.Key("traits")
281		w.Raw(realTraitsJSON(r))
282	}
283	w.EndObject()
284	return w.String()
285}
286
287func assignmentMode(si media.StoreInfo) string {
288	if si.Artworks == 1 {
289		return "edition"
290	}
291	return "shuffled"
292}
293
294// realTraits are the upload-path attributes with the creator's real type
295// names: Tier, the creator's traits in store order, Edition (when the
296// artwork has more than one) and Storage.
297func realTraits(r resolved) []engine.Trait {
298	a := r.art
299	out := []engine.Trait{}
300	if a.Tier != "" {
301		out = append(out, engine.Trait{Type: "Tier", Value: a.Tier})
302	}
303	for k, v := range a.Traits {
304		if v != "" {
305			out = append(out, engine.Trait{Type: r.si.TraitTypes[k], Value: v})
306		}
307	}
308	if a.Editions > 1 {
309		out = append(out, engine.Trait{Type: "Edition", Value: editionLabel(r.edition, a.Editions)})
310	}
311	out = append(out, engine.Trait{Type: "Storage", Value: storageLabel(a.Kind)})
312	return out
313}
314
315var (
316	unrevealed = []engine.Trait{{Type: "Status", Value: "Unrevealed"}}
317	notReady   = []engine.Trait{{Type: "Status", Value: "Not ready"}}
318)
319
320const (
321	unrevealedJSON = `[{"trait_type":"Status","value":"Unrevealed"}]`
322	notReadyJSON   = `[{"trait_type":"Status","value":"Not ready"}]`
323)
324
325// realTraitsJSON is realTraits as JSON, from the names the store escaped
326// once (media.Artwork.TierJSON / TraitsJSON): same bytes as writeTraits of
327// realTraits, without escaping creator text on every read (review UP-M1).
328func realTraitsJSON(r resolved) string {
329	a := r.art
330	parts := make([]string, 0, 4)
331	if a.TierJSON != "" {
332		parts = append(parts, `{"trait_type":"Tier","value":`+a.TierJSON+`}`)
333	}
334	if a.TraitsJSON != "" {
335		parts = append(parts, a.TraitsJSON)
336	}
337	if a.Editions > 1 {
338		parts = append(parts, `{"trait_type":"Edition","value":"`+editionLabel(r.edition, a.Editions)+`"}`)
339	}
340	parts = append(parts, `{"trait_type":"Storage","value":"`+storageLabel(a.Kind)+`"}`)
341	return "[" + strings.Join(parts, ",") + "]"
342}
343
344func writeTraits(w *safe.JSONWriter, ts []engine.Trait) {
345	w.BeginArray()
346	for _, t := range ts {
347		w.BeginObject()
348		w.StrField("trait_type", t.Type)
349		w.StrField("value", t.Value)
350		w.EndObject()
351	}
352	w.EndArray()
353}
354
355// TokenTraitList is the typed real-name trait list of one token (a copy).
356func TokenTraitList(cid, tid string) []engine.Trait {
357	_, r, st := mustReadToken(cid, tid)
358	switch st {
359	case stHidden:
360		return append([]engine.Trait{}, unrevealed...)
361	case stNotReady:
362		return append([]engine.Trait{}, notReady...)
363	}
364	return realTraits(r)
365}
366
367// TokenTraits is TokenTraitList as [{"trait_type","value"}] JSON.
368func TokenTraits(cid, tid string) string {
369	_, r, st := mustReadToken(cid, tid)
370	switch st {
371	case stHidden:
372		return unrevealedJSON
373	case stNotReady:
374		return notReadyJSON
375	}
376	return realTraitsJSON(r)
377}
378
379// TokenMetadata is the canonical metadata (§10.2). Before Final: core's
380// placeholder image and [{Status: Unrevealed}].
381func TokenMetadata(cid, tid string) string {
382	c, r, st := mustReadToken(cid, tid)
383	w := &safe.JSONWriter{}
384	w.BeginObject()
385	w.StrField("name", c.info.Name+" #"+tid)
386	w.StrField("description", c.info.Description)
387	if st != stResolved {
388		uri, _ := core.TokenURI(cid, tid)
389		w.StrField("image", uri)
390		w.Key("attributes")
391		if st == stHidden {
392			writeTraits(w, unrevealed)
393		} else {
394			writeTraits(w, notReady)
395		}
396		w.EndObject()
397		return w.String()
398	}
399	a := r.art
400	w.StrField("image", artURI(r))
401	w.StrField("image_mime", media.MimeType(a.Mime))
402	w.StrField("image_sha256", a.SHA256)
403	w.IntField("image_size", a.Size)
404	w.Key("attributes")
405	w.Raw(realTraitsJSON(r))
406	w.Key("properties")
407	w.BeginObject()
408	w.StrField("collection", cid)
409	w.StrField("store", r.store)
410	w.IntField("artwork", a.Index)
411	w.StrField("edition", editionLabel(r.edition, a.Editions))
412	if a.Kind == media.KindChain {
413		w.StrField("storage", "onchain")
414	} else {
415		w.StrField("storage", "ipfs")
416		w.StrField("cid", a.CID)
417	}
418	w.StrField("title", a.Title)
419	w.StrField("tier", a.Tier)
420	w.StrField("tierSource", "creator")
421	w.StrField("assignment", assignmentMode(r.si))
422	w.BoolField("fair", core.FairLaunch(cid))
423	w.EndObject()
424	w.EndObject()
425	return w.String()
426}
427
428// TraitLists returns, for tokens offset+1 … offset+limit (limit <=
429// MaxTraitLists, burned tokens skipped), the token ids and their real-name
430// traits. The permutation key is computed once per call.
431func TraitLists(cid string, offset, limit int64) ([]string, [][]engine.Trait) {
432	tids, rs, st := tokenPage(cid, offset, limit, MaxTraitLists)
433	lists := make([][]engine.Trait, len(tids))
434	for i := range tids {
435		switch st {
436		case stHidden:
437			lists[i] = append([]engine.Trait{}, unrevealed...)
438		case stNotReady:
439			lists[i] = append([]engine.Trait{}, notReady...)
440		default:
441			lists[i] = realTraits(rs[i])
442		}
443	}
444	return tids, lists
445}
446
447// TraitJSONLists is TraitLists with each token's traits as a JSON array
448// (the bytes TokenTraits returns), for pages that print them (reader.Cards).
449// limit <= MaxTraitJSONLists.
450func TraitJSONLists(cid string, offset, limit int64) ([]string, []string) {
451	tids, rs, st := tokenPage(cid, offset, limit, MaxTraitJSONLists)
452	out := make([]string, len(tids))
453	for i := range tids {
454		switch st {
455		case stHidden:
456			out[i] = unrevealedJSON
457		case stNotReady:
458			out[i] = notReadyJSON
459		default:
460			out[i] = realTraitsJSON(rs[i])
461		}
462	}
463	return tids, out
464}
465
466// tokenPage resolves tokens offset+1 … offset+limit (limit <= max, burned
467// skipped) with one permutation key per call and one record read per
468// distinct artwork. st is stHidden before Final, stNotReady when the
469// collection is Final but not ready, else stResolved.
470func tokenPage(cid string, offset, limit, max int64) ([]string, []resolved, int) {
471	c := mustUpload(cid)
472	if limit <= 0 || limit > max {
473		limit = max
474	}
475	if offset < 0 {
476		offset = 0
477	}
478	st := stHidden
479	key := ""
480	if c.info.State == types.StateFinal {
481		st = stNotReady
482		if ready, _ := c.status(); ready {
483			if salt := saltOf(cid, c.b); salt != "" {
484				key = keyOf(cid, c.b, salt)
485				st = stResolved
486			}
487		}
488	}
489	cache := map[int64]media.Artwork{}
490	var tids []string
491	var rs []resolved
492	for n := offset + 1; n <= c.info.Minted && n <= offset+limit; n++ {
493		tid := strconv.FormatInt(n, 10)
494		if _, err := core.OwnerOf(cid, tid); err != nil {
495			continue // burned
496		}
497		tids = append(tids, tid)
498		if st == stResolved {
499			rs = append(rs, assign(cid, tid, n, c.info, c.store, c.si, key, cache))
500		}
501	}
502	return tids, rs, st
503}
504
505// TraitCounts is {"n": tokens counted, "counts": {type: {value: count}}}
506// over tokens offset+1 … offset+limit (limit <= MaxTraitCounts, burned
507// skipped), with the creator's real names: Tier, the creator's trait types
508// (store order, values in dictionary order), Edition, Storage. Before Final
509// every token counts as {"Status": "Unrevealed"}, Final but not ready as
510// {"Status": "Not ready"}. One permutation key per call; the counting runs in
511// assets/v1 over integer ids (review UP-M1).
512func TraitCounts(cid string, offset, limit int64) string {
513	c := mustUpload(cid)
514	if limit <= 0 || limit > MaxTraitCounts {
515		limit = MaxTraitCounts
516	}
517	if offset < 0 {
518		offset = 0
519	}
520	st := stHidden
521	key := ""
522	if c.info.State == types.StateFinal {
523		st = stNotReady
524		if ready, _ := c.status(); ready {
525			if salt := saltOf(cid, c.b); salt != "" {
526				key = keyOf(cid, c.b, salt)
527				st = stResolved
528			}
529		}
530	}
531	var n int64
532	var idxs, eds []int64
533	for t := offset + 1; t <= c.info.Minted && t <= offset+limit; t++ {
534		if _, err := core.OwnerOf(cid, strconv.FormatInt(t, 10)); err != nil {
535			continue // burned
536		}
537		n++
538		if st == stResolved {
539			idx, ed := assets.SlotArtwork(c.store, media.Slot(key, c.si.Artworks, c.si.Slots, t))
540			idxs = append(idxs, idx)
541			eds = append(eds, ed)
542		}
543	}
544	head := `{"n":` + strconv.FormatInt(n, 10) + `,"counts":{`
545	switch {
546	case n == 0:
547		return head + `}}`
548	case st == stHidden:
549		return head + `"Status":{"Unrevealed":` + strconv.FormatInt(n, 10) + `}}}`
550	case st == stNotReady:
551		return head + `"Status":{"Not ready":` + strconv.FormatInt(n, 10) + `}}}`
552	}
553	return head + assets.CountsJSON(c.store, idxs, eds) + `}}`
554}
555
556// TraitsBatch is [{tid, traits:[{trait_type, value}]}] for tokens
557// offset+1 … offset+limit (limit <= MaxTraitsBatch), burned tokens skipped.
558func TraitsBatch(cid string, offset, limit int64) string {
559	tids, lists := traitJSONPage(cid, offset, limit, MaxTraitsBatch)
560	parts := make([]string, len(tids))
561	for i, tid := range tids {
562		parts[i] = `{"tid":"` + tid + `","traits":` + lists[i] + `}`
563	}
564	return "[" + strings.Join(parts, ",") + "]"
565}
566
567func traitJSONPage(cid string, offset, limit, max int64) ([]string, []string) {
568	if limit <= 0 || limit > max {
569		limit = max
570	}
571	return TraitJSONLists(cid, offset, limit)
572}
573
574// Render stays minimal; uploaded collections are browsed in the gallery.
575func Render(path string) string {
576	return "# Sinopia Upload engine\n\n" + strconv.Itoa(byCID.Size()) +
577		" collections bound to sealed asset stores. Each token shows the artwork of its slot, assigned by a " +
578		"permutation keyed by the collection's final salt; tiers and traits are assigned by the creator.\n"
579}