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.

reader.gno

8.73 Kb · 276 lines
  1// Package reader is the batch JSON read API for the frontend and the
  2// aggregator (design §2.5.6). It is private (re-deployable in place, no
  3// other realm may import it) and holds no state or money: everything comes
  4// from core, market and r/sys/users.
  5//
  6// sinopia4 (mainnet plan M-30): art, traits and metadata are read through
  7// core only — core serves media engines' files and per-collection trait
  8// names — so the reader imports no engine or upload realm and ships in the
  9// first package wave. Upload-only views (drop table, readiness, storage
 10// badge) are read by the frontend from the upload adapter itself.
 11//
 12// Every string goes out through safe.JSONWriter, so stored text can never
 13// forge a record (RA H-1: the old TSV reader split on tabs and newlines).
 14// Art is never batched: one token per Art call, because SVG rendering is
 15// what exhausted the query gas in nftread1 (RA L-9).
 16package reader
 17
 18import (
 19	"strings"
 20
 21	"gno.land/r/sys/users"
 22
 23	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
 24	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
 25	"gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/core"
 26	market "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/market/v1"
 27)
 28
 29// Batch limits. Hypothesis (S-4): sized for the genesis engine under the
 30// public qeval gas cap; measure on Onyx and lower if a full page runs out.
 31const (
 32	MaxCards       = 50
 33	MaxTraitCounts = 500
 34	MaxStudio      = 200
 35	// Collections of media engines (uploads: the creator's real trait names,
 36	// up to 8 types of 20 bytes and values of 32, read per token through
 37	// core since sinopia4, M-30) get smaller pages. assets/v1 refuses
 38	// < > & " \ in stored text (WP-Z), so core's JSON escaping of upload
 39	// traits stays cheap; what remains is the per-token fetch through core
 40	// (adapter Traits + ValidateTraitsFor, ~11M per token on the worst
 41	// store). Worst store (zz_worst_gas_test.gno, run wpz-1): Cards(20)
 42	// 629M, TraitCounts(50) 658M (100: 1.18B, 200: 2.26B). The site counts
 43	// rarity from Cards pages of 20 (frontend realms.live traitCounts). The
 44	// reader is re-deployable in place.
 45	MaxUploadCards       = 20
 46	MaxUploadTraitCounts = 50
 47	// Studio rarity over a Katman store kit: each sample's traits read up
 48	// to 8 SlotArtwork + ArtworkMeta from the store (~17.3M on the largest
 49	// kit, docs/engines/katman.md), so 200 samples would be ~4B.
 50	MaxKitStudio = 50
 51)
 52
 53// kitEngine is the Katman adapter (engines/katman next to this reader,
 54// derived from this realm's own path so staging needs no rewrite). Its
 55// collections read their traits from an assets/v1 store per token
 56// (~17.3M per token on the largest kit, ~1-2M for generative engines):
 57// TraitCounts(500) would be ~8.7B, over the 3B query cap, so they get the
 58// media page sizes (Cards 20, TraitCounts 50: <= ~0.9B). It is an svg
 59// engine, so isMedia alone does not catch it.
 60var kitEngine string
 61
 62func init(cur realm) {
 63	kitEngine = strings.TrimSuffix(cur.PkgPath(), "/reader") + "/engines/katman"
 64}
 65
 66// Cards is one gallery page: [{tid, owner, ownerName, traits, listing}] for
 67// tokens offset+1 … offset+limit (limit <= 50; <= 20 for collections of
 68// media engines and of the Katman kit engine). Burned tokens are skipped; listing is {id, price} or
 69// null. Traits are core.TokenTraitList: checked against the collection's own
 70// trait list (an upload's real trait names, sinopia4 M-6).
 71func Cards(cid string, offset, limit int64) string {
 72	info := core.Info(cid)
 73	max := int64(MaxCards)
 74	if smallPages(info.EngineID) {
 75		max = MaxUploadCards
 76	}
 77	w := &safe.JSONWriter{}
 78	w.BeginArray()
 79	for _, tid := range tokenRange(info.Minted, offset, limit, max) {
 80		owner, err := core.OwnerOf(cid, tid)
 81		if err != nil {
 82			continue // burned
 83		}
 84		w.BeginObject()
 85		w.StrField("tid", tid)
 86		w.StrField("owner", owner.String())
 87		w.StrField("ownerName", nameOf(owner))
 88		w.Key("traits")
 89		writeTraits(w, core.TokenTraitList(cid, tid))
 90		w.Key("listing")
 91		if id, price, ok := market.ActiveListing(cid, tid); ok {
 92			w.BeginObject()
 93			w.StrField("id", id)
 94			w.IntField("price", price)
 95			w.EndObject()
 96		} else {
 97			w.Raw("null")
 98		}
 99		w.EndObject()
100	}
101	w.EndArray()
102	return w.String()
103}
104
105// TraitCounts counts trait values over tokens offset+1 … offset+limit:
106// {"n": tokens counted, "counts": {type: {value: count}}} (limit <= 500;
107// <= 50 for collections of media engines and of the Katman kit engine). Rarity % for a 1000-token
108// collection takes two calls (twenty for an upload). Before Final every token
109// reports Status=Unrevealed. Types and values in first-seen order.
110func TraitCounts(cid string, offset, limit int64) string {
111	info := core.Info(cid)
112	c := newCounter()
113	max := int64(MaxTraitCounts)
114	if smallPages(info.EngineID) {
115		max = MaxUploadTraitCounts
116	}
117	for _, tid := range tokenRange(info.Minted, offset, limit, max) {
118		if _, err := core.OwnerOf(cid, tid); err != nil {
119			continue
120		}
121		c.add(core.TokenTraitList(cid, tid))
122	}
123	return c.json()
124}
125
126// StudioTraits is TraitCounts for an engine and params over n sample seeds
127// (engine.SampleSeed(from) …), for the Studio's rarity preview (n <= 200;
128// <= 50 for the Katman kit engine).
129func StudioTraits(engineID, params string, from, n int64) string {
130	max := int64(MaxStudio)
131	if engineID == kitEngine {
132		max = MaxKitStudio
133	}
134	if n <= 0 || n > max {
135		n = max
136	}
137	if from < 0 {
138		from = 0
139	}
140	c := newCounter()
141	for i := from; i < from+n; i++ {
142		c.add(core.EngineTraits(engineID, params, engine.SampleSeed(int(i))))
143	}
144	return c.json()
145}
146
147// Art is one token's core.TokenURI (placeholder before Final): an SVG or
148// raster data URI, or the "ipfs://<CIDv1>" of an IPFS-stored file (I-15).
149func Art(cid, tid string) string {
150	uri, err := core.TokenURI(cid, tid)
151	if err != nil {
152		panic(err)
153	}
154	return uri
155}
156
157// Card is one token's checked SVG card data URI (core.TokenCard): the art
158// of an SVG engine, the certificate card of a media engine; never remote.
159func Card(cid, tid string) string {
160	uri, err := core.TokenCard(cid, tid)
161	if err != nil {
162		panic(err)
163	}
164	return uri
165}
166
167func Collections(offset, limit int64) string { return core.Collections(offset, limit) }
168
169// Profile is {address, name, collections} for one address. A seller's
170// listings come from the indexer (market "Listed"/"Cancelled" events):
171// market/v1 keeps no per-seller index on chain (storage, M2).
172func Profile(addr address) string {
173	w := &safe.JSONWriter{}
174	w.BeginObject()
175	w.StrField("address", addr.String())
176	w.StrField("name", nameOf(addr))
177	w.Key("collections")
178	w.Raw(core.CollectionsByCreator(addr, 0, MaxCards))
179	w.EndObject()
180	return w.String()
181}
182
183// --- helpers -----------------------------------------------------------------
184
185// nameOf is the r/sys/users name of addr, or "".
186func nameOf(addr address) string {
187	if u := users.ResolveAddress(addr); u != nil {
188		return u.Name()
189	}
190	return ""
191}
192
193// smallPages: collections whose per-token traits are expensive (media
194// engines, the Katman kit engine) get the small page sizes.
195func smallPages(engineID string) bool {
196	return engineID == kitEngine || isMedia(engineID)
197}
198
199// isMedia: the collection's engine serves files (engine/v2 KindMedia).
200func isMedia(engineID string) bool {
201	return core.EngineManifest(engineID).Kind == engine.KindMedia
202}
203
204func tokenRange(minted, offset, limit, max int64) []string {
205	if limit <= 0 || limit > max {
206		limit = max
207	}
208	if offset < 0 {
209		offset = 0
210	}
211	var out []string
212	for n := offset + 1; n <= minted && n <= offset+limit; n++ {
213		out = append(out, itoa(n))
214	}
215	return out
216}
217
218func writeTraits(w *safe.JSONWriter, ts []engine.Trait) {
219	w.BeginArray()
220	for _, t := range ts {
221		w.BeginObject()
222		w.StrField("trait_type", t.Type)
223		w.StrField("value", t.Value)
224		w.EndObject()
225	}
226	w.EndArray()
227}
228
229// counter keeps first-seen order so the JSON is deterministic.
230type counter struct {
231	n      int64
232	types  []string
233	values map[string][]string         // type -> values in first-seen order
234	counts map[string]map[string]int64 // type -> value -> count
235}
236
237func newCounter() *counter {
238	return &counter{values: map[string][]string{}, counts: map[string]map[string]int64{}}
239}
240
241func (c *counter) add(ts []engine.Trait) {
242	c.n++
243	for _, t := range ts {
244		byValue, ok := c.counts[t.Type]
245		if !ok {
246			byValue = map[string]int64{}
247			c.counts[t.Type] = byValue
248			c.types = append(c.types, t.Type)
249		}
250		if _, seen := byValue[t.Value]; !seen {
251			c.values[t.Type] = append(c.values[t.Type], t.Value)
252		}
253		byValue[t.Value]++
254	}
255}
256
257func (c *counter) json() string {
258	w := &safe.JSONWriter{}
259	w.BeginObject()
260	w.IntField("n", c.n)
261	w.Key("counts")
262	w.BeginObject()
263	for _, typ := range c.types {
264		w.Key(typ)
265		w.BeginObject()
266		for _, v := range c.values[typ] {
267			w.IntField(v, c.counts[typ][v])
268		}
269		w.EndObject()
270	}
271	w.EndObject()
272	w.EndObject()
273	return w.String()
274}
275
276func itoa(n int64) string { return safe.PadInt(n, 1) }