Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/linktree/v1"
gno = "0.9"
private = true

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 914308
  max_deposit = "6000000ugnot"

linktree.gno

package linktree

import (
	"strconv"
	"strings"

	"chain"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/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/linktree/v1"

// link is a single labeled URL on a profile.
type link struct {
	Label string
	URL   string
}

// profile is one address's personal links page.
type profile struct {
	Bio   string
	Links []link
}

// profiles maps an address (string key) to its *profile.
// avl.Tree keeps iteration deterministic for Render.
var profiles avl.Tree

// The bounds on what a caller may store. Anyone may create a profile, and the
// root page lists every profile while a profile page lists every link.
const (
	MaxProfiles = 1000
	MaxLinks    = 20
	MaxBioLen   = 280
	MaxLabelLen = 64
	MaxURLLen   = 512
)

// SetBio sets (or replaces) the calling address's bio.
func SetBio(cur realm, bio string) {
	addr := caller(cur)
	if len(bio) > MaxBioLen {
		panic("bio too long")
	}
	p := getOrCreate(addr.String())
	p.Bio = bio
	chain.Emit("BioSet", "addr", addr.String())
}

// AddLink appends a labeled URL to the calling address's profile.
func AddLink(cur realm, label string, url string) {
	addr := caller(cur)
	if label == "" {
		panic("label must not be empty")
	}
	if url == "" {
		panic("url must not be empty")
	}
	// The URL becomes a markdown link destination as written, so it is
	// checked here rather than escaped there: http(s) only, and nothing that
	// could close the destination or start another.
	if !safeURL(url) {
		panic("url must be http:// or https:// with no spaces, parentheses or angle brackets")
	}
	if len(label) > MaxLabelLen || len(url) > MaxURLLen {
		panic("label or url too long")
	}
	p := getOrCreate(addr.String())
	if len(p.Links) >= MaxLinks {
		panic("a profile holds at most " + strconv.Itoa(MaxLinks) + " links")
	}
	p.Links = append(p.Links, link{Label: label, URL: url})
	chain.Emit("LinkAdded", "addr", addr.String(), "label", label)
}

// RemoveLink deletes the link at index from the calling address's profile.
func RemoveLink(cur realm, index int) {
	addr := caller(cur)
	key := addr.String()
	v := profiles.Get(key)
	if v == nil {
		panic("no profile for caller")
	}
	p := v.(*profile)
	if index < 0 || index >= len(p.Links) {
		panic("index out of range")
	}
	// A fresh slice, not append(s[:i], s[i+1:]...): the in-place form keeps the
	// old backing array, so the deposit for a removed link never comes back.
	kept := make([]link, 0, len(p.Links)-1)
	kept = append(kept, p.Links[:index]...)
	kept = append(kept, p.Links[index+1:]...)
	p.Links = kept
	chain.Emit("LinkRemoved", "addr", key, "index", strconv.Itoa(index))
}

// getOrCreate returns the profile for key, creating an empty one if absent.
func getOrCreate(key string) *profile {
	if v := profiles.Get(key); v != nil {
		return v.(*profile)
	}
	if profiles.Size() >= MaxProfiles {
		panic("linktree is full at " + strconv.Itoa(MaxProfiles) + " profiles")
	}
	p := &profile{}
	profiles.Set(key, p)
	return p
}

// Render shows all profiles at root, or a single profile at "/<address>".
func Render(path string) string {
	addr := strings.Trim(path, "/")
	if addr == "" {
		return renderIndex()
	}
	return renderProfile(addr)
}

func renderIndex() string {
	var b strings.Builder
	b.WriteString("# Linktree\n\n")
	if profiles.Size() == 0 {
		b.WriteString("_No profiles yet. Call `SetBio` or `AddLink` to create one._\n")
		return b.String()
	}
	b.WriteString("Profiles:\n\n")
	profiles.Iterate("", "", func(key string, _ interface{}) bool {
		b.WriteString("- [")
		b.WriteString(key)
		b.WriteString("](" + selfPath + ":")
		b.WriteString(key)
		b.WriteString(")\n")
		return false
	})
	return b.String()
}

func renderProfile(addr string) string {
	var b strings.Builder
	b.WriteString("# ")
	b.WriteString(ui.Inline(addr))
	b.WriteString("\n\n")

	v := profiles.Get(addr)
	if v == nil {
		b.WriteString("_No profile for this address._\n")
		return b.String()
	}
	p := v.(*profile)

	if p.Bio != "" {
		b.WriteString(ui.Inline(p.Bio))
		b.WriteString("\n\n")
	}

	if len(p.Links) == 0 {
		b.WriteString("_No links yet._\n")
		return b.String()
	}

	b.WriteString("## Links\n\n")
	for _, l := range p.Links {
		b.WriteString("- [")
		b.WriteString(ui.Inline(l.Label))
		b.WriteString("](")
		b.WriteString(l.URL)
		b.WriteString(")\n")
	}
	return b.String()
}

// caller is the address that crossed into this realm, after checking that the
// realm token is this frame's own.
func caller(cur realm) address {
	if !cur.IsCurrent() {
		panic("linktree: spoofed realm")
	}
	return cur.Previous().Address()
}

// safeURL reports whether u can be written into a markdown link destination
// unescaped.
func safeURL(u string) bool {
	if !strings.HasPrefix(u, "https://") && !strings.HasPrefix(u, "http://") {
		return false
	}
	return !strings.ContainsAny(u, " \t\r\n()<>[]`\\")
}

linktree_test.gno

package linktree

import (
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

func TestProfileLifecycle(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	testing.SetRealm(testing.NewUserRealm(alice))

	SetBio(cross(cur), "gnome builder")
	AddLink(cross(cur), "Home", "https://alice.example")
	AddLink(cross(cur), "GitHub", "https://github.com/alice")

	out := Render("/" + alice.String())
	uassert.True(t, strings.Contains(out, "gnome builder"), "bio present")
	uassert.True(t, strings.Contains(out, "[Home](https://alice.example)"), "first link present")
	uassert.True(t, strings.Contains(out, "[GitHub](https://github.com/alice)"), "second link present")

	// Remove the first link; second must survive.
	RemoveLink(cross(cur), 0)
	out = Render("/" + alice.String())
	uassert.False(t, strings.Contains(out, "[Home]"), "removed link gone")
	uassert.True(t, strings.Contains(out, "[GitHub](https://github.com/alice)"), "kept link present")
}

func TestIndexAndOwnership(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice2")
	bob := testutils.TestAddress("bob2")

	testing.SetRealm(testing.NewUserRealm(alice))
	AddLink(cross(cur), "A", "https://a.example")

	testing.SetRealm(testing.NewUserRealm(bob))
	AddLink(cross(cur), "B", "https://b.example")

	// Root index lists both addresses.
	idx := Render("")
	uassert.True(t, strings.Contains(idx, alice.String()), "alice listed")
	uassert.True(t, strings.Contains(idx, bob.String()), "bob listed")

	// bob is current caller; his profile has only his link, not alice's.
	bobOut := Render("/" + bob.String())
	uassert.True(t, strings.Contains(bobOut, "[B](https://b.example)"), "bob has own link")
	uassert.False(t, strings.Contains(bobOut, "[A]"), "bob does not have alice's link")

	// Out-of-range removal on bob aborts.
	uassert.AbortsWithMessage(t, cur, "index out of range", func() {
		RemoveLink(cross(cur), 99)
	})
}

func TestUnknownProfile(t *testing.T) {
	out := Render("/g1doesnotexist")
	uassert.True(t, strings.Contains(out, "No profile for this address"), "unknown profile message")
}

zz_bounds_test.gno

package linktree

import (
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

// A profile holds a bounded number of links of bounded size, and removing one
// keeps the others in order.
func TestLinksAreBounded(cur realm, t *testing.T) {
	who := testutils.TestAddress("bounded")
	testing.SetRealm(testing.NewUserRealm(who))
	uassert.AbortsContains(t, cur, "bio too long", func() { SetBio(cross(cur), strings.Repeat("b", MaxBioLen+1)) })
	for i := 0; i < MaxLinks; i++ {
		AddLink(cross(cur), "l", "https://e.example/"+strings.Repeat("x", i))
	}
	uassert.AbortsContains(t, cur, "at most", func() { AddLink(cross(cur), "l", "https://e.example/") })
	RemoveLink(cross(cur), 0)
	p := profiles.Get(who.String()).(*profile)
	uassert.Equal(t, MaxLinks-1, len(p.Links))
	uassert.Equal(t, "https://e.example/x", p.Links[0].URL)
}

// The profile count is bounded globally, not just per address.
func TestProfileCountIsBounded(cur realm, t *testing.T) {
	var added []string
	for i := 0; profiles.Size() < MaxProfiles; i++ {
		k := testutils.TestAddress("p" + strings.Repeat("x", i%7) + string(rune('a'+i%26)) + string(rune('a'+i/26%26)) + string(rune('a'+i/676%26))).String()
		if profiles.Get(k) == nil {
			profiles.Set(k, &profile{})
			added = append(added, k)
		}
	}
	defer func() {
		for _, k := range added {
			profiles.Remove(k)
		}
	}()
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("latecomer")))
	uassert.AbortsContains(t, cur, "linktree is full", func() { SetBio(cross(cur), "hi") })
}

zz_escape_test.gno

package linktree

import (
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

// The bio and a label are escaped, and a URL that could break out of its
// link destination, or is not http(s), is refused when it is written.
func TestProfileFieldsAreEscapedAndURLsChecked(cur realm, t *testing.T) {
	who := testutils.TestAddress("escaper")
	testing.SetRealm(testing.NewUserRealm(who))
	SetBio(cross(cur), "[claim](https://evil.example)")
	AddLink(cross(cur), "[claim](https://evil.example)", "https://ok.example/path")
	page := Render(who.String())
	uassert.False(t, strings.Contains(page, "[claim](https://evil.example)"), page)
	uassert.AbortsContains(t, cur, "url must be http", func() { AddLink(cross(cur), "x", "javascript:alert(1)") })
	uassert.AbortsContains(t, cur, "url must be http", func() { AddLink(cross(cur), "x", "https://a.example) [evil](https://b.example") })
}

// 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) `")
	uassert.False(t, strings.Contains(out, "[claim](https://evil.example)"), out)
}

zz_links_test.gno

package linktree

import (
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

// The index links each profile to this realm's own page. It once linked to
// /r/REPLACE_ADDR/linktree.
func TestIndexLinksNameThisRealm(cur realm, t *testing.T) {
	who := testutils.TestAddress("linker")
	testing.SetRealm(testing.NewUserRealm(who))
	SetBio(cross(cur), "links")
	out := Render("")
	uassert.True(t, strings.Contains(out, "](/r/moul/x/daily/linktree/v1:"+who.String()+")"), out)
}