reader.gno
7.36 Kb · 250 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// Every string goes out through safe.JSONWriter, so stored text can never
7// forge a record (RA H-1: the old TSV reader split on tabs and newlines).
8// Art is never batched: one token per Art call, because SVG rendering is
9// what exhausted the query gas in nftread1 (RA L-9).
10package reader
11
12import (
13 "gno.land/r/sys/users"
14
15 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
16 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
17 "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/core"
18 upload "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/engines/upload"
19 market "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/market/v1"
20)
21
22// Batch limits. Hypothesis (S-4): sized for the genesis engine under the
23// public qeval gas cap; measure on Onyx and lower if a full page runs out.
24const (
25 MaxCards = 50
26 MaxTraitCounts = 500
27 MaxStudio = 200
28 // Uploaded collections carry the creator's real trait names (up to 8 types
29 // of 32 bytes); pages are smaller so the worst store the asset limits allow
30 // stays <= 1B test gas per read (review UP-M1, zz_worst_gas_test.gno).
31 MaxUploadCards = 20
32 MaxUploadTraitCounts = 200
33)
34
35// Cards is one gallery page: [{tid, owner, ownerName, traits, listing}] for
36// tokens offset+1 … offset+limit (limit <= 50; <= 20 for uploaded
37// collections). Burned tokens are skipped; listing is
38// {id, price} or null. Uploaded collections carry the creator's real trait
39// names (upload.TraitLists, one permutation key per page) instead of core's
40// fixed engine slots.
41func Cards(cid string, offset, limit int64) string {
42 info := core.Info(cid)
43 var upTraits map[string]string
44 max := int64(MaxCards)
45 if info.EngineID == upload.SelfPath() {
46 max = MaxUploadCards
47 upTraits = uploadTraits(cid, offset, clamp(limit, max))
48 }
49 w := &safe.JSONWriter{}
50 w.BeginArray()
51 for _, tid := range tokenRange(info.Minted, offset, limit, max) {
52 owner, err := core.OwnerOf(cid, tid)
53 if err != nil {
54 continue // burned
55 }
56 w.BeginObject()
57 w.StrField("tid", tid)
58 w.StrField("owner", owner.String())
59 w.StrField("ownerName", nameOf(owner))
60 w.Key("traits")
61 if upTraits != nil {
62 w.Raw(upTraits[tid]) // JSON escaped once by the store (upload.TraitJSONLists)
63 } else {
64 writeTraits(w, core.TokenTraitList(cid, tid))
65 }
66 w.Key("listing")
67 if id, price, ok := market.ActiveListing(cid, tid); ok {
68 w.BeginObject()
69 w.StrField("id", id)
70 w.IntField("price", price)
71 w.EndObject()
72 } else {
73 w.Raw("null")
74 }
75 w.EndObject()
76 }
77 w.EndArray()
78 return w.String()
79}
80
81// TraitCounts counts trait values over tokens offset+1 … offset+limit:
82// {"n": tokens counted, "counts": {type: {value: count}}} (limit <= 500;
83// <= 200 for uploaded collections). Rarity % for a 1000-token collection
84// takes two calls (five for an uploaded one). Before Final every token reports
85// Status=Unrevealed.
86func TraitCounts(cid string, offset, limit int64) string {
87 info := core.Info(cid)
88 c := newCounter()
89 if info.EngineID == upload.SelfPath() {
90 // creator-assigned tiers and real trait names, counted by the store
91 // over integer ids (burned tokens skipped; order: Tier, the creator's
92 // types, Edition, Storage)
93 return upload.TraitCounts(cid, offset, clamp(limit, MaxUploadTraitCounts))
94 }
95 for _, tid := range tokenRange(info.Minted, offset, limit, MaxTraitCounts) {
96 if _, err := core.OwnerOf(cid, tid); err != nil {
97 continue
98 }
99 c.add(core.TokenTraitList(cid, tid))
100 }
101 return c.json()
102}
103
104// StudioTraits is TraitCounts for an engine and params over n sample seeds
105// (engine.SampleSeed(from) …), for the Studio's rarity preview.
106func StudioTraits(engineID, params string, from, n int64) string {
107 if n <= 0 || n > MaxStudio {
108 n = MaxStudio
109 }
110 if from < 0 {
111 from = 0
112 }
113 c := newCounter()
114 for i := from; i < from+n; i++ {
115 c.add(core.EngineTraits(engineID, params, engine.SampleSeed(int(i))))
116 }
117 return c.json()
118}
119
120// Art is one token's data URI (placeholder before Final).
121func Art(cid, tid string) string {
122 uri, err := core.TokenURI(cid, tid)
123 if err != nil {
124 panic(err)
125 }
126 return uri
127}
128
129func Collections(offset, limit int64) string { return core.Collections(offset, limit) }
130
131// SetComposition passes upload.SetComposition through: slots per
132// creator-assigned tier and trait value over an uploaded collection's set.
133func SetComposition(cid string) string { return upload.SetComposition(cid) }
134
135// UploadStatus passes upload.Status through (mint gating, storage badge).
136func UploadStatus(cid string) string { return upload.Status(cid) }
137
138// Profile is {address, name, collections} for one address. A seller's
139// listings come from the indexer (market "Listed"/"Cancelled" events):
140// market/v1 keeps no per-seller index on chain (storage, M2).
141func Profile(addr address) string {
142 w := &safe.JSONWriter{}
143 w.BeginObject()
144 w.StrField("address", addr.String())
145 w.StrField("name", nameOf(addr))
146 w.Key("collections")
147 w.Raw(core.CollectionsByCreator(addr, 0, MaxCards))
148 w.EndObject()
149 return w.String()
150}
151
152// --- helpers -----------------------------------------------------------------
153
154// nameOf is the r/sys/users name of addr, or "".
155func nameOf(addr address) string {
156 if u := users.ResolveAddress(addr); u != nil {
157 return u.Name()
158 }
159 return ""
160}
161
162func uploadTraits(cid string, offset, limit int64) map[string]string {
163 tids, lists := upload.TraitJSONLists(cid, offset, limit)
164 out := make(map[string]string, len(tids))
165 for i, tid := range tids {
166 out[tid] = lists[i]
167 }
168 return out
169}
170
171func clamp(limit, max int64) int64 {
172 if limit <= 0 || limit > max {
173 return max
174 }
175 return limit
176}
177
178func tokenRange(minted, offset, limit, max int64) []string {
179 if limit <= 0 || limit > max {
180 limit = max
181 }
182 if offset < 0 {
183 offset = 0
184 }
185 var out []string
186 for n := offset + 1; n <= minted && n <= offset+limit; n++ {
187 out = append(out, itoa(n))
188 }
189 return out
190}
191
192func writeTraits(w *safe.JSONWriter, ts []engine.Trait) {
193 w.BeginArray()
194 for _, t := range ts {
195 w.BeginObject()
196 w.StrField("trait_type", t.Type)
197 w.StrField("value", t.Value)
198 w.EndObject()
199 }
200 w.EndArray()
201}
202
203// counter keeps first-seen order so the JSON is deterministic.
204type counter struct {
205 n int64
206 types []string
207 values map[string][]string // type -> values in first-seen order
208 counts map[string]map[string]int64 // type -> value -> count
209}
210
211func newCounter() *counter {
212 return &counter{values: map[string][]string{}, counts: map[string]map[string]int64{}}
213}
214
215func (c *counter) add(ts []engine.Trait) {
216 c.n++
217 for _, t := range ts {
218 byValue, ok := c.counts[t.Type]
219 if !ok {
220 byValue = map[string]int64{}
221 c.counts[t.Type] = byValue
222 c.types = append(c.types, t.Type)
223 }
224 if _, seen := byValue[t.Value]; !seen {
225 c.values[t.Type] = append(c.values[t.Type], t.Value)
226 }
227 byValue[t.Value]++
228 }
229}
230
231func (c *counter) json() string {
232 w := &safe.JSONWriter{}
233 w.BeginObject()
234 w.IntField("n", c.n)
235 w.Key("counts")
236 w.BeginObject()
237 for _, typ := range c.types {
238 w.Key(typ)
239 w.BeginObject()
240 for _, v := range c.values[typ] {
241 w.IntField(v, c.counts[typ][v])
242 }
243 w.EndObject()
244 }
245 w.EndObject()
246 w.EndObject()
247 return w.String()
248}
249
250func itoa(n int64) string { return safe.PadInt(n, 1) }