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.

Playground

config.gno

package upload

// Deploy-time configuration (mainnet plan §2.4 M-27, §5.4): everything that
// differs per chain lives in this file, so staging (WP-H,
// deploy/realms/<chain>.json) rewrites one file. The source carries the
// Onyx values.

// author is the engine author: it signs Register (core's in-source
// reservation of the card fingerprint needs OriginCaller == Manifest.Author
// == the reserved author, I-14) and claims the engine (ClaimEngine). On
// mainnet: the platform engine-author key, never the admin or treasury.
var author = address("g1nm8kd8hsmp6pr7mudj2c3y2hnmnl8awx7vcz4m") // stage:engineAuthor

// Access policy (core I-19, docs/mainnet/engine-access-policy.md): a tool
// engine, "open". Core registers every engine closed; the bootstrap calls
// core.SetEnginePolicy(<this realm>, "open") with the author key right after
// ClaimEngine (deploy/realms/<chain>.json engines.<name>.policy).

gnomod.toml

module = "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engines/upload"
gno = "0.9"

[addpkg]
  creator = "g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06"
  height = 1450578
  max_deposit = "30000000ugnot"

reads.gno

package upload

import (
	"errors"
	"strconv"
	"strings"

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/media/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
	assets "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/assets/v1"
	"gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/core"
)

// Every function in this file is read-only. Every token read returns core's
// placeholder / "Unrevealed" before the collection is Final (T5). Every
// cid argument may be "<cid>" or "c/<cid>" (core's K-1 key); JSON and keys
// carry core's bare id.
//
// Art lives in core since sinopia4: core.TokenURI / TokenCard /
// TokenMediaInfo / TokenMetadata / TokenTraits serve every token through
// this engine's Media/Render/Traits. The reads below are the upload-specific
// views (status, drop table, assignment, batches) plus TokenURI/TokenImage
// kept as thin wrappers of core.TokenURI.

// Readiness reasons (Status.reason).
const (
	ReasonNotUpload      = "not-upload"
	ReasonNoStore        = "no-store"
	ReasonNotSealed      = "store-not-sealed"
	ReasonBoundElsewhere = "bound-elsewhere"
	ReasonSupply         = "supply-mismatch"
	ReasonUnbound        = "unbound"
	ReasonReady          = "ready"
)

type col struct {
	cid     string
	info    types.CollectionInfo
	upload  bool
	store   string // params store id ("" if none or unknown)
	si      media.StoreInfo
	b       *binding // this collection's binding (nil if unbound)
	boundTo string   // collection the store is bound to ("" if none)
}

func loadCol(cid string) col {
	c := col{info: core.Info(cid)}
	c.cid = c.info.ID
	c.upload = c.info.EngineID == selfPath
	if !c.upload {
		return c
	}
	if id, ok := parseParams(c.info.Params); ok && storeExists(id) {
		c.store = id
		c.si = assets.Info(id)
		if v := bound.Get(id); v != nil {
			c.boundTo = v.(string)
		}
	}
	if v := byCID.Get(c.cid); v != nil {
		c.b = v.(*binding)
	}
	return c
}

// salt is the final salt: Settle's cache, else core's (Info.Salt).
func (c *col) salt() string {
	if c.b != nil && c.b.salt != "" {
		return c.b.salt
	}
	return finalSalt(c.info.Salt)
}

// status: ready = bound ∧ store sealed ∧ supply match (§6).
func (c *col) status() (bool, string) {
	switch {
	case !c.upload:
		return false, ReasonNotUpload
	case c.store == "":
		return false, ReasonNoStore
	case !c.si.Sealed:
		return false, ReasonNotSealed
	case c.boundTo != "" && c.boundTo != c.cid:
		return false, ReasonBoundElsewhere
	case c.info.MaxSupply != c.si.Slots:
		return false, ReasonSupply
	case c.b == nil || c.b.store != c.store:
		return false, ReasonUnbound
	}
	return true, ReasonReady
}

func (c *col) badge() string {
	if !c.upload {
		return "computed"
	}
	if ok, _ := c.status(); !ok {
		return "unbound"
	}
	return media.Badge(c.si.OnchainN, c.si.IPFSN)
}

func mustUpload(cid string) col {
	c := loadCol(cid)
	if !c.upload {
		panic("collection " + cid + " does not use the upload engine")
	}
	return c
}

// IsUpload reports whether cid's engine is this adapter.
func IsUpload(cid string) bool { return core.Info(cid).EngineID == selfPath }

// StoreOf is the store named by cid's params ("" if none).
func StoreOf(cid string) string { return loadCol(cid).store }

// Readiness is the typed Status for other realms.
func Readiness(cid string) (ready bool, reason, store, badge string) {
	c := loadCol(cid)
	ready, reason = c.status()
	return ready, reason, c.store, c.badge()
}

// Status is {cid, upload, state, store, bound, ready, reason, badge, settled,
// maxSupply, slots}. The frontend shows the mint UI only when ready (T14).
func Status(cid string) string {
	c := loadCol(cid)
	ready, reason := c.status()
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.StrField("cid", c.cid)
	w.BoolField("upload", c.upload)
	w.StrField("state", c.info.State.String())
	w.StrField("store", c.store)
	w.BoolField("bound", c.b != nil)
	w.BoolField("ready", ready)
	w.StrField("reason", reason)
	w.StrField("badge", c.badge())
	w.BoolField("settled", c.b != nil && c.b.key != "")
	w.IntField("maxSupply", c.info.MaxSupply)
	w.IntField("slots", c.si.Slots)
	w.EndObject()
	return w.String()
}

// StorageBadge is "computed" (any other engine), "onchain", "ipfs",
// "mixed", or "unbound" for an upload collection that is not ready (§9).
func StorageBadge(cid string) string {
	c := loadCol(cid)
	return c.badge()
}

// SetComposition is {collection, store, ready, reason, set}, set =
// assets.Composition of the collection's store: slots per tier and per
// trait value over the planned set (public and fixed before the sale, D8).
func SetComposition(cid string) string {
	c := mustUpload(cid)
	if c.store == "" {
		panic("collection " + cid + " names no store")
	}
	ready, reason := c.status()
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.StrField("collection", c.cid)
	w.StrField("store", c.store)
	w.BoolField("ready", ready)
	w.StrField("reason", reason)
	w.Key("set")
	w.Raw(assets.Composition(c.store))
	w.EndObject()
	return w.String()
}

const (
	stHidden   = 0 // not Final: placeholder
	stNotReady = 1 // Final but not bound/ready: no art
	stResolved = 2
)

func readToken(cid, tid string) (col, resolved, int, error) {
	c := mustUpload(cid)
	if _, err := core.OwnerOf(cid, tid); err != nil {
		return c, resolved{}, stHidden, err
	}
	if c.info.State != types.StateFinal {
		return c, resolved{}, stHidden, nil
	}
	if ok, _ := c.status(); !ok {
		return c, resolved{}, stNotReady, nil
	}
	salt := c.salt()
	if salt == "" {
		return c, resolved{}, stNotReady, nil
	}
	n := tidNum(tid)
	r := assign(c.cid, tid, n, c.info, c.store, c.si, keyOf(c.cid, c.b, salt), nil)
	return c, r, stResolved, nil
}

func mustReadToken(cid, tid string) (col, resolved, int) {
	c, r, st, err := readToken(cid, tid)
	if err != nil {
		panic(err)
	}
	return c, r, st
}

// TokenURI is core.TokenURI of an upload collection (sinopia4: core serves
// the art through Media): "data:<mime>;base64,…" for on-chain art,
// "ipfs://<cidv1>" for IPFS art, core's placeholder before Final. Kept for
// callers of the sinopia3 adapter; read core directly.
func TokenURI(cid, tid string) (string, error) {
	if !IsUpload(cid) {
		return "", errors.New("collection " + cid + " does not use the upload engine")
	}
	return core.TokenURI(cid, tid)
}

// artURI is what core.TokenURI returns for a resolved token (same bytes:
// "data:<mime>;base64,<std base64>" or "ipfs://<cid>").
func artURI(r resolved) string {
	if r.art.Kind == media.KindChain {
		return assets.ArtworkDataURI(r.store, r.art.Index)
	}
	return r.art.URI()
}

// TokenImage is the inline image: core.TokenURI, except "" for IPFS art
// (never a remote URL); core's placeholder before Final. Panics on an
// unknown token or a collection of another engine.
func TokenImage(cid, tid string) string {
	mustUpload(cid)
	uri, err := core.TokenURI(cid, tid)
	if err != nil {
		panic(err)
	}
	if strings.HasPrefix(uri, media.IPFSScheme) {
		return ""
	}
	return uri
}

// Assignment is the typed TokenArtwork for other realms (gallery): ready is
// false before Final or when the collection is not ready; a is a copy.
func Assignment(cid, tid string) (ready bool, slot, edition int64, a media.Artwork) {
	_, r, st := mustReadToken(cid, tid)
	if st != stResolved {
		return false, 0, 0, media.Artwork{}
	}
	return true, r.slot, r.edition, r.art
}

// TokenArtwork is the token's assignment as JSON:
// {collection, tid, revealed, ready, reason} and, once revealed and ready,
// {store, artwork, slot, edition, editions, assignment, kind, mime, mimeType,
// size, sha256, digest, cid, uri, tier, tierSource, title, traits}.
// uri is "ipfs://<cid>" for IPFS art and "" for on-chain art (read its bytes
// with TokenImage / TokenURI: base64 of up to 256 KiB is not free).
func TokenArtwork(cid, tid string) string {
	c, r, st := mustReadToken(cid, tid)
	_, reason := c.status()
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.StrField("collection", c.cid)
	w.StrField("tid", tid)
	w.BoolField("revealed", c.info.State == types.StateFinal)
	w.BoolField("ready", st == stResolved)
	w.StrField("reason", reason)
	if st == stResolved {
		a := r.art
		w.StrField("store", r.store)
		w.IntField("artwork", a.Index)
		w.IntField("slot", r.slot)
		w.IntField("edition", r.edition)
		w.IntField("editions", a.Editions)
		w.StrField("assignment", assignmentMode(r.si))
		w.StrField("kind", media.KindName(a.Kind))
		w.StrField("mime", media.MimeName(a.Mime))
		w.StrField("mimeType", a.MimeType())
		w.BoolField("mimeVerified", a.MimeVerified())
		w.IntField("size", a.Size)
		w.StrField("sha256", a.SHA256)
		w.StrField("digest", a.Digest)
		w.StrField("cid", a.CID)
		w.StrField("uri", a.URI())
		w.StrField("tier", a.Tier)
		w.StrField("tierSource", "creator")
		w.StrField("title", a.Title)
		w.Key("traits")
		w.Raw(realTraitsJSON(r))
	}
	w.EndObject()
	return w.String()
}

func assignmentMode(si media.StoreInfo) string {
	if si.Artworks == 1 {
		return "edition"
	}
	return "shuffled"
}

var (
	unrevealed = []engine.Trait{{Type: "Status", Value: "Unrevealed"}}
	notReady   = []engine.Trait{{Type: "Status", Value: "Not ready"}}
)

const (
	unrevealedJSON = `[{"trait_type":"Status","value":"Unrevealed"}]`
	notReadyJSON   = `[{"trait_type":"Status","value":"Not ready"}]`
)

// realTraitsJSON is realTraits as JSON, from the names the store escaped
// once (media.Artwork.TierJSON / TraitsJSON): same bytes as writeTraits of
// realTraits, without escaping creator text on every read (review UP-M1).
func realTraitsJSON(r resolved) string {
	a := r.art
	parts := make([]string, 0, 4)
	if a.TierJSON != "" {
		parts = append(parts, `{"trait_type":"`+TraitTier+`","value":`+a.TierJSON+`}`)
	}
	if a.TraitsJSON != "" {
		parts = append(parts, a.TraitsJSON)
	}
	if a.Editions > 1 {
		parts = append(parts, `{"trait_type":"`+TraitEdition+`","value":"`+editionLabel(r.edition, a.Editions)+`"}`)
	}
	parts = append(parts, `{"trait_type":"`+TraitStorage+`","value":"`+storageLabel(a.Kind)+`"}`)
	return "[" + strings.Join(parts, ",") + "]"
}

func writeTraits(w *safe.JSONWriter, ts []engine.Trait) {
	w.BeginArray()
	for _, t := range ts {
		w.BeginObject()
		w.StrField("trait_type", t.Type)
		w.StrField("value", t.Value)
		w.EndObject()
	}
	w.EndArray()
}

// TokenTraitList is the typed real-name trait list of one token (a copy).
func TokenTraitList(cid, tid string) []engine.Trait {
	_, r, st := mustReadToken(cid, tid)
	switch st {
	case stHidden:
		return append([]engine.Trait{}, unrevealed...)
	case stNotReady:
		return append([]engine.Trait{}, notReady...)
	}
	return realTraits(r)
}

// TokenTraits is TokenTraitList as [{"trait_type","value"}] JSON.
func TokenTraits(cid, tid string) string {
	_, r, st := mustReadToken(cid, tid)
	switch st {
	case stHidden:
		return unrevealedJSON
	case stNotReady:
		return notReadyJSON
	}
	return realTraitsJSON(r)
}

// TokenMetadata is the upload view of the metadata (§10.2): core's
// TokenMetadata fields plus image_size and properties (store, artwork,
// edition, storage, cid, title, tier, tierSource, assignment, fair,
// mimeVerified). "image" equals core.TokenURI and is written with
// RawStrField (a data URI / ipfs URI needs no escaping: M-4, the 256 KiB PNG
// no longer runs out of gas). mimeVerified (UP-I6) is true only for on-chain
// files, whose type the chain checked; an IPFS file's mime is the creator's
// claim. Before Final: core's placeholder image and [{Status: Unrevealed}].
func TokenMetadata(cid, tid string) string {
	c, r, st := mustReadToken(cid, tid)
	w := &safe.JSONWriter{}
	w.BeginObject()
	w.StrField("name", c.info.Name+" #"+tid)
	w.StrField("description", c.info.Description)
	if st != stResolved {
		uri, _ := core.TokenURI(cid, tid)
		w.RawStrField("image", uri)
		w.Key("attributes")
		if st == stHidden {
			writeTraits(w, unrevealed)
		} else {
			writeTraits(w, notReady)
		}
		w.EndObject()
		return w.String()
	}
	a := r.art
	w.RawStrField("image", artURI(r))
	w.StrField("image_mime", a.MimeType())
	w.StrField("image_sha256", a.SHA256)
	w.IntField("image_size", a.Size)
	w.Key("attributes")
	w.Raw(realTraitsJSON(r))
	w.Key("properties")
	w.BeginObject()
	w.StrField("collection", c.cid)
	w.StrField("store", r.store)
	w.IntField("artwork", a.Index)
	w.StrField("edition", editionLabel(r.edition, a.Editions))
	if a.Kind == media.KindChain {
		w.StrField("storage", "onchain")
	} else {
		w.StrField("storage", "ipfs")
		w.StrField("cid", a.CID)
	}
	w.StrField("title", a.Title)
	w.StrField("tier", a.Tier)
	w.StrField("tierSource", "creator")
	w.StrField("assignment", assignmentMode(r.si))
	w.BoolField("fair", core.FairLaunch(c.cid))
	w.BoolField("mimeVerified", a.MimeVerified())
	w.EndObject()
	w.EndObject()
	return w.String()
}

// TraitLists returns, for tokens offset+1 … offset+limit (limit <=
// MaxTraitLists, burned tokens skipped), the token ids and their real-name
// traits. The permutation key is computed once per call.
func TraitLists(cid string, offset, limit int64) ([]string, [][]engine.Trait) {
	tids, rs, st := tokenPage(cid, offset, limit, MaxTraitLists)
	lists := make([][]engine.Trait, len(tids))
	for i := range tids {
		switch st {
		case stHidden:
			lists[i] = append([]engine.Trait{}, unrevealed...)
		case stNotReady:
			lists[i] = append([]engine.Trait{}, notReady...)
		default:
			lists[i] = realTraits(rs[i])
		}
	}
	return tids, lists
}

// TraitJSONLists is TraitLists with each token's traits as a JSON array
// (the bytes TokenTraits returns), for pages that print them (reader.Cards).
// limit <= MaxTraitJSONLists.
func TraitJSONLists(cid string, offset, limit int64) ([]string, []string) {
	tids, rs, st := tokenPage(cid, offset, limit, MaxTraitJSONLists)
	out := make([]string, len(tids))
	for i := range tids {
		switch st {
		case stHidden:
			out[i] = unrevealedJSON
		case stNotReady:
			out[i] = notReadyJSON
		default:
			out[i] = realTraitsJSON(rs[i])
		}
	}
	return tids, out
}

// tokenPage resolves tokens offset+1 … offset+limit (limit <= max, burned
// skipped) with one permutation key per call and one record read per
// distinct artwork. st is stHidden before Final, stNotReady when the
// collection is Final but not ready, else stResolved.
func tokenPage(cid string, offset, limit, max int64) ([]string, []resolved, int) {
	c := mustUpload(cid)
	if limit <= 0 || limit > max {
		limit = max
	}
	if offset < 0 {
		offset = 0
	}
	st := stHidden
	key := ""
	if c.info.State == types.StateFinal {
		st = stNotReady
		if ready, _ := c.status(); ready {
			if salt := c.salt(); salt != "" {
				key = keyOf(c.cid, c.b, salt)
				st = stResolved
			}
		}
	}
	cache := map[int64]media.Artwork{}
	var tids []string
	var rs []resolved
	for n := offset + 1; n <= c.info.Minted && n <= offset+limit; n++ {
		tid := strconv.FormatInt(n, 10)
		if _, err := core.OwnerOf(cid, tid); err != nil {
			continue // burned
		}
		tids = append(tids, tid)
		if st == stResolved {
			rs = append(rs, assign(c.cid, tid, n, c.info, c.store, c.si, key, cache))
		}
	}
	return tids, rs, st
}

// TraitCounts is {"n": tokens counted, "counts": {type: {value: count}}}
// over tokens offset+1 … offset+limit (limit <= MaxTraitCounts, burned
// skipped), with the creator's real names: Tier, the creator's trait types
// (store order, values in dictionary order), Edition, Storage. Before Final
// every token counts as {"Status": "Unrevealed"}, Final but not ready as
// {"Status": "Not ready"}. One permutation key per call; the counting runs in
// assets/v1 over integer ids (review UP-M1).
func TraitCounts(cid string, offset, limit int64) string {
	c := mustUpload(cid)
	if limit <= 0 || limit > MaxTraitCounts {
		limit = MaxTraitCounts
	}
	if offset < 0 {
		offset = 0
	}
	st := stHidden
	key := ""
	if c.info.State == types.StateFinal {
		st = stNotReady
		if ready, _ := c.status(); ready {
			if salt := c.salt(); salt != "" {
				key = keyOf(c.cid, c.b, salt)
				st = stResolved
			}
		}
	}
	var n int64
	var idxs, eds []int64
	for t := offset + 1; t <= c.info.Minted && t <= offset+limit; t++ {
		if _, err := core.OwnerOf(cid, strconv.FormatInt(t, 10)); err != nil {
			continue // burned
		}
		n++
		if st == stResolved {
			idx, ed := assets.SlotArtwork(c.store, media.Slot(key, c.si.Artworks, c.si.Slots, t))
			idxs = append(idxs, idx)
			eds = append(eds, ed)
		}
	}
	head := `{"n":` + strconv.FormatInt(n, 10) + `,"counts":{`
	switch {
	case n == 0:
		return head + `}}`
	case st == stHidden:
		return head + `"Status":{"Unrevealed":` + strconv.FormatInt(n, 10) + `}}}`
	case st == stNotReady:
		return head + `"Status":{"Not ready":` + strconv.FormatInt(n, 10) + `}}}`
	}
	return head + assets.CountsJSON(c.store, idxs, eds) + `}}`
}

// TraitsBatch is [{tid, traits:[{trait_type, value}]}] for tokens
// offset+1 … offset+limit (limit <= MaxTraitsBatch), burned tokens skipped.
func TraitsBatch(cid string, offset, limit int64) string {
	tids, lists := traitJSONPage(cid, offset, limit, MaxTraitsBatch)
	parts := make([]string, len(tids))
	for i, tid := range tids {
		parts[i] = `{"tid":"` + tid + `","traits":` + lists[i] + `}`
	}
	return "[" + strings.Join(parts, ",") + "]"
}

func traitJSONPage(cid string, offset, limit, max int64) ([]string, []string) {
	if limit <= 0 || limit > max {
		limit = max
	}
	return TraitJSONLists(cid, offset, limit)
}

// Render stays minimal; uploaded collections are browsed in the gallery.
func Render(path string) string {
	return "# Sinopia Upload engine\n\n" + strconv.Itoa(byCID.Size()) +
		" collections bound to sealed asset stores. Each token shows the artwork of its slot, assigned by a " +
		"permutation keyed by the collection's final salt; tiers and traits are assigned by the creator.\n"
}

render.gno

package upload

import (
	"strconv"
	"strings"

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/media/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
)

// cardSVG is the generic card (v2): the registration sample (its sha256 is
// the engine's fingerprint, reserved in core's config.gno, I-14), the
// RenderWith output, and the answer to any call that is not core's real
// render of a revealed, bound token. Changing one byte changes the
// fingerprint: update CardFingerprint, docs/test-vectors (gen-upload-v2.py)
// and core's reserved entry together.
const cardSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">` +
	`<rect width="512" height="512" fill="#16130f"/>` +
	`<rect x="20" y="20" width="472" height="472" fill="none" stroke="#b5332e" stroke-width="3"/>` +
	`<text x="256" y="232" fill="#eeeeee" font-family="monospace" font-size="30" text-anchor="middle">Sinopia Upload</text>` +
	`<text x="256" y="272" fill="#999999" font-family="monospace" font-size="15" text-anchor="middle">art from a sealed asset store</text>` +
	`<text x="256" y="300" fill="#777777" font-family="monospace" font-size="12" text-anchor="middle">media engine v2</text>` +
	`</svg>`

// CardFingerprint = sha256(cardSVG) = the engine's sample fingerprint
// (TestCardFingerprint checks it against core's registration).
const CardFingerprint = "0e414b46db68c64891aadfb4e1fc18ef63d9711907538b659b61b41c7d34efd1"

// certificateSVG is the card of a raster or IPFS artwork: what
// core.TokenCard returns (SVG-only clients, gnoweb) while core.TokenURI
// serves the file itself. Every text is XML-escaped; the document stays far
// below MaxSVGBytes.
func certificateSVG(r resolved) string {
	a := r.art
	title := a.Title
	if title == "" {
		title = "Artwork #" + strconv.FormatInt(a.Index+1, 10)
	}
	tier := "no tier"
	if a.Tier != "" {
		tier = a.Tier + " — creator tier"
	}
	where := strings.ToUpper(media.MimeName(a.Mime)) + " · " + sizeLabel(a.Size) + " · stored on-chain"
	if a.Kind != media.KindChain {
		where = "IPFS · " + strings.ToUpper(media.MimeName(a.Mime)) + " · " + sizeLabel(a.Size)
	}
	var b strings.Builder
	b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">`)
	b.WriteString(`<rect width="512" height="512" fill="#16130f"/>`)
	b.WriteString(`<rect x="16" y="16" width="480" height="480" fill="none" stroke="#b5332e" stroke-width="2"/>`)
	line := func(y int, size int, fill, text string) {
		b.WriteString(`<text x="256" y="` + strconv.Itoa(y) + `" fill="` + fill + `" font-family="monospace" font-size="` +
			strconv.Itoa(size) + `" text-anchor="middle">` + safe.XMLEscape(text) + `</text>`)
	}
	line(78, 24, "#eeeeee", r.info.Name)
	line(116, 20, "#cccccc", "#"+r.tid)
	line(196, 20, "#eeeeee", title)
	line(232, 16, "#d9a441", tier)
	if a.Editions > 1 {
		line(262, 14, "#aaaaaa", "edition "+editionLabel(r.edition, a.Editions))
	}
	line(316, 14, "#aaaaaa", where)
	if a.CID != "" {
		line(340, 11, "#888888", a.CID)
	}
	line(364, 12, "#888888", "sha256 "+a.SHA256[:16]+"…")
	line(452, 11, "#777777", "full image: core TokenURI")
	b.WriteString(`</svg>`)
	return b.String()
}

func sizeLabel(n int64) string {
	if n < 1024 {
		return strconv.FormatInt(n, 10) + " B"
	}
	tenths := (n*10 + 512) / 1024
	return strconv.FormatInt(tenths/10, 10) + "." + strconv.FormatInt(tenths%10, 10) + " KB"
}

upload.gno

// Package upload is the engine/v2 adapter for uploaded collections
// (docs/uploaded-collections.md §5.3, §7–§10, §0a; mainnet plan §2.3, WP-F).
// Core knows it as a media engine (Manifest.Kind "media"): each
// collection's params name one sealed asset store ("store:<id>",
// r/…/assets/v1) and Bind locks that store to the collection while it is a
// Draft. After the reveal every token's art is the artwork of the slot a
// salt-keyed permutation gives it, and core itself serves it:
//
//   - core.TokenURI = Media(in): the checked on-chain file as a data URI
//     (raster or SVG) or "ipfs://<CIDv1>" (I-15);
//   - core.TokenCard = Render(in): the on-chain SVG itself, or a
//     certificate card for raster/IPFS art (SVG-only clients, gnoweb);
//   - core.TokenTraits = Traits(in) with the creator's real trait names,
//     checked by core against TraitTypes(params) (stored per collection);
//   - core.Launch runs CheckLaunch (T14: no launch without a bound store).
//
// What holds, and why:
//   - art theft (T1): ValidateParams accepts a store only when its owner
//     signs the Create tx; Bind needs caller == collection creator == store
//     owner, from a wallet;
//   - no swap after sale (T2): stores are sealed before Bind and never
//     change; params are fixed by core; Bind and Unbind run only while core
//     says Draft, i.e. before any token was ever minted;
//   - one collection per store (T3); slots == maxSupply (T13), checked at
//     Bind and again by CheckLaunch;
//   - unbound launch (T14): CheckLaunch refuses a collection whose store is
//     not bound to it, so core never launches one (closes the residual of
//     docs/uploaded-collections.md T14 for every client);
//   - snipe resistance (T4/T5): before Final core shows its placeholder and
//     never calls Media/Render/Traits; every read here checks Final too; the
//     assignment needs the final salt (core.Salt); Media/Render/Traits
//     answer core's real call only (CollectionID, params and seed must match
//     core's), so RenderWith/TraitsWith (CollectionID "0") always get the
//     generic card and no traits;
//   - SA-L5: core's static payee deny list refuses this realm and assets/v1
//     as payees and treasury at Create and SetPayees (also after Final);
//   - I-12/I-16: Media, Render, Traits, TraitTypes, CheckLaunch and
//     ValidateParams only read; Bind, Unbind and Settle are crossing
//     functions; there is no exported non-crossing mutator.
//
// The adapter is stateful by design (bindings and cached keys), declares
// Living false, takes no fee (D3) and holds no coins.
package upload

import (
	"chain"
	"chain/runtime/unsafe"
	"errors"
	"strconv"
	"strings"

	"gno.land/p/nt/avl/v0"

	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/media/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
	assets "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/assets/v1"
	"gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/core"
)

// Author is the engine author (config.gno).
func Author() address { return author }

// FeeBps is the engine-author fee (D3: none; fixed forever at Register).
const FeeBps = 0

// EngineVersion is Manifest().Version.
const EngineVersion = "2.0.0"

// Trait names the adapter adds itself (assets/v1 reserves them, so a
// creator's trait type can never collide). A collection's trait list is
// TraitTypes(params): Tier (if the store has tiers), the creator's types in
// store order, Edition (if an artwork has editions), Storage.
const (
	TraitTier    = "Tier"
	TraitEdition = "Edition"
	TraitStorage = "Storage"
)

// defaultTraitTypes is Manifest().TraitTypes and TraitTypes(""): core
// stores a collection's list only when it differs from this one.
var defaultTraitTypes = []string{TraitTier, TraitEdition, TraitStorage}

// MaxTraitsBatch bounds TraitsBatch (JSON); MaxTraitLists bounds the typed
// TraitLists. Both compute the permutation key once per call (§0a), never
// per token. Sized so the worst store the asset limits allow stays <= 1B
// test gas per call (review UP-M1; zz_worst_gas_test.gno).
const (
	MaxTraitsBatch    = 20  // JSON
	MaxTraitJSONLists = 20  // typed, JSON per token (reader.Cards)
	MaxTraitLists     = 250 // typed
	MaxTraitCounts    = 200 // TraitCounts (reader.TraitCounts)
)

var (
	selfPath   string
	assetsPath string

	bound avl.Tree // store id -> cid
	byCID avl.Tree // cid -> *binding
)

type binding struct {
	store string
	salt  string // cached by Settle ("" = read core.Salt)
	key   string // media.PermKey(cid, salt), cached by Settle
}

func init(cur realm) {
	selfPath = cur.PkgPath()
	assetsPath = strings.TrimSuffix(selfPath, "/engines/upload") + "/assets/v1"
}

// SelfPath and AssetsPath are the engine id and the store realm it reads.
func SelfPath() string   { return selfPath }
func AssetsPath() string { return assetsPath }

// --- engine/v2 ---------------------------------------------------------------

// impl is zero-size and declared here, so core runs it with this realm's
// authority (interrealm v2 borrow rule #1).
type impl struct{}

func (impl) Manifest() engine.Manifest {
	return engine.Manifest{
		Name:    "Sinopia Upload",
		Version: EngineVersion,
		Description: "Uploaded art: each token shows the artwork of its slot in a sealed asset store (assets/v1), " +
			"assigned by a permutation keyed by the final salt. Media engine: core serves the file itself " +
			"(on-chain data URI or ipfs:// CIDv1). Stateful platform engine (store bindings); tiers and traits are " +
			"assigned by the creator.",
		License:       "artist's own",
		Author:        author,
		TraitTypes:    append([]string{}, defaultTraitTypes...),
		Living:        false,
		MaxSVGBytes:   media.MaxSVGBytes, // the card, and on-chain SVG art as its own card
		FeeBps:        FeeBps,
		Kind:          engine.KindMedia,
		MaxMediaBytes: media.MaxRasterBytes,
	}
}

// ValidateParams accepts "" (registration, Studio) or exactly
// "store:<id>" of an existing, sealed, unbound store whose owner signs this
// transaction (art-theft guard). In qeval there is no signer, so store
// params are refused there: intended (Studio never offers them). No writes.
func (impl) ValidateParams(p string) error {
	if p == "" {
		return nil
	}
	id, ok := parseParams(p)
	if !ok {
		return errors.New("params must be store:<id>")
	}
	if !storeExists(id) {
		return errors.New("unknown store " + id)
	}
	si := assets.Info(id)
	if !si.Sealed {
		return errors.New("store " + id + " is not sealed")
	}
	if v := bound.Get(id); v != nil {
		return errors.New("store " + id + " is already bound to collection " + v.(string))
	}
	if si.Owner != unsafe.OriginCaller() {
		return errors.New("store owner is not the signer")
	}
	return nil
}

// TraitTypes is the trait list of a collection over store params: Tier
// (if the store declares tiers), the store's trait types in order, Edition
// (if some artwork has more than one edition), Storage. The store is
// sealed (ValidateParams), so the list is fixed; core stores it at Create
// (when it differs from the manifest's) and checks every Traits result
// against it. Anything but store params gets the manifest's list.
func (impl) TraitTypes(p string) []string {
	id, ok := parseParams(p)
	if !ok || !storeExists(id) {
		return append([]string{}, defaultTraitTypes...)
	}
	return storeTraitTypes(assets.Info(id))
}

func storeTraitTypes(si media.StoreInfo) []string {
	out := make([]string, 0, len(si.TraitTypes)+3)
	if len(si.Tiers) > 0 {
		out = append(out, TraitTier)
	}
	out = append(out, si.TraitTypes...)
	if si.HasEditions() {
		out = append(out, TraitEdition)
	}
	return append(out, TraitStorage)
}

// CheckLaunch is core's launch gate (T14): the collection must be bound to
// the store its params name, that store sealed, its slots == maxSupply.
// Everything comes from this realm and assets/v1; core is not read.
func (impl) CheckLaunch(cid, params string, maxSupply int64) error {
	id, ok := parseParams(params)
	if !ok {
		return errors.New("collection " + cid + " names no store (params store:<id>)")
	}
	v := byCID.Get(cid)
	if v == nil {
		return errors.New("collection " + cid + " is not bound to store " + id + " (call Bind first)")
	}
	if b := v.(*binding); b.store != id {
		return errors.New("collection " + cid + " is bound to store " + b.store + ", not " + id)
	}
	si := assets.Info(id)
	if !si.Sealed {
		return errors.New("store " + id + " is not sealed")
	}
	if si.Slots != maxSupply {
		return errors.New("maxSupply " + strconv.FormatInt(maxSupply, 10) + " must equal the store's slots " +
			strconv.FormatInt(si.Slots, 10))
	}
	return nil
}

// Media is the token's file for core's real TokenURI call: the on-chain
// bytes (Data + Sha256) or "ipfs://<cid>" (+ the declared Sha256). Media{}
// for anything else (core then shows the card).
func (impl) Media(in engine.Input) engine.Media {
	r, ok := coreResolve(in)
	if !ok {
		return engine.Media{}
	}
	a := r.art
	if a.Kind == media.KindChain {
		return engine.Media{Mime: a.MimeType(), Data: assets.ArtworkBytes(r.store, a.Index), Sha256: a.SHA256}
	}
	return engine.Media{Mime: a.MimeType(), URI: a.URI(), Sha256: a.SHA256}
}

// Render is the token's card: an on-chain SVG artwork is its own card
// (passed AssertSVG(16 KiB) at upload; core re-checks), raster and IPFS art
// get the certificate; anything that is not core's real call gets the
// generic card (registration sample, RenderWith).
func (impl) Render(in engine.Input) string {
	r, ok := coreResolve(in)
	if !ok {
		return cardSVG
	}
	if r.art.Kind == media.KindChain && r.art.Mime == media.MimeSVG {
		return assets.ArtworkBytes(r.store, r.art.Index)
	}
	return certificateSVG(r)
}

// Traits are the real-name attributes (realTraits) for core's real call;
// none for the registration sample / RenderWith; {Storage: Not bound} for a
// Final collection that is not ready (unreachable once CheckLaunch passed).
func (impl) Traits(in engine.Input) []engine.Trait {
	if in.Params == "" || in.CollectionID == "0" {
		return []engine.Trait{}
	}
	r, ok := coreResolve(in)
	if !ok {
		return []engine.Trait{{Type: TraitStorage, Value: "Not bound"}}
	}
	return realTraits(r)
}

// Register is an explicit call (not init: under the inert package policy
// init runs in the approver's tx). The card's fingerprint is reserved in
// core's source for the platform author, so only that key can sign it.
func Register(cur realm) string {
	return core.RegisterEngine(cross(cur), impl{}, "")
}

// --- binding -----------------------------------------------------------------

// Bind locks the collection's store (its params "store:<id>") to the
// collection. Caller == core creator == store owner, from a wallet; core
// state Draft; the collection uses this engine; the store is sealed and not
// bound elsewhere; maxSupply == the store's slots. cid may be "<cid>" or
// "c/<cid>"; the binding is kept under core's bare id. Event
// StoreBound{store, cid}.
func Bind(cur realm, cid string) {
	assertWallet(cur)
	who := cur.Previous().Address()
	info := core.Info(cid)
	cid = info.ID
	assertUploadDraft(info, cid)
	if who != info.Creator {
		panic("only the collection's creator can bind its store")
	}
	id, ok := parseParams(info.Params)
	if !ok || !storeExists(id) {
		panic("collection " + cid + " has no store params (store:<id>)")
	}
	si := assets.Info(id)
	if si.Owner != who {
		panic("only the owner of store " + id + " can bind it")
	}
	if !si.Sealed {
		panic("store " + id + " is not sealed")
	}
	if byCID.Has(cid) {
		panic("collection " + cid + " is already bound")
	}
	if v := bound.Get(id); v != nil {
		panic("store " + id + " is already bound to collection " + v.(string))
	}
	if info.MaxSupply != si.Slots {
		panic("maxSupply " + strconv.FormatInt(info.MaxSupply, 10) + " must equal the store's slots " +
			strconv.FormatInt(si.Slots, 10))
	}
	bound.Set(id, cid)
	byCID.Set(cid, &binding{store: id})
	chain.Emit("StoreBound", "store", id, "cid", cid)
}

// Unbind releases the store while the collection is still a Draft.
// Creator only. Event StoreUnbound{store, cid}.
func Unbind(cur realm, cid string) {
	assertWallet(cur)
	info := core.Info(cid)
	cid = info.ID
	assertUploadDraft(info, cid)
	if cur.Previous().Address() != info.Creator {
		panic("only the collection's creator can unbind its store")
	}
	v := byCID.Get(cid)
	if v == nil {
		panic("collection " + cid + " is not bound")
	}
	id := v.(*binding).store
	byCID.Remove(cid)
	bound.Remove(id)
	chain.Emit("StoreUnbound", "store", id, "cid", cid)
}

// Settle caches the salt and permutation key once the collection is Final.
// Anyone may call it; it is deterministic (the salt is final) and
// idempotent, and it only saves read gas: the lazy path computes the same
// key. Event Settled{cid, key} (first call only).
func Settle(cur realm, cid string) {
	if cur.Previous().IsUserCall() && !unsafe.OriginSend().IsZero() {
		panic("this function does not accept coins")
	}
	info := core.Info(cid)
	cid = info.ID
	if info.EngineID != selfPath {
		panic("collection " + cid + " does not use the upload engine")
	}
	if info.State != types.StateFinal {
		panic("collection " + cid + " is not final yet")
	}
	v := byCID.Get(cid)
	if v == nil {
		panic("collection " + cid + " is not bound to a store")
	}
	b := v.(*binding)
	if b.key != "" {
		return
	}
	salt := finalSalt(info.Salt)
	if salt == "" {
		panic("collection " + cid + " has no final salt")
	}
	b.salt = salt
	b.key = media.PermKey(cid, salt)
	chain.Emit("Settled", "cid", cid, "key", b.key)
}

func assertWallet(cur realm) {
	if !cur.Previous().IsUserCall() {
		panic("call this directly from a wallet")
	}
	if !unsafe.OriginSend().IsZero() {
		panic("this function does not accept coins")
	}
}

func assertUploadDraft(info types.CollectionInfo, cid string) {
	if info.EngineID != selfPath {
		panic("collection " + cid + " does not use the upload engine")
	}
	if info.State != types.StateDraft {
		panic("collection " + cid + " is " + info.State.String() +
			"; stores are bound or unbound only while it is a draft (no token was ever minted)")
	}
}

// finalSalt is core's typed salt (M-5: core.Salt / Info.Salt, "" before
// Final) when it is 64 lower-case hex, else "".
func finalSalt(s string) string {
	if !media.IsHex32(s) {
		return ""
	}
	return s
}

// parseParams accepts exactly "store:<id>" with a canonical decimal id.
func parseParams(p string) (string, bool) {
	if !strings.HasPrefix(p, "store:") {
		return "", false
	}
	id := p[len("store:"):]
	if id == "" || len(id) > 10 || id[0] == '0' {
		return "", false
	}
	for i := 0; i < len(id); i++ {
		if id[i] < '0' || id[i] > '9' {
			return "", false
		}
	}
	return id, true
}

func storeExists(id string) bool {
	n, err := strconv.ParseInt(id, 10, 64)
	return err == nil && n >= 1 && n <= assets.StoreCount()
}

// tidNum is the numeric token id, 0 for a non-canonical one.
func tidNum(tid string) int64 {
	if tid == "" || len(tid) > 12 || tid[0] == '0' {
		return 0
	}
	var n int64
	for i := 0; i < len(tid); i++ {
		c := tid[i]
		if c < '0' || c > '9' {
			return 0
		}
		n = n*10 + int64(c-'0')
	}
	return n
}

// --- resolution ----------------------------------------------------------------

// resolved is one token's assignment.
type resolved struct {
	cid, tid      string
	info          types.CollectionInfo
	store         string
	si            media.StoreInfo
	key           string
	slot, edition int64
	art           media.Artwork
}

// coreResolve answers only core's own TokenURI/TokenCard/TokenTraits call
// for a Final, bound collection: CollectionID, params and seed must be
// exactly what core passes (§7 snipe resistance). Anything else gets the
// card (Media{} / cardSVG).
func coreResolve(in engine.Input) (resolved, bool) {
	var r resolved
	if in.Params == "" || in.CollectionID == "0" {
		return r, false
	}
	v := byCID.Get(in.CollectionID)
	if v == nil {
		return r, false
	}
	b := v.(*binding)
	if in.Params != "store:"+b.store {
		return r, false
	}
	info := core.Info(in.CollectionID)
	if info.ID != in.CollectionID || info.EngineID != selfPath || info.State != types.StateFinal ||
		info.Params != in.Params {
		return r, false
	}
	salt := b.salt
	if salt == "" {
		salt = finalSalt(info.Salt)
	}
	if salt == "" || in.Seed != safe.Seed(in.CollectionID, in.TokenID, salt) {
		return r, false
	}
	n := tidNum(in.TokenID)
	if n < 1 || n > info.MaxSupply {
		return r, false
	}
	return assign(in.CollectionID, in.TokenID, n, info, b.store, assets.Info(b.store), keyOf(in.CollectionID, b, salt), nil), true
}

func keyOf(cid string, b *binding, salt string) string {
	if b.key != "" {
		return b.key
	}
	return media.PermKey(cid, salt)
}

// assign maps token n to its slot, artwork and edition. With a cache (trait
// batches) artworks are read once per batch and without their hashes/CID
// (assets.ArtworkMeta); without one the full record is read.
func assign(cid, tid string, n int64, info types.CollectionInfo, store string, si media.StoreInfo, key string,
	cache map[int64]media.Artwork,
) resolved {
	slot := media.Slot(key, si.Artworks, si.Slots, n)
	idx, edition := assets.SlotArtwork(store, slot)
	var a media.Artwork
	if cache != nil {
		if c, ok := cache[idx]; ok {
			a = c
		} else {
			a = assets.ArtworkMeta(store, idx)
			cache[idx] = a
		}
	} else {
		a = assets.ArtworkAt(store, idx)
	}
	return resolved{cid: cid, tid: tid, info: info, store: store, si: si, key: key, slot: slot, edition: edition, art: a}
}

// realTraits are the upload-path attributes with the creator's real type
// names, in TraitTypes order: Tier, the creator's traits in store order,
// Edition (when the artwork has more than one) and Storage.
func realTraits(r resolved) []engine.Trait {
	a := r.art
	out := []engine.Trait{}
	if a.Tier != "" {
		out = append(out, engine.Trait{Type: TraitTier, Value: a.Tier})
	}
	for k, v := range a.Traits {
		if v != "" {
			out = append(out, engine.Trait{Type: r.si.TraitTypes[k], Value: v})
		}
	}
	if a.Editions > 1 {
		out = append(out, engine.Trait{Type: TraitEdition, Value: editionLabel(r.edition, a.Editions)})
	}
	out = append(out, engine.Trait{Type: TraitStorage, Value: storageLabel(a.Kind)})
	return out
}

func editionLabel(e, of int64) string {
	return strconv.FormatInt(e, 10) + "/" + strconv.FormatInt(of, 10)
}

func storageLabel(kind int) string {
	if kind == media.KindChain {
		return "On-chain"
	}
	return "IPFS"
}