tokens.gno
13.33 Kb · 424 lines
1package core
2
3import (
4 "chain"
5 "encoding/base64"
6
7 "gno.land/p/nt/avl/v0"
8 "gno.land/p/nt/grc721/royalty/v0"
9 "gno.land/p/nt/grc721/v0"
10
11 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
12 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
13)
14
15// tokenState is the per-collection data the transfer hook needs. It is
16// shared by the collection and its lockExt, so neither points at the other.
17//
18// Per-token state is packed (storage-cost-analysis P1+P3): one fixed-width
19// entry of packEntry bytes per token, packSlots tokens per avl key. Entry =
20// four big-endian uint32 fields: mint height, transfer count (H-2), height
21// of the last transfer, and the token's approval nonce (SA-L3). A mint
22// appends entries in tid order (a new key every packSlots tokens, ~2 KB the
23// minter of that bucket's first token pays); a transfer or an Approve only
24// rewrites bytes in place, so neither creates a storage object.
25type tokenState struct {
26 final bool
27 pack avl.Tree // safe.PadInt((tid-1)/packSlots, packKeyWidth) -> string of packed entries
28}
29
30const (
31 packSlots = 128
32 packFields = 4
33 packEntry = packFields * 4
34 packKeyWidth = 3 // MaxSupplyCap/packSlots < 1000
35
36 fieldMintHeight = 0
37 fieldMoves = 1
38 fieldLastMove = 2
39 fieldNonce = 3
40)
41
42func packKey(tid int64) string { return safe.PadInt((tid-1)/packSlots, packKeyWidth) }
43
44// u32 encodes v as 4 big-endian bytes. Heights stay below 2^32 for ~470
45// years of 3.5 s blocks; 2^32 transfers or approvals of one token cannot
46// happen, so overflow is a hard error rather than a wrap.
47func u32(v int64) string {
48 if v < 0 || v > 0xFFFFFFFF {
49 panic("token state: value out of uint32 range")
50 }
51 return string([]byte{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)})
52}
53
54// appendTokens adds zeroed entries (mint height h) for first..last, which
55// must directly follow the last stored token.
56func (st *tokenState) appendTokens(first, last, h int64) {
57 entry := u32(h) + u32(0) + u32(0) + u32(0)
58 for tid := first; tid <= last; {
59 k := packKey(tid)
60 v, _ := st.pack.Get(k).(string)
61 if int64(len(v)) != ((tid-1)%packSlots)*packEntry {
62 panic("token state: tokens must be appended in order")
63 }
64 for ; tid <= last && packKey(tid) == k; tid++ {
65 v += entry
66 }
67 st.pack.Set(k, v)
68 }
69}
70
71// field reads one field of token tid; 0 for a token that was never minted.
72func (st *tokenState) field(tid int64, f int) int64 {
73 if tid <= 0 {
74 return 0
75 }
76 v, _ := st.pack.Get(packKey(tid)).(string)
77 off := int((tid-1)%packSlots)*packEntry + f*4
78 if off+4 > len(v) {
79 return 0
80 }
81 return int64(v[off])<<24 | int64(v[off+1])<<16 | int64(v[off+2])<<8 | int64(v[off+3])
82}
83
84// setFields rewrites one or two fields of token tid in place (one avl
85// update; f2 < 0 means none).
86func (st *tokenState) setFields(tid int64, f1 int, v1 int64, f2 int, v2 int64) {
87 k := packKey(tid)
88 v, _ := st.pack.Get(k).(string)
89 base := int((tid-1)%packSlots) * packEntry
90 if tid <= 0 || base+packEntry > len(v) {
91 panic("token state: unknown token")
92 }
93 o1 := base + f1*4
94 v = v[:o1] + u32(v1) + v[o1+4:]
95 if f2 >= 0 {
96 o2 := base + f2*4
97 v = v[:o2] + u32(v2) + v[o2+4:]
98 }
99 st.pack.Set(k, v)
100}
101
102func (st *tokenState) mintHeight(tid int64) int64 { return st.field(tid, fieldMintHeight) }
103
104func (st *tokenState) moveOf(tid string) (moves, lastMove int64) {
105 n := tidNum(tid)
106 return st.field(n, fieldMoves), st.field(n, fieldLastMove)
107}
108
109// tidNum is the numeric token id, or 0 for anything that is not a
110// canonical positive decimal (no such token exists).
111func tidNum(tid string) int64 {
112 if len(tid) == 0 || len(tid) > 12 || tid[0] == '0' {
113 return 0
114 }
115 var n int64
116 for i := 0; i < len(tid); i++ {
117 c := tid[i]
118 if c < '0' || c > '9' {
119 return 0
120 }
121 n = n*10 + int64(c-'0')
122 }
123 return n
124}
125
126// lockExt is the grc721 Extension behind two invariants:
127//
128// - I-11: before Final no token moves or burns (the reveal lock that
129// closes RA H-3's information-advantage branch). The veto is a panic,
130// which aborts the whole transaction — the documented Extension
131// semantics of p/nt/grc721/v0.
132// - H-2: every transfer bumps the token's move counter, so a market
133// listing taken at moves=N is dead after any transfer, even if the
134// token later comes back to the seller.
135//
136// It is declared in this realm, so the hooks write core state with core's
137// authority even when another realm moves the token via RealmTeller.
138type lockExt struct {
139 cid string
140 st *tokenState
141}
142
143const lockKind = "art-lock"
144
145func (e *lockExt) ExtensionKind() string { return lockKind }
146
147// The hooks also emit the platform's per-token history events with the
148// collection id ("Minted", "Transfer"); grc721's own Transfer event carries
149// only the token's grc721 id.
150func (e *lockExt) OnMint(to address, tid grc721.TokenID) {
151 chain.Emit("Minted", "cid", e.cid, "tid", tid.String(), "to", to.String())
152}
153
154func (e *lockExt) OnTransfer(from, to address, tid grc721.TokenID) {
155 if !e.st.final {
156 panic("tokens are locked until the collection is final (reveal)")
157 }
158 key := tid.String()
159 n := tidNum(key)
160 e.st.setFields(n, fieldMoves, e.st.field(n, fieldMoves)+1, fieldLastMove, height())
161 chain.Emit("Transfer", "cid", e.cid, "tid", key, "from", from.String(), "to", to.String())
162}
163
164func (e *lockExt) OnBurn(tid grc721.TokenID) {
165 if !e.st.final {
166 panic("tokens are locked until the collection is final (reveal)")
167 }
168 // the packed entry stays: a burned id is never minted again (I-5)
169}
170
171// --- owner actions (I-2: never paused) ---------------------------------------
172//
173// The acting account is always the immediate caller (cur.Previous()), the
174// same rule as grc721's CallerTeller: a realm a user merely calls cannot act
175// for that user. Another realm moves tokens only after an Approve, through
176// Token(cid).RealmTeller (market/v1 does exactly that).
177
178// Every Approve of a token and every SetApprovalForAll of an (owner,
179// operator) pair bumps a nonce. A market pins the nonces at listing time,
180// so revoking an approval kills a listing for good: approving again later
181// starts a new nonce and never revives the old listing (SA-L3).
182func Approve(cur realm, cid, tid string, to address) {
183 assertNoDeposit(cur)
184 c := mustCollection(cid)
185 if err := c.ledger.Approve(caller(cur), to, grc721.TokenID(tid)); err != nil {
186 panic(err)
187 }
188 n := tidNum(tid)
189 c.st.setFields(n, fieldNonce, c.st.field(n, fieldNonce)+1, -1, 0)
190}
191
192func SetApprovalForAll(cur realm, cid string, operator address, approved bool) {
193 assertNoDeposit(cur)
194 c := mustCollection(cid)
195 owner := caller(cur)
196 if err := c.ledger.SetApprovalForAll(owner, operator, approved); err != nil {
197 panic(err)
198 }
199 bumpNonce(c, "o:"+owner.String()+":"+operator.String())
200}
201
202// ApprovalNonces returns the token's approval nonce and the (owner,
203// operator) approval-for-all nonce. Approvals made directly through
204// Token(cid).RealmTeller by a realm acting for itself do not bump them.
205func ApprovalNonces(cid, tid string, owner, operator address) (tokenNonce, operatorNonce int64) {
206 c := mustCollection(cid)
207 return c.st.field(tidNum(tid), fieldNonce), nonceOf(c, "o:"+owner.String()+":"+operator.String())
208}
209
210func bumpNonce(c *collection, key string) {
211 c.approvals.Set(key, nonceOf(c, key)+1)
212}
213
214func nonceOf(c *collection, key string) int64 {
215 if v := c.approvals.Get(key); v != nil {
216 return v.(int64)
217 }
218 return 0
219}
220
221func TransferFrom(cur realm, cid, tid string, from, to address) {
222 assertNoDeposit(cur)
223 c := mustCollection(cid)
224 if err := c.ledger.TransferFrom(caller(cur), from, to, grc721.TokenID(tid)); err != nil {
225 panic(err)
226 }
227}
228
229// Burn is owner-only. The supply gate uses nextTID, so a burn never reopens
230// a slot (I-5).
231func Burn(cur realm, cid, tid string) {
232 assertNoDeposit(cur)
233 c := mustCollection(cid)
234 owner, err := c.token.OwnerOf(grc721.TokenID(tid))
235 if err != nil {
236 panic(err)
237 }
238 if owner != caller(cur) {
239 panic("only the owner can burn a token")
240 }
241 if err := c.ledger.Burn(grc721.TokenID(tid)); err != nil {
242 panic(err)
243 }
244}
245
246// --- token reads ---------------------------------------------------------------
247
248// Token publishes the collection's official *grc721.Token. Its exported
249// methods are reads or teller factories that need the caller's live realm;
250// the ledger itself is never published.
251func Token(cid string) *grc721.Token { return mustCollection(cid).token }
252
253// Royalty publishes the read-only royalty view (EIP-2981 RoyaltyInfo).
254func Royalty(cid string) *royalty.Royalty { return mustCollection(cid).roy }
255
256func OwnerOf(cid, tid string) (address, error) {
257 return mustCollection(cid).token.OwnerOf(grc721.TokenID(tid))
258}
259
260func BalanceOf(cid string, owner address) (int64, error) {
261 return mustCollection(cid).token.BalanceOf(owner)
262}
263
264// TokenMoves is the transfer counter market/v1 pins in a listing (H-2).
265func TokenMoves(cid, tid string) int64 {
266 n, _ := mustCollection(cid).st.moveOf(tid)
267 return n
268}
269
270// TokenSeed is "" until the collection is Final: no read path can leak the
271// rarity map early.
272func TokenSeed(cid, tid string) string {
273 c := mustCollection(cid)
274 if !c.st.final || !exists(c, tid) {
275 return ""
276 }
277 return safe.Seed(c.id, tid, c.prov.salt)
278}
279
280// TokenState is {mintHeight, lastMoveHeight, moves} as JSON.
281func TokenState(cid, tid string) string {
282 c := mustCollection(cid)
283 if !exists(c, tid) {
284 panic(grc721.ErrInvalidTokenId)
285 }
286 in := tokenInput(c, tid)
287 w := &safe.JSONWriter{}
288 w.BeginObject()
289 w.IntField("mintHeight", in.MintHeight)
290 w.IntField("lastMoveHeight", in.LastMoveHeight)
291 w.IntField("moves", in.Moves)
292 w.EndObject()
293 return w.String()
294}
295
296// TokenURI is a base64 SVG data URI. Before Final every token shows core's
297// neutral placeholder, never engine output (design §4.2).
298func TokenURI(cid, tid string) (string, error) {
299 c := mustCollection(cid)
300 if _, err := c.token.OwnerOf(grc721.TokenID(tid)); err != nil {
301 return "", err
302 }
303 if !c.st.final {
304 return dataURI(placeholderSVG(c.name, "Unrevealed")), nil
305 }
306 return dataURI(renderToken(c, tid)), nil
307}
308
309// TokenTraits is [{"trait_type":…,"value":…}] JSON.
310func TokenTraits(cid, tid string) string {
311 c := mustCollection(cid)
312 w := &safe.JSONWriter{}
313 writeTraits(w, tokenTraits(c, tid))
314 return w.String()
315}
316
317// TokenTraitList is the typed form of TokenTraits for other realms (a copy).
318func TokenTraitList(cid, tid string) []engine.Trait {
319 return append([]engine.Trait{}, tokenTraits(mustCollection(cid), tid)...)
320}
321
322// TokenMetadata is OpenSea-style metadata JSON.
323func TokenMetadata(cid, tid string) string {
324 c := mustCollection(cid)
325 uri, err := TokenURI(cid, tid)
326 if err != nil {
327 panic(err)
328 }
329 w := &safe.JSONWriter{}
330 w.BeginObject()
331 w.StrField("name", c.name+" #"+tid)
332 w.StrField("description", c.description)
333 w.StrField("image", uri)
334 w.Key("attributes")
335 writeTraits(w, tokenTraits(c, tid))
336 w.EndObject()
337 return w.String()
338}
339
340func exists(c *collection, tid string) bool {
341 _, err := c.token.OwnerOf(grc721.TokenID(tid))
342 return err == nil
343}
344
345func tokenInput(c *collection, tid string) engine.Input {
346 n := safe.ParseID("tid", tid)
347 moves, lastMove := c.st.moveOf(tid)
348 mh := c.st.mintHeight(n)
349 if lastMove == 0 {
350 lastMove = mh
351 }
352 in := engine.Input{
353 Params: c.params,
354 CollectionID: c.id,
355 TokenID: tid,
356 MintHeight: mh,
357 LastMoveHeight: lastMove,
358 Moves: moves,
359 Height: height(),
360 }
361 if c.st.final {
362 in.Seed = safe.Seed(c.id, tid, c.prov.salt)
363 }
364 return in
365}
366
367// renderToken runs the collection's engine on a read path. A bad output
368// degrades to a placeholder; a panicking engine only fails reads of its own
369// collections (interrealm v2 §9: cross-realm panics abort the query).
370func renderToken(c *collection, tid string) string {
371 rec := mustEngine(c.engineID)
372 svg := rec.impl.Render(tokenInput(c, tid))
373 if err := engine.CheckSVG(rec.manifest, svg); err != nil {
374 return placeholderSVG(c.name, "Engine output rejected")
375 }
376 return svg
377}
378
379func tokenTraits(c *collection, tid string) []engine.Trait {
380 if !exists(c, tid) {
381 panic(grc721.ErrInvalidTokenId)
382 }
383 if !c.st.final {
384 return []engine.Trait{{Type: "Status", Value: "Unrevealed"}}
385 }
386 rec := mustEngine(c.engineID)
387 ts := rec.impl.Traits(tokenInput(c, tid))
388 if err := engine.ValidateTraits(rec.manifest, ts); err != nil {
389 return []engine.Trait{{Type: "Status", Value: "Engine output rejected"}}
390 }
391 return ts
392}
393
394func writeTraits(w *safe.JSONWriter, ts []engine.Trait) {
395 w.BeginArray()
396 for _, t := range ts {
397 w.BeginObject()
398 w.StrField("trait_type", t.Type)
399 w.StrField("value", t.Value)
400 w.EndObject()
401 }
402 w.EndArray()
403}
404
405// placeholderSVG is core's own neutral art: identical for every token of a
406// collection, so it carries no rarity signal.
407func placeholderSVG(name, label string) string {
408 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">` +
409 `<rect width="512" height="512" fill="#111"/>` +
410 `<text x="256" y="236" fill="#ddd" font-family="monospace" font-size="24" text-anchor="middle">` +
411 safe.XMLEscape(name) + `</text>` +
412 `<text x="256" y="286" fill="#888" font-family="monospace" font-size="18" text-anchor="middle">` +
413 safe.XMLEscape(label) + `</text></svg>`
414}
415
416func dataURI(svg string) string {
417 return "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(svg))
418}
419
420// emitBatch announces one MintTo ("MintBatch") or ReserveTo ("Reserved")
421// call; each token also gets its own "Minted" event from lockExt.
422func emitBatch(kind string, c *collection, to address, first, last int64) {
423 chain.Emit(kind, "cid", c.id, "to", to.String(), "first", itoa(first), "last", itoa(last))
424}