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

gnomod.toml

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

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

reads.gno

package upload

import (
	"errors"
	"strconv"
	"strings"

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

// Every function in this file is read-only. Every token read returns core's
// placeholder / "Unrevealed" before the collection is Final (T5).

// 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{cid: cid, info: core.Info(cid)}
	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(cid); v != nil {
		c.b = v.(*binding)
	}
	return c
}

// 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", 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", 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 := saltOf(cid, c.b)
	if salt == "" {
		return c, resolved{}, stNotReady, nil
	}
	n := tidNum(tid)
	r := assign(cid, tid, n, c.info, c.store, c.si, keyOf(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 the canonical art URI: "data:<mime>;base64,…" for on-chain
// art, "ipfs://<cidv1>" for IPFS art; core's placeholder before Final and
// core's TokenURI (the generic card) for a collection that is not ready.
func TokenURI(cid, tid string) (string, error) {
	if !IsUpload(cid) {
		return "", errors.New("collection " + cid + " does not use the upload engine")
	}
	_, r, st, err := readToken(cid, tid)
	if err != nil {
		return "", err
	}
	if st != stResolved {
		return core.TokenURI(cid, tid)
	}
	return artURI(r), nil
}

func artURI(r resolved) string {
	if r.art.Kind == media.KindChain {
		return assets.ArtworkDataURI(r.store, r.art.Index)
	}
	return "ipfs://" + r.art.CID
}

// TokenImage is the inline image: a data URI for on-chain art, "" for IPFS
// art (never a remote URL); core's placeholder before Final.
func TokenImage(cid, tid string) string {
	_, r, st := mustReadToken(cid, tid)
	if st != stResolved {
		uri, _ := core.TokenURI(cid, tid)
		return uri
	}
	if r.art.Kind != media.KindChain {
		return ""
	}
	return assets.ArtworkDataURI(r.store, r.art.Index)
}

// 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", 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", media.MimeType(a.Mime))
		w.IntField("size", a.Size)
		w.StrField("sha256", a.SHA256)
		w.StrField("digest", a.Digest)
		w.StrField("cid", a.CID)
		if a.Kind == media.KindChain {
			w.StrField("uri", "")
		} else {
			w.StrField("uri", "ipfs://"+a.CID)
		}
		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"
}

// realTraits are the upload-path attributes with the creator's real type
// names: 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: "Tier", 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: "Edition", Value: editionLabel(r.edition, a.Editions)})
	}
	out = append(out, engine.Trait{Type: "Storage", Value: storageLabel(a.Kind)})
	return out
}

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":"Tier","value":`+a.TierJSON+`}`)
	}
	if a.TraitsJSON != "" {
		parts = append(parts, a.TraitsJSON)
	}
	if a.Editions > 1 {
		parts = append(parts, `{"trait_type":"Edition","value":"`+editionLabel(r.edition, a.Editions)+`"}`)
	}
	parts = append(parts, `{"trait_type":"Storage","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 canonical metadata (§10.2). 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.StrField("image", uri)
		w.Key("attributes")
		if st == stHidden {
			writeTraits(w, unrevealed)
		} else {
			writeTraits(w, notReady)
		}
		w.EndObject()
		return w.String()
	}
	a := r.art
	w.StrField("image", artURI(r))
	w.StrField("image_mime", media.MimeType(a.Mime))
	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", 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(cid))
	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 := saltOf(cid, c.b); salt != "" {
				key = keyOf(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(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 := saltOf(cid, c.b); salt != "" {
				key = keyOf(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/sinopia/media/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
)

// cardSVG is the generic card: the registration sample (unique
// fingerprint, CV-L3), RenderWith output, and the answer to any call that
// is not core's real render of a revealed, bound token.
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="240" fill="#eeeeee" font-family="monospace" font-size="30" text-anchor="middle">Sinopia Upload</text>` +
	`<text x="256" y="282" fill="#999999" font-family="monospace" font-size="15" text-anchor="middle">art from a sealed asset store</text>` +
	`</svg>`

// certificateSVG stands in for raster and IPFS art on core's TokenURI
// path, which only carries allowlisted SVG (§10.1). 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: "+selfPath+" 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/v1 adapter for uploaded collections
// (docs/uploaded-collections.md §5.3, §7–§10, §0a). Core knows it as one
// more engine; 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 shows the artwork of the
// slot a salt-keyed permutation gives it.
//
// 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);
//   - snipe resistance (T4/T5): before Final core shows its placeholder and
//     never calls Render/Traits; every read here checks Final too; the
//     assignment needs the final salt; Render answers core's real call only
//     (CollectionID, params and seed must match core's), so RenderWith
//     (CollectionID "0") always gets the generic card;
//   - SA-L5: this realm and assets/v1 may not be payees (Bind refuses);
//   - I-12: Render, Traits 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/sinopia/engine/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/media/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/types/v1"
	assets "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/assets/v1"
	"gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/core"
)

// author claims the engine in core (ClaimEngine).
// TODO(mainnet): the platform's engine-author key, not the deployer.
var author = address("g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06")

func Author() address { return author }

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

// Core-path trait slots (engine/v1 manifests fix their trait types at
// registration, so creator trait types appear as "Trait k" = "<Type>: <Value>").
const (
	TraitTier    = "Creator tier"
	TraitArtwork = "Artwork"
	TraitEdition = "Edition"
	TraitStorage = "Storage"
	TraitSlots   = assets.MaxTraitTypes
)

// MaxTraitsBatch bounds TraitsBatch (JSON); MaxTraitLists bounds the typed
// TraitLists the reader pages rarity counts with. 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; r/reader/zz_worst_gas_test.gno).
const (
	MaxTraitsBatch    = 20  // JSON (was 50)
	MaxTraitJSONLists = 20  // typed, JSON per token (reader.Cards)
	MaxTraitLists     = 250 // typed (was 500)
	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.Provenance)
	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/v1 ---------------------------------------------------------------

// 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 traitTypes() []string {
	out := []string{TraitTier, TraitArtwork, TraitEdition, TraitStorage}
	for k := 1; k <= TraitSlots; k++ {
		out = append(out, "Trait "+strconv.Itoa(k))
	}
	return out
}

func (impl) Manifest() engine.Manifest {
	return engine.Manifest{
		Name:    "Sinopia Upload",
		Version: "1.0.0",
		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. Stateful platform engine (store bindings); " +
			"tiers and traits are assigned by the creator.",
		License:     "artist's own",
		Author:      author,
		TraitTypes:  traitTypes(),
		Living:      false,
		MaxSVGBytes: media.MaxSVGBytes,
		FeeBps:      FeeBps,
	}
}

// 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
}

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) // passed AssertSVG(16 KiB) at upload; core re-checks
	}
	return certificateSVG(r)
}

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"}}
	}
	a := r.art
	var out []engine.Trait
	if a.Tier != "" {
		out = append(out, engine.Trait{Type: TraitTier, Value: a.Tier})
	}
	title := a.Title
	if title == "" {
		title = "#" + strconv.FormatInt(a.Index+1, 10)
	}
	out = append(out, engine.Trait{Type: TraitArtwork, Value: title})
	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)})
	for k, v := range a.Traits {
		if v != "" {
			out = append(out, engine.Trait{Type: "Trait " + strconv.Itoa(k+1), Value: r.si.TraitTypes[k] + ": " + v})
		}
	}
	return out
}

// Register is an explicit call (not init: under the inert package policy
// init runs in the approver's tx). Anyone may call it, once.
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; no primary or royalty
// payee is this realm or assets/v1 (SA-L5). Event StoreBound{store, cid}.
func Bind(cur realm, cid string) {
	assertWallet(cur)
	who := cur.Previous().Address()
	info := core.Info(cid)
	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))
	}
	assertPayees(cid)
	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)
	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 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)
	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 := provenanceSalt(core.Provenance(cid))
	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)")
	}
}

// assertPayees refuses this realm and assets/v1 as primary or royalty
// payees (SA-L5: neither can ever spend a payment). Core already refuses
// itself, its sub-addresses, minters, the engine adapter and its siblings.
func assertPayees(cid string) {
	bad := []address{chain.PackageAddress(selfPath), chain.PackageAddress(assetsPath)}
	var addrs []address
	for _, p := range core.PrimaryPayees(cid) {
		addrs = append(addrs, p.Addr)
	}
	for _, part := range strings.Split(jsonStrField(core.Collection(cid), "royaltyPayees"), ",") {
		if a, _, ok := strings.Cut(part, ":"); ok {
			addrs = append(addrs, address(a))
		}
	}
	for _, a := range addrs {
		for _, b := range bad {
			if a == b {
				panic("payee " + a.String() + " is a platform realm that cannot spend; use a wallet")
			}
		}
	}
}

// jsonStrField reads a string field of core's JSON. Values written by
// safe.JSONWriter escape '"', so the key pattern cannot be forged by user text.
func jsonStrField(js, key string) string {
	pat := `"` + key + `":"`
	i := strings.Index(js, pat)
	if i < 0 {
		return ""
	}
	rest := js[i+len(pat):]
	j := strings.IndexByte(rest, '"')
	if j < 0 {
		return ""
	}
	return rest[:j]
}

// provenanceSalt is the final salt from core.Provenance JSON ("" before
// Final). The pattern `"salt":"` cannot be forged: JSONWriter escapes every
// '"' inside a secret.
func provenanceSalt(prov string) string {
	s := jsonStrField(prov, "salt")
	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/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.
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.EngineID != selfPath || info.State != types.StateFinal || info.Params != in.Params {
		return r, false
	}
	salt := saltOf(in.CollectionID, b)
	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 saltOf(cid string, b *binding) string {
	if b.salt != "" {
		return b.salt
	}
	return provenanceSalt(core.Provenance(cid))
}

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}
}

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"
}