Playground
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/microblog/v1" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914308 max_deposit = "6000000ugnot"
microblog.gno
// Package microblog is a public microblog wall for gno.land.
//
// Anyone can Post a short message (<= maxMsgLen chars). Every post records
// the caller address, the message, and the block height at which it was made.
// Render displays the wall newest-first, 20 posts per page, with pagination
// driven by the Render path (e.g. "?page=2" or "/2").
package microblog
import (
"chain"
"chain/runtime"
"chain/runtime/unsafe"
"strconv"
"strings"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
)
// maxMsgLen is the maximum length (in bytes) of a single post.
const maxMsgLen = 280
// pageSize is how many posts a single Render page shows.
const pageSize = 20
// post is a single microblog entry.
type post struct {
Author string // bech32 address of the poster
Msg string // the message body
Height int64 // block height at which it was posted
}
// posts is the append-only wall, in chronological (oldest-first) order.
// Render reverses this view to show newest-first.
var posts []post
// Post publishes msg to the wall. It is a crossing function: callers invoke it
// with Post(cross(cur), "hello"). It panics if msg is empty or longer than
// maxMsgLen bytes.
func Post(cur realm, msg string) {
if !cur.IsCurrent() {
panic("spoofed realm: cur is not the live crossing frame")
}
if len(msg) == 0 {
panic("microblog: empty message")
}
if len(msg) > maxMsgLen {
panic("microblog: message too long (max " + strconv.Itoa(maxMsgLen) + " bytes)")
}
author := unsafe.PreviousRealm().Address()
posts = append(posts, post{
Author: author.String(),
Msg: msg,
Height: runtime.ChainHeight(),
})
chain.Emit("Post", "author", author.String(), "len", strconv.Itoa(len(msg)))
}
// Count returns the total number of posts on the wall.
func Count() int {
return len(posts)
}
// Render renders the wall as Markdown, newest-first, pageSize posts per page.
// The page is parsed from path: "?page=N", "?p=N", "/N", or a bare "N" all
// select page N (1-indexed). Anything else defaults to page 1.
func Render(path string) string {
total := len(posts)
page := parsePage(path)
var b strings.Builder
b.WriteString("# Microblog Wall\n\n")
if total == 0 {
b.WriteString("_No posts yet. Be the first to post._\n")
return b.String()
}
pages := (total + pageSize - 1) / pageSize
if page < 1 {
page = 1
}
if page > pages {
page = pages
}
b.WriteString(strconv.Itoa(total))
b.WriteString(" posts total · page ")
b.WriteString(strconv.Itoa(page))
b.WriteString(" of ")
b.WriteString(strconv.Itoa(pages))
b.WriteString("\n\n")
// Newest-first: post index total-1 is newest. For page p (1-indexed),
// skip (p-1)*pageSize newest posts, then take up to pageSize.
start := total - 1 - (page-1)*pageSize
end := start - pageSize + 1
if end < 0 {
end = 0
}
for i := start; i >= end; i-- {
p := posts[i]
b.WriteString("- **")
b.WriteString(ui.AddrOf(p.Author))
b.WriteString("** · height ")
b.WriteString(strconv.FormatInt(p.Height, 10))
b.WriteString("\n\n ")
b.WriteString(ui.Inline(p.Msg))
b.WriteString("\n")
}
b.WriteString("\n")
b.WriteString(renderNav(page, pages))
return b.String()
}
// renderNav builds a simple prev/next navigation footer as Markdown links.
func renderNav(page, pages int) string {
var b strings.Builder
if page > 1 {
b.WriteString("[← newer](?page=")
b.WriteString(strconv.Itoa(page - 1))
b.WriteString(")")
}
if page > 1 && page < pages {
b.WriteString(" · ")
}
if page < pages {
b.WriteString("[older →](?page=")
b.WriteString(strconv.Itoa(page + 1))
b.WriteString(")")
}
if b.Len() == 0 {
return ""
}
return b.String() + "\n"
}
// parsePage extracts the 1-indexed page number from a Render path. It accepts
// "?page=N", "?p=N", "/N", and a bare "N". Unrecognized input yields page 1.
func parsePage(path string) int {
path = strings.TrimSpace(path)
if path == "" {
return 1
}
// Query form: "?page=2&foo=bar" or "?p=2".
if idx := strings.IndexByte(path, '?'); idx >= 0 {
query := path[idx+1:]
for _, part := range strings.Split(query, "&") {
kv := strings.SplitN(part, "=", 2)
if len(kv) != 2 {
continue
}
if kv[0] == "page" || kv[0] == "p" {
if n, err := strconv.Atoi(strings.TrimSpace(kv[1])); err == nil {
return n
}
}
}
return 1
}
// Path form: "/2" or "2".
seg := strings.TrimPrefix(path, "/")
if n, err := strconv.Atoi(seg); err == nil {
return n
}
return 1
}
microblog_test.gno
package microblog
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// resetWall clears package state between tests (globals persist in-process,
// and subtests do not reset them — do it explicitly).
func resetWall() { posts = nil }
// asUser must be inlined into each test: SetRealm affects the calling frame
// only. We therefore call it directly in the test bodies below.
func TestPostAndCount(cur realm, t *testing.T) {
resetWall()
alice := testutils.TestAddress("alice")
testing.SetRealm(testing.NewUserRealm(alice))
Post(cross(cur), "hello wall")
if got := Count(); got != 1 {
t.Fatalf("Count() = %d, want 1", got)
}
if posts[0].Msg != "hello wall" {
t.Errorf("Msg = %q, want %q", posts[0].Msg, "hello wall")
}
if posts[0].Author != alice.String() {
t.Errorf("Author = %q, want %q", posts[0].Author, alice.String())
}
}
func TestPostTooLongPanics(cur realm, t *testing.T) {
resetWall()
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("bob")))
// Aborts from a cross(cur) call cannot be caught by a plain recover();
// assert on the abort message instead.
uassert.AbortsWithMessage(t, cur, "microblog: message too long (max 280 bytes)", func() {
Post(cross(cur), strings.Repeat("x", maxMsgLen+1))
})
}
func TestPostEmptyPanics(cur realm, t *testing.T) {
resetWall()
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("bob")))
// Aborts from a cross(cur) call cannot be caught by a plain recover();
// assert on the abort message instead.
uassert.AbortsWithMessage(t, cur, "microblog: empty message", func() {
Post(cross(cur), "")
})
}
func TestPostMaxLenOK(cur realm, t *testing.T) {
resetWall()
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("carol")))
// Exactly maxMsgLen bytes must be accepted.
Post(cross(cur), strings.Repeat("y", maxMsgLen))
if got := Count(); got != 1 {
t.Fatalf("Count() = %d, want 1 for exactly-max message", got)
}
}
func TestRenderEmpty(t *testing.T) {
resetWall()
out := Render("")
if !strings.Contains(out, "No posts yet") {
t.Errorf("empty Render should mention no posts, got:\n%s", out)
}
}
func TestRenderNewestFirstAndPagination(cur realm, t *testing.T) {
resetWall()
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("dave")))
// 25 posts -> 2 pages (20 + 5).
for i := 0; i < 25; i++ {
Post(cross(cur), "msg"+itoa(i))
}
if got := Count(); got != 25 {
t.Fatalf("Count() = %d, want 25", got)
}
page1 := Render("")
// Newest (msg24) must appear before older (msg5) on page 1.
i24 := strings.Index(page1, "msg24")
i5 := strings.Index(page1, "msg5")
if i24 < 0 || i5 < 0 {
t.Fatalf("page 1 missing expected posts: msg24=%d msg5=%d", i24, i5)
}
if i24 > i5 {
t.Errorf("page 1 not newest-first: msg24 at %d should precede msg5 at %d", i24, i5)
}
if !strings.Contains(page1, "page 1 of 2") {
t.Errorf("page 1 header wrong, got:\n%s", page1)
}
// Page 2 via query form must contain the oldest post.
page2 := Render("?page=2")
if !strings.Contains(page2, "msg0") {
t.Errorf("page 2 should contain oldest msg0, got:\n%s", page2)
}
if !strings.Contains(page2, "page 2 of 2") {
t.Errorf("page 2 header wrong, got:\n%s", page2)
}
// Path form "/2" should equal query form "?page=2".
if Render("/2") != page2 {
t.Errorf("path form /2 differs from query form ?page=2")
}
}
func TestParsePage(t *testing.T) {
cases := []struct {
in string
want int
}{
{"", 1},
{"?page=3", 3},
{"?p=4", 4},
{"/2", 2},
{"5", 5},
{"?page=abc", 1},
{"garbage", 1},
}
for _, c := range cases {
if got := parsePage(c.in); got != c.want {
t.Errorf("parsePage(%q) = %d, want %d", c.in, got, c.want)
}
}
}
// itoa is a tiny local int->string helper for building test messages.
func itoa(n int) string {
if n == 0 {
return "0"
}
neg := n < 0
if neg {
n = -n
}
var buf [20]byte
i := len(buf)
for n > 0 {
i--
buf[i] = byte('0' + n%10)
n /= 10
}
if neg {
i--
buf[i] = '-'
}
return string(buf[i:])
}