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

board.gno

package connect4_v2

const (
	cols = 7
	rows = 6
)

// board is indexed [column][row]; row 0 is the bottom. 0 = empty, 1/2 = player.
type board [cols][rows]byte

// drop places piece p in column c (0-based) and returns its row, or -1 if the column is full.
func (b *board) drop(c int, p byte) int {
	for r := 0; r < rows; r++ {
		if b[c][r] == 0 {
			b[c][r] = p
			return r
		}
	}
	return -1
}

// wins reports whether the piece at (c, r) is part of four in a row.
func (b *board) wins(c, r int) bool { return b.winLine(c, r) != nil }

// winLine returns the cells of the four-or-more line through (c, r), in order
// along the line, or nil if the piece there completes none.
func (b *board) winLine(c, r int) [][2]int {
	p := b[c][r]
	for _, d := range [4][2]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}} {
		back := b.count(c, r, -d[0], -d[1], p)
		n := 1 + back + b.count(c, r, d[0], d[1], p)
		if n >= 4 {
			line := make([][2]int, n)
			for i := range line {
				k := i - back
				line[i] = [2]int{c + k*d[0], r + k*d[1]}
			}
			return line
		}
	}
	return nil
}

// count returns how many consecutive p pieces follow (c, r) in direction (dc, dr).
func (b *board) count(c, r, dc, dr int, p byte) int {
	n := 0
	for {
		c, r = c+dc, r+dr
		if c < 0 || c >= cols || r < 0 || r >= rows || b[c][r] != p {
			return n
		}
		n++
	}
}

board_test.gno

package connect4_v2

import "testing"

func play(b *board, p byte, colsPlayed ...int) (int, int) {
	c, r := 0, 0
	for _, c = range colsPlayed {
		r = b.drop(c, p)
	}
	return c, r
}

func TestWins(t *testing.T) {
	cases := []struct {
		name  string
		setup func(b *board) (int, int)
		want  bool
	}{
		{"horizontal", func(b *board) (int, int) { return play(b, 1, 0, 1, 2, 3) }, true},
		{"vertical", func(b *board) (int, int) { return play(b, 1, 4, 4, 4, 4) }, true},
		{"three only", func(b *board) (int, int) { return play(b, 1, 0, 1, 2) }, false},
		{"diagonal up", func(b *board) (int, int) {
			play(b, 2, 1, 2, 2, 3, 3, 3)
			return play(b, 1, 0, 1, 2, 3)
		}, true},
		{"diagonal down", func(b *board) (int, int) {
			play(b, 2, 3, 3, 3, 2, 2, 1)
			return play(b, 1, 3, 2, 1, 0)
		}, true},
		{"gap breaks line", func(b *board) (int, int) { return play(b, 1, 0, 1, 3, 4) }, false},
	}
	for _, tc := range cases {
		var b board
		c, r := tc.setup(&b)
		if got := b.wins(c, r); got != tc.want {
			t.Errorf("%s: wins=%v, want %v", tc.name, got, tc.want)
		}
	}
}

func TestDropFullColumn(t *testing.T) {
	var b board
	for i := 0; i < rows; i++ {
		if b.drop(0, 1) != i {
			t.Fatalf("drop %d landed on wrong row", i)
		}
	}
	if b.drop(0, 1) != -1 {
		t.Fatal("drop into full column should return -1")
	}
}

func TestWinLine(t *testing.T) {
	var b board
	if c, r := play(&b, 1, 0, 1, 2); b.winLine(c, r) != nil {
		t.Fatal("three in a row is not a win")
	}
	c, r := play(&b, 1, 3)
	line := b.winLine(c, r)
	if len(line) != 4 {
		t.Fatalf("want 4 winning cells, got %v", line)
	}
	for i, cell := range line {
		if cell != [2]int{i, 0} {
			t.Fatalf("cell %d = %v, want [%d 0]", i, cell, i)
		}
	}
}

connect4.gno

// package connect4_v2 is a staked Connect 4 game. A creator posts an offer with
// a ugnot stake; anyone (or a named opponent) accepts with the same stake;
// the winner takes the pot minus a flat house fee.
//
// The first mover is picked by commit-reveal: the creator offers with
// sha256(passphrase) and must Reveal the passphrase within 90s of Accept, or
// forfeit. Randomness computed in Accept could be re-rolled by an acceptor
// who bundles [Accept, Play] in one atomic tx and lets it revert.
//
// Every move has a 90s clock measured in block time. Nothing on-chain fires
// by itself, so an expired clock is settled by anyone calling ClaimTimeout:
// an unrevealed game is won by the acceptor, a game whose first mover never
// moved is void and both stakes are refunded, otherwise the player who ran
// out of time forfeits.
package connect4_v2

import (
	"chain"
	"chain/banker"
	"chain/runtime/unsafe"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"

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

const (
	moveTimeout = 90 * time.Second
	maxOfferTTL = 60        // minutes
	minStake    = 1_000_000 // ugnot
	denom       = "ugnot"
)

type Status int

const (
	Open Status = iota
	Playing
	Won
	Draw
	Void
	Cancelled
)

func (s Status) String() string {
	return [...]string{"open", "playing", "won", "draw", "void", "cancelled"}[s]
}

type Game struct {
	ID        int
	Creator   address
	Opponent  address // optional; if set, only this address may accept
	Acceptor  address
	Stake     int64 // ugnot, per player
	Fee       int64 // ugnot house fee, fixed at offer time
	ExpiresAt time.Time
	// Commitment is the lowercase hex sha256 of the creator's passphrase.
	Commitment string

	Board    board
	Turn     byte // 0 = awaiting Reveal, 1 = creator, 2 = acceptor
	Moves    int
	LastCol  int // column and row of the last piece dropped, valid if Moves > 0
	LastRow  int
	LastMove time.Time
	Status   Status
	Winner   address
}

type Stats struct {
	Games, Wins, Draws int
	GnotWon            int64 // total ugnot received from wins
}

var (
	games         avl.Tree // key(id) -> *Game
	active        avl.Tree // key(id) -> *Game, only Open and Playing
	stats         avl.Tree // address -> *Stats
	nextID        int
	fee           int64 = 100_000 // ugnot per decisive game
	feesCollected int64
	owner         = ownable.NewWithAddress("g1cvr48r7l7lkmvp77cr6zg2zhu26jgfwr0y8pew")
)

// Offer posts a game open for validFor minutes. The stake is the ugnot sent
// with the call. A non-empty opponent makes the offer private. commitment is
// the lowercase hex sha256 of a secret passphrase, revealed after Accept.
func Offer(cur realm, opponent address, validFor int, commitment string) int {
	stake := received(cur)
	caller := cur.Previous().Address()
	if opponent == caller {
		panic("cannot challenge yourself")
	}
	if errs := validateOffer(stake, validFor, opponent, commitment); len(errs) > 0 {
		panic(errs[0])
	}
	nextID++
	g := &Game{
		ID:        nextID,
		Creator:   caller,
		Opponent:  opponent,
		Stake:     stake,
		Fee:       fee,
		ExpiresAt: time.Now().Add(time.Duration(validFor) * time.Minute),

		Commitment: commitment,
	}
	games.Set(key(g.ID), g)
	active.Set(key(g.ID), g)
	return g.ID
}

// validateOffer returns every rule an offer breaks. Offer panics with the
// first; the "new" page lists them all before anyone signs.
func validateOffer(stake int64, validFor int, opponent address, commitment string) []string {
	var errs []string
	if stake < minStake {
		errs = append(errs, "stake below minimum of "+gnot(minStake))
	}
	if stake <= fee {
		errs = append(errs, "stake must exceed the house fee of "+gnot(fee))
	}
	if validFor < 1 || validFor > maxOfferTTL {
		errs = append(errs, "validFor must be between 1 and 60 minutes")
	}
	if opponent != "" && !opponent.IsValid() {
		errs = append(errs, "invalid opponent address")
	}
	if !isHexSHA256(commitment) {
		errs = append(errs, "commitment must be 64 lowercase hex chars (sha256 of your passphrase)")
	}
	return errs
}

// Accept joins an open offer by sending exactly its stake. The creator then
// has 90s to Reveal, which picks the first mover.
func Accept(cur realm, id int) {
	stake := received(cur)
	caller := cur.Previous().Address()
	g := mustGet(id)
	if g.Status != Open {
		panic("game is not open")
	}
	if !time.Now().Before(g.ExpiresAt) {
		panic("offer expired")
	}
	if caller == g.Creator {
		panic("cannot accept your own offer")
	}
	if g.Opponent != "" && caller != g.Opponent {
		panic("offer is reserved for another player")
	}
	if stake != g.Stake {
		panic("must send exactly " + strconv.FormatInt(g.Stake, 10) + denom)
	}
	g.Acceptor = caller
	g.Status = Playing
	g.LastMove = time.Now() // Turn stays 0 until Reveal
}

// Reveal discloses the creator's passphrase, which picks the first mover.
// It must come within 90s of Accept.
func Reveal(cur realm, id int, passphrase string) {
	noCoins()
	g := mustGet(id)
	if g.Status != Playing || g.Turn != 0 {
		panic("game is not awaiting a reveal")
	}
	if cur.Previous().Address() != g.Creator {
		panic("only the creator can reveal")
	}
	if time.Now().After(g.deadline()) {
		panic("reveal clock ran out")
	}
	if sha256Hex(passphrase) != g.Commitment {
		panic("passphrase does not match the commitment")
	}
	h := sha256.Sum256([]byte(strings.Join([]string{
		passphrase, strconv.Itoa(g.ID), g.Creator.String(), g.Acceptor.String(),
	}, "|")))
	g.Turn = 1 + h[0]&1
	g.LastMove = time.Now()
}

// Play drops a piece in column (1-7).
func Play(cur realm, id, column int) {
	noCoins()
	g := mustGet(id)
	if g.Status != Playing {
		panic("game is not in progress")
	}
	if g.Turn == 0 {
		panic("waiting for the creator to reveal")
	}
	if cur.Previous().Address() != g.player(g.Turn) {
		panic("not your turn")
	}
	if time.Now().After(g.deadline()) {
		panic("move clock ran out")
	}
	if column < 1 || column > cols {
		panic("column must be between 1 and 7")
	}
	r := g.Board.drop(column-1, g.Turn)
	if r < 0 {
		panic("column is full")
	}
	g.Moves++
	g.LastCol, g.LastRow = column-1, r
	switch {
	case g.Board.wins(column-1, r):
		settleWin(cur, g, g.player(g.Turn))
	case g.Moves == cols*rows:
		settleDraw(cur, g)
	default:
		g.Turn = 3 - g.Turn
		g.LastMove = time.Now()
	}
}

// ClaimTimeout settles a game whose move clock ran out. Anyone may call it.
func ClaimTimeout(cur realm, id int) {
	noCoins()
	g := mustGet(id)
	if g.Status != Playing {
		panic("game is not in progress")
	}
	if !time.Now().After(g.deadline()) {
		panic("move clock has not run out")
	}
	if g.Turn == 0 { // creator never revealed: forfeit
		settleWin(cur, g, g.Acceptor)
		return
	}
	if g.Moves == 0 {
		settleVoid(cur, g)
		return
	}
	settleWin(cur, g, g.player(3-g.Turn))
}

// Resign concedes a game in progress.
func Resign(cur realm, id int) {
	noCoins()
	g := mustGet(id)
	if g.Status != Playing {
		panic("game is not in progress")
	}
	switch cur.Previous().Address() {
	case g.Creator:
		settleWin(cur, g, g.Acceptor)
	case g.Acceptor:
		settleWin(cur, g, g.Creator)
	default:
		panic("not a player in this game")
	}
}

// Cancel withdraws an open offer and refunds the creator. The creator may
// cancel at any time; anyone may once the offer has expired.
func Cancel(cur realm, id int) {
	noCoins()
	g := mustGet(id)
	if g.Status != Open {
		panic("game is not open")
	}
	if cur.Previous().Address() != g.Creator && time.Now().Before(g.ExpiresAt) {
		panic("only the creator can cancel an unexpired offer")
	}
	finish(g, Cancelled)
	send(cur, g.Creator, g.Stake)
}

// SetFee changes the flat house fee, in ugnot, for new offers. Games already
// offered keep the fee they were created with.
func SetFee(cur realm, amount int64) {
	noCoins()
	owner.AssertOwnedBy(cur.Previous().Address())
	if amount < 0 {
		panic("fee must not be negative")
	}
	fee = amount
}

// WithdrawFees sends all collected fees to to.
func WithdrawFees(cur realm, to address) {
	noCoins()
	owner.AssertOwnedBy(cur.Previous().Address())
	amount := feesCollected
	feesCollected = 0
	send(cur, to, amount)
}

func TransferOwnership(cur realm, newOwner address) {
	noCoins()
	if err := owner.TransferOwnership(0, cur, newOwner); err != nil {
		panic(err)
	}
}

// received returns the ugnot sent with a direct user call. OriginSend only
// describes a real payment to this realm when the caller is an EOA using
// maketx call; see docs/resources/effective-gno.md.
func received(cur realm) int64 {
	if !cur.Previous().IsUserCall() {
		panic("only user-call (maketx call) accepted")
	}
	sent := unsafe.OriginSend()
	if len(sent) != 1 || sent[0].Denom != denom {
		panic("send exactly one " + denom + " coin")
	}
	return sent[0].Amount
}

// noCoins guards calls that take no payment: coins sent with them would be
// stuck in the realm.
func noCoins() {
	if len(unsafe.OriginSend()) != 0 {
		panic("this function does not accept coins")
	}
}

func sha256Hex(s string) string {
	h := sha256.Sum256([]byte(s))
	return hex.EncodeToString(h[:])
}

func isHexSHA256(s string) bool {
	if len(s) != 64 {
		return false
	}
	for _, c := range s {
		if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
			return false
		}
	}
	return true
}

func settleWin(cur realm, g *Game, winner address) {
	loser := g.Creator
	if winner == g.Creator {
		loser = g.Acceptor
	}
	pot := 2 * g.Stake
	finish(g, Won)
	g.Winner = winner
	feesCollected += g.Fee
	w := statsOf(winner)
	w.Games++
	w.Wins++
	w.GnotWon += pot - g.Fee
	statsOf(loser).Games++
	send(cur, winner, pot-g.Fee)
}

func settleDraw(cur realm, g *Game) {
	finish(g, Draw)
	for _, p := range []address{g.Creator, g.Acceptor} {
		s := statsOf(p)
		s.Games++
		s.Draws++
		send(cur, p, g.Stake)
	}
}

func settleVoid(cur realm, g *Game) {
	finish(g, Void)
	send(cur, g.Creator, g.Stake)
	send(cur, g.Acceptor, g.Stake)
}

func finish(g *Game, s Status) {
	g.Status = s
	active.Remove(key(g.ID))
}

func send(cur realm, to address, amount int64) {
	if amount == 0 {
		return
	}
	banker.NewBanker(banker.BankerTypeRealmSend, cur).
		SendCoins(cur.Address(), to, chain.Coins{{denom, amount}})
}

func (g *Game) player(turn byte) address {
	if turn == 1 {
		return g.Creator
	}
	return g.Acceptor
}

func (g *Game) deadline() time.Time { return g.LastMove.Add(moveTimeout) }

func statsOf(addr address) *Stats {
	if v := stats.Get(addr.String()); v != nil {
		return v.(*Stats)
	}
	s := &Stats{}
	stats.Set(addr.String(), s)
	return s
}

// key zero-pads ids so avl iteration order matches creation order.
func key(id int) string {
	s := strconv.Itoa(id)
	if len(s) < 10 {
		s = strings.Repeat("0", 10-len(s)) + s
	}
	return s
}

func get(id int) *Game {
	if v := games.Get(key(id)); v != nil {
		return v.(*Game)
	}
	return nil
}

func mustGet(id int) *Game {
	g := get(id)
	if g == nil {
		panic("game not found")
	}
	return g
}

connect4_test.gno

package connect4_v2

import (
	"chain"
	"chain/banker"
	"strconv"
	"testing"

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

const stake = int64(10_000_000)

var (
	alice   = testutils.TestAddress("alice")
	bob     = testutils.TestAddress("bob")
	carol   = testutils.TestAddress("carol")
	admin   = address("g1cvr48r7l7lkmvp77cr6zg2zhu26jgfwr0y8pew")
	pkgAddr = chain.PackageAddress("gno.land/r/samcrew/connect4")
)

func reset() {
	games, active, stats = avl.Tree{}, avl.Tree{}, avl.Tree{}
	nextID, fee, feesCollected = 0, 100_000, 0
}

// pay sets the ugnot sent with the next call and credits the realm with it,
// mirroring what the chain does. testing.SetRealm must be called in the same
// frame that makes the cross call, so tests call it inline rather than here.
func pay(amount int64) {
	if amount == 0 {
		testing.SetOriginSend(nil)
		return
	}
	coins := chain.Coins{{"ugnot", amount}}
	testing.SetOriginSend(coins)
	testing.IssueCoins(pkgAddr, coins)
}

func balance(addr address) int64 {
	return banker.NewReadonlyBanker().GetCoin(addr, "ugnot")
}

// phrase returns a passphrase unique to the next game id.
func phrase() string { return "four random words " + strconv.Itoa(nextID+1) }

// commit returns the commitment for phrase().
func commit() string { return sha256Hex(phrase()) }

// accepted returns a game between alice (creator) and bob awaiting Reveal,
// and its passphrase.
func accepted(cur realm) (*Game, string) {
	p := phrase()
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	id := Offer(cross(cur), "", 10, sha256Hex(p))
	testing.SetRealm(testing.NewUserRealm(bob))
	pay(stake)
	Accept(cross(cur), id)
	return mustGet(id), p
}

// started returns a revealed Playing game between alice (creator) and bob.
func started(cur realm) *Game {
	g, p := accepted(cur)
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	Reveal(cross(cur), g.ID, p)
	return g
}

// move plays column for whoever is on turn.
func move(cur realm, g *Game, column int) {
	testing.SetRealm(testing.NewUserRealm(g.player(g.Turn)))
	pay(0)
	Play(cross(cur), g.ID, column)
}

// expireClock advances block time past the 90s move clock (SkipHeights is 5s/block).
func expireClock() { testing.SkipHeights(19) }

func TestWinPaysPotMinusFee(cur realm, t *testing.T) {
	reset()
	g := started(cur)
	first := g.player(g.Turn)
	before := balance(first)
	for _, c := range []int{1, 2, 1, 2, 1, 2, 1} { // first mover stacks column 1
		move(cur, g, c)
	}
	uassert.Equal(t, "won", g.Status.String())
	uassert.Equal(t, first, g.Winner)
	uassert.Equal(t, 2*stake-100_000, balance(first)-before)
	uassert.Equal(t, int64(100_000), feesCollected)
	uassert.Equal(t, 1, statsOf(first).Wins)
	uassert.Equal(t, 2*stake-100_000, statsOf(first).GnotWon)
	uassert.Equal(t, 1, statsOf(g.player(3-g.Turn)).Games)
	uassert.Equal(t, 0, active.Size())
}

func TestOfferRejects(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(minStake - 1)
	uassert.AbortsContains(t, cur, "stake below minimum", func() { Offer(cross(cur), "", 10, commit()) })
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	uassert.AbortsContains(t, cur, "validFor", func() { Offer(cross(cur), "", 0, commit()) })
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	uassert.AbortsContains(t, cur, "validFor", func() { Offer(cross(cur), "", 61, commit()) })
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	uassert.AbortsContains(t, cur, "yourself", func() { Offer(cross(cur), alice, 10, commit()) })
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	uassert.AbortsContains(t, cur, "send exactly one", func() { Offer(cross(cur), "", 10, commit()) })
	testing.SetRealm(testing.NewUserRealm(alice))
	testing.SetOriginSend(chain.Coins{{"ugnot", stake}, {"foo", 1}})
	uassert.AbortsContains(t, cur, "send exactly one", func() { Offer(cross(cur), "", 10, commit()) })
}

func TestAcceptRejects(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	id := Offer(cross(cur), bob, 1, commit())
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	uassert.AbortsContains(t, cur, "own offer", func() { Accept(cross(cur), id) })
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(stake)
	uassert.AbortsContains(t, cur, "reserved", func() { Accept(cross(cur), id) })
	testing.SetRealm(testing.NewUserRealm(bob))
	pay(stake - 1)
	uassert.AbortsContains(t, cur, "must send exactly", func() { Accept(cross(cur), id) })
	testing.SetRealm(testing.NewUserRealm(bob))
	pay(stake + 1)
	uassert.AbortsContains(t, cur, "must send exactly", func() { Accept(cross(cur), id) })
	testing.SkipHeights(13) // 65s > 1 minute
	testing.SetRealm(testing.NewUserRealm(bob))
	pay(stake)
	uassert.AbortsContains(t, cur, "expired", func() { Accept(cross(cur), id) })
	testing.SetRealm(testing.NewUserRealm(bob))
	pay(stake)
	uassert.AbortsContains(t, cur, "not found", func() { Accept(cross(cur), 99) })
}

func TestPlayRejects(cur realm, t *testing.T) {
	reset()
	g := started(cur)
	testing.SetRealm(testing.NewUserRealm(g.player(3 - g.Turn)))
	pay(0)
	uassert.AbortsContains(t, cur, "not your turn", func() { Play(cross(cur), g.ID, 1) })
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(0)
	uassert.AbortsContains(t, cur, "not your turn", func() { Play(cross(cur), g.ID, 1) })
	testing.SetRealm(testing.NewUserRealm(g.player(g.Turn)))
	pay(0)
	uassert.AbortsContains(t, cur, "column must be", func() { Play(cross(cur), g.ID, 0) })
	testing.SetRealm(testing.NewUserRealm(g.player(g.Turn)))
	pay(0)
	uassert.AbortsContains(t, cur, "column must be", func() { Play(cross(cur), g.ID, 8) })
	expireClock()
	testing.SetRealm(testing.NewUserRealm(g.player(g.Turn)))
	pay(0)
	uassert.AbortsContains(t, cur, "clock ran out", func() { Play(cross(cur), g.ID, 1) })
}

func TestFullColumnRejected(cur realm, t *testing.T) {
	reset()
	g := started(cur)
	for i := 0; i < rows; i++ {
		move(cur, g, 4) // alternating players never make 4 in a column
	}
	testing.SetRealm(testing.NewUserRealm(g.player(g.Turn)))
	pay(0)
	uassert.AbortsContains(t, cur, "column is full", func() { Play(cross(cur), g.ID, 4) })
}

// The creator revealed, then the first mover never moved.
func TestTimeoutBeforeFirstMoveIsVoid(cur realm, t *testing.T) {
	reset()
	g := started(cur)
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(0)
	uassert.AbortsContains(t, cur, "has not run out", func() { ClaimTimeout(cross(cur), g.ID) })
	a, b := balance(alice), balance(bob)
	expireClock()
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(0) // anyone may settle
	ClaimTimeout(cross(cur), g.ID)
	uassert.Equal(t, "void", g.Status.String())
	uassert.Equal(t, stake, balance(alice)-a)
	uassert.Equal(t, stake, balance(bob)-b)
	uassert.Equal(t, int64(0), feesCollected)
	uassert.Equal(t, 0, stats.Size())
}

func TestTimeoutAfterMoveForfeits(cur realm, t *testing.T) {
	reset()
	g := started(cur)
	mover := g.player(g.Turn)
	loser := g.player(3 - g.Turn)
	move(cur, g, 1)
	expireClock()
	before := balance(mover)
	testing.SetRealm(testing.NewUserRealm(mover))
	pay(0)
	ClaimTimeout(cross(cur), g.ID)
	uassert.Equal(t, "won", g.Status.String())
	uassert.Equal(t, mover, g.Winner)
	uassert.Equal(t, 2*stake-100_000, balance(mover)-before)
	uassert.Equal(t, int64(100_000), feesCollected)
	uassert.Equal(t, 1, statsOf(loser).Games)
}

func TestResign(cur realm, t *testing.T) {
	reset()
	g := started(cur)
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(0)
	uassert.AbortsContains(t, cur, "not a player", func() { Resign(cross(cur), g.ID) })
	before := balance(bob)
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	Resign(cross(cur), g.ID)
	uassert.Equal(t, "won", g.Status.String())
	uassert.Equal(t, bob, g.Winner)
	uassert.Equal(t, 2*stake-100_000, balance(bob)-before)
	uassert.Equal(t, int64(100_000), feesCollected)
	uassert.Equal(t, 1, statsOf(alice).Games)
}

func TestCancel(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	id := Offer(cross(cur), "", 1, commit())
	testing.SetRealm(testing.NewUserRealm(bob))
	pay(0)
	uassert.AbortsContains(t, cur, "only the creator", func() { Cancel(cross(cur), id) })
	before := balance(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	Cancel(cross(cur), id) // creator, before expiry
	uassert.Equal(t, "cancelled", mustGet(id).Status.String())
	uassert.Equal(t, stake, balance(alice)-before)

	// Once expired, anyone may cancel; the refund still goes to the creator.
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	id = Offer(cross(cur), "", 1, commit())
	testing.SkipHeights(13) // 65s > 1 minute
	before = balance(alice)
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(0)
	Cancel(cross(cur), id)
	uassert.Equal(t, "cancelled", mustGet(id).Status.String())
	uassert.Equal(t, stake, balance(alice)-before)

	g := started(cur)
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	uassert.AbortsContains(t, cur, "not open", func() { Cancel(cross(cur), g.ID) })
}

func TestDrawRefundsBoth(cur realm, t *testing.T) {
	reset()
	g := started(cur)
	// Fill every cell but the top of column 7 with a pattern that has no
	// four in a row; player 1 owns the last cell.
	for c := 0; c < cols; c++ {
		for r := 0; r < rows; r++ {
			g.Board[c][r] = byte(1 + (c/2+r)%2)
		}
	}
	g.Board[6][5] = 0
	g.Moves, g.Turn = cols*rows-1, 1
	a, b := balance(alice), balance(bob)
	move(cur, g, 7)
	uassert.Equal(t, "draw", g.Status.String())
	uassert.Equal(t, stake, balance(alice)-a)
	uassert.Equal(t, stake, balance(bob)-b)
	uassert.Equal(t, 1, statsOf(alice).Draws)
}

func TestFeeSnapshotAndWithdraw(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(0)
	uassert.AbortsContains(t, cur, "not owner", func() { SetFee(cross(cur), 0) })
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(0)
	uassert.AbortsContains(t, cur, "not owner", func() { WithdrawFees(cross(cur), carol) })
	g := started(cur) // offered at the default 0.1 GNOT fee
	testing.SetRealm(testing.NewUserRealm(admin))
	pay(0)
	uassert.AbortsContains(t, cur, "negative", func() { SetFee(cross(cur), -1) })
	SetFee(cross(cur), 5_000_000)
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	Resign(cross(cur), g.ID)
	uassert.Equal(t, int64(100_000), feesCollected)

	before := balance(carol)
	testing.SetRealm(testing.NewUserRealm(admin))
	pay(0)
	WithdrawFees(cross(cur), carol)
	uassert.Equal(t, int64(100_000), balance(carol)-before)
	uassert.Equal(t, int64(0), feesCollected)

	// A raised fee applies to new offers, which must stake more than it.
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(5_000_000)
	uassert.AbortsContains(t, cur, "exceed the house fee", func() { Offer(cross(cur), "", 10, commit()) })
}

func TestFinishedGameRejects(cur realm, t *testing.T) {
	reset()
	g := started(cur)
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	Resign(cross(cur), g.ID)
	testing.SetRealm(testing.NewUserRealm(bob))
	pay(0)
	uassert.AbortsContains(t, cur, "not in progress", func() { Play(cross(cur), g.ID, 1) })
	uassert.AbortsContains(t, cur, "not in progress", func() { Resign(cross(cur), g.ID) })
	expireClock()
	testing.SetRealm(testing.NewUserRealm(bob))
	pay(0)
	uassert.AbortsContains(t, cur, "not in progress", func() { ClaimTimeout(cross(cur), g.ID) })
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(stake)
	uassert.AbortsContains(t, cur, "not open", func() { Accept(cross(cur), g.ID) })
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(stake)
	uassert.AbortsContains(t, cur, "invalid opponent", func() { Offer(cross(cur), "notanaddress", 10, commit()) })
}

func TestRevealPhase(cur realm, t *testing.T) {
	reset()
	g, p := accepted(cur)
	uassert.Equal(t, byte(0), g.Turn)
	for _, who := range []address{alice, bob} {
		testing.SetRealm(testing.NewUserRealm(who))
		pay(0)
		uassert.AbortsContains(t, cur, "waiting for the creator", func() { Play(cross(cur), g.ID, 1) })
	}
	testing.SetRealm(testing.NewUserRealm(bob))
	pay(0)
	uassert.AbortsContains(t, cur, "only the creator", func() { Reveal(cross(cur), g.ID, p) })
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	uassert.AbortsContains(t, cur, "does not match", func() { Reveal(cross(cur), g.ID, p+"x") })
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	Reveal(cross(cur), g.ID, p)
	uassert.True(t, g.Turn == 1 || g.Turn == 2)
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	uassert.AbortsContains(t, cur, "not awaiting a reveal", func() { Reveal(cross(cur), g.ID, p) })
	move(cur, g, 1) // the picked first mover can play
	uassert.Equal(t, 1, g.Moves)
}

func TestLateRevealForfeits(cur realm, t *testing.T) {
	reset()
	g, p := accepted(cur)
	expireClock()
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	uassert.AbortsContains(t, cur, "reveal clock ran out", func() { Reveal(cross(cur), g.ID, p) })
	before := balance(bob)
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(0)
	ClaimTimeout(cross(cur), g.ID)
	uassert.Equal(t, "won", g.Status.String())
	uassert.Equal(t, bob, g.Winner)
	uassert.Equal(t, 2*stake-100_000, balance(bob)-before)
	uassert.Equal(t, int64(100_000), feesCollected)
	uassert.Equal(t, 1, statsOf(bob).Wins)
	uassert.Equal(t, 1, statsOf(alice).Games)
}

func TestCommitmentRejects(cur realm, t *testing.T) {
	reset()
	good := commit()
	for _, bad := range []string{"", good[:63], good + "0", "G" + good[1:], "A" + good[1:]} {
		testing.SetRealm(testing.NewUserRealm(alice))
		pay(stake)
		uassert.AbortsContains(t, cur, "64 lowercase hex", func() { Offer(cross(cur), "", 10, bad) })
	}
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	Offer(cross(cur), "", 10, good)
	testing.SetRealm(testing.NewUserRealm(carol))
	pay(stake)
	Offer(cross(cur), "", 10, good) // the same commitment may be offered again
}

func TestPaymentsRequireUserCall(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/demo/somerealm"))
	pay(stake)
	uassert.AbortsContains(t, cur, "only user-call", func() { Offer(cross(cur), "", 10, commit()) })
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	id := Offer(cross(cur), "", 10, commit())
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/demo/somerealm"))
	pay(stake)
	uassert.AbortsContains(t, cur, "only user-call", func() { Accept(cross(cur), id) })
}

func TestNonPayableRejectsCoins(cur realm, t *testing.T) {
	reset()
	g, p := accepted(cur)
	calls := map[string]func(){
		"Reveal":            func() { Reveal(cross(cur), g.ID, p) },
		"Play":              func() { Play(cross(cur), g.ID, 1) },
		"ClaimTimeout":      func() { ClaimTimeout(cross(cur), g.ID) },
		"Resign":            func() { Resign(cross(cur), g.ID) },
		"Cancel":            func() { Cancel(cross(cur), g.ID) },
		"SetFee":            func() { SetFee(cross(cur), 0) },
		"WithdrawFees":      func() { WithdrawFees(cross(cur), admin) },
		"TransferOwnership": func() { TransferOwnership(cross(cur), carol) },
	}
	for name, call := range calls {
		testing.SetRealm(testing.NewUserRealm(admin))
		pay(1)
		uassert.AbortsContains(t, cur, "does not accept coins", call, name)
	}
}

gnomod.toml

module = "gno.land/r/nym-mikecito001/connect4_v2"
gno = "0.9"

[addpkg]
  creator = "g1cvr48r7l7lkmvp77cr6zg2zhu26jgfwr0y8pew"
  height = 70138
  max_deposit = "100000000ugnot"

json.gno

package connect4_v2

import (
	"strconv"
	"strings"
	"time"
)

// GameJSON returns {"now":<unix>,"game":<game>|null}. It is a read-only
// accessor for clients querying over vm/qeval; now is the block time.
func GameJSON(id int) string {
	var b strings.Builder
	writeNow(&b)
	b.WriteString(`,"game":`)
	if g := get(id); g != nil {
		writeGame(&b, g)
	} else {
		b.WriteString("null")
	}
	b.WriteString("}")
	return b.String()
}

// ActiveJSON returns {"now":<unix>,"games":[...]}: Open and Playing games in
// id order, skipping offset and returning at most limit (clamped to 1-100).
func ActiveJSON(offset, limit int) string {
	if offset < 0 {
		offset = 0
	}
	if limit < 1 {
		limit = 1
	}
	if limit > 100 {
		limit = 100
	}
	var b strings.Builder
	writeNow(&b)
	b.WriteString(`,"games":[`)
	n := 0
	active.IterateByOffset(offset, limit, func(_ string, v any) bool {
		if n > 0 {
			b.WriteString(",")
		}
		writeGame(&b, v.(*Game))
		n++
		return false
	})
	b.WriteString("]}")
	return b.String()
}

func writeNow(b *strings.Builder) {
	b.WriteString(`{"now":`)
	b.WriteString(strconv.FormatInt(time.Now().Unix(), 10))
}

// writeGame emits one game. Every stored string is validated on write
// (addresses by IsValid, the commitment as hex), so Quote is defence in depth.
func writeGame(b *strings.Builder, g *Game) {
	turnPlayer := ""
	deadline := int64(0)
	if g.Status == Playing {
		deadline = g.deadline().Unix()
		if g.Turn != 0 {
			turnPlayer = g.player(g.Turn).String()
		}
	}
	b.WriteString(`{"id":`)
	b.WriteString(strconv.Itoa(g.ID))
	writeStr(b, "creator", g.Creator.String())
	writeStr(b, "opponent", g.Opponent.String())
	writeStr(b, "acceptor", g.Acceptor.String())
	writeNum(b, "stake", g.Stake)
	writeNum(b, "fee", g.Fee)
	writeNum(b, "expiresAt", g.ExpiresAt.Unix())
	writeStr(b, "commitment", g.Commitment)
	b.WriteString(`,"board":"`)
	for c := 0; c < cols; c++ {
		for r := 0; r < rows; r++ {
			b.WriteByte('0' + g.Board[c][r])
		}
	}
	b.WriteString(`"`)
	writeNum(b, "turn", int64(g.Turn))
	writeStr(b, "turnPlayer", turnPlayer)
	writeNum(b, "moves", int64(g.Moves))
	writeNum(b, "lastCol", int64(g.LastCol))
	writeNum(b, "lastRow", int64(g.LastRow))
	writeNum(b, "deadline", deadline)
	writeStr(b, "status", g.Status.String())
	writeStr(b, "winner", g.Winner.String())
	b.WriteString("}")
}

// writeStr and writeNum append `,"k":v`; the caller writes the first field.
func writeStr(b *strings.Builder, k, v string) {
	b.WriteString(`,"`)
	b.WriteString(k)
	b.WriteString(`":`)
	b.WriteString(strconv.Quote(v))
}

func writeNum(b *strings.Builder, k string, v int64) {
	b.WriteString(`,"`)
	b.WriteString(k)
	b.WriteString(`":`)
	b.WriteString(strconv.FormatInt(v, 10))
}

json_test.gno

package connect4_v2

import (
	"strconv"
	"strings"
	"testing"

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

func TestGameJSONUnknown(t *testing.T) {
	reset()
	uassert.True(t, strings.HasSuffix(GameJSON(42), `,"game":null}`))
	uassert.True(t, strings.HasPrefix(GameJSON(42), `{"now":`))
}

func TestGameJSONOpenOffer(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	id := Offer(cross(cur), bob, 10, commit())
	s := GameJSON(id)
	uassert.True(t, strings.Contains(s, `"id":1,`))
	uassert.True(t, strings.Contains(s, `"creator":"`+alice.String()+`"`))
	uassert.True(t, strings.Contains(s, `"opponent":"`+bob.String()+`"`))
	uassert.True(t, strings.Contains(s, `"acceptor":""`))
	uassert.True(t, strings.Contains(s, `"stake":10000000,`))
	uassert.True(t, strings.Contains(s, `"fee":100000,`))
	uassert.True(t, strings.Contains(s, `"status":"open"`))
	uassert.True(t, strings.Contains(s, `"turn":0,`))
	uassert.True(t, strings.Contains(s, `"turnPlayer":""`))
	uassert.True(t, strings.Contains(s, `"deadline":0,`))
	uassert.True(t, strings.Contains(s, `"board":"`+strings.Repeat("0", 42)+`"`))
}

func TestGameJSONMidPlayAndWon(cur realm, t *testing.T) {
	reset()
	g := started(cur)
	first := g.player(g.Turn)
	move(cur, g, 3) // first mover, column 3 -> c=2, r=0
	s := GameJSON(g.ID)
	uassert.True(t, strings.Contains(s, `"status":"playing"`))
	uassert.True(t, strings.Contains(s, `"moves":1,`))
	uassert.True(t, strings.Contains(s, `"lastCol":2,"lastRow":0,`))
	uassert.True(t, strings.Contains(s, `"turnPlayer":"`+g.player(g.Turn).String()+`"`))
	uassert.True(t, strings.Contains(s, `"deadline":`+strconv.FormatInt(g.deadline().Unix(), 10)+`,`))
	want := strings.Repeat("0", 12) + string(rune('0'+int(3-g.Turn))) + strings.Repeat("0", 29)
	uassert.True(t, strings.Contains(s, `"board":"`+want+`"`))
	// Second mover plays 2,2,2,4; first mover stacks column 1 four times.
	move(cur, g, 2)
	move(cur, g, 1)
	move(cur, g, 2)
	move(cur, g, 1)
	move(cur, g, 2)
	move(cur, g, 1)
	move(cur, g, 4)
	move(cur, g, 1) // first mover: column 1 rows 0-3 -> win
	s = GameJSON(g.ID)
	uassert.True(t, strings.Contains(s, `"status":"won"`))
	uassert.True(t, strings.Contains(s, `"winner":"`+first.String()+`"`))
	uassert.True(t, strings.Contains(s, `"turnPlayer":""`))
}

func TestActiveJSON(cur realm, t *testing.T) {
	reset()
	for i := 0; i < 3; i++ {
		testing.SetRealm(testing.NewUserRealm(alice))
		pay(stake)
		Offer(cross(cur), "", 10, commit())
	}
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	Cancel(cross(cur), 2)
	s := ActiveJSON(0, 10)
	uassert.True(t, strings.Contains(s, `"id":1,`))
	uassert.False(t, strings.Contains(s, `"id":2,`))
	uassert.True(t, strings.Contains(s, `"id":3,`))
	uassert.Equal(t, 1, strings.Count(ActiveJSON(1, 10), `"id":`))
	uassert.Equal(t, 1, strings.Count(ActiveJSON(-5, 1), `"id":`)) // offset clamps to 0, limit 1
	uassert.Equal(t, 1, strings.Count(ActiveJSON(0, 0), `"id":`))  // limit clamps to 1
	uassert.Equal(t, 2, strings.Count(ActiveJSON(0, 1000), `"id":`))
	uassert.True(t, strings.HasSuffix(ActiveJSON(50, 10), `"games":[]}`))
}

render.gno

package connect4_v2

import (
	"chain/runtime"
	"chain/runtime/unsafe"
	"net/url"
	"strconv"
	"strings"
	"time"

	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/svg/v0"
)

// Board colours. gnoweb only embeds SVG as data-URI images, so each column is
// its own image, wrapped in its Play link while the game is being played.
const (
	red            = "#e53935"
	yellow         = "#fdd835"
	hole           = "#ffffff"
	boardBlue      = "#1565c0"
	lastMoveStroke = "#212121"
	winStroke      = "#00e676"
	cellPx         = 48
	headerPx       = 20
)

var pieceColor = [...]string{hole, red, yellow}
var pieceName = [...]string{"empty", "red", "yellow"}

// Render serves "" (lobby and leaderboards), "new" (offer form) and
// "game/<id>" (one game with every action its state allows).
// Everything written comes from realm state or from query values that have
// been validated and re-formatted; raw path input is never echoed.
func Render(path string) string {
	p, query, _ := strings.Cut(path, "?")
	switch {
	case p == "":
		return renderLobby()
	case p == "new":
		return renderNew(query)
	}
	if s, ok := strings.CutPrefix(p, "game/"); ok {
		if id, err := strconv.Atoi(s); err == nil {
			if g := get(id); g != nil {
				return renderGame(g)
			}
		}
	}
	return "# Not found\n"
}

// pageURL links to one of this realm's Render pages. The realm path is read
// at runtime, like txlink does, so links work wherever the realm is deployed.
func pageURL(page string) string {
	base := strings.TrimPrefix(unsafe.CurrentRealm().PkgPath(), runtime.ChainDomain())
	if page == "" {
		return base
	}
	return base + ":" + page
}

func gameLink(base string, id int) string {
	return "[#" + strconv.Itoa(id) + "](" + base + ":game/" + strconv.Itoa(id) + ")"
}

func renderLobby() string {
	now := time.Now()
	base := pageURL("")
	var open, live strings.Builder
	active.Iterate("", "", func(_ string, v any) bool {
		g := v.(*Game)
		switch {
		case g.Status == Open && now.Before(g.ExpiresAt):
			open.WriteString("| " + gameLink(base, g.ID) + " | " + gnot(g.Stake) + " | " + g.Creator.String() + " | " + openTo(g) +
				" | " + remaining(g.ExpiresAt.Sub(now)) + " | [Accept](" + acceptURL(g) + ") |\n")
		case g.Status == Playing:
			turn := g.player(g.Turn).String()
			if g.Turn == 0 {
				turn = g.Creator.String() + " (reveal)"
			}
			live.WriteString("| " + gameLink(base, g.ID) + " | " + gnot(2*g.Stake) + " | " + turn + " | " + remaining(g.deadline().Sub(now)) + " |\n")
		}
		return false
	})

	var b strings.Builder
	b.WriteString("# Connect 4\n\n")
	b.WriteString("Both players stake the same amount; the winner takes the pot minus a " + gnot(fee) + " fee. " +
		"90s per move: run out and you forfeit. If the first mover never moves, both stakes are refunded.\n\n")
	b.WriteString("**[Post an offer](" + base + ":new)** · open a game below to play it\n\n")
	b.WriteString("## Open offers\n\n")
	if open.Len() == 0 {
		b.WriteString("No open offers.\n\n")
	} else {
		b.WriteString("| Game | Stake | Creator | For | Expires in | |\n|---|---|---|---|---|---|\n" + open.String() + "\n")
	}
	b.WriteString("## Live games\n\n")
	if live.Len() == 0 {
		b.WriteString("No games in progress.\n\n")
	} else {
		b.WriteString("| Game | Pot | Turn | Time left |\n|---|---|---|---|\n" + live.String() + "\n")
	}
	b.WriteString("## Most games won\n\n")
	b.WriteString(leaderboard(func(s *Stats) int64 { return int64(s.Wins) }, func(v int64) string { return strconv.FormatInt(v, 10) }))
	b.WriteString("## Most gnot won\n\n")
	b.WriteString(leaderboard(func(s *Stats) int64 { return s.GnotWon }, gnot))
	return b.String()
}

// renderNew shows the offer form and, once submitted, a single Offer link
// with the stake and every argument prefilled (gnoweb cannot edit .send).
func renderNew(query string) string {
	var b strings.Builder
	b.WriteString("# Post an offer\n\n[← Lobby](" + pageURL("") + ")\n\n")
	b.WriteString("Pick a passphrase of 4+ random words, fresh for every offer, and keep it: " +
		"once someone accepts you have 90s to reveal it, or you forfeit. " +
		"Paste only its sha256 below, never the passphrase itself:\n\n" +
		"    printf %s 'your pass phrase' | shasum -a 256\n\n")
	b.WriteString(`<gno-form path="new">
<gno-input name="stake" type="text" placeholder="Stake in GNOT, e.g. 10 (min 1)" />
<gno-input name="validFor" type="number" placeholder="Minutes the offer stays open, 1-60 (default 15)" />
<gno-input name="opponent" type="text" placeholder="Opponent address (optional, leave empty for anyone)" />
<gno-input name="commitment" type="text" placeholder="sha256 of your passphrase (64 hex chars)" />
</gno-form>

`)
	if query == "" {
		return b.String()
	}

	q, err := url.ParseQuery(query)
	if err != nil {
		return b.String() + "Could not read the form.\n"
	}
	// Parse first; the offer rules themselves live in validateOffer so this
	// page and Offer cannot drift apart.
	var errs []string
	stake, ok := parseGNOT(q.Get("stake"))
	if !ok {
		errs = append(errs, "stake must be a GNOT amount with at most 6 decimals, e.g. 10 or 2.5")
	}
	validFor := 15
	if v := q.Get("validFor"); v != "" {
		n, err := strconv.Atoi(v)
		if err != nil {
			errs = append(errs, "validFor must be a whole number of minutes")
		}
		validFor = n
	}
	opponent := address(q.Get("opponent"))
	commitment := q.Get("commitment")
	if len(errs) == 0 {
		errs = validateOffer(stake, validFor, opponent, commitment)
	}
	if len(errs) > 0 {
		b.WriteString("**Fix the following:**\n\n")
		for _, e := range errs {
			b.WriteString("- " + e + "\n")
		}
		return b.String()
	}

	b.WriteString("## Ready\n\n")
	who := "anyone"
	if opponent != "" {
		who = opponent.String()
	}
	b.WriteString("Stake " + gnot(stake) + ", open to " + who + " for " + strconv.Itoa(validFor) + " min.\n\n")
	b.WriteString("**[Post offer for " + gnot(stake) + "](" + txlink.NewLink("Offer").
		AddArgs("opponent", opponent.String(), "validFor", strconv.Itoa(validFor), "commitment", commitment).
		SetSend(strconv.FormatInt(stake, 10)+denom).URL() + ")**\n")
	return b.String()
}

func renderGame(g *Game) string {
	now := time.Now()
	var b strings.Builder
	id := strconv.Itoa(g.ID)
	b.WriteString("# Game #" + id + " — " + g.Status.String() + "\n\n[← Lobby](" + pageURL("") + ")\n\n")
	b.WriteString("🔴 " + g.Creator.String() + "  \n🟡 " + orNone(g.Acceptor) + "  \n")
	b.WriteString("Stake: " + gnot(g.Stake) + " each · fee " + gnot(g.Fee) + "\n\n")
	b.WriteString(boardView(g, now) + "\n\n")

	switch g.Status {
	case Open:
		cancel := "[Cancel offer](" + txlink.NewLink("Cancel").AddArgs("id", id).URL() + ")"
		if now.Before(g.ExpiresAt) {
			b.WriteString("Open offer for " + openTo(g) + ", expires in " + remaining(g.ExpiresAt.Sub(now)) + ".\n\n")
			b.WriteString("**[Accept for " + gnot(g.Stake) + "](" + acceptURL(g) + ")**\n\n")
			b.WriteString(cancel + " (creator)\n")
		} else {
			b.WriteString("This offer expired. Anyone can " + cancel + " to refund the creator.\n")
		}
	case Playing:
		left := g.deadline().Sub(now)
		claim := "Clock ran out: **[Claim timeout](" + txlink.NewLink("ClaimTimeout").AddArgs("id", id).URL() + ")**\n\n"
		resign := "[Resign](" + txlink.NewLink("Resign").AddArgs("id", id).URL() + ")\n"
		if g.Turn == 0 {
			b.WriteString("Waiting for the creator to reveal the passphrase.\n\n")
			if left > 0 {
				b.WriteString("Time left: " + remaining(left) + "\n\n")
				b.WriteString("**[Reveal](" + txlink.NewLink("Reveal").AddArgs("id", id, "passphrase", "").URL() + ")** (creator)\n\n")
			} else {
				b.WriteString(claim)
			}
			b.WriteString(resign)
			break
		}
		b.WriteString("Turn: " + [...]string{"", "🔴", "🟡"}[g.Turn] + " " + g.player(g.Turn).String() + "\n\n")
		if left > 0 {
			b.WriteString("Time left: " + remaining(left) + " · click a column to drop your piece\n\n")
		} else {
			b.WriteString(claim)
		}
		b.WriteString(resign)
	case Won:
		b.WriteString("Winner: " + g.Winner.String() + ", paid " + gnot(2*g.Stake-g.Fee) + ".\n")
	case Draw:
		b.WriteString("Draw: both stakes refunded.\n")
	case Void:
		b.WriteString("Void: the first mover never moved, both stakes refunded.\n")
	case Cancelled:
		b.WriteString("Cancelled: stake refunded to the creator.\n")
	}
	return b.String()
}

// boardView draws the board. While a move can be played it is 7 column
// images, each wrapped in its Play link (gnoweb lays linked images out side by
// side). Otherwise it is one image of all 7 columns, since gnoweb stacks bare
// images vertically. The last move gets a dark ring, a winning line a green one.
func boardView(g *Game, now time.Time) string {
	playable := g.Status == Playing && g.Turn != 0 && !now.After(g.deadline())
	var win [cols][rows]bool
	if g.Status == Won && g.Moves > 0 {
		for _, cell := range g.Board.winLine(g.LastCol, g.LastRow) {
			win[cell[0]][cell[1]] = true
		}
	}
	const height = headerPx + rows*cellPx
	if !playable {
		canvas := svg.NewCanvas(cols*cellPx, height).WithViewBox(0, 0, cols*cellPx, height)
		alt := "board:"
		for c := 0; c < cols; c++ {
			alt += " " + drawColumn(canvas, g, &win, c, c*cellPx) + ";"
		}
		return canvas.Render(alt)
	}
	id := strconv.Itoa(g.ID)
	var b strings.Builder
	for c := 0; c < cols; c++ {
		canvas := svg.NewCanvas(cellPx, height).WithViewBox(0, 0, cellPx, height)
		alt := drawColumn(canvas, g, &win, c, 0)
		b.WriteString("[" + canvas.Render(alt) + "](" +
			txlink.NewLink("Play").AddArgs("id", id, "column", strconv.Itoa(c+1)).URL() + ")")
	}
	return b.String()
}

// drawColumn draws column c at horizontal offset x and returns its alt text.
func drawColumn(canvas *svg.Canvas, g *Game, win *[cols][rows]bool, c, x int) string {
	bg := svg.NewRectangle(x, 0, cellPx, headerPx+rows*cellPx, boardBlue)
	bg.Attr.Class = "col"
	canvas.Append(bg, svg.NewText(x+cellPx/2-4, 15, strconv.Itoa(c+1), hole))
	alt := "column " + strconv.Itoa(c+1) + ":"
	for r := 0; r < rows; r++ {
		disc := svg.NewCircle(x+cellPx/2, headerPx+(rows-1-r)*cellPx+cellPx/2, cellPx/2-5, pieceColor[g.Board[c][r]])
		switch {
		case win[c][r]:
			disc.Attr.Stroke, disc.Attr.StrokeWidth = winStroke, "5"
		case g.Moves > 0 && c == g.LastCol && r == g.LastRow:
			disc.Attr.Stroke, disc.Attr.StrokeWidth = lastMoveStroke, "3"
		}
		canvas.Append(disc)
		alt += " " + pieceName[g.Board[c][r]]
	}
	return alt
}

func acceptURL(g *Game) string {
	return txlink.NewLink("Accept").AddArgs("id", strconv.Itoa(g.ID)).
		SetSend(strconv.FormatInt(g.Stake, 10) + denom).URL()
}

func digits(s string) bool {
	for _, c := range s {
		if c < '0' || c > '9' {
			return false
		}
	}
	return true
}

func openTo(g *Game) string {
	if g.Opponent != "" {
		return g.Opponent.String()
	}
	return "anyone"
}

// parseGNOT parses a decimal GNOT amount ("10", "2.5") into ugnot.
func parseGNOT(s string) (int64, bool) {
	whole, frac, _ := strings.Cut(s, ".")
	if whole == "" || len(whole) > 12 || len(frac) > 6 {
		return 0, false
	}
	if !digits(whole) || !digits(frac) {
		return 0, false
	}
	w, _ := strconv.ParseInt(whole, 10, 64)
	f, _ := strconv.ParseInt(frac+strings.Repeat("0", 6-len(frac)), 10, 64)
	return w*1_000_000 + f, true
}

// leaderboard renders the top 10 players by score, skipping zero scores.
func leaderboard(score func(*Stats) int64, format func(int64) string) string {
	type row struct {
		addr  string
		score int64
	}
	var top []row // kept sorted, highest first, at most 10
	stats.Iterate("", "", func(addr string, v any) bool {
		sc := score(v.(*Stats))
		if sc == 0 {
			return false
		}
		i := len(top)
		for i > 0 && top[i-1].score < sc {
			i--
		}
		if i < 10 {
			top = append(top, row{})
			copy(top[i+1:], top[i:])
			top[i] = row{addr, sc}
			if len(top) > 10 {
				top = top[:10]
			}
		}
		return false
	})
	if len(top) == 0 {
		return "No finished games yet.\n\n"
	}
	var b strings.Builder
	b.WriteString("| # | Player | |\n|---|---|---|\n")
	for i, r := range top {
		b.WriteString("| " + strconv.Itoa(i+1) + " | " + r.addr + " | " + format(r.score) + " |\n")
	}
	b.WriteString("\n")
	return b.String()
}

// gnot formats ugnot as GNOT with up to 6 decimals.
func gnot(ugnot int64) string {
	whole := strconv.FormatInt(ugnot/1_000_000, 10)
	frac := ugnot % 1_000_000
	if frac == 0 {
		return whole + " GNOT"
	}
	f := strconv.FormatInt(frac, 10)
	f = strings.TrimRight(strings.Repeat("0", 6-len(f))+f, "0")
	return whole + "." + f + " GNOT"
}

func remaining(d time.Duration) string { return d.Truncate(time.Second).String() }

func orNone(a address) string {
	if a == "" {
		return "waiting for opponent"
	}
	return a.String()
}

render_test.gno

package connect4_v2

import (
	"encoding/base64"
	"strconv"
	"strings"
	"testing"
	"time"

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

func TestLeaderboardTopTen(t *testing.T) {
	reset()
	for i := 1; i <= 12; i++ {
		statsOf(testutils.TestAddress("p" + strconv.Itoa(i))).Wins = i
	}
	out := leaderboard(func(s *Stats) int64 { return int64(s.Wins) }, func(v int64) string { return strconv.FormatInt(v, 10) })
	uassert.True(t, strings.HasPrefix(strings.Split(out, "\n")[2], "| 1 | "+testutils.TestAddress("p12").String()+" | 12 |"))
	uassert.True(t, strings.Contains(out, "| 10 | "+testutils.TestAddress("p3").String()+" | 3 |"))
	uassert.False(t, strings.Contains(out, testutils.TestAddress("p2").String()))
}

func TestGamePageShowsActionsForEveryState(cur realm, t *testing.T) {
	reset()
	contains := func(out string, want ...string) {
		for _, w := range want {
			uassert.True(t, strings.Contains(out, w), "missing "+w+" in:\n"+out)
		}
	}

	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	id := Offer(cross(cur), "", 10, commit())
	page := "game/" + strconv.Itoa(id)
	contains(Render(page), "func=Accept", ".send=10000000ugnot", "func=Cancel", "Open offer")

	g := mustGet(id)
	g.ExpiresAt = time.Now().Add(-time.Second)
	out := Render(page)
	contains(out, "expired", "func=Cancel")
	uassert.False(t, strings.Contains(out, "func=Accept"))

	g, p := accepted(cur)
	page = "game/" + strconv.Itoa(g.ID)
	contains(Render(page), "Waiting for", "func=Reveal", "func=Resign")

	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	Reveal(cross(cur), g.ID, p)
	contains(Render(page), "func=Play", "column=7", "func=Resign", "Turn:")

	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	Resign(cross(cur), g.ID)
	contains(Render(page), "Winner", bob.String(), gnot(2*stake-fee))

	for status, want := range map[Status]string{
		Draw:      "both stakes refunded",
		Void:      "both stakes refunded",
		Cancelled: "refunded to the creator",
	} {
		g.Status = status
		contains(Render(page), want)
	}
}

func TestLobbyLinksEveryGameToItsPage(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	pay(stake)
	id := Offer(cross(cur), "", 10, commit())
	g, _ := accepted(cur)
	// Render as if deployed elsewhere: links must follow the realm's real path.
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/nym-mikecito001/connect4"))
	out := Render("")
	base := "(/r/nym-mikecito001/connect4:"
	uassert.True(t, strings.Contains(out, base+"game/"+strconv.Itoa(id)+")"), out)
	uassert.True(t, strings.Contains(out, base+"game/"+strconv.Itoa(g.ID)+")"), out)
	uassert.True(t, strings.Contains(out, base+"new)"), out)
	uassert.False(t, strings.Contains(out, "samcrew"), "links must not hardcode the realm path")
}

func TestNewOfferPage(t *testing.T) {
	reset()
	c := sha256Hex("some four random words")

	out := Render("new")
	uassert.True(t, strings.Contains(out, `<gno-form path="new">`))
	uassert.False(t, strings.Contains(out, "func=Offer"))

	out = Render("new?stake=12.5&validFor=10&opponent=" + bob.String() + "&commitment=" + c)
	for _, want := range []string{"func=Offer", ".send=12500000ugnot", "validFor=10", "opponent=" + bob.String(), "commitment=" + c, "12.5 GNOT"} {
		uassert.True(t, strings.Contains(out, want), "missing "+want+" in:\n"+out)
	}

	out = Render("new?stake=3&commitment=" + c) // validFor defaults, opponent optional
	uassert.True(t, strings.Contains(out, ".send=3000000ugnot"))
	uassert.True(t, strings.Contains(out, "validFor=15"))

	for _, q := range []string{
		"stake=%3Cscript%3E&validFor=10&commitment=" + c, // not a number
		"stake=0.5&validFor=10&commitment=" + c,          // below minimum
		"stake=1.0000001&validFor=10&commitment=" + c,    // more than 6 decimals
		"stake=5&validFor=61&commitment=" + c,
		"stake=5&validFor=10&opponent=%3Cscript%3E&commitment=" + c,
		"stake=5&validFor=10&commitment=%3Cscript%3E",
		"stake=5&validFor=10",
	} {
		out := Render("new?" + q)
		uassert.False(t, strings.Contains(out, "func=Offer"), q)
		uassert.True(t, strings.Contains(out, "Fix the following"), q)
		uassert.False(t, strings.Contains(out, "<script>"), "form input echoed: "+q)
	}
}

// svgs returns the decoded SVG of every data-URI image in out, and the
// markdown that immediately wraps each image ("[" link or "" for none).
func svgs(t *testing.T, out string) (images []string, linked []bool) {
	parts := strings.Split(out, "(data:image/svg+xml;base64,")
	for i, p := range parts[1:] {
		end := strings.Index(p, ")")
		raw, err := base64.StdEncoding.DecodeString(p[:end])
		if err != nil {
			t.Fatalf("image %d is not base64: %v", i, err)
		}
		images = append(images, string(raw))
		before := parts[i]
		img := strings.LastIndex(before, "![")
		linked = append(linked, img > 0 && before[img-1] == '[')
	}
	return images, linked
}

func TestBoardIsClickableSVGColumns(cur realm, t *testing.T) {
	reset()
	g, p := accepted(cur)
	page := "game/" + strconv.Itoa(g.ID)

	// Reveal phase: the board is one image holding all 7 columns, not a link.
	out := Render(page)
	images, linked := svgs(t, out)
	uassert.Equal(t, 1, len(images))
	uassert.Equal(t, 7, strings.Count(images[0], `class="col"`))
	uassert.False(t, linked[0], "no clickable column before the reveal")
	uassert.True(t, strings.Contains(out, "![board: column 1:"), "alt text")
	uassert.False(t, strings.Contains(out, "func=Play"))

	testing.SetRealm(testing.NewUserRealm(alice))
	pay(0)
	Reveal(cross(cur), g.ID, p)
	first := g.Turn
	move(cur, g, 3) // first mover drops in column 3

	out = Render(page)
	for c := 1; c <= 7; c++ {
		uassert.True(t, strings.Contains(out, "](/r/samcrew/connect4$help&func=Play&column="+strconv.Itoa(c)+"&id=") ||
			strings.Contains(out, "$help&func=Play&column="+strconv.Itoa(c)+"&id="), "column link "+strconv.Itoa(c))
	}
	images, linked = svgs(t, out)
	boardImgs := 0
	for i, img := range images {
		if strings.Contains(img, `class="col"`) {
			boardImgs++
			uassert.True(t, linked[i], "board column must be a link while playing")
		}
	}
	uassert.Equal(t, 7, boardImgs)
	col3 := images[boardIndex(images, 3)]
	uassert.True(t, strings.Contains(col3, `fill="`+[...]string{"", red, yellow}[first]+`"`), col3)
	uassert.True(t, strings.Contains(col3, `stroke="`+lastMoveStroke+`"`), "last move ring")
	uassert.True(t, strings.Contains(out, "![column 3: "+[...]string{"", "red", "yellow"}[first]), "alt text")

	// Win with four stacked in column 1: the four cells get the win ring.
	for _, c := range []int{1, 2, 1, 2, 1, 2} {
		move(cur, g, c)
	}
	move(cur, g, 1)
	uassert.Equal(t, "won", g.Status.String())
	out = Render(page)
	images, _ = svgs(t, out)
	uassert.Equal(t, 1, len(images))
	uassert.Equal(t, 4, strings.Count(images[0], `stroke="`+winStroke+`"`), images[0])
	uassert.False(t, strings.Contains(out, "func=Play"))
}

// boardIndex returns the index in images of board column c (1-based).
func boardIndex(images []string, c int) int {
	n := 0
	for i, img := range images {
		if strings.Contains(img, `class="col"`) {
			n++
			if n == c {
				return i
			}
		}
	}
	return -1
}