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

admin.gno

package arena

import (
	"chain"
	"chain/banker"
	"chain/runtime/unsafe"
	"strconv"
	"strings"
)

// SetPaused freezes posts, replies, tips, and ticket buys when on is true/1/yes.
// Pass false/0/no to reopen. Ticket sells are never paused.
func SetPaused(cur realm, on string) {
	mustAdmin(cur)
	switch on {
	case "true", "1", "yes":
		state.paused = true
	case "false", "0", "no":
		state.paused = false
	default:
		panic("paused must be true or false")
	}
	chain.Emit("ArenaPause", "paused", on, "admin", state.admin.String())
}

// SetTreasury moves future protocol fees and surplus sweeps to next.
func SetTreasury(cur realm, next address) {
	mustAdmin(cur)
	if !next.IsValid() {
		panic("bad treasury")
	}
	state.treasury = next
	chain.Emit("ArenaTreasury", "treasury", next.String())
}

// TransferAdmin rotates the pause/sweep key.
func TransferAdmin(cur realm, next address) {
	mustAdmin(cur)
	if !next.IsValid() {
		panic("bad admin")
	}
	state.admin = next
	chain.Emit("ArenaAdmin", "admin", next.String())
}

// SetSuccessor records the package path of a later realm.
// An empty path clears it. This does not move coins or shares.
func SetSuccessor(cur realm, next string) {
	mustAdmin(cur)
	next = strings.TrimSpace(next)
	if next != "" {
		if !validSuccessor(next) || next == unsafe.CurrentRealm().PkgPath() {
			panic("bad successor")
		}
	}
	state.successor = next
	chain.Emit("ArenaSuccessor", "path", next)
}

func validSuccessor(path string) bool {
	const prefix = "gno.land/r/"
	if !strings.HasPrefix(path, prefix) || len(path) > 128 {
		return false
	}
	rest := path[len(prefix):]
	if rest == "" || strings.HasSuffix(rest, "/") || strings.Contains(rest, "//") || strings.Contains(rest, ".") {
		return false
	}
	for i := 0; i < len(rest); i++ {
		c := rest[i]
		switch {
		case c >= 'a' && c <= 'z', c >= '0' && c <= '9', c == '/', c == '_':
		default:
			return false
		}
	}
	return true
}

// Sweep sends this realm's ugnot above TotalReserve to the treasury.
// confirm must be the word "sweep". Ticket collateral is not included.
func Sweep(cur realm, confirm string) {
	mustAdmin(cur)
	if confirm != "sweep" {
		panic("confirm sweep")
	}
	if !state.treasury.IsValid() {
		panic("treasury not set")
	}
	bal := banker.NewReadonlyBanker().GetCoins(cur.Address()).AmountOf("ugnot")
	if bal < state.totalReserve {
		panic("insolvent")
	}
	surplus := bal - state.totalReserve
	payout(cur, state.treasury, surplus, "treasury")
	chain.Emit("ArenaSweep", "ugnot", strconv.FormatInt(surplus, 10))
}

gnomod.toml

module = "gno.land/r/g10ragdr3cjqkael8rslpw4y6rlelhev4h0fswcx/arena"
gno = "0.9"

[addpkg]
  creator = "g10ragdr3cjqkael8rslpw4y6rlelhev4h0fswcx"
  height = 298006
  max_deposit = "10000000ugnot"

post.gno

package arena

import (
	"chain"
	"chain/runtime"
	"math/overflow"
	"strconv"
)

// Post publishes a top-level post and returns its id.
// gated is yes/1/true/khoa to withhold the body from Render.
// The body is still public chain state. Pass an empty gated value for a public post.
func Post(cur realm, body, gated string) int {
	who := caller(cur)
	mustNoPay()
	if state.paused {
		panic("paused")
	}
	author := mustMember(who)
	return writePost(author, 0, body, isYes(gated))
}

// Reply publishes a reply to parent and returns the new id. Replies are public.
func Reply(cur realm, parent int, body string) int {
	who := caller(cur)
	mustNoPay()
	if state.paused {
		panic("paused")
	}
	author := mustMember(who)
	target := postByID(parent)
	if target == nil {
		panic("unknown post")
	}
	if target.Deleted {
		panic("deleted")
	}
	id := writePost(author, parent, body, false)
	target.Replies++
	state.replies.Set(pad(parent)+"/"+pad(id), id)
	return id
}

func writePost(author *Profile, parent int, body string, gated bool) int {
	body = cleanBody(body)
	id := state.nextID
	state.nextID++
	p := &Article{
		ID:      id,
		Author:  author.Addr,
		Body:    body,
		Height:  runtime.ChainHeight(),
		ReplyTo: parent,
		Gated:   gated,
	}
	state.posts.Set(pad(id), p)
	if parent == 0 {
		author.Posts++
		state.feed.Set(pad(id), id)
		state.byAuthor.Set(authorKey(author.Addr, id), id)
		chain.Emit(
			"ArenaPost",
			"id", strconv.Itoa(id),
			"author", author.Addr.String(),
			"handle", author.Handle,
			"gated", yesNo(gated),
		)
	} else {
		chain.Emit(
			"ArenaReply",
			"id", strconv.Itoa(id),
			"parent", strconv.Itoa(parent),
			"author", author.Addr.String(),
			"handle", author.Handle,
		)
	}
	return id
}

func yesNo(v bool) string {
	if v {
		return "yes"
	}
	return "no"
}

// Delete soft-deletes the caller's post and clears its body from current state.
// The original transaction still holds the text in chain history.
func Delete(cur realm, id int) {
	who := caller(cur)
	mustNoPay()
	mustMember(who)
	p := postByID(id)
	if p == nil {
		panic("unknown post")
	}
	if p.Deleted {
		panic("deleted")
	}
	if p.Author != who {
		panic("author only")
	}
	if p.ReplyTo == 0 {
		state.feed.Remove(pad(id))
		state.byAuthor.Remove(authorKey(who, id))
		if author := profileByAddr(who); author != nil && author.Posts > 0 {
			author.Posts--
		}
	} else {
		state.replies.Remove(pad(p.ReplyTo) + "/" + pad(id))
		if parent := postByID(p.ReplyTo); parent != nil && parent.Replies > 0 {
			parent.Replies--
		}
	}
	p.Deleted = true
	p.Body = ""
	p.Gated = false
	chain.Emit("ArenaDelete", "id", strconv.Itoa(id), "author", who.String())
}

// Like adds the caller's like. One like per account.
func Like(cur realm, id int) {
	who := caller(cur)
	mustNoPay()
	mustMember(who)
	p := livePost(id)
	k := likeKey(id, who)
	if state.likes.Has(k) {
		panic("already liked")
	}
	state.likes.Set(k, 1)
	p.Likes++
	chain.Emit("ArenaLike", "id", strconv.Itoa(id), "from", who.String())
}

// Unlike removes the caller's like.
func Unlike(cur realm, id int) {
	who := caller(cur)
	mustNoPay()
	mustMember(who)
	p := livePost(id)
	k := likeKey(id, who)
	if !state.likes.Has(k) {
		panic("not liked")
	}
	state.likes.Remove(k)
	if p.Likes > 0 {
		p.Likes--
	}
	chain.Emit("ArenaUnlike", "id", strconv.Itoa(id), "from", who.String())
}

// Tip forwards the attached ugnot to the post's author. The realm does not keep it.
func Tip(cur realm, id int) {
	who := caller(cur)
	if state.paused {
		panic("paused")
	}
	mustMember(who)
	sent := takeUgnot(cur)
	p := livePost(id)
	author := profileByAddr(p.Author)
	if author == nil {
		panic("register first")
	}
	p.Tips = overflow.Add64p(p.Tips, sent)
	author.TipsIn = overflow.Add64p(author.TipsIn, sent)
	if self := profileByAddr(who); self != nil {
		self.TipsOut = overflow.Add64p(self.TipsOut, sent)
	}
	payout(cur, p.Author, sent, "author")
	chain.Emit(
		"ArenaTip",
		"id", strconv.Itoa(id),
		"from", who.String(),
		"to", p.Author.String(),
		"ugnot", strconv.FormatInt(sent, 10),
	)
}

// GatedBody returns a gated post's text for the author or a current ticket holder.
// Chain storage is public; this only gates the convenience call and Render.
func GatedBody(cur realm, id int) string {
	who := caller(cur)
	mustNoPay()
	mustMember(who)
	p := livePost(id)
	if !p.Gated {
		return p.Body
	}
	if p.Author != who && getShares(who, p.Author) < 1 {
		panic("need a ticket")
	}
	return p.Body
}

func livePost(id int) *Article {
	p := postByID(id)
	if p == nil {
		panic("unknown post")
	}
	if p.Deleted {
		panic("deleted")
	}
	return p
}

// Liked reports whether who liked the post.
func Liked(who address, id int) bool {
	if id <= 0 {
		return false
	}
	return state.likes.Has(likeKey(id, who))
}

profile.gno

package arena

import (
	"chain"
	"chain/runtime"
	"strings"
)

// Register opens a profile for the calling account.
// handle is 3–16 chars of a-z, 0-9 and underscore. referrer may be empty
// or the bech32 address of an existing member. A member can register once.
func Register(cur realm, handle, name, bio, referrer string) {
	who := caller(cur)
	mustNoPay()
	if profileByAddr(who) != nil {
		panic("already registered")
	}
	handle = strings.ToLower(strings.TrimSpace(handle))
	if !validHandle(handle) {
		panic("bad handle")
	}
	if state.byHandle.Has(handle) {
		panic("handle taken")
	}
	if name == "" {
		name = handle
	}
	name = cleanLine(name, maxNameRunes, maxNameBytes, "name", false)
	bio = cleanLine(bio, maxBioRunes, maxBioBytes, "bio", true)

	var ref address
	referrer = strings.TrimSpace(referrer)
	if referrer != "" {
		if len(referrer) > 60 {
			panic("bad referrer")
		}
		ref = address(referrer)
		if !ref.IsValid() {
			panic("bad referrer")
		}
		if ref == who {
			panic("self referral")
		}
		if profileByAddr(ref) == nil {
			panic("referrer not registered")
		}
	}

	p := &Profile{
		Addr:     who,
		Handle:   handle,
		Name:     name,
		Bio:      bio,
		Referrer: ref,
		Joined:   runtime.ChainHeight(),
	}
	state.byAddr.Set(who.String(), p)
	state.byHandle.Set(handle, p)
	state.books.Set(who.String(), &book{})
	chain.Emit(
		"ArenaRegister",
		"addr", who.String(),
		"handle", handle,
		"referrer", ref.String(),
	)
}

// UpdateProfile replaces the display name and bio. The handle stays.
func UpdateProfile(cur realm, name, bio string) {
	who := caller(cur)
	mustNoPay()
	p := mustMember(who)
	if strings.TrimSpace(name) == "" {
		name = p.Handle
	}
	p.Name = cleanLine(name, maxNameRunes, maxNameBytes, "name", false)
	p.Bio = cleanLine(bio, maxBioRunes, maxBioBytes, "bio", true)
	chain.Emit("ArenaProfile", "addr", who.String(), "handle", p.Handle)
}

// Follow records that the caller follows handle.
func Follow(cur realm, handle string) {
	who := caller(cur)
	mustNoPay()
	self := mustMember(who)
	target := lookup(handle)
	if target == nil {
		panic("unknown handle")
	}
	if target.Addr == who {
		panic("cannot follow self")
	}
	k := followKey(who, target.Addr)
	if state.follows.Has(k) {
		panic("already following")
	}
	state.follows.Set(k, 1)
	state.fans.Set(fanKey(target.Addr, who), 1)
	self.Following++
	target.Followers++
	chain.Emit("ArenaFollow", "from", who.String(), "to", target.Addr.String(), "handle", target.Handle)
}

// Unfollow removes a follow.
func Unfollow(cur realm, handle string) {
	who := caller(cur)
	mustNoPay()
	self := mustMember(who)
	target := lookup(handle)
	if target == nil {
		panic("unknown handle")
	}
	k := followKey(who, target.Addr)
	if !state.follows.Has(k) {
		panic("not following")
	}
	state.follows.Remove(k)
	state.fans.Remove(fanKey(target.Addr, who))
	if self.Following > 0 {
		self.Following--
	}
	if target.Followers > 0 {
		target.Followers--
	}
	chain.Emit("ArenaUnfollow", "from", who.String(), "to", target.Addr.String(), "handle", target.Handle)
}

// Following reports whether from follows the handle.
func Following(from address, handle string) bool {
	target := lookup(handle)
	if target == nil {
		return false
	}
	return state.follows.Has(followKey(from, target.Addr))
}

query.gno

package arena

import (
	"strings"
)

// Holding is one creator's tickets in a wallet. It is a copy.
type Holding struct {
	Creator address
	Handle  string
	Amount  int
}

func mustLimit(n int) int {
	if n < 1 || n > 20 {
		panic("limit")
	}
	return n
}

// Feed lists newest top-level posts with id < before. before 0 starts at the newest.
func Feed(before, limit int) []Article {
	limit = mustLimit(limit)
	posts := recentPosts(before, limit)
	out := make([]Article, len(posts))
	for i, p := range posts {
		out[i] = *p
	}
	return out
}

// PostsBy lists one member's newest top-level posts with id < before.
func PostsBy(addr address, before, limit int) []Article {
	limit = mustLimit(limit)
	prefix := addr.String() + "/"
	out := make([]Article, 0, limit)
	state.byAuthor.ReverseIterate(prefix, prefix+"~", func(key string, value any) bool {
		id, ok := value.(int)
		if !ok {
			panic("author type")
		}
		if before > 0 && id >= before {
			return false
		}
		p := postByID(id)
		if p == nil || p.Deleted {
			return false
		}
		out = append(out, *p)
		return len(out) >= limit
	})
	return out
}

// Replies lists direct replies of parent with id > after, oldest first.
func Replies(parent, after, limit int) []Article {
	limit = mustLimit(limit)
	if parent <= 0 {
		panic("id")
	}
	prefix := pad(parent) + "/"
	start := prefix
	if after > 0 {
		start = prefix + pad(after) + "\x00"
	}
	out := make([]Article, 0, limit)
	state.replies.Iterate(start, prefix+"~", func(key string, value any) bool {
		id, ok := value.(int)
		if !ok {
			panic("reply type")
		}
		p := postByID(id)
		if p == nil || p.Deleted {
			return false
		}
		out = append(out, *p)
		return len(out) >= limit
	})
	return out
}

// Handles lists profiles in handle order, strictly after the given handle.
func Handles(after string, limit int) []Profile {
	limit = mustLimit(limit)
	start := ""
	after = strings.ToLower(strings.TrimSpace(after))
	if after != "" {
		start = after + "\x00"
	}
	out := make([]Profile, 0, limit)
	state.byHandle.Iterate(start, "", func(key string, value any) bool {
		p, ok := value.(*Profile)
		if !ok {
			panic("profile type")
		}
		out = append(out, *p)
		return len(out) >= limit
	})
	return out
}

// FollowingList lists profiles `who` follows, in address order, after `after`.
func FollowingList(who, after address, limit int) []Profile {
	return edgeList(who, after, limit, ">")
}

// FollowerList lists profiles that follow `who`, in address order, after `after`.
func FollowerList(who, after address, limit int) []Profile {
	return edgeList(who, after, limit, "<")
}

func edgeList(who, after address, limit int, sep string) []Profile {
	limit = mustLimit(limit)
	if !who.IsValid() {
		panic("bad address")
	}
	prefix := who.String() + sep
	start := prefix
	if after.IsValid() {
		start = prefix + after.String() + "\x00"
	}
	out := make([]Profile, 0, limit)
	tree := state.follows
	if sep == "<" {
		tree = state.fans
	}
	tree.Iterate(start, prefix+"~", func(key string, value any) bool {
		i := strings.LastIndex(key, sep)
		if i < 0 {
			return false
		}
		p := profileByAddr(address(key[i+1:]))
		if p == nil {
			return false
		}
		out = append(out, *p)
		return len(out) >= limit
	})
	return out
}

// Holdings lists ticket balances of holder, after the given creator address.
func Holdings(holder, after address, limit int) []Holding {
	limit = mustLimit(limit)
	if !holder.IsValid() {
		panic("bad address")
	}
	prefix := holder.String() + "/"
	start := prefix
	if after.IsValid() {
		start = prefix + after.String() + "\x00"
	}
	out := make([]Holding, 0, limit)
	state.shares.Iterate(start, prefix+"~", func(key string, value any) bool {
		n, ok := value.(int)
		if !ok {
			panic("share type")
		}
		i := strings.LastIndex(key, "/")
		if i < 0 || n < 1 {
			return false
		}
		creator := address(key[i+1:])
		handle := ""
		if p := profileByAddr(creator); p != nil {
			handle = p.Handle
		}
		out = append(out, Holding{Creator: creator, Handle: handle, Amount: n})
		return len(out) >= limit
	})
	return out
}

// Hot ranks the newest window the same way Render does. It is not a global index.
func Hot(limit int) []Article {
	limit = mustLimit(limit)
	posts := recentPosts(0, hotWindow)
	top := make([]scoredPost, 0, limit)
	for _, p := range posts {
		score := int64(p.Likes)*1_000_000 + p.Tips
		top = insertRank(top, scoredPost{p: p, score: score}, limit)
	}
	out := make([]Article, len(top))
	for i, row := range top {
		out[i] = *row.p
	}
	return out
}

// MemberCount is the number of registered handles.
func MemberCount() int { return state.byHandle.Size() }

// FeedCount is the number of live top-level posts still in the feed index.
func FeedCount() int { return state.feed.Size() }

// LatestID is the newest post id, or 0 when nothing has been posted.
func LatestID() int {
	if state.nextID <= 1 {
		return 0
	}
	return state.nextID - 1
}

const hotWindow = 30

type scoredPost struct {
	p     *Article
	score int64
}

func insertRank(top []scoredPost, row scoredPost, limit int) []scoredPost {
	if len(top) == limit && row.score <= top[len(top)-1].score {
		return top
	}
	top = append(top, row)
	for i := len(top) - 1; i > 0; i-- {
		if top[i].score <= top[i-1].score {
			break
		}
		top[i], top[i-1] = top[i-1], top[i]
	}
	if len(top) > limit {
		top = top[:limit]
	}
	return top
}

func recentPosts(before, limit int) []*Article {
	end := ""
	if before > 0 {
		end = pad(before)
	}
	out := make([]*Article, 0, limit)
	state.feed.ReverseIterate("", end, func(key string, value any) bool {
		id, ok := value.(int)
		if !ok {
			panic("feed type")
		}
		if before > 0 && id >= before {
			return false
		}
		p := postByID(id)
		if p == nil || p.Deleted || p.ReplyTo != 0 {
			return false
		}
		out = append(out, p)
		return len(out) >= limit
	})
	return out
}

render.gno

package arena

import "strconv"

// Render is the short gnoweb page for this fund realm.
// The long client and Sheet live in the view realm. A realm has to declare
// Render, and the storage deposit of this package cannot hold both the curve
// and the full client.
func Render(path string) string {
	line := "# Arena\n\nPhien ban " + ProtocolVersion
	if state.successor != "" {
		line += "\n\nKe tiep: " + state.successor
	}
	if state.paused {
		line += "\n\nTam dung dang bat. Ban ve van mo."
	}
	line += "\n\nThanh vien: " + strconv.Itoa(MemberCount())
	return line
}

state.gno

// Package arena is a SocialFi realm: profiles, posts, follows, GNOT tips,
// and creator tickets priced on a quadratic bonding curve.
//
// Ticket collateral sits in this realm as totalReserve. Trade fees are
// forwarded out of that collateral, and Sweep only sends coins above it.
package arena

import (
	"chain"
	"chain/banker"
	"chain/runtime/unsafe"
	"strconv"
	"strings"
	"unicode/utf8"

	"gno.land/p/nt/avl/v0"
)

const (
	// CreatorFeeBps is the creator's cut of each ticket trade.
	CreatorFeeBps int64 = 500
	// ProtocolFeeBps is forwarded to the treasury on each ticket trade.
	ProtocolFeeBps int64 = 500
	// ReferralFeeBps is paid to the creator's referrer when they have one.
	ReferralFeeBps int64 = 100
	// TicketUnit is the ugnot price of ticket number 1. Ticket i costs i² units.
	TicketUnit int64 = 10_000
	// MaxSupply is the most tickets one creator can have outstanding.
	MaxSupply = 2000
	// MaxTrade is the most tickets one buy or sell can move.
	MaxTrade = 20
	// MaxBodyRunes is the longest post, counted in runes.
	MaxBodyRunes = 280
	// ProtocolVersion is the immutable revision of this package.
	// A later package is announced with SetSuccessor. It does not hold this reserve.
	ProtocolVersion = "1"

	maxHandle    = 16
	minHandle    = 3
	maxNameRunes = 32
	maxNameBytes = 128
	maxBioRunes  = 160
	maxBioBytes  = 640
	maxBodyBytes = 1120
)

// Profile is a copy of a member's public record.
type Profile struct {
	Addr      address
	Handle    string
	Name      string
	Bio       string
	Referrer  address
	Joined    int64
	Posts     int
	Followers int
	Following int
	TipsIn    int64
	TipsOut   int64
}

// Article is a copy of one post. Gated bodies are still stored on chain;
// Render withholds them, and GatedBody checks the caller.
type Article struct {
	ID      int
	Author  address
	Body    string
	Height  int64
	ReplyTo int
	Likes   int
	Replies int
	Tips    int64
	Gated   bool
	Deleted bool
}

type book struct {
	Supply  int
	Reserve int64
	Holders int
}

// Trees stay unexported. avl.Iterate takes a callback; handing out the
// tree would let another realm run that callback under this realm.
type store struct {
	admin        address
	treasury     address
	paused       bool
	nextID       int
	totalReserve int64
	byAddr       *avl.Tree
	byHandle     *avl.Tree
	posts        *avl.Tree
	feed         *avl.Tree
	replies      *avl.Tree
	byAuthor     *avl.Tree
	follows      *avl.Tree
	fans         *avl.Tree
	likes        *avl.Tree
	books        *avl.Tree
	shares       *avl.Tree
	successor    string
}

var state *store

func init() {
	if CreatorFeeBps < 0 || ProtocolFeeBps < 0 || ReferralFeeBps < 0 {
		panic("fees")
	}
	if CreatorFeeBps+ProtocolFeeBps+ReferralFeeBps >= 10_000 {
		panic("fees")
	}
	state = newStore()
	deployer := unsafe.OriginCaller()
	if deployer.IsValid() {
		state.admin = deployer
		state.treasury = deployer
	}
}

func newStore() *store {
	return &store{
		nextID:   1,
		byAddr:   avl.NewTree(),
		byHandle: avl.NewTree(),
		posts:    avl.NewTree(),
		feed:     avl.NewTree(),
		replies:  avl.NewTree(),
		byAuthor: avl.NewTree(),
		follows:  avl.NewTree(),
		fans:     avl.NewTree(),
		likes:    avl.NewTree(),
		books:    avl.NewTree(),
		shares:   avl.NewTree(),
	}
}

// Admin is the address allowed to pause, sweep surplus, and rotate treasury.
func Admin() address { return state.admin }

// Treasury receives protocol fees and swept surplus.
func Treasury() address { return state.treasury }

// Version is this package revision. It has no setter.
func Version() string { return ProtocolVersion }

// Successor is the package path of a later realm, or empty.
// The later realm does not receive this realm's ticket reserve.
func Successor() string { return state.successor }

// Paused reports whether new posts, replies, tips, and ticket buys are frozen.
// Sells stay open so ticket collateral can still exit.
func Paused() bool { return state.paused }

// TotalReserve is the ugnot locked to back outstanding tickets.
func TotalReserve() int64 { return state.totalReserve }

func caller(cur realm) address {
	if !cur.Previous().IsUserCall() {
		panic("direct user call only")
	}
	return cur.Previous().Address()
}

func mustNoPay() {
	if len(unsafe.OriginSend()) != 0 {
		panic("this call takes no payment")
	}
}

func takeUgnot(cur realm) int64 {
	if !cur.Previous().IsUserCall() {
		panic("direct user call only")
	}
	coins := unsafe.OriginSend()
	if len(coins) != 1 || coins[0].Denom != "ugnot" || coins[0].Amount <= 0 {
		panic("send ugnot only")
	}
	return coins[0].Amount
}

func payout(cur realm, to address, amt int64, why string) {
	if amt == 0 {
		return
	}
	if amt < 0 || !to.IsValid() {
		panic("bad recipient: " + why)
	}
	bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	bnk.SendCoins(cur.Address(), to, chain.Coins{chain.NewCoin("ugnot", amt)})
}

func mustAdmin(cur realm) {
	who := caller(cur)
	mustNoPay()
	if who != state.admin {
		panic("admin only")
	}
}

func pad(n int) string {
	if n < 0 {
		panic("id")
	}
	s := strconv.Itoa(n)
	for len(s) < 10 {
		s = "0" + s
	}
	return s
}

func validHandle(s string) bool {
	if len(s) < minHandle || len(s) > maxHandle {
		return false
	}
	alnum := false
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch {
		case c >= 'a' && c <= 'z', c >= '0' && c <= '9':
			alnum = true
		case c == '_':
		default:
			return false
		}
	}
	if !alnum || reserved(s) {
		return false
	}
	return true
}

func reserved(h string) bool {
	switch h {
	case "about", "people", "hot", "feed", "following", "admin", "arena", "u", "p", "t":
		return true
	default:
		return false
	}
}

func cleanLine(s string, maxRunes, maxBytes int, label string, allowEmpty bool) string {
	s = strings.TrimSpace(s)
	if s == "" {
		if allowEmpty {
			return ""
		}
		panic(label + " length")
	}
	if utf8.RuneCountInString(s) > maxRunes || len(s) > maxBytes {
		panic(label + " length")
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if c < 0x20 || c == 0x7f || c == '<' {
			panic(label + " has markup")
		}
	}
	return s
}

func cleanBody(s string) string {
	s = strings.ReplaceAll(s, "\r\n", "\n")
	s = strings.ReplaceAll(s, "\r", "\n")
	s = strings.TrimSpace(s)
	if s == "" || utf8.RuneCountInString(s) > MaxBodyRunes || len(s) > maxBodyBytes {
		panic("body length")
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if c == '\n' || c == '\t' {
			continue
		}
		if c < 0x20 || c == 0x7f || c == '<' {
			panic("body has markup")
		}
	}
	return s
}

func isYes(s string) bool {
	switch strings.ToLower(strings.TrimSpace(s)) {
	case "", "0", "no", "false", "n":
		return false
	case "1", "yes", "true", "y", "khoa":
		return true
	default:
		panic("gated must be yes or no")
	}
}

func profileByAddr(a address) *Profile {
	v := state.byAddr.Get(a.String())
	if v == nil {
		return nil
	}
	p, ok := v.(*Profile)
	if !ok {
		panic("profile type")
	}
	return p
}

func lookup(handle string) *Profile {
	h := strings.ToLower(strings.TrimSpace(handle))
	if !validHandle(h) {
		return nil
	}
	v := state.byHandle.Get(h)
	if v == nil {
		return nil
	}
	p, ok := v.(*Profile)
	if !ok {
		panic("profile type")
	}
	return p
}

func mustMember(a address) *Profile {
	p := profileByAddr(a)
	if p == nil {
		panic("register first")
	}
	return p
}

func bookOf(creator address) *book {
	v := state.books.Get(creator.String())
	if v == nil {
		panic("no book")
	}
	b, ok := v.(*book)
	if !ok {
		panic("book type")
	}
	return b
}

func postByID(id int) *Article {
	if id <= 0 {
		panic("id")
	}
	v := state.posts.Get(pad(id))
	if v == nil {
		return nil
	}
	p, ok := v.(*Article)
	if !ok {
		panic("post type")
	}
	return p
}

func shareKey(holder, creator address) string {
	return holder.String() + "/" + creator.String()
}

func getShares(holder, creator address) int {
	v := state.shares.Get(shareKey(holder, creator))
	if v == nil {
		return 0
	}
	n, ok := v.(int)
	if !ok {
		panic("share type")
	}
	return n
}

func setShares(holder, creator address, n int) {
	k := shareKey(holder, creator)
	if n == 0 {
		state.shares.Remove(k)
		return
	}
	state.shares.Set(k, n)
}

func authorKey(a address, id int) string {
	return a.String() + "/" + pad(id)
}

func followKey(from, to address) string {
	return from.String() + ">" + to.String()
}

func fanKey(creator, fan address) string {
	return creator.String() + "<" + fan.String()
}

func likeKey(id int, who address) string {
	return pad(id) + "/" + who.String()
}

// ProfileByHandle returns a copy of the profile, or false when the handle is unknown.
func ProfileByHandle(handle string) (Profile, bool) {
	p := lookup(handle)
	if p == nil {
		return Profile{}, false
	}
	return *p, true
}

// ProfileOf returns a copy of the profile bound to addr.
func ProfileOf(addr address) (Profile, bool) {
	p := profileByAddr(addr)
	if p == nil {
		return Profile{}, false
	}
	return *p, true
}

// GetPost returns a copy of the post. The copy does not alias storage.
func GetPost(id int) (Article, bool) {
	if id <= 0 {
		return Article{}, false
	}
	p := postByID(id)
	if p == nil {
		return Article{}, false
	}
	return *p, true
}

// SharesOf returns how many tickets holder has of the creator's handle.
func SharesOf(holder address, handle string) int {
	p := lookup(handle)
	if p == nil {
		panic("unknown handle")
	}
	return getShares(holder, p.Addr)
}

// SupplyOf returns tickets outstanding, ugnot locked in that curve, and holders.
func SupplyOf(handle string) (supply int, reserve int64, holders int) {
	p := lookup(handle)
	if p == nil {
		panic("unknown handle")
	}
	b := bookOf(p.Addr)
	return b.Supply, b.Reserve, b.Holders
}

ticket.gno

package arena

import (
	"chain"
	"math/overflow"
	"strconv"
)

// QuoteBuy is the exact ugnot a buyer must attach to mint amount tickets.
// due = curve + creator fee + protocol fee + referral fee.
// curve is what stays in the reserve. Fees are paid on top and forwarded.
func QuoteBuy(handle string, amount int) (due, curve, creatorFee, protocolFee, referralFee int64) {
	p := lookup(handle)
	if p == nil {
		panic("unknown handle")
	}
	curve = curveCost(bookOf(p.Addr).Supply, amount)
	creatorFee, protocolFee, referralFee = splitFees(curve, p.Referrer.IsValid())
	due = overflow.Add64p(curve, overflow.Add64p(creatorFee, overflow.Add64p(protocolFee, referralFee)))
	return
}

// QuoteSell is what a seller receives, and the fees taken out of the curve refund.
// The reserve drops by the full curve amount, so later sells stay solvent.
func QuoteSell(handle string, amount int) (proceeds, curve, creatorFee, protocolFee, referralFee int64) {
	p := lookup(handle)
	if p == nil {
		panic("unknown handle")
	}
	b := bookOf(p.Addr)
	if amount < 1 || amount > MaxTrade {
		panic("amount")
	}
	if amount > b.Supply {
		panic("not enough tickets")
	}
	curve = curveCost(b.Supply-amount, amount)
	creatorFee, protocolFee, referralFee = splitFees(curve, p.Referrer.IsValid())
	proceeds = curve - creatorFee - protocolFee - referralFee
	if proceeds <= 0 {
		panic("proceeds")
	}
	return
}

// Buy mints amount tickets of handle. Attach exactly QuoteBuy's due in ugnot.
func Buy(cur realm, handle string, amount int) {
	who := caller(cur)
	if state.paused {
		panic("paused")
	}
	mustMember(who)
	due, curve, creatorFee, protocolFee, referralFee := QuoteBuy(handle, amount)
	sent := takeUgnot(cur)
	if sent != due {
		panic("send exactly " + strconv.FormatInt(due, 10) + "ugnot")
	}
	p := lookup(handle)
	b := bookOf(p.Addr)
	b.Supply += amount
	b.Reserve = overflow.Add64p(b.Reserve, curve)
	state.totalReserve = overflow.Add64p(state.totalReserve, curve)
	addShares(who, p.Addr, amount)
	forwardFees(cur, p, creatorFee, protocolFee, referralFee)
	chain.Emit(
		"ArenaBuy",
		"buyer", who.String(),
		"creator", p.Addr.String(),
		"handle", p.Handle,
		"amount", strconv.Itoa(amount),
		"curve", strconv.FormatInt(curve, 10),
		"due", strconv.FormatInt(due, 10),
	)
}

// Sell burns amount tickets and pays the caller from the reserve, minus fees.
// Sells stay available while the realm is paused.
func Sell(cur realm, handle string, amount int) {
	who := caller(cur)
	mustNoPay()
	mustMember(who)
	proceeds, curve, creatorFee, protocolFee, referralFee := QuoteSell(handle, amount)
	if getShares(who, lookup(handle).Addr) < amount {
		panic("not enough tickets")
	}
	p := lookup(handle)
	b := bookOf(p.Addr)
	if b.Reserve < curve || state.totalReserve < curve {
		panic("insolvent")
	}
	b.Supply -= amount
	b.Reserve = overflow.Sub64p(b.Reserve, curve)
	state.totalReserve = overflow.Sub64p(state.totalReserve, curve)
	subShares(who, p.Addr, amount)
	payout(cur, who, proceeds, "seller")
	forwardFees(cur, p, creatorFee, protocolFee, referralFee)
	chain.Emit(
		"ArenaSell",
		"seller", who.String(),
		"creator", p.Addr.String(),
		"handle", p.Handle,
		"amount", strconv.Itoa(amount),
		"curve", strconv.FormatInt(curve, 10),
		"proceeds", strconv.FormatInt(proceeds, 10),
	)
}

func forwardFees(cur realm, creator *Profile, creatorFee, protocolFee, referralFee int64) {
	if protocolFee > 0 && !state.treasury.IsValid() {
		panic("treasury not set")
	}
	payout(cur, creator.Addr, creatorFee, "creator")
	payout(cur, state.treasury, protocolFee, "treasury")
	if referralFee > 0 {
		payout(cur, creator.Referrer, referralFee, "referrer")
	}
}

func addShares(holder, creator address, n int) {
	if n < 1 {
		panic("amount")
	}
	had := getShares(holder, creator)
	setShares(holder, creator, had+n)
	if had == 0 {
		bookOf(creator).Holders++
	}
}

func subShares(holder, creator address, n int) {
	had := getShares(holder, creator)
	if n < 1 || had < n {
		panic("not enough tickets")
	}
	setShares(holder, creator, had-n)
	if had == n {
		b := bookOf(creator)
		if b.Holders > 0 {
			b.Holders--
		}
	}
}

func splitFees(curve int64, referred bool) (creator, protocol, referral int64) {
	creator = bps(curve, CreatorFeeBps)
	protocol = bps(curve, ProtocolFeeBps)
	if referred {
		referral = bps(curve, ReferralFeeBps)
	}
	return
}

func bps(amount, points int64) int64 {
	if amount == 0 || points == 0 {
		return 0
	}
	if amount < 0 || points < 0 {
		panic("fee")
	}
	return overflow.Mul64p(amount, points) / 10_000
}

// curveCost is the ugnot reserve needed to move `amount` tickets starting at supply.
// Ticket i (1-based) is priced i² * TicketUnit. The sum of squares is exact.
func curveCost(supply, amount int) int64 {
	if amount < 1 || amount > MaxTrade {
		panic("amount")
	}
	if supply < 0 {
		panic("supply")
	}
	from := int64(supply)
	to := from + int64(amount)
	if to > int64(MaxSupply) {
		panic("supply cap")
	}
	return overflow.Mul64p(sumSq(to)-sumSq(from), TicketUnit)
}

func sumSq(n int64) int64 {
	if n <= 0 {
		return 0
	}
	if n > int64(MaxSupply) {
		panic("supply cap")
	}
	// n*(n+1)*(2n+1)/6, dividing 2 and 3 out before multiplying.
	a := n
	b := n + 1
	if a%2 == 0 {
		a /= 2
	} else {
		b /= 2
	}
	c := 2*n + 1
	if a%3 == 0 {
		a /= 3
	} else if b%3 == 0 {
		b /= 3
	} else if c%3 == 0 {
		c /= 3
	} else {
		panic("sumSq")
	}
	return overflow.Mul64p(overflow.Mul64p(a, b), c)
}