Playground
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/handles/v1" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914308 max_deposit = "7000000ugnot"
handles.gno
// Package handles is a tiny on-chain nickname registry.
//
// Any address may claim one unique handle (3-20 lowercase letters/digits,
// starting with a letter), attach a short bio, transfer the handle to
// another address, or release it back to the pool. It is deliberately
// small: two AVL indexes (handle -> record, address -> record) and a
// handful of guarded mutators.
package handles
import (
"strconv"
"strings"
"chain"
"chain/runtime"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
"gno.land/p/nt/avl/v0"
)
// selfPath is this realm's own page. A root-relative link resolves against
// the domain, not the realm, so every link back into it names it in full.
const selfPath = "/r/moul/x/daily/handles/v1"
const maxBioLen = 140
// record is the persisted state for one claimed handle.
type record struct {
handle string
owner address
bio string
sinceBlk int64
}
var (
byHandle avl.Tree // handle (string) -> *record
byOwner avl.Tree // owner address.String() -> *record
)
// validHandle reports whether h is 3-20 chars, starts with a lowercase
// letter, and contains only lowercase letters and digits thereafter.
func validHandle(h string) bool {
if len(h) < 3 || len(h) > 20 {
return false
}
for i := 0; i < len(h); i++ {
c := h[i]
switch {
case c >= 'a' && c <= 'z':
case c >= '0' && c <= '9' && i > 0:
default:
return false
}
}
return true
}
// Register claims handle for the caller. Aborts if the handle is invalid,
// already taken, or the caller already owns a handle (release it first).
func Register(cur realm, handle string) {
if !cur.IsCurrent() {
panic("invalid realm")
}
if !cur.Previous().IsUserCall() {
panic("only a direct user call can register a handle")
}
if !validHandle(handle) {
panic("handle must be 3-20 lowercase letters/digits, starting with a letter")
}
caller := cur.Previous().Address()
if byOwner.Has(caller.String()) {
panic("this address already owns a handle; release it first")
}
if byHandle.Has(handle) {
panic("handle already taken")
}
r := &record{
handle: handle,
owner: caller,
sinceBlk: runtime.ChainHeight(),
}
byHandle.Set(handle, r)
byOwner.Set(caller.String(), r)
chain.Emit("HandleRegistered", "handle", handle, "owner", caller.String())
}
// SetBio updates the bio of the handle owned by the caller.
func SetBio(cur realm, bio string) {
if !cur.IsCurrent() {
panic("invalid realm")
}
if len(bio) > maxBioLen {
panic("bio too long (max " + strconv.Itoa(maxBioLen) + " chars)")
}
r := ownRecord(cur)
r.bio = bio
chain.Emit("BioUpdated", "handle", r.handle)
}
// Release frees the handle owned by the caller, making it claimable again.
func Release(cur realm) {
if !cur.IsCurrent() {
panic("invalid realm")
}
r := ownRecord(cur)
byHandle.Remove(r.handle)
byOwner.Remove(r.owner.String())
chain.Emit("HandleReleased", "handle", r.handle)
}
// Transfer moves the caller's handle to another address that does not
// already own one.
func Transfer(cur realm, to address) {
if !cur.IsCurrent() {
panic("invalid realm")
}
if !to.IsValid() {
panic("invalid recipient address")
}
r := ownRecord(cur)
if byOwner.Has(to.String()) {
panic("recipient already owns a handle")
}
byOwner.Remove(r.owner.String())
r.owner = to
byOwner.Set(to.String(), r)
chain.Emit("HandleTransferred", "handle", r.handle, "to", to.String())
}
// ownRecord resolves the record for the current caller, panicking if the
// caller does not own a handle.
func ownRecord(cur realm) *record {
caller := cur.Previous().Address()
v := byOwner.Get(caller.String())
if v == nil {
panic("this address does not own a handle")
}
return v.(*record)
}
// OwnerOf returns the owner of handle and whether it exists.
func OwnerOf(handle string) (address, bool) {
v := byHandle.Get(handle)
if v == nil {
return address(""), false
}
return v.(*record).owner, true
}
// HandleOf returns the handle owned by addr, if any.
func HandleOf(addr address) (string, bool) {
v := byOwner.Get(addr.String())
if v == nil {
return "", false
}
return v.(*record).handle, true
}
// Count returns the number of currently registered handles.
func Count() int {
return byHandle.Size()
}
// Render renders Markdown. "/" lists every handle; "/<handle>" shows a
// single record's detail.
func Render(path string) string {
path = strings.TrimPrefix(path, "/")
if path == "" {
return renderIndex()
}
return renderHandle(path)
}
func renderIndex() string {
var b strings.Builder
b.WriteString("# 🪪 Handles\n\n")
b.WriteString("A tiny on-chain nickname registry. Claim a short handle, ")
b.WriteString("attach a bio, transfer it, or release it.\n\n")
if byHandle.Size() == 0 {
b.WriteString("_No handles registered yet._\n\n")
b.WriteString("Call `Register(handle)` to claim the first one.\n")
return b.String()
}
b.WriteString("| Handle | Owner | Since block |\n")
b.WriteString("|--------|-------|-------------|\n")
byHandle.Iterate("", "", func(key string, value interface{}) bool {
r := value.(*record)
b.WriteString("| [" + key + "](" + selfPath + ":" + key + ") | " + ui.Addr(r.owner) +
" | " + strconv.Itoa(int(r.sinceBlk)) + " |\n")
return false
})
b.WriteString("\nTotal handles: " + strconv.Itoa(byHandle.Size()) + "\n")
return b.String()
}
func renderHandle(handle string) string {
v := byHandle.Get(handle)
if v == nil {
return "# Handles\n\nNo handle named " + md.InlineCode(handle) + ".\n\n[← all handles](" + selfPath + ")\n"
}
r := v.(*record)
var b strings.Builder
b.WriteString("# 🪪 @" + r.handle + "\n\n")
b.WriteString("**Owner:** " + r.owner.String() + "\n\n")
if r.bio != "" {
b.WriteString("**Bio:** " + ui.Inline(r.bio) + "\n\n")
}
b.WriteString("**Registered at block:** " + strconv.Itoa(int(r.sinceBlk)) + "\n\n")
b.WriteString("[← all handles](" + selfPath + ")\n")
return b.String()
}
handles_test.gno
package handles
import (
"testing"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
)
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
)
// reset clears package state between tests so cases stay independent.
func reset() {
byHandle = avl.Tree{}
byOwner = avl.Tree{}
}
func TestValidHandle(t *testing.T) {
cases := map[string]bool{
"moul": true,
"m": false, // too short
"ab": false, // too short
"Moul": false, // uppercase
"1moul": false, // starts with digit
"moul1": true,
"moul-1": false, // hyphen
"averylonghandlethatistoolong12": false, // too long
}
for h, want := range cases {
if got := validHandle(h); got != want {
t.Errorf("validHandle(%q) = %v, want %v", h, got, want)
}
}
}
func TestRegisterAndLookup(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
Register(cross(cur), "moul")
owner, ok := OwnerOf("moul")
if !ok || owner != alice {
t.Fatalf("OwnerOf(moul) = %v, %v; want %v, true", owner, ok, alice)
}
handle, ok := HandleOf(alice)
if !ok || handle != "moul" {
t.Fatalf("HandleOf(alice) = %q, %v; want moul, true", handle, ok)
}
if got := Count(); got != 1 {
t.Fatalf("Count() = %d, want 1", got)
}
}
func TestRegisterRejectsTakenHandle(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
Register(cross(cur), "moul")
testing.SetRealm(testing.NewUserRealm(bob))
defer func() {
if r := recover(); r == nil {
t.Errorf("expected panic registering a taken handle")
}
}()
Register(cur, "moul")
}
func TestRegisterRejectsSecondHandleForSameOwner(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
Register(cross(cur), "moul")
testing.SetRealm(testing.NewUserRealm(alice))
defer func() {
if r := recover(); r == nil {
t.Errorf("expected panic when the same owner registers twice")
}
}()
Register(cur, "second")
}
func TestTransferAndRelease(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
Register(cross(cur), "moul")
testing.SetRealm(testing.NewUserRealm(alice))
Transfer(cross(cur), bob)
if _, ok := HandleOf(alice); ok {
t.Fatalf("alice should no longer own a handle after transfer")
}
handle, ok := HandleOf(bob)
if !ok || handle != "moul" {
t.Fatalf("HandleOf(bob) = %q, %v; want moul, true", handle, ok)
}
testing.SetRealm(testing.NewUserRealm(bob))
Release(cross(cur))
if Count() != 0 {
t.Fatalf("Count() = %d, want 0 after release", Count())
}
if _, ok := OwnerOf("moul"); ok {
t.Fatalf("moul should be unclaimed after release")
}
}
func TestSetBioAndRender(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
Register(cross(cur), "moul")
SetBio(cross(cur), "building gno stuff")
out := Render("/moul")
if !contains(out, "moul") || !contains(out, "building gno stuff") {
t.Fatalf("Render(/moul) missing expected content: %s", out)
}
index := Render("")
if !contains(index, "moul") {
t.Fatalf("Render('') missing handle in index: %s", index)
}
missing := Render("/nobody")
if !contains(missing, "No handle named") {
t.Fatalf("Render(/nobody) should report missing handle: %s", missing)
}
}
func contains(s, substr string) bool {
for i := 0; i+len(substr) <= len(s); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
zz_escape_test.gno
package handles
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
"gno.land/p/nt/uassert/v0"
)
// A bio is the caller's text: escaped on the handle page.
func TestBioIsEscaped(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("escaper")))
Register(cross(cur), "escaper")
SetBio(cross(cur), "[claim](https://evil.example)")
page := Render("escaper")
uassert.False(t, strings.Contains(page, "[claim](https://evil.example)"), page)
}
// A path that names nothing is echoed back on the not-found page. It is the
// visitor's text, so a backtick in it must not close a code span and let a
// link through.
func TestNotFoundPathIsEscaped(t *testing.T) {
out := Render("x` [claim](https://evil.example) `")
// Still there, but inside a span md.InlineCode widened past its backticks.
uassert.True(t, strings.Contains(out, md.InlineCode("x` [claim](https://evil.example) `")), out)
}
zz_links_test.gno
package handles
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// The index links each handle to this realm's own page, and a missing
// handle links back to the index. Both once resolved to gno.land itself.
func TestLinksNameThisRealm(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("linker")))
Register(cross(cur), "linker")
idx := Render("")
uassert.True(t, strings.Contains(idx, "[linker](/r/moul/x/daily/handles/v1:linker)"), idx)
miss := Render("nobodyhere")
uassert.True(t, strings.Contains(miss, "[← all handles](/r/moul/x/daily/handles/v1)"), miss)
}