Playground
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/nativereg/v0" gno = "0.9" [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914348 max_deposit = "8000000ugnot"
nativereg.gno
// Package nativereg is the metadata a native coin does not have.
//
// A realm-issued coin is a string and a balance. `/gno.land/r/moul/x/moultest/v0:moultest`
// is the entire object: no name, no symbol, no decimals, no icon, no link to
// whoever issues it. The bank knows the number and nothing else, so a wallet or
// an explorer showing you a balance has only that path to print.
//
// This realm is where a denom says what it is. It is the mirror image of
// `r/nt/grc20reg`, and the two solve opposite problems: a GRC20 is an object
// that carries its own name and is hard to FIND, so the registry maps a key to
// the object; a native denom is trivial to find and carries no name, so the
// registry maps the denom to what it means.
//
// # Registration is proved, not claimed
//
// A denom embeds the package path of the realm allowed to issue it, verbatim:
// `"/" + pkgPath + ":" + baseName` (`chain.CoinDenom`). So the issuer is
// readable from the denom, and [Register] simply requires the caller to be it.
// A realm registers its own coins and nobody else's, with no allowlist, no
// owner and no signature scheme.
//
// A user account cannot register anything, not even a denom it holds all of:
// there is no package path in a user call to compare against. That is the
// intended shape, since the thing being described is the issuance, not the
// holding.
//
// # What is a hint and what is a fact
//
// `Denom` and `Issuer` are facts: the chain enforces the relation between them.
// Everything else is whatever the issuing realm chose to say, and `Decimals` in
// particular is a DISPLAY hint with nothing behind it. The bank has no notion of
// divisibility; a coin wrapped out of a 6-decimal GRC20 is still counted in
// whole units by every balance query. Rendering 1000000 as 1.000000 is a
// convention between this realm and whoever reads it.
//
// So trusting an entry means trusting the realm that wrote it, exactly as much
// as holding its coin already means trusting it not to call `RemoveCoin` on you.
package nativereg
import (
"chain/runtime"
"strings"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/ufmt/v0"
)
// Entry is what one denom says about itself.
type Entry struct {
// Denom is the full chain denom, the key of this registry.
Denom string
// Issuer is the package path embedded in Denom: the only realm that can
// issue, remove or re-describe this coin.
Issuer string
// Name, Symbol and Decimals are display metadata, chosen by the issuer.
// Decimals is a hint; see the package doc.
Name string
Symbol string
Decimals int
// Doc is one line about what the coin is for.
Doc string
// Height is when the entry was last written.
Height int64
// Revisions counts how many times the issuer has rewritten it.
Revisions int
}
const (
// MaxName, MaxSymbol and MaxDoc bound what an issuer can store here. The
// registry pays the storage for every byte a caller hands it, so the
// limits are the realm's own cost control, not a style rule.
MaxName = 40
MaxSymbol = 12
MaxDoc = 200
// MaxDecimals matches the GRC20 ceiling, which is where a wrapped coin's
// hint comes from in practice.
MaxDecimals = 18
)
var (
byDenom = avl.NewTree() // denom -> *Entry
denoms []string // registration order, for a stable Render
)
// Register records or rewrites what a denom means. The caller must be the realm
// the denom names, which is the entire authorization.
//
// Calling it again overwrites the entry and bumps [Entry.Revisions]. An issuer
// can always re-describe its own coin, and can never describe anybody else's.
func Register(cur realm, denom, name, symbol string, decimals int, doc string) {
issuer := issuerOf(denom)
prev := cur.Previous()
if prev.PkgPath() == "" {
panic("only the issuing realm can register a denom; a user account has no package path to prove")
}
if prev.PkgPath() != issuer {
panic(ufmt.Sprintf("%s is issued by %s, not by %s", denom, issuer, prev.PkgPath()))
}
assertLen("name", name, MaxName)
assertLen("symbol", symbol, MaxSymbol)
assertLen("doc", doc, MaxDoc)
if decimals < 0 || decimals > MaxDecimals {
panic(ufmt.Sprintf("decimals is %d, must be 0 to %d", decimals, MaxDecimals))
}
e := &Entry{
Denom: denom,
Issuer: issuer,
Name: name,
Symbol: symbol,
Decimals: decimals,
Doc: doc,
Height: runtime.ChainHeight(),
}
if old := byDenom.Get(denom); old != nil {
e.Revisions = old.(*Entry).Revisions + 1
} else {
denoms = append(denoms, denom)
}
byDenom.Set(denom, e)
}
// Get returns the entry for a denom, and whether it has one.
func Get(denom string) (Entry, bool) {
v := byDenom.Get(denom)
if v == nil {
return Entry{}, false
}
return *v.(*Entry), true
}
// MustGet is [Get] for a caller that treats an unregistered denom as a bug.
func MustGet(denom string) Entry {
e, ok := Get(denom)
if !ok {
panic("no entry for " + denom)
}
return e
}
// IsRegistered reports whether a denom has said anything about itself.
func IsRegistered(denom string) bool {
return byDenom.Get(denom) != nil
}
// List returns every entry, in registration order.
func List() []Entry {
out := make([]Entry, 0, len(denoms))
for _, d := range denoms {
out = append(out, MustGet(d))
}
return out
}
// ByIssuer returns every entry issued by one realm, in registration order.
func ByIssuer(pkgPath string) []Entry {
out := []Entry{}
for _, d := range denoms {
if e := MustGet(d); e.Issuer == pkgPath {
out = append(out, e)
}
}
return out
}
// Count returns how many denoms are registered.
func Count() int { return byDenom.Size() }
// IssuerOf returns the package path embedded in a denom, without consulting the
// registry: the relation is in the string itself. It aborts on anything that is
// not a realm denom, which includes `ugnot`.
//
// It is exported because it is useful to anybody handling a denom, registered or
// not: given a balance, this is how you find the code that can take it away.
func IssuerOf(denom string) string { return issuerOf(denom) }
func issuerOf(denom string) string {
if !strings.HasPrefix(denom, "/") {
panic("not a realm denom (it must start with /): " + denom)
}
i := strings.LastIndex(denom, ":")
if i < 0 {
panic("not a realm denom (it must contain :): " + denom)
}
issuer := denom[1:i]
if issuer == "" || denom[i+1:] == "" {
panic("malformed denom: " + denom)
}
return issuer
}
func assertLen(what, s string, max int) {
if len(s) > max {
panic(ufmt.Sprintf("%s is %d bytes, max %d", what, len(s), max))
}
}
nativereg_test.gno
package nativereg
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
const (
issuerPath = "gno.land/r/test/coiner"
issuerCoin = "/gno.land/r/test/coiner:testcoin"
otherPath = "gno.land/r/test/stranger"
otherCoin = "/gno.land/r/test/stranger:othercoin"
)
// testing.SetRealm governs only the crossing calls made from the frame that
// called it, so each switch below is inline in the test body.
func TestOnlyTheIssuerRegisters(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(issuerPath))
Register(cross(cur), issuerCoin, "Test Coin", "TEST", 6, "a coin for a test")
e := MustGet(issuerCoin)
uassert.Equal(t, issuerPath, e.Issuer, "the issuer is read out of the denom, not supplied")
uassert.Equal(t, "TEST", e.Symbol)
uassert.Equal(t, 6, e.Decimals)
uassert.Equal(t, 0, e.Revisions)
// The same realm cannot describe somebody else's coin.
uassert.AbortsContains(t, cur, "is issued by "+otherPath, func() {
Register(cross(cur), otherCoin, "Not Mine", "NOPE", 0, "")
})
}
func TestAUserAccountCannotRegister(cur realm, t *testing.T) {
alice := testutils.TestAddress("nr-alice")
testing.SetRealm(testing.NewUserRealm(alice))
// Even for a denom she holds every unit of: what is being described is the
// issuance, and a wallet has no package path to prove.
uassert.AbortsContains(t, cur, "no package path to prove", func() {
Register(cross(cur), issuerCoin, "Mine Now", "MINE", 0, "")
})
}
func TestReregisteringBumpsRevisions(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(issuerPath))
before := Count()
Register(cross(cur), issuerCoin, "Test Coin v2", "TEST2", 4, "renamed")
e := MustGet(issuerCoin)
uassert.Equal(t, "TEST2", e.Symbol, "an issuer can always re-describe its own coin")
uassert.Equal(t, 1, e.Revisions)
uassert.Equal(t, before, Count(), "a rewrite is not a second entry")
uassert.Equal(t, 1, len(ByIssuer(issuerPath)))
uassert.Equal(t, 0, len(ByIssuer(otherPath)))
}
func TestBounds(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(issuerPath))
uassert.AbortsContains(t, cur, "name is", func() {
Register(cross(cur), issuerCoin, strings.Repeat("x", MaxName+1), "T", 0, "")
})
uassert.AbortsContains(t, cur, "symbol is", func() {
Register(cross(cur), issuerCoin, "n", strings.Repeat("x", MaxSymbol+1), 0, "")
})
uassert.AbortsContains(t, cur, "doc is", func() {
Register(cross(cur), issuerCoin, "n", "T", 0, strings.Repeat("x", MaxDoc+1))
})
uassert.AbortsContains(t, cur, "decimals is 19", func() {
Register(cross(cur), issuerCoin, "n", "T", MaxDecimals+1, "")
})
uassert.AbortsContains(t, cur, "decimals is -1", func() {
Register(cross(cur), issuerCoin, "n", "T", -1, "")
})
}
func TestIssuerOfReadsTheDenom(cur realm, t *testing.T) {
// The relation is in the string, so this answers for a denom nobody ever
// registered, which is the case that matters: given a balance you did not
// ask for, this is how you find the code that can take it away.
uassert.Equal(t, "gno.land/r/nobody/here/v3", IssuerOf("/gno.land/r/nobody/here/v3:ghost"))
uassert.Equal(t, issuerPath, IssuerOf(issuerCoin))
uassert.PanicsContains(t, cur, "must start with /", func() { IssuerOf("ugnot") })
uassert.PanicsContains(t, cur, "must contain :", func() { IssuerOf("/gno.land/r/a/v0") })
uassert.PanicsContains(t, cur, "malformed", func() { IssuerOf("/gno.land/r/a/v0:") })
uassert.PanicsContains(t, cur, "malformed", func() { IssuerOf("/:x") })
}
func TestUnregisteredReadsCleanly(cur realm, t *testing.T) {
_, ok := Get("/gno.land/r/nobody/here/v3:ghost")
uassert.False(t, ok)
uassert.False(t, IsRegistered("/gno.land/r/nobody/here/v3:ghost"))
uassert.PanicsContains(t, cur, "no entry for", func() { MustGet("/gno.land/r/x/y/v0:zz") })
}
func TestRender(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(otherPath))
Register(cross(cur), otherCoin, "Other Coin", "OTHER", 0, "the second one")
index := Render("")
uassert.True(t, strings.Contains(index, "# nativereg"), index)
uassert.True(t, strings.Contains(index, "OTHER"), "the index lists entries:\n"+index)
one := Render(otherCoin)
uassert.True(t, strings.Contains(one, "the second one"), one)
uassert.True(t, strings.Contains(one, otherPath), one)
byIssuer := Render(issuerPath)
uassert.True(t, strings.Contains(byIssuer, "TEST2"), byIssuer)
uassert.False(t, strings.Contains(byIssuer, "OTHER"), "one issuer's page shows only its own")
// A Render never aborts on a path a reader typed, registered or not.
uassert.True(t, strings.Contains(Render("/gno.land/r/x/y/v0:nope"), "Not registered"))
uassert.True(t, strings.Contains(Render("ugnot"), "registered nothing"),
"a non-denom path falls through to the issuer view rather than aborting")
uassert.True(t, strings.Contains(Render("/garbage"), "not a realm denom"))
}
func TestRenderEscapesWhatAnIssuerWrote(cur realm, t *testing.T) {
// An issuer's own name and doc are still caller-supplied text, and a realm
// that can register can write a table-breaking pipe as easily as a name.
const nasty = "gno.land/r/test/nasty"
testing.SetRealm(testing.NewCodeRealm(nasty))
Register(cross(cur), "/gno.land/r/test/nasty:nastycoin", "a|b", "x|y", 0, "")
index := Render("")
uassert.False(t, strings.Contains(index, "| a|b |"), "a raw pipe would open a column:\n"+index)
uassert.True(t, strings.Contains(index, "a\\|b"), "it is escaped instead:\n"+index)
}
render.gno
package nativereg
import (
"strings"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
"gno.land/p/nt/ufmt/v0"
)
// Render lists the registry. `?<denom>` shows one entry, `?<pkgpath>` shows
// everything one realm issues.
func Render(path string) string {
if path == "" {
return renderIndex()
}
if strings.HasPrefix(path, "/") {
return renderDenom(path)
}
return renderIssuer(path)
}
func renderIndex() string {
var sb strings.Builder
sb.WriteString(md.H1("nativereg: what a native denom means"))
sb.WriteString("\nA realm-issued coin is a string and a balance. The chain stores no name, " +
"no symbol and no decimals for it, so this realm does. An issuer registers its own " +
"denoms and nobody else's: the package path is embedded in the denom, and that is " +
"the whole authorization.\n\n")
t := ui.NewTable("denom", "symbol", "name", "decimals", "issuer")
for _, e := range List() {
t.Row(md.InlineCode(ui.ShortN(e.Denom, 22, 12)), ui.Cell(e.Symbol), ui.Cell(e.Name),
ufmt.Sprintf("%d", e.Decimals), md.Link(ui.Short(e.Issuer), "/"+strings.TrimPrefix(e.Issuer, "gno.land/")))
}
sb.WriteString(md.H2("Registered"))
sb.WriteString("\n" + t.OrEmpty("Nothing registered yet.") + "\n")
sb.WriteString(md.H2("Register your own"))
sb.WriteString("\nFrom inside the realm that issues the coin, never from a wallet:\n\n")
sb.WriteString(md.LanguageCodeBlock("go",
"import \"gno.land/r/moul/x/nativereg/v0\"\n\n"+
"func init(cur realm) {\n"+
"\tnativereg.Register(cross(cur), Denom, \"My Coin\", \"MINE\", 6,\n"+
"\t\t\"one line about what it is for\")\n"+
"}"))
sb.WriteString("\n" + md.Italic("Decimals is a display hint. The bank counts whole units and "+
"knows nothing about divisibility.") + "\n")
return sb.String()
}
func renderDenom(denom string) string {
e, ok := Get(denom)
if !ok {
return md.H1("Not registered") + "\n" + md.InlineCode(denom) +
" has said nothing about itself.\n\nIts issuer is " +
md.InlineCode(safeIssuer(denom)) + ", and only that realm can change it.\n"
}
t := ui.NewTable("", "")
t.Row("denom", md.InlineCode(e.Denom))
t.Row("issuer", md.InlineCode(e.Issuer))
t.Row("name", ui.Cell(e.Name))
t.Row("symbol", ui.Cell(e.Symbol))
t.Row("decimals", ufmt.Sprintf("%d (display hint)", e.Decimals))
t.Row("registered at block", ufmt.Sprintf("%d", e.Height))
t.Row("revisions", ufmt.Sprintf("%d", e.Revisions))
s := md.H1(ui.Inline(e.Symbol)) + "\n"
if e.Doc != "" {
s += ui.Inline(e.Doc) + "\n\n"
}
s += t.String() + "\n"
s += md.Blockquote("The issuer can rewrite every row but the first two, and can remove "+
"this coin from any balance at any time. That is what a realm-issued coin is.") + "\n"
return s
}
func renderIssuer(pkgPath string) string {
entries := ByIssuer(pkgPath)
s := md.H1("Issued by "+ui.Inline(pkgPath)) + "\n"
t := ui.NewTable("denom", "symbol", "name")
for _, e := range entries {
t.Row(md.InlineCode(ui.ShortN(e.Denom, 22, 12)), ui.Cell(e.Symbol), ui.Cell(e.Name))
}
return s + t.OrEmpty("This realm has registered nothing here.") + "\n"
}
// safeIssuer is IssuerOf for a Render, which must never abort on a path a reader
// typed into the URL bar.
func safeIssuer(denom string) string {
if !strings.HasPrefix(denom, "/") {
return "unknown (not a realm denom)"
}
i := strings.LastIndex(denom, ":")
if i < 1 {
return "unknown (not a realm denom)"
}
return denom[1:i]
}