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.

engines.gno

9.34 Kb · 289 lines
  1package core
  2
  3import (
  4	"chain"
  5	"chain/runtime"
  6	"strings"
  7
  8	"gno.land/p/nt/avl/v0"
  9
 10	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
 11	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
 12)
 13
 14// Engine registry ("art as code", design §5).
 15//
 16// An engine registers itself from its own /r/ adapter realm; its id is that
 17// realm's package path, so nobody can register in someone else's name. The
 18// stored interface value's methods are declared in the adapter, so every
 19// call runs with the adapter's authority, not core's (interrealm v2 borrow
 20// rule #1): engine code cannot write core state. It also cannot call back
 21// into a core mutator: all of core's state-changing functions are crossing
 22// and need a live cur the engine never has.
 23//
 24// Honest limits, surfaced to users rather than hidden:
 25//   - an adapter realm with state could change its art later; the sample
 26//     fingerprint (VerifyEngine) detects a change of the sample, and review
 27//     means reading the adapter for statelessness;
 28//   - a private (re-deployable) adapter cannot register: the VM aborts the
 29//     registration when core's state would retain the private realm's type
 30//     (spike A9, observed in gno v1.7.0 test mode; confirm on Onyx).
 31type engineRecord struct {
 32	id               string
 33	impl             engine.Engine
 34	manifest         engine.Manifest // core-owned copy
 35	fingerprint      string          // sha256 of Render(SampleInput())
 36	claimed          bool
 37	deprecated       bool
 38	reviewed         bool
 39	registeredHeight int64
 40}
 41
 42var (
 43	engines     avl.Tree // engine id -> *engineRecord
 44	engineOrder avl.Tree // safe.PadInt(seq) -> engine id
 45	engineCount int64
 46)
 47
 48// RegisterEngine stores the calling realm's engine (I-12 exception: one
 49// sample render in the engine's own registration transaction). The record
 50// is immutable afterwards except for the claim/deprecate/review flags.
 51func RegisterEngine(cur realm, e engine.Engine) string {
 52	id := cur.Previous().PkgPath()
 53	if !strings.HasPrefix(id, runtime.ChainDomain()+"/r/") || strings.Contains(id, "#") {
 54		panic("an engine registers from its own realm (an /r/ package, not a sub-realm or wallet)")
 55	}
 56	if e == nil {
 57		panic("nil engine")
 58	}
 59	if engines.Has(id) {
 60		panic("engine already registered: " + id + " (publish a new version under a new path)")
 61	}
 62	m := copyManifest(e.Manifest())
 63	if err := engine.ValidateManifest(m); err != nil {
 64		panic(err)
 65	}
 66	if err := e.ValidateParams(""); err != nil {
 67		panic("engine must accept empty params (its defaults): " + err.Error())
 68	}
 69	sample := e.Render(engine.SampleInput())
 70	if err := engine.CheckSVG(m, sample); err != nil {
 71		panic("sample render: " + err.Error())
 72	}
 73	if err := engine.ValidateTraits(m, e.Traits(engine.SampleInput())); err != nil {
 74		panic("sample traits: " + err.Error())
 75	}
 76
 77	rec := &engineRecord{
 78		id:               id,
 79		impl:             e,
 80		manifest:         m,
 81		fingerprint:      safe.Sha256Hex(sample),
 82		registeredHeight: height(),
 83	}
 84	engines.Set(id, rec)
 85	engineCount++
 86	engineOrder.Set(safe.PadInt(engineCount, cidWidth), id)
 87	chain.Emit("EngineRegistered", "id", id, "author", m.Author.String(), "feeBps", itoa(m.FeeBps),
 88		"fingerprint", rec.fingerprint)
 89	return id
 90}
 91
 92// ClaimEngine proves the manifest author controls that address. Unclaimed
 93// engines cannot back a collection.
 94func ClaimEngine(cur realm, id string) {
 95	assertNoDeposit(cur)
 96	rec := mustEngine(id)
 97	if caller(cur) != rec.manifest.Author {
 98		panic("only the manifest author " + rec.manifest.Author.String() + " can claim this engine")
 99	}
100	rec.claimed = true
101	chain.Emit("EngineClaimed", "id", id)
102}
103
104// DeprecateEngine stops new collections; existing ones keep rendering.
105func DeprecateEngine(cur realm, id string) {
106	assertNoDeposit(cur)
107	rec := mustEngine(id)
108	if !rec.claimed || caller(cur) != rec.manifest.Author {
109		panic("only the engine's author can deprecate it")
110	}
111	rec.deprecated = true
112	chain.Emit("EngineDeprecated", "id", id)
113}
114
115// --- engine-author fee ---------------------------------------------------------
116//
117// An engine's author earns FeeBps (manifest, fixed at registration, <=
118// EngineFeeCapBps) of every primary and secondary sale of a collection that
119// uses the engine, capped by the platform's fees.EngineCapBps. A collection
120// snapshots the fee at Launch (like the protocol fee, SA-I5) and later sales
121// pay min(snapshot, current platform cap), so neither the author nor the
122// admin can raise it on a running collection. No fee when the creator is
123// the author: the creator's own payees already get the sale.
124
125// engineFeeOf is the engine's fee under the current platform cap.
126func engineFeeOf(rec *engineRecord) int64 {
127	if rec.manifest.FeeBps < fees.EngineCapBps {
128		return rec.manifest.FeeBps
129	}
130	return fees.EngineCapBps
131}
132
133// engineFeeQuote is what c would snapshot at a Launch now.
134func engineFeeQuote(c *collection) (address, int64) {
135	rec := mustEngine(c.engineID)
136	author := rec.manifest.Author
137	if author == c.creator {
138		return author, 0
139	}
140	return author, engineFeeOf(rec)
141}
142
143// collectionEngineFee is the fee a sale of c pays now: the Launch snapshot
144// bounded by the current cap; before Launch, the current quote.
145func collectionEngineFee(c *collection) (address, int64) {
146	if c.prov == nil {
147		return engineFeeQuote(c)
148	}
149	if c.engineBps < fees.EngineCapBps {
150		return c.engineAuthor, c.engineBps
151	}
152	return c.engineAuthor, fees.EngineCapBps
153}
154
155// EngineFee is the engine-author share of cid's sales: the author and the
156// bps a sale pays now (0 when the creator is the author). mint/v1 and
157// market/v1 pay safe.BpsOf(amount, bps) to author.
158func EngineFee(cid string) (author address, bps int64) {
159	return collectionEngineFee(mustCollection(cid))
160}
161
162func mustEngine(id string) *engineRecord {
163	v := engines.Get(id)
164	if v == nil {
165		panic("unknown engine " + id)
166	}
167	return v.(*engineRecord)
168}
169
170// copyManifest gives core its own copy: the engine's slice was allocated in
171// the engine realm.
172func copyManifest(m engine.Manifest) engine.Manifest {
173	out := m
174	out.TraitTypes = append([]string{}, m.TraitTypes...)
175	return out
176}
177
178// --- engine reads (Studio, Verify) -------------------------------------------
179
180// RenderWith renders any registered engine for arbitrary params and seed as
181// a data URI — Studio previews and the Verify button.
182func RenderWith(id, params, seed string) string {
183	rec := mustEngine(id)
184	if err := rec.impl.ValidateParams(params); err != nil {
185		panic("params rejected by engine: " + err.Error())
186	}
187	svg := rec.impl.Render(studioInput(params, seed))
188	if err := engine.CheckSVG(rec.manifest, svg); err != nil {
189		return dataURI(placeholderSVG(rec.manifest.Name, "Engine output rejected"))
190	}
191	return dataURI(svg)
192}
193
194// EngineTraits returns a core-owned copy of the engine's traits for seed.
195func EngineTraits(id, params, seed string) []engine.Trait {
196	rec := mustEngine(id)
197	if err := rec.impl.ValidateParams(params); err != nil {
198		panic("params rejected by engine: " + err.Error())
199	}
200	ts := rec.impl.Traits(studioInput(params, seed))
201	if err := engine.ValidateTraits(rec.manifest, ts); err != nil {
202		panic("engine traits rejected: " + err.Error())
203	}
204	return append([]engine.Trait{}, ts...)
205}
206
207func TraitsWith(id, params, seed string) string {
208	w := &safe.JSONWriter{}
209	writeTraits(w, EngineTraits(id, params, seed))
210	return w.String()
211}
212
213// VerifyEngine re-renders the sample and compares it with the fingerprint
214// stored at registration.
215func VerifyEngine(id string) bool {
216	rec := mustEngine(id)
217	return safe.Sha256Hex(rec.impl.Render(engine.SampleInput())) == rec.fingerprint
218}
219
220// EngineManifest is the typed read for other realms (gallery).
221func EngineManifest(id string) engine.Manifest { return copyManifest(mustEngine(id).manifest) }
222
223// EngineStatus is "unclaimed", "unverified", "reviewed" or "deprecated".
224func EngineStatus(id string) string { return engineStatus(mustEngine(id)) }
225
226func engineStatus(rec *engineRecord) string {
227	switch {
228	case rec.deprecated:
229		return "deprecated"
230	case !rec.claimed:
231		return "unclaimed"
232	case rec.reviewed:
233		return "reviewed"
234	}
235	return "unverified"
236}
237
238// Engine is the record as JSON.
239func Engine(id string) string {
240	w := &safe.JSONWriter{}
241	writeEngine(w, mustEngine(id))
242	return w.String()
243}
244
245func Engines(offset, limit int64) string {
246	w := &safe.JSONWriter{}
247	w.BeginArray()
248	engineOrder.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
249		writeEngine(w, mustEngine(v.(string)))
250		return false
251	})
252	w.EndArray()
253	return w.String()
254}
255
256func writeEngine(w *safe.JSONWriter, rec *engineRecord) {
257	m := rec.manifest
258	w.BeginObject()
259	w.StrField("id", rec.id)
260	w.StrField("pkgPath", rec.id) // the adapter realm; read its source (and imports) with vm/qfile
261	w.StrField("name", m.Name)
262	w.StrField("version", m.Version)
263	w.StrField("description", m.Description)
264	w.StrField("license", m.License)
265	w.StrField("author", m.Author.String())
266	w.IntField("feeBps", m.FeeBps)
267	w.IntField("effectiveFeeBps", engineFeeOf(rec))
268	w.StrField("paramsSchema", m.ParamsSchema)
269	w.Key("traitTypes")
270	w.BeginArray()
271	for _, t := range m.TraitTypes {
272		w.Str(t)
273	}
274	w.EndArray()
275	w.BoolField("living", m.Living)
276	w.IntField("maxSvgBytes", m.MaxSVGBytes)
277	w.StrField("fingerprint", rec.fingerprint)
278	w.StrField("status", engineStatus(rec))
279	w.IntField("registeredHeight", rec.registeredHeight)
280	w.EndObject()
281}
282
283func studioInput(params, seed string) engine.Input {
284	in := engine.SampleInput()
285	in.Seed = seed
286	in.Params = params
287	in.Height = height()
288	return in
289}