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