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

13.55 Kb · 414 lines
  1package assets
  2
  3import (
  4	"encoding/base64"
  5	"strconv"
  6	"strings"
  7
  8	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/media/v1"
  9	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
 10)
 11
 12// Every function in this file is read-only. The artwork set of a store is
 13// public by design (D8: on-chain and plain IPFS art cannot be hidden); the
 14// site shows only the set composition before a collection's reveal.
 15
 16func StoreCount() int64 { return storeCount }
 17
 18// Info is the typed store header for other realms (a copy).
 19func Info(storeID string) media.StoreInfo {
 20	s := mustStore(storeID)
 21	return media.StoreInfo{
 22		ID:           s.idStr(),
 23		Owner:        s.owner,
 24		Label:        s.label,
 25		Sealed:       s.sealed,
 26		SealedHeight: s.sealedHeight,
 27		Artworks:     s.n,
 28		Slots:        s.slots,
 29		OnchainN:     s.onchainN,
 30		IPFSN:        s.ipfsN,
 31		OnchainBytes: s.onchainBytes,
 32		TraitTypes:   append([]string{}, s.traitTypes...),
 33		Tiers:        append([]string{}, s.tiers...),
 34	}
 35}
 36
 37// Store is the store header as JSON: {id, owner, label, state, createdHeight,
 38// sealedHeight, artworks, slots, onchainN, ipfsN, onchainBytes, received,
 39// complete, nextUpload, badge, traitTypes, tiers}. received = on-chain bytes
 40// stored so far; nextUpload = index of the artwork AppendBytes expects next
 41// (-1 when every on-chain artwork is complete); badge = media.Badge.
 42func Store(storeID string) string {
 43	s := mustStore(storeID)
 44	w := &safe.JSONWriter{}
 45	w.BeginObject()
 46	w.StrField("id", s.idStr())
 47	w.StrField("owner", s.owner.String())
 48	w.StrField("label", s.label)
 49	if s.sealed {
 50		w.StrField("state", "sealed")
 51	} else {
 52		w.StrField("state", "draft")
 53	}
 54	w.IntField("createdHeight", s.createdHeight)
 55	w.IntField("sealedHeight", s.sealedHeight)
 56	w.IntField("artworks", s.n)
 57	w.IntField("slots", s.slots)
 58	w.IntField("onchainN", s.onchainN)
 59	w.IntField("ipfsN", s.ipfsN)
 60	w.IntField("onchainBytes", s.onchainBytes)
 61	w.IntField("received", s.logLen)
 62	w.BoolField("complete", s.logLen == s.onchainBytes)
 63	w.IntField("nextUpload", s.nextUpload())
 64	w.StrField("badge", media.Badge(s.onchainN, s.ipfsN))
 65	w.Key("traitTypes")
 66	w.Raw("[" + strings.Join(s.names[:len(s.traitTypes)], ",") + "]")
 67	w.Key("tiers")
 68	w.Raw("[" + strings.Join(s.names[len(s.traitTypes):], ",") + "]")
 69	w.EndObject()
 70	return w.String()
 71}
 72
 73// nextUpload is the on-chain artwork AppendBytes expects next, -1 when all
 74// are complete. O(1): bytes arrive in artwork order (chainIdx, chainDone).
 75func (s *store) nextUpload() int64 {
 76	if s.chainDone >= s.onchainN {
 77		return -1
 78	}
 79	return getU32(s.chainIdx, int(s.chainDone)*4)
 80}
 81
 82// ArtworkAt is the typed artwork record (a copy).
 83func ArtworkAt(storeID string, idx int64) media.Artwork {
 84	s := mustStore(storeID)
 85	return s.artwork(s.assertIdx(idx))
 86}
 87
 88// ArtworkMeta is ArtworkAt without SHA256, Digest and CID (left ""): the
 89// cheap form for trait reads (a CID costs ~1.4M gas to encode in the VM).
 90func ArtworkMeta(storeID string, idx int64) media.Artwork {
 91	s := mustStore(storeID)
 92	return s.artworkMeta(s.assertIdx(idx))
 93}
 94
 95func (s *store) assertIdx(idx int64) int64 {
 96	if idx < 0 || idx >= s.n {
 97		panic("no artwork " + strconv.FormatInt(idx, 10) + " in store " + s.idStr())
 98	}
 99	return idx
100}
101
102func (s *store) artwork(idx int64) media.Artwork {
103	b, i := s.bucketOf(idx)
104	r := decodeRecord(b.raw(i))
105	a := s.meta(b, i, idx, &r)
106	a.SHA256, a.Digest, a.CID = r.shaHex(), r.digestHex(), r.cid()
107	return a
108}
109
110func (s *store) artworkMeta(idx int64) media.Artwork {
111	b, i := s.bucketOf(idx)
112	r := decodeRecord(b.raw(i))
113	return s.meta(b, i, idx, &r)
114}
115
116func (s *store) meta(b *bucket, i int, idx int64, r *record) media.Artwork {
117	a := media.Artwork{
118		Index:    idx,
119		Kind:     r.kind,
120		Mime:     r.mime,
121		Size:     r.size,
122		Have:     r.have,
123		Editions: r.editions,
124		SlotEnd:  r.slotEnd,
125		Title:    b.title(i),
126		Tier:     s.tierName(r.tier),
127		Traits:   make([]string, len(s.traitTypes)),
128		Complete: r.complete(),
129	}
130	var js []string
131	for k := range s.traitTypes {
132		if id := r.traits[k]; id > 0 {
133			e := s.dict[id-1]
134			a.Traits[k] = e.v
135			js = append(js, `{"trait_type":`+s.names[k]+`,"value":`+e.js+`}`)
136		}
137	}
138	a.TraitsJSON = strings.Join(js, ",")
139	if r.tier > 0 {
140		a.TierJSON = s.names[len(s.traitTypes)+r.tier-1]
141	}
142	return a
143}
144
145// Artworks is one page of records as JSON (limit <= MaxPage = 20):
146// [{index, kind, mime, mimeType, size, have, complete, editions, slotStart,
147// slotEnd, sha256, digest, cid, title, tier, traits:[{trait_type,value}]}].
148// kind is "chain" | "ipfs"; digest is the dag-pb root ("" otherwise); cid is
149// "" for on-chain artworks. Built from parts escaped once at write time
150// (type names, tiers, trait values) and joined once (UP-M1).
151func Artworks(storeID string, offset, limit int64) string {
152	s := mustStore(storeID)
153	if limit <= 0 || limit > MaxPage {
154		limit = MaxPage
155	}
156	if offset < 0 {
157		offset = 0
158	}
159	parts := make([]string, 0, limit)
160	for idx := offset; idx < s.n && idx < offset+limit; idx++ {
161		parts = append(parts, s.artworkJSON(idx))
162	}
163	return "[" + strings.Join(parts, ",") + "]"
164}
165
166// ArtworkJSON is the JSON object of one artwork (also used by the
167// upload engine's reads so both realms emit one shape).
168func ArtworkJSON(storeID string, idx int64) string {
169	s := mustStore(storeID)
170	return s.artworkJSON(s.assertIdx(idx))
171}
172
173func (s *store) artworkJSON(idx int64) string {
174	b, i := s.bucketOf(idx)
175	r := decodeRecord(b.raw(i))
176	tier := `""`
177	if r.tier > 0 {
178		tier = s.names[len(s.traitTypes)+r.tier-1]
179	}
180	traits := make([]string, 0, len(s.traitTypes))
181	for k := range s.traitTypes {
182		if id := r.traits[k]; id > 0 {
183			traits = append(traits, `{"trait_type":`+s.names[k]+`,"value":`+s.dict[id-1].js+`}`)
184		}
185	}
186	return `{"index":` + itoa(idx) +
187		`,"kind":"` + media.KindName(r.kind) + `","mime":"` + media.MimeName(r.mime) + `","mimeType":"` + media.MimeType(r.mime) +
188		`","size":` + itoa(r.size) + `,"have":` + itoa(r.have) + `,"complete":` + strconv.FormatBool(r.complete()) +
189		`,"editions":` + itoa(r.editions) + `,"slotStart":` + itoa(r.slotEnd-r.editions) + `,"slotEnd":` + itoa(r.slotEnd) +
190		`,"sha256":"` + r.shaHex() + `","digest":"` + r.digestHex() + `","cid":"` + r.cid() +
191		`","title":` + jsonStr(b.title(i)) + `,"tier":` + tier + `,"traits":[` + strings.Join(traits, ",") + `]}`
192}
193
194func itoa(n int64) string { return strconv.FormatInt(n, 10) }
195
196// ArtworkBytes is the raw file of a complete on-chain artwork, "" for an
197// incomplete or IPFS one. Only complete files passed sha256 + CheckImage.
198func ArtworkBytes(storeID string, idx int64) string {
199	s := mustStore(storeID)
200	b, i := s.bucketOf(s.assertIdx(idx))
201	r := decodeRecord(b.raw(i))
202	if r.kind != media.KindChain || !r.complete() {
203		return ""
204	}
205	return s.readLog(r.logOff, r.size)
206}
207
208// ArtworkDataURI is "data:<mime>;base64,…" for a complete on-chain artwork,
209// "" otherwise. mime is one of the four checked types (ENG-I3: no
210// free-form media type ever reaches a data URI).
211func ArtworkDataURI(storeID string, idx int64) string {
212	s := mustStore(storeID)
213	b, i := s.bucketOf(s.assertIdx(idx))
214	r := decodeRecord(b.raw(i))
215	if r.kind != media.KindChain || !r.complete() {
216		return ""
217	}
218	return "data:" + media.MimeType(r.mime) + ";base64," +
219		base64.StdEncoding.EncodeToString([]byte(s.readLog(r.logOff, r.size)))
220}
221
222// SlotArtwork maps a slot (0..slots-1) to its artwork index and 1-based
223// edition: artwork i covers [slotEnd(i-1), slotEnd(i)). O(log n).
224func SlotArtwork(storeID string, slot int64) (idx, edition int64) {
225	s := mustStore(storeID)
226	if slot < 0 || slot >= s.slots {
227		panic("slot " + strconv.FormatInt(slot, 10) + " out of range 0.." + strconv.FormatInt(s.slots-1, 10))
228	}
229	if s.slots == s.n { // every artwork has one edition
230		return slot, 1
231	}
232	var cached *bucket
233	cachedKey := int64(-1)
234	end := func(idx int64) int64 {
235		if bk := idx / bucketSize; bk != cachedKey {
236			cached, _ = s.bucketOf(idx)
237			cachedKey = bk
238		}
239		return getU32(cached.raw(int(idx%bucketSize)), offSlotEnd)
240	}
241	lo, hi := int64(0), s.n-1
242	for lo < hi {
243		mid := (lo + hi) / 2
244		if end(mid) > slot {
245			hi = mid
246		} else {
247			lo = mid + 1
248		}
249	}
250	b, i := s.bucketOf(lo)
251	raw := b.raw(i)
252	return lo, slot - (getU32(raw, offSlotEnd) - getU32(raw, offEditions)) + 1
253}
254
255// Composition is the set composition (design §8, D8 "drop table") as JSON:
256// {store, sealed, artworks, slots,
257//  tiers:[{name, artworks, slots}] (low -> high), untiered:{artworks, slots},
258//  traits:[{trait_type, values:[{value, artworks, slots}], none:{artworks, slots}}]}.
259// "slots" counts editions, i.e. the odds of a token: slots/total slots.
260// O(tiers + distinct values): the counters are kept by AddArtworks /
261// Truncate and the names are escaped once, so the largest store the limits
262// allow stays far below the query gas cap (UP-M1).
263func Composition(storeID string) string {
264	s := mustStore(storeID)
265	t := len(s.tiers)
266	nt := len(s.traitTypes)
267	tiers := make([]string, t)
268	for i := 0; i < t; i++ {
269		tiers[i] = `{"name":` + s.names[nt+i] + `,` + countPair(s.cnt[i+1], s.cnt[t+2+i]) + `}`
270	}
271	vals := make([][]string, nt)
272	sumA := make([]int64, nt)
273	sumS := make([]int64, nt)
274	base := s.cntBase()
275	for i, e := range s.dict {
276		a, sl := s.cnt[base+2*i], s.cnt[base+2*i+1]
277		sumA[e.k] += a
278		sumS[e.k] += sl
279		if a == 0 {
280			continue // only used by truncated artworks
281		}
282		vals[e.k] = append(vals[e.k], `{"value":`+e.js+`,`+countPair(a, sl)+`}`)
283	}
284	traits := make([]string, nt)
285	for k := 0; k < nt; k++ {
286		traits[k] = `{"trait_type":` + s.names[k] + `,"values":[` + strings.Join(vals[k], ",") + `],"none":{` +
287			countPair(s.n-sumA[k], s.slots-sumS[k]) + `}}`
288	}
289	return `{"store":"` + s.idStr() + `","sealed":` + strconv.FormatBool(s.sealed) + `,"artworks":` + itoa(s.n) +
290		`,"slots":` + itoa(s.slots) + `,"tiers":[` + strings.Join(tiers, ",") + `],"untiered":{` +
291		countPair(s.cnt[0], s.cnt[t+1]) + `},"traits":[` + strings.Join(traits, ",") + `]}`
292}
293
294// CountsJSON aggregates the real-name trait counts of a set of tokens, given
295// each token's artwork index and edition (from SlotArtwork), as the members
296// of a JSON object: "Tier":{tier:n}, then each creator trait type
297// {value:n} in store order, "Edition":{"e/E":n} (artworks with E > 1) and
298// "Storage":{"On-chain"|"IPFS":n}; types and values with no count are left
299// out. Names are the JSON escaped once at write time, values in dictionary
300// order (review UP-M1: no per-read escaping, integer counters only).
301func CountsJSON(storeID string, idx, edition []int64) string {
302	s := mustStore(storeID)
303	if len(idx) != len(edition) {
304		panic("CountsJSON: idx and edition differ in length")
305	}
306	t := len(s.tiers)
307	nt := len(s.traitTypes)
308	tierC := make([]int64, t+1)
309	valC := make([]int64, len(s.dict))
310	var onchain, ipfs int64
311	edC := map[string]int64{}
312	var edOrder []string
313	recs := map[int64]record{}
314	for i, x := range idx {
315		r, ok := recs[x]
316		if !ok {
317			b, j := s.bucketOf(s.assertIdx(x))
318			r = decodeRecord(b.raw(j))
319			recs[x] = r
320		}
321		tierC[r.tier]++
322		for k := 0; k < nt; k++ {
323			if id := r.traits[k]; id > 0 {
324				valC[id-1]++
325			}
326		}
327		if r.kind == media.KindChain {
328			onchain++
329		} else {
330			ipfs++
331		}
332		if r.editions > 1 {
333			label := itoa(edition[i]) + "/" + itoa(r.editions)
334			if _, seen := edC[label]; !seen {
335				edOrder = append(edOrder, label)
336			}
337			edC[label]++
338		}
339	}
340	var members []string
341	var tiers []string
342	for i := 1; i <= t; i++ {
343		if tierC[i] > 0 {
344			tiers = append(tiers, s.names[nt+i-1]+`:`+itoa(tierC[i]))
345		}
346	}
347	if len(tiers) > 0 {
348		members = append(members, `"Tier":{`+strings.Join(tiers, ",")+`}`)
349	}
350	vals := make([][]string, nt)
351	for i, e := range s.dict {
352		if valC[i] > 0 {
353			vals[e.k] = append(vals[e.k], e.js+`:`+itoa(valC[i]))
354		}
355	}
356	for k := 0; k < nt; k++ {
357		if len(vals[k]) > 0 {
358			members = append(members, s.names[k]+`:{`+strings.Join(vals[k], ",")+`}`)
359		}
360	}
361	if len(edOrder) > 0 {
362		eds := make([]string, len(edOrder))
363		for i, l := range edOrder {
364			eds[i] = `"` + l + `":` + itoa(edC[l])
365		}
366		members = append(members, `"Edition":{`+strings.Join(eds, ",")+`}`)
367	}
368	var st []string
369	if onchain > 0 {
370		st = append(st, `"On-chain":`+itoa(onchain))
371	}
372	if ipfs > 0 {
373		st = append(st, `"IPFS":`+itoa(ipfs))
374	}
375	if len(st) > 0 {
376		members = append(members, `"Storage":{`+strings.Join(st, ",")+`}`)
377	}
378	return strings.Join(members, ",")
379}
380
381func countPair(artworks, slots int64) string {
382	return `"artworks":` + itoa(artworks) + `,"slots":` + itoa(slots)
383}
384
385// TierSlots is the typed tier part of Composition: tier names (low ->
386// high), the slots each holds, and the slots of untiered artworks. O(tiers).
387func TierSlots(storeID string) (tiers []string, slots []int64, untiered int64) {
388	s := mustStore(storeID)
389	t := len(s.tiers)
390	return append([]string{}, s.tiers...), append([]int64{}, s.cnt[t+2:2*t+2]...), s.cnt[t+1]
391}
392
393// Render stays minimal and prints no creator text; uploaded collections
394// are browsed in the gallery realm.
395func Render(path string) string {
396	out := "# Sinopia asset stores\n\n" + strconv.FormatInt(storeCount, 10) +
397		" stores. Sealed stores never change; uploaded collections are browsed in the Sinopia gallery.\n"
398	if strings.HasPrefix(path, "s/") {
399		id := strings.TrimPrefix(path, "s/")
400		if n, err := strconv.ParseInt(id, 10, 64); err == nil && n >= 1 && n <= storeCount {
401			s := mustStore(strconv.FormatInt(n, 10))
402			state := "draft"
403			if s.sealed {
404				state = "sealed at height " + strconv.FormatInt(s.sealedHeight, 10)
405			}
406			out += "\n## Store " + s.idStr() + "\n\n- State: " + state +
407				"\n- Artworks: " + strconv.FormatInt(s.n, 10) + " (" + strconv.FormatInt(s.onchainN, 10) +
408				" on-chain, " + strconv.FormatInt(s.ipfsN, 10) + " IPFS)\n- Slots: " + strconv.FormatInt(s.slots, 10) +
409				"\n- On-chain bytes: " + strconv.FormatInt(s.onchainBytes, 10) + "\n- Storage: " +
410				media.Badge(s.onchainN, s.ipfsN) + "\n"
411		}
412	}
413	return out
414}