Playground
art.gno
package nsskin
import (
"chain/runtime"
"encoding/base64"
"strconv"
"strings"
"gno.land/p/nt/grc721/v0"
)
/*
WHAT A WALLET SHOWS FOR A SKIN.
Adena puts TokenURI(tid) straight into an <img src>, so it must return
the image itself, as a data URI, and it reads TokenMetadata as a camelCase
JSON string. The previous TokenURI returned a gnoweb path, which no wallet
can draw.
The picture is drawn HERE, from the definition's own sprite, rather than
by nsview: nsview imports this realm to put skins on name cards, so this
realm cannot import it back. It is the bare artwork on a dark matte —
nsview's matted shop card stays the gnoweb page, linked as externalUrl.
This realm is replaceable, so a richer wallet image is a redeploy away.
A WITHDRAWN SKIN DRAWS NOTHING. Withdrawal is the takedown control
(SKINS.md §6): a design that turns out to be somebody else's character or
something vile must stop appearing in wallets with our name beside it the
moment it is withdrawn. So its image is a neutral placeholder, its
metadata omits its name and link, and nothing else about the token
changes — the holder keeps it.
*/
// TokenURI is the skin's image, as a data URI, for a token that exists.
func TokenURI(tid grc721.TokenID) (string, error) {
if _, err := token.OwnerOf(tid); err != nil {
return "", err
}
s, ok := skinOfTID(string(tid))
if !ok {
return placeholderImage("UNKNOWN SKIN"), nil
}
if s.withdrawn {
return placeholderImage("WITHDRAWN"), nil
}
if svg, ok := spriteSVG(s.art); ok {
return dataURI(svg), nil
}
return placeholderImage("ART WILL NOT RENDER"), nil
}
// TokenMetadata is the skin's metadata as a camelCase JSON string: name,
// description, externalUrl and attributes of {traitType, value}. No image
// in it; that is TokenURI.
func TokenMetadata(tid grc721.TokenID) (string, error) {
if _, err := token.OwnerOf(tid); err != nil {
return "", err
}
t := string(tid)
id, serial := t, ""
if h := strings.LastIndex(t, "#"); h > 0 {
id, serial = t[:h], t[h+1:]
}
s, ok := skinOfTID(t)
if !ok || s.withdrawn {
return `{"name":"Withdrawn skin #` + escapeJSON(serial) + `",` +
`"description":"This skin has been withdrawn and no longer draws on any name.",` +
`"attributes":[{"traitType":"Skin","value":"` + escapeJSON(id) + `"},` +
`{"traitType":"Status","value":"withdrawn"}]}`, nil
}
goesOn := "any name"
if s.lock != "" {
goesOn = "*" + s.lock + " names"
}
worn := "no"
if bindingIsLive(t) {
b := bound.Get(t).(*binding)
worn = b.label + "*" + b.domain
}
out := `{"name":"` + escapeJSON(s.name) + ` #` + escapeJSON(serial) + `",` +
`"description":"Card art for a Meme Name Service name. Wear it and it travels with the name.",`
if u := externalURL(t); u != "" {
out += `"externalUrl":"` + escapeJSON(u) + `",`
}
out += `"attributes":[` +
`{"traitType":"Skin","value":"` + escapeJSON(id) + `"},` +
`{"traitType":"Edition","value":"` + escapeJSON(serial) + `"},` +
`{"traitType":"Goes on","value":"` + escapeJSON(goesOn) + `"},` +
`{"traitType":"Worn by","value":"` + escapeJSON(worn) + `"}]}`
return out, nil
}
func skinOfTID(tid string) (*skin, bool) {
id, ok := skinOfToken(tid)
if !ok {
return nil, false
}
v := skins.Get(strings.ToLower(strings.TrimSpace(id)))
if v == nil {
return nil, false
}
return v.(*skin), true
}
// externalURL is the skin's own page: tokenURIBase plus the token id, on
// the chain's gnoweb when the base is a path. "#" would start a URL
// fragment, so it is escaped.
func externalURL(tid string) string {
esc := strings.ReplaceAll(tid, "#", "%23")
switch {
case strings.HasPrefix(tokenURIBase, "https://"):
return tokenURIBase + esc
case strings.HasPrefix(tokenURIBase, "/"):
return "https://" + runtime.ChainDomain() + tokenURIBase + esc
}
return ""
}
/*
spriteSVG draws the sprite format DefineSkin validates ("A#rrggbb,..|row|row")
as one rect per horizontal run, on a dark matte. It re-checks every rule
assertValidArt applies rather than trusting that it ran, and refuses the
whole sprite on any fault — a picture with holes in it is worse than an
honest placeholder. Colours are emitted only after they are checked to be
exactly # and six hex digits, so nothing from the definition reaches the
SVG unvalidated.
*/
func spriteSVG(art string) (string, bool) {
parts := strings.Split(art, "|")
n := len(parts) - 1
if n < 4 || n > 64 {
return "", false
}
pal := map[byte]string{}
for _, e := range strings.Split(parts[0], ",") {
if len(e) != 8 || e[1] != '#' || !isHex6(e[2:]) {
return "", false
}
pal[e[0]] = e[1:]
}
size := strconv.Itoa(n)
var b strings.Builder
b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ` + size + ` ` + size +
`" shape-rendering="crispEdges"><rect width="` + size + `" height="` + size + `" fill="#0b0d10"/>`)
for y := 0; y < n; y++ {
row := parts[y+1]
if len(row) != n {
return "", false
}
for x := 0; x < n; {
c := row[x]
if c == '.' {
x++
continue
}
col, ok := pal[c]
if !ok {
return "", false
}
x0 := x
for x < n && row[x] == c {
x++
}
b.WriteString(`<rect x="` + strconv.Itoa(x0) + `" y="` + strconv.Itoa(y) +
`" width="` + strconv.Itoa(x-x0) + `" height="1" fill="` + col + `"/>`)
}
}
b.WriteString(`</svg>`)
return b.String(), true
}
func isHex6(s string) bool {
if len(s) != 6 {
return false
}
for i := 0; i < 6; i++ {
c := s[i]
if (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') {
continue
}
return false
}
return true
}
func placeholderImage(msg string) string {
return dataURI(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">` +
`<rect width="400" height="400" fill="#0b0d10"/>` +
`<rect x="40" y="40" width="320" height="320" fill="none" stroke="#3f3f46" stroke-width="2" stroke-dasharray="7 6"/>` +
`<text x="200" y="206" text-anchor="middle" font-family="monospace" font-size="16" fill="#a1a1aa">` +
escapeXML(msg) + `</text></svg>`)
}
func dataURI(svg string) string {
return "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(svg))
}
func escapeXML(s string) string {
s = strings.ReplaceAll(s, "&", "&")
s = strings.ReplaceAll(s, "<", "<")
s = strings.ReplaceAll(s, ">", ">")
s = strings.ReplaceAll(s, `"`, """)
s = strings.ReplaceAll(s, "'", "'")
return s
}
func escapeJSON(s string) string {
var b strings.Builder
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == '"':
b.WriteString(`\"`)
case c == '\\':
b.WriteString(`\\`)
case c < 0x20:
const hex = "0123456789abcdef"
b.WriteString(`\u00`)
b.WriteByte(hex[c>>4])
b.WriteByte(hex[c&0xf])
default:
b.WriteByte(c)
}
}
return b.String()
}
attach.gno
package nsskin
import (
"gno.land/p/nt/grc721/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/nym-mnsrehearsal001/nsdata/v1"
)
func nameKey(label, domain string) string { return domain + "*" + label }
// bindingIsLive reports whether a token's binding still points at the
// registration it was made against. Same test ArtForName and Claim
// already apply; named once so the four copies cannot drift.
func bindingIsLive(tid string) bool {
v := bound.Get(tid)
if v == nil {
return false
}
b := v.(*binding)
if !nsdata.NameExists(b.label, b.domain) {
return false
}
_, registered, _, _, _, _ := nsdata.GetNameInfo(b.label, b.domain)
return registered == b.registered
}
// grcID saves every call site from importing grc721 just to cast.
func grcID(tid string) grc721.TokenID { return grc721.TokenID(tid) }
/*
Attach binds a skin to a name and puts the token into this realm's
custody. See the long note in types.gno for why custody rather than a
lock in place: it is what makes a marketplace's escrow of the NAME
irrelevant to the skin.
ONE SKIN, ONE NAME, both ways. A token may be attached to one name, and
a name may wear one skin. Letting one copy dress every name a person owns
would make the second copy pointless, and the object stops meaning
anything.
*/
func Attach(cur realm, tid, label, domain string) {
assertNoSend(cur)
wear(cur, tid, label, domain, cur.Previous().Address())
}
// wear is Attach's body, shared with Buy so that buying and wearing
// settle in one transaction. Splitting them would let a buyer stop
// halfway and end up holding a skin they paid for and did not put on.
func wear(cur realm, tid, label, domain string, caller address) {
id, ok := skinOfToken(tid)
if !ok {
panic("nsskin: no such skin token: " + tid)
}
s := mustSkin(id)
if s.withdrawn {
panic("nsskin: " + id + " has been withdrawn and cannot be worn")
}
if bound.Has(tid) {
panic("nsskin: " + tid + " is already on a name — claim it back first")
}
/* A STALE BINDING IS NOT A BINDING, and this used to be the one
place in the realm that forgot it.
Every other consumer — ArtForName, Refresh, refresh, Claim — pins
on `registered` and treats a mismatch as no binding at all. This
guard tested existence only, so: somebody attaches a skin, lets
the name lapse, never claims. A stranger re-registers the label
and can NEVER wear a skin on it — their Attach panics here, and
Claim refuses them because the stale binding entitles its own
binder. No admin call could clear it either. One registration
permanently killed the cosmetic slot on any label, and an honest
holder who simply let a name go did it by accident.
So a dead binding is evicted rather than obeyed. Only the reverse
index goes: `bound[tid]` stays, so the old binder can still Claim
their own token back — they paid for it and it is not forfeit. */
nk := nameKey(label, domain)
if cur := nameBound.Get(nk); cur != nil {
if !bindingIsLive(cur.(string)) {
nameBound.Remove(nk)
} else {
panic("nsskin: " + label + "*" + domain + " already wears a skin")
}
}
owner, err := token.OwnerOf(grcID(tid))
if err != nil {
panic("nsskin: " + err.Error())
}
if owner != caller {
panic("nsskin: you do not own " + tid)
}
if !nsdata.NameExists(label, domain) {
panic("nsskin: no such name: " + label + "*" + domain)
}
if !nsdata.IsNameValid(label, domain) {
panic("nsskin: " + label + "*" + domain + " has expired")
}
nameOwner, registered, _, _, _, _ := nsdata.GetNameInfo(label, domain)
if nameOwner != caller {
panic("nsskin: you do not own " + label + "*" + domain)
}
if s.lock != "" && s.lock != domain {
panic(ufmt.Sprintf("nsskin: %s only goes on *%s names, not *%s", id, s.lock, domain))
}
// Into custody. From here the token is in nobody's wallet, so it
// cannot be listed anywhere or sold out from under the name.
if err := ledger.TransferFrom(caller, caller, cur.Address(), grcID(tid)); err != nil {
panic("nsskin: could not take custody: " + err.Error())
}
bound.Set(tid, &binding{label: label, domain: domain, registered: registered, binder: caller})
nameBound.Set(nameKey(label, domain), tid)
}
/*
Refresh points a binding's `binder` at the name's CURRENT owner.
WHY THIS EXISTS, and it is the fix for a real hole. `binder` decides who
gets the skin back once the name record is gone. Set once at Attach and
never updated, it names whoever ATTACHED the skin — so: Alice attaches,
sells the name to Bob, the skin travels with it as intended, Bob lets the
name lapse, and the skin goes back to ALICE. Bob paid for it. That is
not a limitation, it is taking something from the person who bought it.
nsdata cannot tell us a name changed hands — it is permanent, it has no
hook, and it never will. So `binder` cannot be maintained; it can only be
CAUGHT UP. This is that, and it is deliberately open to anyone:
it only ever writes the name's real current owner, so calling it can
never move the skin anywhere it should not go, and there is nothing
to gain by calling it on somebody else's binding
which means the site can call it on a purchase, a keeper can call it
on a schedule, the buyer can call it themselves, or nobody calls it
at all and the next Attach or Claim does it — all with the same
result and none of them needing to be trusted
Nothing on chain is automatic here. gno has no scheduler and nsdata has
no callback, so every version of "the skin follows the sale" is one extra
call by someone. Making that call safe for ANYONE to make is as close to
automatic as this can get, and it is close enough.
*/
func Refresh(cur realm, tid string) {
// Permissionless and routinely called by keepers, so it is exactly
// the entry point a script attaches coins to by accident — and this
// realm's only banker moves that transaction's own OriginSend, so
// anything left here is stranded at the realm address forever.
assertNoSend(cur)
v := bound.Get(tid)
if v == nil {
return
}
b := v.(*binding)
if !nsdata.NameExists(b.label, b.domain) {
return
}
owner, registered, _, _, frozen, _ := nsdata.GetNameInfo(b.label, b.domain)
// Only for THIS registration. If the name lapsed and somebody else
// took it, the current owner is a stranger to this binding and must
// not be recorded as entitled to anything. Nor while the name is
// frozen: a disputed or stolen name's holder is not who the skin
// travels with (re-audit 2026-10-16, L-5).
if registered != b.registered || frozen {
return
}
b.binder = owner
}
// refresh is Refresh without the realm ceremony, for the callers below.
func refresh(b *binding) {
if !nsdata.NameExists(b.label, b.domain) {
return
}
owner, registered, _, _, frozen, _ := nsdata.GetNameInfo(b.label, b.domain)
if registered != b.registered || frozen {
return
}
b.binder = owner
}
/*
claimEntitled is Claim's rule on its own, with the record handed in (exists
false and zeros when the record is gone), so it can be tested without a
registry under it. A live, FROZEN registration is refused outright: the
admin freezes a stolen or disputed name so nothing moves while it is sorted
out, and its skin used to be claimable and sellable all the same (re-audit
2026-10-16, L-5). The record's frozen bit, not the ledger's holds, so a
free-tier name's skin still travels.
*/
func claimEntitled(b *binding, caller address, exists bool, owner address, registered int64, frozen bool) (bool, string) {
if exists && registered == b.registered {
if frozen {
return false, b.label + "*" + b.domain + " is frozen; its skin stays put until the name is released"
}
return owner == caller, ""
}
// The name lapsed and was taken by somebody else, or the record is
// gone: back to whoever the binding last knew. Another registration's
// freeze is not this binding's.
return caller == b.binder, ""
}
/*
Claim takes a skin out of custody and into the caller's wallet.
WHO MAY, and this is the whole travels-with-the-name rule:
the CURRENT OWNER of the name, while the name record still exists.
Buy the name, claim the skin — including a name bought from someone
else, which is the point.
the LAST KNOWN NAME OWNER, once the record is gone entirely. That is
the "it comes back to your wallet when the name expires" case — and
"last known" rather than "whoever attached it", because after a sale
those are different people and only one of them paid for it. See
Refresh above for how that is kept current without a hook nsdata
does not have.
The binding is pinned to one REGISTRATION. If a name lapsed and somebody
else registered it, its timestamp has changed, so the new registrant is
not the owner of anything here and cannot claim.
*/
func Claim(cur realm, tid string) {
assertNoSend(cur)
caller := cur.Previous().Address()
v := bound.Get(tid)
if v == nil {
panic("nsskin: " + tid + " is not on a name")
}
b := v.(*binding)
// Catch `binder` up before deciding, so a name that changed hands
// since it was attached settles on the person who holds it now
// rather than the person who first attached it.
refresh(b)
exists := nsdata.NameExists(b.label, b.domain)
var owner address
var registered int64
frozen := false
if exists {
owner, registered, _, _, frozen, _ = nsdata.GetNameInfo(b.label, b.domain)
}
entitled, why := claimEntitled(b, caller, exists, owner, registered, frozen)
if why != "" {
panic("nsskin: " + why)
}
if !entitled {
panic("nsskin: " + tid + " belongs to " + b.label + "*" + b.domain +
", and you are neither its owner nor the person who attached this")
}
if err := ledger.TransferFrom(cur.Address(), cur.Address(), caller, grcID(tid)); err != nil {
panic("nsskin: could not release: " + err.Error())
}
bound.Remove(tid)
// Only clear the reverse entry if it still points at THIS token — a
// stale binding may have been superseded by a new registrant's own
// skin, and clearing it blindly would strip theirs.
if cur := nameBound.Get(nameKey(b.label, b.domain)); cur != nil && cur.(string) == tid {
nameBound.Remove(nameKey(b.label, b.domain))
}
}
// SkinOnName returns the token currently worn by a name, or "".
func SkinOnName(label, domain string) string {
v := nameBound.Get(nameKey(label, domain))
if v == nil {
return ""
}
return v.(string)
}
// BindingOf reports where a token is attached, for a wallet or a shop.
func BindingOf(tid string) (label, domain string, registered int64, binder address) {
v := bound.Get(tid)
if v == nil {
return "", "", 0, ""
}
b := v.(*binding)
return b.label, b.domain, b.registered, b.binder
}
buy.gno
package nsskin
import (
"chain"
"strings"
"chain/banker"
"chain/runtime/unsafe"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/nym-mnsrehearsal001/nsdata/v1"
)
const ugnot = "ugnot"
/*
BUYING ONE, AND WEARING IT, IN A SINGLE TRANSACTION.
Splitting these would mean a buyer signs twice and can stop between —
leaving a skin they paid for sitting unworn in a wallet, which is the
state nobody wants and the one a two-step flow produces most often. So
the name is an argument: pass it and the skin is minted and attached
together; pass "" and it is minted loose, which is what somebody buying
ahead of registering a name needs.
NOTHING IS EVER HELD. Payment, treasury and refund all settle inside the
buyer's own transaction, exactly as nslogic does it — and for the same
reason, which is worth restating because it is a legal position rather
than a style: a realm you can have a BALANCE in is a different kind of
thing to operate, subject to different rules, run by people with
licences. Every ugnot that arrives leaves again in the same call.
THE 70/30 SPLIT IS NOT HERE, and that is deliberate rather than
forgotten. Every skin in this collection is ours, so the artist and the
treasury are the same address and a split would move money from a
pocket to itself while costing gas to do it. The artist is recorded on
every definition so the day it stops being us, this is where the split
goes — see SKINS.md.
*/
func Buy(cur realm, id, label, domain string) string {
if !cur.Previous().IsUserCall() {
panic("nsskin: only direct wallet calls may attach payment")
}
buyer := cur.Previous().Address()
// Same normalization as Mint, for the same reason: the token id is
// built from this string, and an un-lowercased one mints a token
// that can never render. See the note in write.gno.
id = strings.ToLower(strings.TrimSpace(id))
s := mustSkin(id)
if s.withdrawn {
panic("nsskin: " + id + " has been withdrawn and is not for sale")
}
// Refuse the sale rather than the attach. Minting a locked skin to
// somebody who wanted it for a name it will never go on is a refund
// request wearing the clothes of a successful purchase.
if label != "" && s.lock != "" && s.lock != domain {
panic(ufmt.Sprintf("nsskin: %s only goes on *%s names, not *%s", id, s.lock, domain))
}
sent := unsafe.OriginSend()
for _, c := range sent {
if c.Denom != ugnot {
panic("nsskin: only ugnot is accepted, got: " + c.Denom)
}
}
// PER DESIGN, not one figure for the collection. A third of the
// definitions are free by the rule in price.gno, and an admin may
// have priced any of them by hand — see PriceOf, which is the only
// place that decides.
due := PriceOf(id)
paid := sent.AmountOf(ugnot)
if paid < due {
panic(ufmt.Sprintf("nsskin: insufficient payment: need %d ugnot, got %d", due, paid))
}
// A FREE SKIN TAKES NO PAYMENT AND MOVES NO COINS, and the refund
// below is what makes that safe: somebody whose page quoted the old
// price, or who simply attached coins to a free mint, gets every
// ugnot back in the same transaction rather than donating it.
b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
me := cur.Address()
if due > 0 {
b.SendCoins(me, nsdata.GetTreasury(), chain.Coins{chain.NewCoin(ugnot, due)})
}
if excess := paid - due; excess > 0 {
b.SendCoins(me, buyer, chain.Coins{chain.NewCoin(ugnot, excess)})
}
s.minted++
tid := ufmt.Sprintf("%s#%d", id, s.minted)
if err := ledger.Mint(buyer, grcID(tid)); err != nil {
panic("nsskin: mint failed: " + err.Error())
}
tokenSkin.Set(tid, id)
if label != "" {
wear(cur, tid, label, domain, buyer)
}
return tid
}
// SetPrice sets the BASE price, in ugnot — what a design costs when the
// rule has not made it free and no admin has priced it by hand. ugnot
// because that is what the chain moves: what it is worth in anything
// else is a question for the page that quotes it, and pinning a dollar
// figure into a contract that cannot see an exchange rate would be a lie
// with a number in it.
func SetPrice(cur realm, p int64) {
assertIsAdmin(cur)
if p < 0 {
panic("nsskin: a negative price is not a discount")
}
price = p
}
func GetPrice() int64 { return price }
// Free calls must not be able to strand coins here. This realm has no
// withdrawal path, so anything attached to one would sit in its address
// permanently.
func assertNoSend(cur realm) {
if !cur.Previous().IsUserCall() {
return
}
if len(unsafe.OriginSend()) > 0 {
panic("nsskin: this call takes no payment")
}
}
gnomod.toml
module = "gno.land/r/nym-mnsrehearsal001/nsskin/v1" gno = "0.9" [addpkg] creator = "g1lh4rrf9pq9k9tvka9p6vwhyv70e4h09szap6zu" height = 452703 max_deposit = "25000000ugnot"
init.gno
package nsskin
import (
"gno.land/p/nt/grc721/v0"
"gno.land/p/nt/seqid/v0"
)
// The deployer is the first admin. Rotatable with SetAdmin, and
// deliberately NOT the vault's timelocked governance: this realm is
// replaceable, so it does not need machinery built for one that is not.
// See the note in types.gno.
//
// The ledger is the chain's own gno.land/p/nt/grc721/v0, created here
// once: NewToken emits the NewToken event and every later mint and
// transfer is stamped with that package, which is what wallets and
// indexers require before they will list a skin at all. The collection
// id is "<this realm's path>.MNSKIN.0000000".
func init(cur realm) {
token, ledger = grc721.NewToken("Meme Name Service Skins", "MNSKIN", seqid.ID(0), cur)
admin = cur.Previous().Address()
}
price.gno
package nsskin
import (
"strings"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/ufmt/v0"
)
/*
WHAT ONE COSTS, PER DESIGN.
There used to be a single `price` for the whole collection, which is the
right shape for a launch batch and the wrong one the moment anything in
it is worth more or less than the rest — or worth nothing, which is the
interesting case.
Three sources, in order, and only the first of them stores anything:
an ADMIN OVERRIDE, if one has been set for this id
ZERO, if the id falls in the free share by the rule below
the BASE PRICE otherwise
# WHY THE FREE ONES ARE COMPUTED RATHER THAN LISTED
Marking a third of sixty definitions free by storing a flag on each is
sixty writes and sixty entries that live forever, to record something
that never changes. The rule below derives it from the id, so it costs
nothing to store, nothing to keep in step, and cannot drift between the
contract, the shop and the collection file — all three ask the same
question of the same string and get the same answer.
It is ARBITRARY, which is the point: nothing about a design implies its
price, and a rule nobody can lobby is fairer than a list somebody picked.
An admin who disagrees about a particular one sets an override, and that
override is then a deliberate, visible, single stored fact.
# WHY A HASH AND NOT EVERY THIRD ONE
Definitions are iterated and displayed in id order, so "every third"
would put the free ones in a visible stripe down the grid and make the
whole thing look like a pricing table rather than a collection.
*/
/*
The threshold, out of a hundred, under which a hashed id is free.
THIRTY-FIVE, NOT THIRTY, AND THE FOUR-POINT GAP IS THE HONEST PART. The
rule is a statement about ids, not a quota, so any particular collection
lands near the threshold rather than on it — sixty ids at a threshold of
thirty came out at thirteen, which is twenty-one per cent and not the
third that was asked for. Thirty-five puts the launch batch at eighteen,
which is thirty per cent exactly.
So the constant was chosen to fit the collection that exists. That is
worth saying plainly rather than dressing up: what it buys is that every
FUTURE id still gets an answer nobody can lobby for, which is the
property that mattered, while the batch on sale today is the share that
was promised.
A constant rather than a stored value, because changing it would
silently reprice every skin nobody has overridden — including ones
people have already been shown a price for. That should cost a deploy.
*/
const freeShare = 35
// priceOverride holds ONLY the ids an admin has priced by hand. An id
// that is absent is not "free" and not "base" — it is unopinionated, and
// PriceOf decides. Storing a value for every skin would make the common
// case cost as much as the exception.
var priceOverride = avl.NewTree() // definition id -> int64 ugnot
/*
freeByRule is FNV-1a over the id, taken modulo one hundred.
freeShare of every hundred ids fall under the threshold, so the share
lands NEAR it rather than on it for any particular collection — see the
note on the constant. The launch batch of sixty comes out at eighteen,
and ListFreeSkins says so rather than asking anyone to trust the
arithmetic.
The same hash is in nsview.faceForArt, deliberately not shared: one runs
over a sprite and one over an id, they answer different questions, and a
helper spanning both realms would be a dependency between them for four
lines of arithmetic.
*/
func freeByRule(id string) bool {
h := uint32(2166136261)
for i := 0; i < len(id); i++ {
h ^= uint32(id[i])
h *= 16777619
}
return h%100 < freeShare
}
// IsFreeByRule reports what the rule alone says, ignoring any override.
// Exposed so an admin panel can show what it would revert to.
func IsFreeByRule(id string) bool {
return freeByRule(strings.ToLower(strings.TrimSpace(id)))
}
// HasPriceOverride reports whether this id has been priced by hand. A
// panel needs it to tell "set to zero" from "free by the rule", which
// look identical in the price alone and are different decisions.
func HasPriceOverride(id string) bool {
return priceOverride.Has(strings.ToLower(strings.TrimSpace(id)))
}
// PriceOf is what this design costs right now, in ugnot.
//
// It does NOT check that the id exists: a price for a definition that is
// not there is meaningless rather than wrong, and Buy is the thing that
// must refuse an unknown id — which it already does, by name, before it
// ever asks what the price is.
func PriceOf(id string) int64 {
id = strings.ToLower(strings.TrimSpace(id))
if v := priceOverride.Get(id); v != nil {
return v.(int64)
}
if freeByRule(id) {
return 0
}
return price
}
/*
SetSkinPrice prices one design by hand, overriding the rule.
Zero is a legitimate value and is NOT the same as removing the override:
it says "this one is free because I said so", which survives a change to
the base price and to the rule. ClearSkinPrice is how you go back to
being unopinionated.
*/
func SetSkinPrice(cur realm, id string, p int64) {
assertIsAdmin(cur)
setSkinPrice(id, p)
}
// setSkinPrice is SetSkinPrice without the realm ceremony. Split for the
// same reason attach.gno splits refresh from Refresh: the rules are
// worth testing on their own, and the gate above them is the same
// assertIsAdmin every other write in this realm goes through.
func setSkinPrice(id string, p int64) {
id = strings.ToLower(strings.TrimSpace(id))
if !skins.Has(id) {
panic("nsskin: no such skin: " + id)
}
if p < 0 {
panic("nsskin: a negative price is not a discount")
}
priceOverride.Set(id, p)
}
// ClearSkinPrice drops an override, putting the design back under the
// rule and the base price.
func ClearSkinPrice(cur realm, id string) {
assertIsAdmin(cur)
clearSkinPrice(id)
}
func clearSkinPrice(id string) {
priceOverride.Remove(strings.ToLower(strings.TrimSpace(id)))
}
/*
SetSkinPrices prices many designs in one call.
A panel that lets somebody retune a collection produces a batch of
changes, and sixty separate transactions is sixty flat fees for what is
one decision. Same encoding as AllSkins reads back — tab between the id
and the price, newline between records — so the two halves of the panel
speak one format.
An empty price field CLEARS the override rather than setting zero. The
panel shows an empty box for "no opinion" and a 0 for "free on purpose",
and those must not collapse into each other on the way here.
*/
func SetSkinPrices(cur realm, packed string) {
assertIsAdmin(cur)
setSkinPrices(packed)
}
func setSkinPrices(packed string) {
/* CHECKED IN FULL BEFORE ANYTHING IS WRITTEN.
A panic reverts the whole transaction on chain, so applying as we
go would come out right in production — but only because of a
guarantee living somewhere else. Validating first makes the
promise true of this function on its own, which is what the tests
can actually hold it to, and it costs one pass over a list that is
sixty lines at its largest. */
type change struct {
id string
clear bool
p int64
}
var pending []change
for _, raw := range strings.Split(packed, "\n") {
/* TRIMMED AROUND THE FIELDS, NOT AROUND THE LINE. Trimming the
whole line first ate the trailing tab of "id\t", which is the
form that CLEARS an override — so "no opinion" arrived here
looking like a line with no tab at all and was rejected as
malformed. Only the carriage return goes, because a form
posting CRLF is not making a statement about pricing. */
line := strings.TrimRight(raw, "\r")
if strings.TrimSpace(line) == "" {
continue
}
tab := strings.Index(line, "\t")
if tab < 0 {
panic("nsskin: each line is <id>\\t<ugnot>, got: " + line)
}
id := strings.ToLower(strings.TrimSpace(line[:tab]))
val := strings.TrimSpace(line[tab+1:])
if !skins.Has(id) {
panic("nsskin: no such skin: " + id)
}
if val == "" {
pending = append(pending, change{id: id, clear: true})
continue
}
p, ok := parseU64(val)
if !ok {
panic("nsskin: not a number of ugnot: " + val)
}
pending = append(pending, change{id: id, p: p})
}
for _, c := range pending {
if c.clear {
priceOverride.Remove(c.id)
continue
}
priceOverride.Set(c.id, c.p)
}
}
// parseU64 is strconv.ParseInt without the import, and without accepting
// a sign — every price here is a non-negative amount of ugnot, and "-0"
// or "+5" arriving from a form should be refused rather than guessed at.
func parseU64(s string) (int64, bool) {
if len(s) == 0 || len(s) > 18 {
return 0, false
}
var n int64
for i := 0; i < len(s); i++ {
c := s[i]
if c < '0' || c > '9' {
return 0, false
}
n = n*10 + int64(c-'0')
}
return n, true
}
/*
ListFreeSkins names every definition that costs nothing right now,
counting overrides — so it answers "what can I have for free", which is
the question, rather than "what does the rule say", which is trivia.
*/
func ListFreeSkins() string {
var b strings.Builder
skins.Iterate("", "", func(k string, _ any) bool {
if PriceOf(k) == 0 {
b.WriteString(k + "\n")
}
return false
})
return b.String()
}
// AllPrices is every id and its price, for a shop that wants the lot in
// one read. AllSkins carries the price too; this exists for a panel that
// wants prices without the rest and for checking the two agree.
func AllPrices() string {
var b strings.Builder
skins.Iterate("", "", func(k string, _ any) bool {
o := "0"
if priceOverride.Has(k) {
o = "1"
}
b.WriteString(k + "\t" + ufmt.Sprintf("%d", PriceOf(k)) + "\t" + o + "\n")
return false
})
return b.String()
}
read.gno
package nsskin
import (
"strings"
"gno.land/p/nt/grc721/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/nym-mnsrehearsal001/nsdata/v1"
)
/*
ArtForName is the one question the renderer asks, and it is answered here
so the rule lives with the data it depends on.
It returns the sprite a name should be drawn with, or "" for the ordinary
card. Everything the renderer would otherwise have to remember to check
is inside it, because a renderer that has to remember three things before
drawing is one that eventually forgets one.
The checks, and what each of them makes self-cleaning:
the name wears a token at all
that token's definition has not been WITHDRAWN — so a takedown
reverts every name wearing it, everywhere, at once, with no
migration and no per-name cleanup
the binding is FRESH, pinned to this registration — so a name that
lapsed and was taken by somebody else inherits nothing
the LOCK still matches — belt and braces, since Attach checks it too
Note what is NOT checked: who holds the token in their wallet. Nobody
does. It is in this realm's custody for as long as it is attached, which
is what makes the skin travel with the name instead of with a wallet.
*/
func ArtForName(label, domain string) string {
tid := SkinOnName(label, domain)
if tid == "" {
return ""
}
v := bound.Get(tid)
if v == nil {
return ""
}
b := v.(*binding)
if !nsdata.NameExists(label, domain) {
return ""
}
_, registered, _, _, _, _ := nsdata.GetNameInfo(label, domain)
if registered != b.registered {
return "" // a different registration of the same label
}
id, ok := skinOfToken(tid)
if !ok {
return ""
}
// Normalized on the way in, so a token minted from a non-canonical
// id before Buy/Mint were fixed starts rendering instead of staying
// a blank card its holder already paid for.
sv := skins.Get(strings.ToLower(strings.TrimSpace(id)))
if sv == nil {
return ""
}
s := sv.(*skin)
if s.withdrawn {
return ""
}
if s.lock != "" && s.lock != domain {
return ""
}
return s.art
}
// SkinInfo describes a DEFINITION, for a shop listing or a skin's own
// card. Withdrawn is returned rather than hidden: a holder is entitled
// to know, and a listing that silently vanishes is worse than one that
// says what happened.
func SkinInfo(id string) (name, art, lock string, artist address, withdrawn bool, minted int64) {
s := mustSkin(id)
return s.name, s.art, s.lock, s.artist, s.withdrawn, s.minted
}
func SkinExists(id string) bool {
return skins.Has(strings.ToLower(strings.TrimSpace(id)))
}
// ListSkins returns every definition id, in tree order. Small by
// construction — this is a curated shop, not a submission firehose — and
// if that ever stops being true it wants paging rather than a bigger
// answer.
func ListSkins() []string {
var out []string
skins.Iterate("", "", func(k string, _ any) bool {
out = append(out, k)
return false
})
return out
}
/*
AllSkins packs the whole catalogue into ONE read.
A shop page needs every definition's name, lock and availability, and
asking for them one at a time is sixty round trips before anything
appears on screen. The ART is deliberately NOT here: it is the bulk of
the data, it is committed in the repo as the canonical source, and a
page that already has it does not need to fetch it again.
Six fields: id, name, lock, withdrawn, minted, price in ugnot.
Tab-separated fields, newline-separated records — not JSON, because
building JSON by string concatenation in a realm is how quoting bugs get
shipped, and a shop is not worth that risk. No field can contain a tab
or a newline: ids and locks are [a-z0-9-] by rule, and a name is checked
here rather than assumed.
*/
func AllSkins() string {
var b strings.Builder
skins.Iterate("", "", func(k string, v any) bool {
s := v.(*skin)
nm := s.name
if strings.ContainsAny(nm, "\t\n") {
nm = "?" // never seen: DefineSkin would have to have accepted it
}
w := "0"
if s.withdrawn {
w = "1"
}
// PRICE IS THE SIXTH FIELD, appended rather than inserted, so a
// page shipped before per-design pricing keeps reading the five
// it knows and simply does not see this one.
b.WriteString(k + "\t" + nm + "\t" + s.lock + "\t" + w + "\t" +
ufmt.Sprintf("%d", s.minted) + "\t" +
ufmt.Sprintf("%d", PriceOf(k)) + "\n")
return false
})
return b.String()
}
func skinOfToken(tid string) (string, bool) {
v := tokenSkin.Get(tid)
if v == nil {
return "", false
}
return v.(string), true
}
// SkinOfToken is skinOfToken for callers outside the realm.
func SkinOfToken(tid string) string {
id, _ := skinOfToken(tid)
return id
}
func GetAdmin() address { return admin }
func GetTokenURIBase() string { return tokenURIBase }
func IsTrustedShop(a address) bool {
return trustedShop.Has(a.String())
}
// ---------------------------------------------------------------- grc721
func Name() string { return token.GetName() }
func Symbol() string { return token.GetSymbol() }
func GetName() string { return token.GetName() }
func GetSymbol() string { return token.GetSymbol() }
func TokenCount() int64 { return token.TotalSupply() }
func TotalSupply() int64 { return token.TotalSupply() }
// ID is the collection id wallets and indexers key on:
// "<this realm's path>.MNSKIN.0000000".
func ID() string { return token.ID() }
func BalanceOf(owner address) int64 {
bal, err := token.BalanceOf(owner)
if err != nil {
panic(err)
}
return bal
}
// OwnerOf does NOT hide a withdrawn skin's owner, and that is the
// opposite of what nsdata does for an expired name.
//
// There, hiding the owner is an anti-scam measure: a lapsed name must
// not be listable, because the seller no longer controls it. Here the
// holder still owns the token completely — withdrawal only stops it
// being DRAWN. Hiding the owner would break transfers and approvals for
// somebody who has done nothing wrong, to solve a problem that is not
// theirs.
func OwnerOf(tid grc721.TokenID) address {
owner, err := token.OwnerOf(tid)
if err != nil {
panic(err)
}
return owner
}
// Total, the same way nsdata.GetApproved is: the zero address means
// nobody is approved, and only an unknown token id panics. Collapsing
// "no approval" into "no such token" would leave no caller able to fall
// back to the operator grant without catching a panic first.
func GetApproved(tid grc721.TokenID) address {
a, err := token.GetApproved(tid)
if err != nil {
if _, oerr := token.OwnerOf(tid); oerr != nil {
panic(err)
}
return ""
}
return a
}
func IsApprovedForAll(owner, operator address) bool {
return token.IsApprovedForAll(owner, operator)
}
types.gno
// Package nsskin holds purchasable card art — the skins — as tokens of
// their own, and binds them to names.
//
// WHY THIS IS ITS OWN REALM AND NOT PART OF nsdata. SKINS.md §8 listed
// it as undecided; it is decided here, because the reasoning turned out
// to be one-sided rather than balanced.
//
// nsdata IS PERMANENT. It cannot be replaced, ever. A second kind of
// token in it means every mistake in the skin model is permanent too,
// and the skin model is the newest and least settled thing here.
//
// nsdata.OwnerOf DELIBERATELY PANICS FOR EXPIRED TOKENS so a lapsed
// name cannot be listed anywhere. Skins do not expire. That machinery
// is exactly wrong for them, and a conditional on token kind inside
// the one realm that can never be fixed is the worst place for it.
//
// A NEW REALM CAN BE REPLACED while it holds a handful of tokens. The
// vault cannot, at any point, for any reason.
//
// So being wrong here costs a migration nobody notices. Being wrong
// inside nsdata costs forever.
//
// # A SKIN IS TWO THINGS
//
// A DEFINITION is the artwork: a name, a sprite, an optional extension
// lock, and the artist to pay. One per design, stored once — a
// thousand holders of one design cost one sprite, not a thousand.
//
// A TOKEN is somebody's copy. Editions are unlimited, because SKINS.md
// is explicit that a cap is a floor price with extra steps and resale
// value is never part of the pitch.
//
// # A SKIN BINDS TO ONE NAME, AND TRAVELS WITH IT
//
// This reverses an earlier recommendation of mine, and the new answer is
// better. I had argued for keeping them separate — a pointer from the
// name, reverting on sale — because names expire and skins should not.
// The objection to bundling was that a buyer sees a skinned card on a
// marketplace and receives an unskinned name.
//
// Binding solves that rather than working around it. The skin genuinely
// comes with the name, so the card is not misleading, and the small
// disclosure line the old model needed inside the artwork disappears.
// And a skin still does not die with a name: when the name goes, the
// skin comes back.
//
// # WHY ATTACHING ESCROWS THE TOKEN, WHICH IS THE WHOLE CUSTODY ANSWER
//
// The worry: a name listed on a marketplace that takes CUSTODY. If the
// skin lived in the seller's wallet, a custodial listing would hold the
// name while the skin sat somewhere else, and untangling that on expiry
// would need cooperation we cannot compel.
//
// So attaching moves the token to THIS REALM'S OWN ADDRESS. While
// attached it is in nobody's wallet: it cannot be listed, cannot be sold
// out from under the name, and a marketplace escrowing the NAME never
// touches it. The question of freeing a skin from somebody else's
// custody does not arise, because it was never in it.
//
// Taking it out again is one rule with one fallback:
//
// WHILE THE NAME EXISTS, its CURRENT OWNER may claim the skin. That is
// what makes it travel: buy the name, claim the skin.
//
// IF THE NAME RECORD IS GONE — lapsed and reclaimed — whoever attached
// it may take it back, which is the "it returns to your wallet" case.
//
// One limitation, stated rather than hidden: buy a name with a skin,
// never claim it, and let that name lapse completely, and the skin
// returns to whoever attached it. Claiming on purchase avoids it
// entirely, and the site prompts for exactly that.
package nsskin
import (
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/grc721/v0"
)
type skin struct {
name string // as the shop shows it
art string // the sprite string, in the format nsview parses
lock string // an extension label, or "" for one that goes anywhere
artist address
// WITHDRAWN IS NOT DELETED, and the distinction is the whole
// takedown mechanism (SKINS.md §6). Deleting a definition orphans
// every token pointing at it. Withdrawing leaves everything in place
// and stops it drawing — every name wearing it reverts at once, with
// no migration and no per-name cleanup, because the card is
// generated on every read.
withdrawn bool
minted int64 // how many copies exist, and the next serial
}
// A live attachment. `registered` pins it to one REGISTRATION of the
// name, not to the label: if the name lapses and somebody else takes it,
// the timestamp changes and this binding is stale, so the new registrant
// inherits nothing.
type binding struct {
label string
domain string
registered int64
binder address // who attached it, and who gets it back if the name dies
}
var (
// Constructed in init, which is where it can be handed the realm:
// the chain's own GRC-721, so every mint and transfer is stamped
// gno.land/p/nt/grc721/v0. token is the read side; ledger, the write
// side, never leaves this realm.
token *grc721.Token
ledger *grc721.PrivateLedger
skins = avl.NewTree() // definition id -> *skin
// token id -> definition id. Derivable by splitting the token id,
// but stored so a lookup is a tree read rather than string surgery
// that has to agree with the minter forever.
tokenSkin = avl.NewTree()
bound = avl.NewTree() // token id -> *binding
nameBound = avl.NewTree() // "domain*label" -> token id
// Where a skin's own page lives, for the externalUrl in its metadata.
// A gnoweb path ("/r/.../nsview:skin/") or a full https URL. The
// IMAGE is drawn here (art.gno), from the definition's own sprite,
// because wallets put TokenURI straight into an <img>.
tokenURIBase = "/r/demo/nsview:skin/"
// Day-to-day authority: define, mint, withdraw. Deliberately a plain
// address rather than the vault's timelocked governance — this realm
// is replaceable, so it does not need machinery built for one that
// is not.
admin address
// Realms allowed to mint on somebody's behalf, which is what a shop
// is. Empty at first: the launch batch is minted by the admin.
trustedShop = avl.NewTree()
// What one costs, in ugnot. Zero until an admin sets it, so a
// misconfigured deploy gives skins away rather than charging an
// accidental amount — the failure that costs nobody money.
price int64
)
const (
maxSkinName = 40
maxSkinArt = 2048 // a 32x32 sprite is about 1,100 bytes
maxSkinID = 24 // appears in every token id and every binding
)
write.gno
package nsskin
import (
"strings"
"gno.land/p/nt/grc721/v0"
"gno.land/p/nt/ufmt/v0"
)
func assertIsAdmin(cur realm) {
if cur.Previous().Address() != admin {
panic("nsskin: not the admin")
}
}
func assertIsAdminOrShop(cur realm) {
a := cur.Previous().Address()
if a == admin {
return
}
if !trustedShop.Has(a.String()) {
panic("nsskin: not the admin or a trusted shop")
}
}
/*
DefineSkin registers a design. It does not mint anything.
Definitions and copies are separate calls on purpose: defining is the
expensive, careful, one-off act that puts an artist's work and a sprite
on chain, while minting is the cheap repeated one. Rolling them together
would mean re-sending the artwork with every sale.
A definition may be REDEFINED only while nothing has been minted from it.
After the first copy exists, the art is what its holders bought and it
stops being ours to edit — the only lever left is withdrawal, which is
honest about what it is doing.
*/
func DefineSkin(cur realm, id, name, art, lock string, artist address) {
assertIsAdmin(cur)
id = strings.ToLower(strings.TrimSpace(id))
assertValidID(id)
if len(name) == 0 || len(name) > maxSkinName {
panic("nsskin: a skin needs a name, of at most 40 characters")
}
if len(art) == 0 || len(art) > maxSkinArt {
panic(ufmt.Sprintf("nsskin: art is %d bytes, the limit is %d", len(art), maxSkinArt))
}
// The SHAPE of the sprite is checked here; whether it renders is
// nsview's business. Storing something the renderer will reject
// silently is the failure mode this exists to prevent — a skin that
// draws nothing, sold to somebody, discovered later.
assertValidArt(art)
if lock != "" {
assertValidLabel(lock)
}
if artist == "" {
panic("nsskin: a skin needs an artist to pay")
}
if v := skins.Get(id); v != nil {
s := v.(*skin)
if s.minted > 0 {
panic(ufmt.Sprintf(
"nsskin: %s has %d copies out — redefining it would change "+
"what those holders bought; withdraw it instead", id, s.minted))
}
s.name, s.art, s.lock, s.artist = name, art, lock, artist
return
}
skins.Set(id, &skin{name: name, art: art, lock: lock, artist: artist})
}
/*
Mint issues one copy of a definition to somebody.
The serial is the definition's own running count, so token ids read as
"ember#1", "ember#2". Never reused: the counter only goes up, even across
burns, because a reissued id would let a new token inherit whatever an
old one was pointed at.
*/
func Mint(cur realm, id string, to address) string {
assertIsAdminOrShop(cur)
assertNoSend(cur)
/* NORMALIZED BEFORE THE TOKEN ID IS BUILT.
mustSkin and PriceOf lowercase what they are given; this did not,
so Mint("Ember", …) resolved the right definition and then minted
"Ember#3" while tokenSkin recorded the raw id. ArtForName looks the
definition up in a tree DefineSkin lowercased, so the token bound,
charged, and then rendered nothing, forever. An admin typing a
capital into a form was all it took. */
id = strings.ToLower(strings.TrimSpace(id))
s := mustSkin(id)
if s.withdrawn {
panic("nsskin: " + id + " has been withdrawn and cannot be minted")
}
if to == "" {
panic("nsskin: no recipient")
}
s.minted++
tid := ufmt.Sprintf("%s#%d", id, s.minted)
if err := ledger.Mint(to, grc721.TokenID(tid)); err != nil {
panic("nsskin: mint failed: " + err.Error())
}
tokenSkin.Set(tid, id)
return tid
}
/*
Withdraw is the takedown control, and SKINS.md §6 makes it
non-negotiable: it has to exist before a single outside submission is
accepted, which means it has to exist now, while there is nothing to take
down and it is cheap to build.
Somebody will submit a character somebody else owns, or a bank's logo, or
something vile, and it will render inside other people's wallets with our
name beside it. When that happens the fix has to be one call, not a
migration.
It does NOT burn anything. The holder keeps the token; it simply stops
rendering, and every name pointing at it falls back to the ordinary card
at once. Burning somebody's property to solve our problem is a different
act with different consequences, and it is not this one.
*/
func Withdraw(cur realm, id string, withdrawn bool) {
assertNoSend(cur)
assertIsAdmin(cur)
mustSkin(id).withdrawn = withdrawn
}
func SetTokenURIBase(cur realm, base string) {
assertNoSend(cur)
assertIsAdmin(cur)
tokenURIBase = base
}
func SetAdmin(cur realm, a address) {
assertNoSend(cur)
assertIsAdmin(cur)
if a == "" {
panic("nsskin: refusing to leave the realm with no admin")
}
admin = a
}
func TrustShop(cur realm, a address, trusted bool) {
assertNoSend(cur)
assertIsAdmin(cur)
if trusted {
trustedShop.Set(a.String(), true)
return
}
trustedShop.Remove(a.String())
}
// ---------------------------------------------------------------- grc721
func TransferFrom(cur realm, from, to address, tid grc721.TokenID) {
assertNoSend(cur)
if err := ledger.TransferFrom(cur.Previous().Address(), from, to, tid); err != nil {
panic("nsskin: " + err.Error())
}
}
func Approve(cur realm, to address, tid grc721.TokenID) {
assertNoSend(cur)
if err := ledger.Approve(cur.Previous().Address(), to, tid); err != nil {
panic("nsskin: " + err.Error())
}
}
func SetApprovalForAll(cur realm, operator address, approved bool) {
assertNoSend(cur)
if err := ledger.SetApprovalForAll(cur.Previous().Address(), operator, approved); err != nil {
panic("nsskin: " + err.Error())
}
}
// ---------------------------------------------------------------- checks
func mustSkin(id string) *skin {
v := skins.Get(strings.ToLower(strings.TrimSpace(id)))
if v == nil {
panic("nsskin: no such skin: " + id)
}
return v.(*skin)
}
// An id goes into every token id and into the pointer a name stores, so
// it has to survive being split on "#" and compared byte for byte.
func assertValidID(id string) {
if len(id) == 0 || len(id) > maxSkinID {
panic("nsskin: a skin id must be 1 to 24 characters")
}
for i := 0; i < len(id); i++ {
c := id[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' {
continue
}
panic("nsskin: a skin id may only use a-z, 0-9 and -: " + id)
}
}
func assertValidLabel(l string) {
if len(l) == 0 || len(l) > 63 {
panic("nsskin: a lock must be a domain label")
}
for i := 0; i < len(l); i++ {
c := l[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' {
continue
}
panic("nsskin: a lock may only use a-z, 0-9 and -: " + l)
}
}
/*
assertValidArt mirrors the sprite checks nsview makes, and it is here for
one reason: nsview REJECTS THE WHOLE SPRITE SILENTLY. A malformed skin
does not draw a broken picture, it draws nothing at all, with no error
anywhere a person would see it.
Storing one would mean selling somebody a blank card and finding out
weeks later. So the shape is checked at the point of storage, where the
failure is a panic in a transaction nobody has paid for yet.
Deliberately checks the SHAPE and not the rendering. This realm does not
know how a card is composed and should not learn — that is the whole
reason the renderer is swappable.
*/
func assertValidArt(enc string) {
parts := strings.Split(enc, "|")
n := len(parts) - 1
if n < 4 || n > 64 {
panic(ufmt.Sprintf("nsskin: a sprite needs 4 to 64 rows, this has %d", n))
}
keys := map[string]bool{}
for _, e := range strings.Split(parts[0], ",") {
if len(e) != 8 || e[1] != '#' {
panic("nsskin: a palette entry must be a letter, #, and six hex digits: " + e)
}
for i := 2; i < 8; i++ {
c := e[i]
if (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') {
continue
}
panic("nsskin: not a hex colour: " + e)
}
keys[e[:1]] = true
}
for y := 1; y <= n; y++ {
if len(parts[y]) != n {
panic(ufmt.Sprintf(
"nsskin: row %d is %d wide but the sprite is %d rows tall — it must be square",
y, len(parts[y]), n))
}
for x := 0; x < n; x++ {
ch := parts[y][x : x+1]
if ch == "." || keys[ch] {
continue
}
panic(ufmt.Sprintf("nsskin: row %d uses colour %s, which the palette does not define", y, ch))
}
}
}