Playground
art.gno
package nft
import (
"encoding/base64"
"strconv"
"time"
"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/svg/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
)
// Tickets are drawn on-chain as SVG in the GnoRadio sober style: white,
// black and greys with a single red accent. The perforation is cut out with a
// mask so it reads as holes on any page background. Text is escaped by
// svg.Text. Nothing extra is stored: a ticket is drawn from its records.
// The artist's name and visibility are read from the catalog's artist
// records in the data realm (nft.gno, CArtists).
const (
ink = "#0d0d0d"
paper = "#fafaf8"
grey = "#9a9a96"
accent = "#e5432f"
)
// removedTitle replaces the details of a concert hidden by moderation.
const removedTitle = "Removed by moderation"
// concert is what a ticket shows of its concert.
type concert struct {
id, artist, capacity int
title, venue string
start, price int64
cancelled bool
}
// shown decodes an event record for a ticket: everything while the concert
// and its artist are visible, a neutral placeholder otherwise. ok is false
// when the concert is not visible.
func shown(id int, rec string) (c concert, ok bool) {
if rec == "" {
return concert{title: removedTitle}, false
}
// store.Field reads "" past a record's end, and texts are checked again
// here: whatever a later release writes, the metadata is valid JSON (a
// record that is not a store.Rec may also make the read panic).
c = concert{id: id, start: text.Atoi64(store.Field(rec, EStart)), capacity: text.Atoi(store.Field(rec, ECapacity)),
cancelled: store.Field(rec, ECancelled) != ""}
artist, title, venue := text.Atoi(store.Field(rec, EArtist)), store.Field(rec, ETitle), store.Field(rec, EVenue)
if store.Field(rec, EHidden) != "" || !artistVisible(artist) || !text.Valid(title, 1, 64) || !text.Valid(venue, 0, 64) {
c.title = removedTitle
return c, false
}
c.artist, c.title, c.venue, c.price = artist, title, venue, text.Atoi64(store.Field(rec, EPrice))
return c, true
}
// fields reads ticket id's event, serial and attended mark (ok false when
// unknown).
func fields(id int) (ev, serial int, attended, ok bool) {
rec := ticket(id)
if rec == "" {
return 0, 0, false, false
}
return text.Atoi(store.Field(rec, TEvent)), text.Atoi(store.Field(rec, TSerial)), store.Field(rec, TAttended) != "", true
}
// EventSVG is the specimen ticket of a visible concert as a markdown image,
// or "" when the concert is not visible.
func EventSVG(id int) string {
c, ok := shown(id, event(id))
if !ok {
return ""
}
return draw(c, 0, false).Image("ticket for " + c.title)
}
// TicketSVG is a ticket as a markdown image, or "" if unknown.
func TicketSVG(id int) string {
ev, serial, attended, ok := fields(id)
if !ok {
return ""
}
c, _ := shown(ev, event(ev))
return draw(c, serial, attended).Image("ticket for " + c.title)
}
// TokenURI is a ticket's GRC721 metadata as a data URI, its artwork drawn on
// the fly. It panics for an unknown ticket.
func TokenURI(tokenID string) string {
id := text.Atoi(tokenID)
ev, serial, attended, ok := fields(id)
if !ok || strconv.Itoa(id) != tokenID {
panic("nft: unknown ticket")
}
c, _ := shown(ev, event(ev))
meta := `{"name":` + text.Str("GnoRadio · "+c.title+" #"+pad3(serial)) +
`,"description":"GnoRadio concert ticket, drawn on-chain on gno.land","image":` + text.Str(draw(c, serial, attended).Data()) +
`,"attributes":[{"trait_type":"event","value":` + strconv.Itoa(c.id) +
`},{"trait_type":"artist","value":` + text.Str(ArtistName(c.artist)) +
`},{"trait_type":"attended","value":` + strconv.FormatBool(attended) + `}]}`
return "data:application/json;base64," + base64.StdEncoding.EncodeToString([]byte(meta))
}
func newCanvas(w, h int) *svg.Canvas {
return svg.New(w, h, `text{font-family:system-ui,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-weight:600}.m{font-weight:500}.l{font-weight:600;letter-spacing:.08em}.n{font-family:ui-monospace,Menlo,monospace;font-weight:500}`)
}
func drawText(c *svg.Canvas, x, y int, s, fill string, size int, anchor, class string) {
attrs := ` text-anchor="` + anchor + `"`
if class != "" {
attrs += ` class="` + class + `"`
}
c.Text(x, y, s, fill, size, attrs)
}
// draw draws a ticket; serial 0 is the specimen shown before purchase.
func draw(e concert, serial int, attended bool) *svg.Canvas {
c := newCanvas(640, 250)
// Black ticket with perforation and side notches cut out.
c.Raw(`<mask id="h"><rect width="640" height="250" fill="#fff"/>`)
for y := 18; y < 250; y += 16 {
c.Circle(470, y, 3, "#000")
}
c.Circle(470, 0, 14, "#000")
c.Circle(470, 250, 14, "#000")
c.Raw(`</mask><g mask="url(#h)">`)
c.Rect(0, 0, 640, 250, 24, ink, "")
c.Raw(`</g>`)
drawText(c, 30, 44, "GNORADIO · ADMIT ONE", grey, 12, "start", "l")
drawText(c, 30, 96, svg.Clip(e.title, 24), paper, 32, "start", "")
drawText(c, 30, 128, svg.Clip(ArtistName(e.artist), 34), grey, 18, "start", "m")
drawText(c, 30, 182, svg.Clip(e.venue, 34), paper, 15, "start", "m")
drawText(c, 30, 206, time.Unix(e.start, 0).UTC().Format("2006-01-02 15:04")+" UTC", paper, 15, "start", "m")
price := "FREE"
if e.price > 0 {
price = text.GNOT(e.price)
}
drawText(c, 440, 206, price, grey, 14, "end", "l")
// Stub: serial, barcode, red dot.
num := "SPECIMEN"
if serial > 0 {
num = "#" + pad3(serial) + "/" + strconv.Itoa(e.capacity)
}
drawText(c, 555, 54, num, paper, 16, "middle", "n")
h := svg.FNV("event" + strconv.Itoa(e.id) + e.title)
for i := 0; i < 22; i++ {
h ^= uint32(i + 1)
h *= 16777619
c.Rect(502+i*5, 80, 1+int(h>>24)%3, 80, 0, paper, "")
}
c.Circle(555, 200, 14, accent)
if e.cancelled {
stamp(c, "CANCELLED")
} else if attended {
stamp(c, "I WAS THERE")
}
return c
}
func stamp(c *svg.Canvas, label string) {
c.Raw(`<g transform="rotate(-10 240 125)">`)
c.Rect(70, 95, 340, 60, 8, "none", ` stroke="`+accent+`" stroke-width="4"`)
drawText(c, 240, 137, label, accent, 30, "middle", "l")
c.Raw(`</g>`)
}
func pad3(n int) string {
s := strconv.Itoa(n)
for len(s) < 3 {
s = "0" + s
}
return s
}
// artistVisible reports whether artist id exists and is not hidden.
func artistVisible(id int) bool {
rec := artist(id)
return rec != "" && store.Field(rec, AHidden) == ""
}
// ArtistName is a visible artist's name, "" otherwise (one data read: the
// catalog's artist record, through the frozen layout).
func ArtistName(id int) string {
rec := artist(id)
if rec == "" || store.Field(rec, AHidden) != "" {
return ""
}
name := store.Field(rec, AName)
if !text.Valid(name, 1, 64) {
return ""
}
return name
}
gnomod.toml
module = "gno.land/r/nym-alexiscolin000/gnoradio/tickets/nft" gno = "0.9" [addpkg] creator = "g1mpkp5lm8lwpm0pym4388836d009zfe4maxlqsq" height = 253147 max_deposit = "100000000ugnot"
nft.gno
// Package nft holds GnoRadio's concert tickets as GRC721 NFTs. It is
// permanent, like the data realm: a tickets release changes the rules, never
// this ledger, so no ticket ever moves to a new contract.
//
// Only the realm that writes the tickets role now (data.Writer("tickets"))
// mints and transfers, only while that role is not paused, and only for the
// wallet that signs the transaction (OriginCaller): a release can never move
// the ticket of a holder who signs nothing. That is the whole guarantee. The
// signature proves the holder sent some transaction through the tickets
// writer, not that they asked for this move: a malicious tickets release (it
// takes over only after the data realm's public 72 h window, which the
// guardian can cancel) could move every ticket of a holder who then signs any
// call to it. This realm cannot see further up the call stack. Anyone reads.
//
// A ticket's metadata and artwork are drawn on the fly from the tickets data
// (art.gno), whose record layout below is frozen for that reason.
package nft
import (
"chain/runtime/unsafe"
"strconv"
"gno.land/p/nym-alexiscolin000/gnoradio/role/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
"gno.land/p/nt/grc721/v0"
"gno.land/r/nym-alexiscolin000/gnoradio/data"
)
// The tickets records this realm reads, written by the tickets writer. Every
// tickets release keeps this layout: the artwork of existing tickets depends
// on it.
const (
CEvents = "tickets/events" // store.Pad(id) -> event record
CTickets = "tickets/tickets" // store.Pad((id-1)/Chunk) -> Chunk ticket records
Chunk = 16
)
// Event record fields (store.Rec); the one each sale changes comes first.
const (
ESold = iota
EArtist
EStart
EPrice
ECapacity
ECancelled // "1" or ""
EHidden // "1" or ""
ERemoved // the moderator's public reason while hidden
ETitle
EVenue
ELink
EFields
)
// Ticket record fields.
const (
TEvent = iota
TSerial
TAttended // "1" or ""
)
// The catalog's artist heads, read for a ticket's artist line: every catalog
// release keeps this layout, since it shares the data realm's records
// (catalog/v1 records.gno). Reading them here, not through a catalog realm,
// keeps this permanent realm free of any versioned import.
const (
CArtists = "catalog/artists" // store.Pad((id-1)/ArtistChunk) -> ArtistChunk artist heads
ArtistChunk = 8
AHidden = 0 // "1" or ""
AName = 6
)
var (
token *grc721.Token
ledger *grc721.PrivateLedger
)
// init creates the token, so its storage is paid at deploy and never by a
// first buyer.
func init(cur realm) {
token, ledger = grc721.NewToken("GnoRadio Ticket", "GRTIX", 1, cur)
}
// writer lets only the tickets writer through, while its role is not paused.
func writer(cur realm) {
if cur.Previous().PkgPath() != data.Writer("tickets") {
panic("nft: only " + data.Writer("tickets") + " mints and transfers tickets")
}
if data.Paused("tickets") {
panic("nft: tickets is paused")
}
}
// maxID is the largest id a data key holds (store.Pad); readers answer ""
// past it instead of panicking.
const maxID = 99999999
func tid(id int) grc721.TokenID { return grc721.TokenID(strconv.Itoa(id)) }
// Mint creates ticket id for to, the wallet that signed the transaction.
// The tickets writer only.
func Mint(cur realm, to address, id int) {
writer(cur)
if to != unsafe.OriginCaller() {
panic("nft: a ticket is minted to the wallet that signs")
}
if id < 1 || id > maxID {
panic("nft: invalid ticket id")
}
if err := ledger.Mint(to, tid(id)); err != nil {
panic("nft: " + err.Error())
}
}
// Transfer moves ticket id from its holder from to to. The tickets writer
// only, and only in a transaction from signed: no release moves the tickets
// of a holder who signs nothing (see the package comment for what a
// malicious release could still do). The rules decide who may gift.
func Transfer(cur realm, from, to address, id int) {
writer(cur)
if from != unsafe.OriginCaller() {
panic("nft: only the holder's own transaction moves a ticket")
}
if !role.Canonical(to) {
panic("nft: not an address")
}
if err := ledger.TransferFrom(from, from, to, tid(id)); err != nil {
panic("nft: " + err.Error())
}
}
// ---- GRC721 reads ----
func Name() string { return token.GetName() }
func Symbol() string { return token.GetSymbol() }
func TotalSupply() int64 { return token.TotalSupply() }
// BalanceOf is how many tickets owner holds.
func BalanceOf(owner address) int64 {
n, err := token.BalanceOf(owner)
if err != nil {
panic("nft: " + err.Error())
}
return n
}
// OwnerOf is a ticket's holder; it panics for an unknown ticket.
func OwnerOf(tokenID string) address {
owner, err := token.OwnerOf(grc721.TokenID(tokenID))
if err != nil {
panic("nft: " + err.Error())
}
return owner
}
// Holder is a ticket's holder, "" for an unknown ticket.
func Holder(id int) address {
owner, _ := token.OwnerOf(tid(id))
return owner
}
// Render shows the collection.
func Render(_ string) string {
return token.RenderHome() + "\nGnoRadio concert tickets. Each one is drawn on-chain: `TokenURI(id)`. Only `" +
data.Writer("tickets") + "` mints and transfers them.\n"
}
// ---- the tickets records ----
// ticket returns ticket id's record ("" when absent).
func ticket(id int) string {
if id < 1 || id > maxID {
return ""
}
ch, ok := data.Get(CTickets, store.Pad((id-1)/Chunk))
if !ok {
return ""
}
return store.Field(ch, (id-1)%Chunk)
}
// artist returns artist id's head record ("" when absent).
func artist(id int) string {
if id < 1 || id > maxID {
return ""
}
ch, ok := data.Get(CArtists, store.Pad((id-1)/ArtistChunk))
if !ok {
return ""
}
return store.Field(ch, (id-1)%ArtistChunk)
}
func event(id int) string {
if id < 1 || id > maxID {
return ""
}
rec, _ := data.Get(CEvents, store.Pad(id))
return rec
}