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

exchange_book.gno

package game32

// ── P2P exchange: escrowed limit-order book (any coin pair) ──────────────────
//
// A maker escrows `give` and asks for `want` at their own price; takers fill
// at the maker's price (fully or partly). Cancel or expiry refunds the
// remaining escrow; the 2-grin posting fee is not refunded. No price bands.
//
// Storage (≈ 200 bytes per open order): no per-order tree node (one avl
// insert costs ~2.1 KB of storage deposit). Each maker has ONE compact string
// holding their ≤ 20 open orders, and each book side (want>give) is ONE
// fixed-width string of sorted 76-byte entries (priceKey24 + id12 + maker40),
// capped at maxSideOrders; when a side is full a new order must beat the
// worst one, which is then refunded to its maker (evicted).

import (
	"math/bits"
	"strconv"
	"strings"
	"time"

	"chain"
)

type order struct {
	id               uint64
	maker            string
	give, want       string
	remGive, remWant uint64
	expiry           int64
	pk               string // price key part of the book key
}

func padU(n uint64, w int) string {
	s := strconv.FormatUint(n, 10)
	for len(s) < w {
		s = "0" + s
	}
	return s
}

const hexDigits = "0123456789abcdef"

// priceKey = want-per-give × 1e12 as a fixed-width 24-hex-digit number
// (96 bits; amounts ≤ 1e15 keep it < 2^90). Lexicographic = numeric order,
// so ascending book keys are the cheapest asks first for takers.
func priceKey(wantAmt, giveAmt uint64) string {
	hi, lo := bits.Mul64(wantAmt, 1000000000000)
	qhi := hi / giveAmt
	qlo, _ := bits.Div64(hi%giveAmt, lo, giveAmt)
	if qhi >= 1<<32 {
		panic("price out of range")
	}
	b := make([]byte, 24)
	for i := 7; i >= 0; i-- {
		b[i] = hexDigits[qhi&15]
		qhi >>= 4
	}
	for i := 23; i >= 8; i-- {
		b[i] = hexDigits[qlo&15]
		qlo >>= 4
	}
	return string(b)
}

const (
	sideEntryLen  = 76  // priceKey(24) + id(12) + maker address(40)
	sideSortLen   = 36  // entries sort by priceKey then id (FIFO within a price)
	maxSideOrders = 256 // open orders per book side; bounds every string we rewrite
)

// maker record: id12|give|want|remGive|remWant|expiry|pk
func encodeOrder(o *order) string {
	return padU(o.id, 12) + "|" + o.give + "|" + o.want + "|" + u(o.remGive) + "|" + u(o.remWant) + "|" +
		strconv.FormatInt(o.expiry, 10) + "|" + o.pk
}

func decodeOrder(maker, rec string) *order {
	f := strings.Split(rec, "|")
	if len(f) != 7 {
		panic("corrupt order")
	}
	id, _ := strconv.ParseUint(f[0], 10, 64)
	rg, _ := strconv.ParseUint(f[3], 10, 64)
	rw, _ := strconv.ParseUint(f[4], 10, 64)
	ex, _ := strconv.ParseInt(f[5], 10, 64)
	return &order{id: id, maker: maker, give: f[1], want: f[2], remGive: rg, remWant: rw, expiry: ex, pk: f[6]}
}

func makerRecs(maker string) []string {
	if !makerBooks.Has(maker) {
		return nil
	}
	v := makerBooks.Get(maker).(string)
	if v == "" {
		return nil
	}
	return strings.Split(v, ";")
}

func setMakerRecs(maker string, recs []string) {
	if len(recs) == 0 {
		makerBooks.Remove(maker)
		return
	}
	makerBooks.Set(maker, strings.Join(recs, ";"))
}

// loadOrderOf finds one of maker's open orders (≤ 20 records scanned).
func loadOrderOf(maker string, id uint64) *order {
	pre := padU(id, 12) + "|"
	for _, r := range makerRecs(maker) {
		if strings.HasPrefix(r, pre) {
			return decodeOrder(maker, r)
		}
	}
	return nil
}

func saveOrder(o *order) {
	recs := makerRecs(o.maker)
	pre := padU(o.id, 12) + "|"
	for i, r := range recs {
		if strings.HasPrefix(r, pre) {
			recs[i] = encodeOrder(o)
			setMakerRecs(o.maker, recs)
			return
		}
	}
	panic("invariant: order not found")
}

func sideKey(want, give string) string { return want + ">" + give }

func sideEntry(o *order) string { return o.pk + padU(o.id, 12) + o.maker }

func sideStr(k string) string {
	if !sides.Has(k) {
		return ""
	}
	return sides.Get(k).(string)
}

// sideSearch returns the index of the first entry whose sort key is ≥ key.
func sideSearch(s, key string) int {
	lo, hi := 0, len(s)/sideEntryLen
	for lo < hi {
		mid := (lo + hi) / 2
		if s[mid*sideEntryLen:mid*sideEntryLen+sideSortLen] < key {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	return lo
}

func sideInsert(o *order) {
	k := sideKey(o.want, o.give)
	s := sideStr(k)
	e := sideEntry(o)
	i := sideSearch(s, e[:sideSortLen]) * sideEntryLen
	sides.Set(k, s[:i]+e+s[i:])
}

func sideRemove(o *order) {
	k := sideKey(o.want, o.give)
	s := sideStr(k)
	e := sideEntry(o)
	i := sideSearch(s, e[:sideSortLen]) * sideEntryLen
	if i+sideEntryLen > len(s) || s[i:i+sideEntryLen] != e {
		panic("invariant: book entry missing")
	}
	s = s[:i] + s[i+sideEntryLen:]
	if s == "" {
		sides.Remove(k)
	} else {
		sides.Set(k, s)
	}
}

// iterSide walks a taker's side (pays `pay`, gets `get`) best price first.
func iterSide(pay, get string, fn func(maker string, id uint64) bool) {
	s := sideStr(sideKey(pay, get))
	for i := 0; i+sideEntryLen <= len(s); i += sideEntryLen {
		e := s[i : i+sideEntryLen]
		id, _ := strconv.ParseUint(e[24:36], 10, 64)
		if fn(e[36:], id) {
			return
		}
	}
}

func sideCount(pay, get string) int { return len(sideStr(sideKey(pay, get))) / sideEntryLen }

// grinValueMilli = amt × reference value (milli-grin), saturating at 2^64-1.
func grinValueMilli(coin string, amt uint64) uint64 {
	hi, lo := bits.Mul64(amt, prefMilli[requireCoin(coin)])
	if hi != 0 {
		return ^uint64(0)
	}
	return lo
}

func openOrderCount(maker string) uint64 { return uint64(len(makerRecs(maker))) }

// PlaceOrder escrows giveAmt of `give` and lists it for wantAmt of `want`
// (any pair). No upfront posting fee — the 0.90% maker fee is deducted
// from the maker's proceeds at fill time. Returns the order id.
// expirySecs 0 = 72 h; max 7 days.
func PlaceOrder(cur realm, give string, giveAmt uint64, want string, wantAmt uint64, expirySecs int64) uint64 {
	caller := exchangeCaller(cur)
	requireMarketOpen(caller)
	requireCoin(give)
	requireCoin(want)
	if give == want {
		panic("give and want must differ")
	}
	requireAmount("giveAmt", giveAmt)
	requireAmount("wantAmt", wantAmt)
	if grinValueMilli(give, giveAmt) < minOrderGrinX1k {
		panic("order too small: minimum is 50 grin of value")
	}
	if expirySecs == 0 {
		expirySecs = defaultExpiry
	}
	if expirySecs < 60 || expirySecs > maxExpiry {
		panic("expiry must be between 60 s and 7 days")
	}
	if openOrderCount(caller) >= maxOpenOrders {
		panic("max 20 open orders")
	}
	if len(caller) != 40 {
		panic("invalid maker address")
	}
	pk := priceKey(wantAmt, giveAmt)
	nextId := addChk(nextOrderId, 1)
	// A full side only takes an order that beats its worst one (which is then
	// refunded to its maker): spam can't lock the book with absurd prices.
	var evict *order
	if sideCount(want, give) >= maxSideOrders {
		s := sideStr(sideKey(want, give))
		w := s[len(s)-sideEntryLen:]
		if pk+padU(nextId, 12) >= w[:sideSortLen] {
			panic("book side full: price must beat the worst open order")
		}
		wid, _ := strconv.ParseUint(w[24:36], 10, 64)
		evict = loadOrderOf(w[36:], wid)
		if evict == nil {
			panic("invariant: book entry without order")
		}
	}
	requireBalance(caller, give, giveAmt)
	// ── all checks passed; writes start here ──
	debitBal(caller, give, giveAmt) // escrow

	if evict != nil {
		closeOrder(evict, "evicted")
	}
	nextOrderId = nextId
	o := &order{id: nextId, maker: caller, give: give, want: want, remGive: giveAmt, remWant: wantAmt,
		expiry: time.Now().Unix() + expirySecs, pk: pk}
	setMakerRecs(caller, append(makerRecs(caller), encodeOrder(o)))
	sideInsert(o)
	openOrderTotal = addChk(openOrderTotal, 1)
	chain.Emit("OrderPlaced", "id", u(o.id), "maker", caller, "give", give, "giveAmt", u(giveAmt),
		"want", want, "wantAmt", u(wantAmt), "expiry", strconv.FormatInt(o.expiry, 10))
	return o.id
}

// closeOrder refunds the remaining escrow to the MAKER (never anyone else)
// and deletes the order. Every close path goes through here.
func closeOrder(o *order, reason string) {
	refund := o.remGive
	if refund > 0 {
		creditBal(o.maker, o.give, refund)
		o.remGive = 0
	}
	sideRemove(o)
	recs := makerRecs(o.maker)
	pre := padU(o.id, 12) + "|"
	for i, r := range recs {
		if strings.HasPrefix(r, pre) {
			recs = append(recs[:i], recs[i+1:]...)
			break
		}
	}
	setMakerRecs(o.maker, recs)
	openOrderTotal = subChk(openOrderTotal, 1)
	chain.Emit("OrderClosed", "id", u(o.id), "maker", o.maker, "reason", reason, "refund", u(refund))
}

// CancelOrder: the maker gets the remaining escrow back. Works while paused
// and for banned makers; only the maker can cancel.
func CancelOrder(cur realm, id uint64) {
	caller := exchangeCaller(cur)
	// Lookup is by the caller's own orders only: nobody can name someone
	// else's order here.
	o := loadOrderOf(caller, id)
	if o == nil {
		panic("no such open order (or not your order)")
	}
	closeOrder(o, "cancel")
}

// SweepExpiredOrders closes up to maxScanPerTx expired orders of one book
// side, refunding each maker. Anyone may call it (also while paused).
func SweepExpiredOrders(cur realm, pay string, get string) int {
	exchangeCaller(cur)
	now := time.Now().Unix()
	var expired []*order
	scanned := 0
	iterSide(pay, get, func(maker string, id uint64) bool {
		scanned++
		if scanned > maxScanPerTx {
			return true
		}
		o := loadOrderOf(maker, id)
		if o != nil && o.expiry < now {
			expired = append(expired, o)
		}
		return false
	})
	for _, o := range expired {
		closeOrder(o, "expired")
	}
	return len(expired)
}

type fillStep struct {
	o    *order
	x, g uint64 // taker pays x (+fee) of `pay`, receives g of `get`
}

// planFills walks the book for a taker (read-only). budget is the most the
// taker will spend INCLUDING the taker fee. Own orders are skipped (no
// self-match); expired orders are returned for closing.
func planFills(caller, pay, get string, budget uint64, maxFills int, now int64) ([]fillStep, []*order, uint64, uint64) {
	if maxFills <= 0 || maxFills > maxFillsPerTx {
		maxFills = maxFillsPerTx
	}
	var steps []fillStep
	var expired []*order
	remaining := budget
	spent, got := uint64(0), uint64(0)
	scanned := 0
	iterSide(pay, get, func(maker string, id uint64) bool {
		scanned++
		if scanned > maxScanPerTx || len(steps) >= maxFills || remaining == 0 {
			return true
		}
		o := loadOrderOf(maker, id)
		if o == nil {
			return false
		}
		if o.expiry < now {
			expired = append(expired, o)
			return false
		}
		if o.maker == caller {
			return false // no self-match: skip, never touch the taker's own order
		}
		// largest x with x + ceil(x × takerFee) ≤ remaining
		x := mulDiv(remaining, 10000, 10000+takerFeeBps)
		for i := 0; i < 4 && x > 0 && addChk(x, mulDivUp(x, takerFeeBps, 10000)) > remaining; i++ {
			x--
		}
		if x > o.remWant {
			x = o.remWant
		}
		if x == 0 {
			return true
		}
		g := o.remGive
		if x < o.remWant {
			g = mulDiv(x, o.remGive, o.remWant) // floor: the maker never sells below their price
		}
		if g == 0 {
			return true
		}
		cost := addChk(x, mulDivUp(x, takerFeeBps, 10000))
		steps = append(steps, fillStep{o: o, x: x, g: g})
		remaining = subChk(remaining, cost)
		spent = addChk(spent, cost)
		got = addChk(got, g)
		return false
	})
	return steps, expired, spent, got
}

// executeFills applies a plan: the taker pays each maker x (plus taker fee),
// receives g from escrow. The maker receives x minus the 0.90% maker fee
// (deducted from proceeds, not from escrow). Returns total received by taker.
func executeFills(caller, pay string, steps []fillStep) uint64 {
	got := uint64(0)
	for _, st := range steps {
		o := st.o
		takerFee := mulDivUp(st.x, takerFeeBps, 10000)
		makerFee := mulDivUp(st.x, makerFeeBps, 10000)
		// Taker pays x + takerFee; maker receives x - makerFee
		debitBal(caller, pay, addChk(st.x, takerFee))
		accrueProtocolFee(pay, addChk(takerFee, makerFee))
		creditBal(o.maker, pay, subChk(st.x, makerFee))
		o.remWant = subChk(o.remWant, st.x)
		o.remGive = subChk(o.remGive, st.g)
		got = addChk(got, st.g)
		chain.Emit("OrderFilled", "id", u(o.id), "maker", o.maker, "taker", caller,
			"paid", u(st.x), "takerFee", u(takerFee), "makerFee", u(makerFee), "got", u(st.g))
		if o.remWant == 0 || o.remGive == 0 {
			closeOrder(o, "filled")
		} else if grinValueMilli(o.give, o.remGive) < minOrderGrinX1k {
			closeOrder(o, "dust")
		} else {
			saveOrder(o)
		}
	}
	return got
}

// FillOrders: spend at most payAmt of `pay` (taker fee included) on the
// best-priced orders that give `get`; receive at least minGet or revert.
// ≤ 10 fills and ≤ 20 scanned entries per call.
func FillOrders(cur realm, pay string, get string, payAmt uint64, minGet uint64, maxFills int, deadline int64) uint64 {
	caller := exchangeCaller(cur)
	requireMarketOpen(caller)
	requireDeadline(deadline)
	requireCoin(pay)
	requireCoin(get)
	requireAmount("payAmt", payAmt)
	steps, expired, spent, planned := planFills(caller, pay, get, payAmt, maxFills, time.Now().Unix())
	if planned == 0 || planned < minGet {
		panic("slippage: received below minimum")
	}
	requireBalance(caller, pay, spent)
	// ── all checks passed; writes start here ──
	for _, o := range expired {
		closeOrder(o, "expired")
	}
	got := executeFills(caller, pay, steps)
	if got != planned {
		panic("invariant: fill plan mismatch")
	}
	creditBal(caller, get, got)
	return got
}

// ── views ────────────────────────────────────────────────────────────────────

func orderJSON(o *order) string {
	return `{"id":"` + u(o.id) + `","maker":"` + o.maker + `","give":` + jsonStr(o.give) + `,"want":` + jsonStr(o.want) +
		`,"remGive":"` + u(o.remGive) + `","remWant":"` + u(o.remWant) + `","expiry":` + strconv.FormatInt(o.expiry, 10) + `}`
}

// Order shows one open order of `maker` (lookups are per maker by design).
func Order(maker string, id uint64) string {
	o := loadOrderOf(maker, id)
	if o == nil {
		return `{"id":"` + u(id) + `","open":false}`
	}
	return orderJSON(o)
}

// OrdersOf lists an address's open orders (≤ 20 by construction).
func OrdersOf(addr string) string {
	out := "["
	for i, r := range makerRecs(addr) {
		if i > 0 {
			out += ","
		}
		out += orderJSON(decodeOrder(addr, r))
	}
	return out + "]"
}

// BookDepth lists asks for a taker who pays `pay` and gets `get`, best price
// first (≤ 50 rows; offset < maxSideOrders).
func BookDepth(pay string, get string, limit int, offset int) string {
	if limit <= 0 || limit > maxViewLimit {
		limit = maxViewLimit
	}
	if offset < 0 || offset >= maxSideOrders {
		offset = 0
	}
	out := "["
	i, n := 0, 0
	iterSide(pay, get, func(maker string, id uint64) bool {
		if i < offset {
			i++
			return false
		}
		if o := loadOrderOf(maker, id); o != nil {
			if n > 0 {
				out += ","
			}
			out += orderJSON(o)
			n++
		}
		return n >= limit
	})
	return out + "]"
}

// QuoteFill previews FillOrders for a budget (fee included): {"spent","got"}.
func QuoteFill(caller string, pay string, get string, payAmt uint64, maxFills int) string {
	if payAmt == 0 || payAmt > maxAmount {
		return `{"spent":"0","got":"0","fills":0}`
	}
	steps, _, spent, got := planFills(caller, pay, get, payAmt, maxFills, time.Now().Unix())
	return `{"spent":"` + u(spent) + `","got":"` + u(got) + `","fills":` + strconv.Itoa(len(steps)) + `}`
}

exchange_core.gno

package game32

// ── P2P exchange: core (docs/P2P_EXCHANGE_PLAN.md, docs/EXCHANGE_SECURITY_REVIEW.md)
//
// Open economy (Simion, 2026-10-11): no price-impact cap, no price bands, no
// reference-price checks on deposits. Every value-moving call takes the
// trader's own protection instead: a minimum output (minOut / minShares /
// minGet) and a deadline.
//
// Security rules this file enforces for the whole exchange:
//   - The exchange only moves coins that already exist in `balances`
//     (debitBal → reserves/escrow → creditBal). It never mints.
//   - The admin has NO path to pool reserves, LP positions, escrowed orders,
//     accrued casino fees or player balances. Admin powers are listed in
//     docs/EXCHANGE_SECURITY_REVIEW.md §2.
//   - Pause stops only NEW swaps / orders / deposits. Exits — RemoveLiquidity,
//     CancelOrder, SweepExpiredOrders, WithdrawProtocolFees — always work,
//     also while paused and for banned addresses.
//   - All amounts are uint64; every add/mul is checked (panics, never wraps);
//     products use 128-bit intermediates; rounding favors the pool / maker.
//   - No exchange path calls another realm or sends coins: no reentrancy.
//   - Loops are bounded by constants (≤ maxFillsPerTx fills, ≤ maxScanPerTx
//     scanned entries, ≤ maxViewLimit view rows, ≤ maxOpenOrders per maker).
//   - Block time is used only for deadlines, order expiry and the LP warm-up.

import (
	"math/bits"
	"strconv"
	"time"

	"chain"

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

const (
	hubCoin = "grin"

	// Pools: 0.50% of the input; 0.35% stays in the pool (LPs), 0.15% is the
	// protocol fee, split 50/50 between the admin and the casino pool.
	poolFeeBps  = uint64(50)
	protoFeeBps = uint64(15)

	minLiquidity     = uint64(1000) // first-deposit shares burned forever
	minOpenDepthGrin = uint64(2000) // a pool takes swaps only once rGrin ≥ this
	warmupSecs       = int64(600)   // LP fee warm-up (principal always instant)
	rootKScale       = uint64(1000000000)

	// Order book: takers 0.50% of what they pay; makers 0.90% of what they
	// receive (deducted from the maker's proceeds at fill time, never upfront).
	// No flat posting fee — any amount meeting the size floor can be listed.
	takerFeeBps     = uint64(50)
	makerFeeBps     = uint64(90)
	minOrderGrinX1k = uint64(50000) // 50 grin of value (reference table) — size floor only
	maxOpenOrders   = uint64(20)
	defaultExpiry   = int64(72 * 3600)
	maxExpiry       = int64(7 * 24 * 3600)
	maxFillsPerTx   = 10
	maxScanPerTx    = 20
	maxViewLimit    = 50

	// Upper bound for any single amount argument. Keeps every intermediate far
	// from uint64 limits (balances are uint64 too) and rejects absurd inputs.
	maxAmount = uint64(1000000000000000) // 1e15

)

// Reference value per rarity in milli-grin (RARITY_VALUE ×1000). Used ONLY
// for the 50-grin minimum order size — never for prices.
var prefMilli = [7]uint64{1000, 3200, 11000, 40000, 160000, 720000, 3600000}

var (
	pools       avl.Tree // coin → *pool
	lpPositions avl.Tree // coin+":"+addr → *lpPos
	adminFees   avl.Tree // coin → admin's accrued protocol fees (pull)
	casinoPool  avl.Tree // coin → casino pool balance (fees in, capped jackpots out)
	makerBooks     avl.Tree // maker → ";"-joined compact order records (≤ maxOpenOrders)
	sides          avl.Tree // want+">"+give → sorted fixed-width entries (≤ maxSideOrders)
	openOrderTotal uint64
	nextOrderId    uint64
	exPaused    bool

	// Lifetime accounting (Render + audits).
	adminFeesWithdrawn avl.Tree // coin → lifetime withdrawn by the admin
	adminGnotWithdrawn int64    // ugnot withdrawn by WithdrawFunds (≤ passRevenueUgnot)
)

// ── checked math ─────────────────────────────────────────────────────────────

func addChk(a, b uint64) uint64 {
	s, carry := bits.Add64(a, b, 0)
	if carry != 0 {
		panic("math overflow")
	}
	return s
}

func subChk(a, b uint64) uint64 {
	if b > a {
		panic("math underflow")
	}
	return a - b
}

// mulDiv = floor(a*b/c) with a 128-bit product; panics if c == 0 or the
// quotient does not fit in 64 bits.
func mulDiv(a, b, c uint64) uint64 {
	if c == 0 {
		panic("division by zero")
	}
	hi, lo := bits.Mul64(a, b)
	if hi >= c {
		panic("math overflow")
	}
	q, _ := bits.Div64(hi, lo, c)
	return q
}

// mulDivUp = ceil(a*b/c).
func mulDivUp(a, b, c uint64) uint64 {
	if c == 0 {
		panic("division by zero")
	}
	hi, lo := bits.Mul64(a, b)
	if hi >= c {
		panic("math overflow")
	}
	q, r := bits.Div64(hi, lo, c)
	if r > 0 {
		q = addChk(q, 1)
	}
	return q
}

// isqrt128 = floor(sqrt(a*b)) for the 128-bit product (Newton, bounded).
func isqrt128(a, b uint64) uint64 {
	hi, lo := bits.Mul64(a, b)
	if hi == 0 {
		return isqrt(lo)
	}
	// sqrt of a 128-bit number < 2^64. Start above the root and descend.
	x := ^uint64(0)
	for i := 0; i < 200; i++ {
		if hi >= x { // product/x overflows ⇒ x below the root; cannot happen when descending from max
			panic("isqrt: bad state")
		}
		q, _ := bits.Div64(hi, lo, x)
		nx := (x >> 1) + (q >> 1) + (x & q & 1)
		if nx >= x {
			return x
		}
		x = nx
	}
	panic("isqrt: no convergence")
}

func isqrt(n uint64) uint64 {
	if n < 2 {
		return n
	}
	x := n
	y := x/2 + 1
	for i := 0; i < 200 && y < x; i++ {
		x = y
		y = (x + n/x) / 2
	}
	return x
}

// mulLess reports a*b < c*d using 128-bit products.
func mulLess(a, b, c, d uint64) bool {
	h1, l1 := bits.Mul64(a, b)
	h2, l2 := bits.Mul64(c, d)
	return h1 < h2 || (h1 == h2 && l1 < l2)
}

// requireBalance checks a balance before any write, so a failing call
// changes nothing (validate-then-write).
func requireBalance(addr, coin string, amt uint64) {
	if have := balOf(addr, coin); have < amt {
		panic("insufficient " + coin + ": need " + u(amt) + " have " + u(have))
	}
}

func requireAmount(name string, v uint64) {
	if v == 0 || v > maxAmount {
		panic(name + " must be between 1 and " + strconv.FormatUint(maxAmount, 10))
	}
}

func u(n uint64) string { return strconv.FormatUint(n, 10) }

// ── gates ────────────────────────────────────────────────────────────────────

// exchangeCaller returns the caller for exchange writes. Only end users (an
// EOA MsgCall or the user's own MsgRun) may trade: other realms can't act
// through the exchange, so there is no cross-realm call surface at all.
func exchangeCaller(cur realm) string {
	prev := cur.Previous()
	if prev.PkgPath() != "" {
		panic("exchange calls must come directly from a user")
	}
	return prev.Address().String()
}

// requireMarketOpen gates NEW activity (swaps, deposits, orders, fills).
// Trading opens only after FinalizeMigration: MigrateBatch SETs balances, so
// trading before that could duplicate or lose escrowed coins.
func requireMarketOpen(caller string) {
	if !migrationFinalized {
		panic("exchange opens after FinalizeMigration")
	}
	if exPaused {
		panic("exchange paused: new trades are off; unstake and cancel still work")
	}
	if isBlacklisted(caller) {
		panic("address banned")
	}
}

func requireDeadline(deadline int64) {
	if deadline <= 0 {
		panic("deadline required (unix seconds)")
	}
	if time.Now().Unix() > deadline {
		panic("deadline passed")
	}
}

func requireCoin(coin string) int {
	r, ok := coinRarity[coin]
	if !ok {
		panic("unknown coin id: " + coin)
	}
	return r
}

// Trading is open to every account (Simion, 2026-10-11): no tool requirement
// to swap, post, fill or stake. Anti-spam comes from the 50-grin order
// minimum, the 2-grin post fee, the 0.5% taker/pool fees, the 20-open-orders
// limit per maker and the 2,000-grin minimum pool depth.

// No receive cap (Simion, 2026-10-11): every coin is freely transferable and
// tradable, whatever tools the receiver owns.

// ── protocol fees ────────────────────────────────────────────────────────────

// accrueProtocolFee splits amt of coin 50/50: the floor half to the admin's
// fee ledger, the rest to the casino pool. Both stay inside the realm.
func accrueProtocolFee(coin string, amt uint64) {
	if amt == 0 {
		return
	}
	half := amt / 2
	if half > 0 {
		setU(&adminFees, coin, addChk(getU(&adminFees, coin), half))
	}
	setU(&casinoPool, coin, addChk(getU(&casinoPool, coin), amt-half))
	casStat(coin, "", "fees", amt-half)
	chain.Emit("ProtocolFeesAccrued", "coin", coin, "admin", u(half), "casino", u(amt-half))
}

// WithdrawProtocolFees moves the admin's OWN accrued fees for `coin` into the
// admin's balance. It reads only adminFees (never reserves, escrow, the
// casino pool or anyone's balance) and works while paused.
func WithdrawProtocolFees(cur realm, coin string) uint64 {
	requireAdmin(cur)
	requireCoin(coin)
	amt := getU(&adminFees, coin)
	if amt == 0 {
		panic("no fees to withdraw for " + coin)
	}
	adminFees.Remove(coin)
	setU(&adminFeesWithdrawn, coin, addChk(getU(&adminFeesWithdrawn, coin), amt))
	to := admin.String()
	creditBal(to, coin, amt)
	chain.Emit("ProtocolFeesWithdrawn", "coin", coin, "to", to, "amount", u(amt))
	return amt
}

// ── casino pool (fee share + losing stakes in, wins out; never minted) ─────
//
// casinoPool[coin]     total pool, including the reserved part
// casinoReserved[coin] sum of potential net payouts of unsettled bets
// casinoDay[coin]      "day:snapshot:paid:received" for the current UTC day
//
// A bet is accepted only if the pool can pay it in full: its potential net
// payout (= the stake, since a win pays 2×) is reserved at placement, so a
// reveal never pays partially and the pool can't go below zero.









// ── admin controls (launch only; none touch user funds) ──────────────────────

// SetExchangePaused stops NEW swaps, deposits, orders and fills. It can't
// stop RemoveLiquidity, CancelOrder, SweepExpiredOrders or fee withdrawals.
func SetExchangePaused(cur realm, p bool) {
	requireAdmin(cur)
	exPaused = p
	chain.Emit("ExchangePaused", "paused", strconv.FormatBool(p))
}

func ExchangeStatus() string {
	return `{"open":` + strconv.FormatBool(migrationFinalized && !exPaused) +
		`,"paused":` + strconv.FormatBool(exPaused) +
		`,"finalized":` + strconv.FormatBool(migrationFinalized) +
		`,"pools":` + strconv.Itoa(pools.Size()) +
		`,"openOrders":` + strconv.FormatUint(openOrderTotal, 10) +
		`,"nextOrderId":"` + u(nextOrderId) + `"` +
		`,"poolFeeBps":` + u(poolFeeBps) + `,"protoFeeBps":` + u(protoFeeBps) +
		`,"takerFeeBps":` + u(takerFeeBps) + `,"makerFeeBps":` + u(makerFeeBps) +
		`,"postFeeGrin":0` +
		`,"minOpenDepthGrin":` + u(minOpenDepthGrin) + `,"warmupSecs":` + strconv.FormatInt(warmupSecs, 10) + `}`
}

func ProtocolFees(coin string) string {
	return `{"coin":` + jsonStr(coin) + `,"admin":"` + u(getU(&adminFees, coin)) +
		`","adminWithdrawn":"` + u(getU(&adminFeesWithdrawn, coin)) +
		`","casino":"` + u(getU(&casinoPool, coin)) + `"}`
}

exchange_pool.gno

package game32

// ── P2P exchange: COIN/GRIN constant-product pools ───────────────────────────
//
// Reserves are internal counters, never "the realm's balance": a Transfer or
// bank send to the realm address can't move them (no donation attack).
// Rounding: swap fee up, output down, minted shares down, withdrawals down —
// always in the pool's favor. k (and √k per share) never decreases on a swap.

import (
	"strconv"
	"time"

	"chain"
)

type pool struct {
	coin        string
	rCoin, rHub uint64 // reserves (coin side, grin side)
	shares      uint64 // total shares, including the burned minLiquidity
	paused      bool   // per-pool: stops new swaps/deposits only
}

type lpPos struct {
	shares    uint64
	entryRKPS uint64 // √k per share × rootKScale at (share-weighted) entry
	depositTs int64  // share-weighted deposit time (warm-up clock)
}

func getPool(coin string) *pool {
	if !pools.Has(coin) {
		panic("no pool for " + coin)
	}
	return pools.Get(coin).(*pool)
}

func rootKPerShare(p *pool) uint64 {
	if p.shares == 0 {
		return 0
	}
	return mulDiv(isqrt128(p.rCoin, p.rHub), rootKScale, p.shares)
}

// CreatePool opens an empty COIN/GRIN pool (admin, per the launch schedule).
// It holds nothing until players deposit; the admin can't deposit for anyone,
// withdraw from it or close it.
func CreatePool(cur realm, coin string) {
	requireAdmin(cur)
	if coin == hubCoin {
		panic("grin is the hub coin: pools are COIN/GRIN")
	}
	requireCoin(coin)
	if pools.Has(coin) {
		panic("pool exists")
	}
	pools.Set(coin, &pool{coin: coin})
	chain.Emit("PoolCreated", "coin", coin)
}

// OpenPool creates a new COIN/GRIN pool and immediately deposits the first
// liquidity, atomically setting the opening price. Any player who holds the
// coin and enough Grin can call this — no admin required.
//
// coinAmt and grinAmt set the price ratio; whoever calls this first for a coin
// controls the opening price, so choose amounts that reflect the coin's real
// value. 1,000 shares are permanently burned as a sandwich-resistance seed.
// Returns the number of LP shares minted for the caller.
func OpenPool(cur realm, coin string, coinAmt uint64, grinAmt uint64, minShares uint64, deadline int64) uint64 {
	caller := exchangeCaller(cur)
	requireMarketOpen(caller)
	requireDeadline(deadline)
	requireAmount("coinAmt", coinAmt)
	requireAmount("grinAmt", grinAmt)
	if coin == hubCoin {
		panic("grin is the hub coin: pools are COIN/GRIN")
	}
	requireCoin(coin)
	if pools.Has(coin) {
		panic("pool already exists: use AddLiquidity to stake")
	}
	// First-deposit size check: sqrt(coinAmt*grinAmt) must exceed minLiquidity.
	s := isqrt128(coinAmt, grinAmt)
	if s <= minLiquidity {
		panic("first deposit too small: sqrt(coinAmt x grinAmt) must exceed 1000")
	}
	minted := s - minLiquidity
	if minted < minShares {
		panic("slippage: shares below minimum")
	}
	requireBalance(caller, coin, coinAmt)
	requireBalance(caller, hubCoin, grinAmt)
	// ── all checks passed; writes start here ──
	pools.Set(coin, &pool{coin: coin})
	chain.Emit("PoolCreated", "coin", coin)
	p := getPool(coin)
	p.shares = addChk(minted, minLiquidity) // minLiquidity shares burned forever
	debitBal(caller, coin, coinAmt)
	debitBal(caller, hubCoin, grinAmt)
	p.rCoin = coinAmt
	p.rHub = grinAmt
	now := time.Now().Unix()
	rk := rootKPerShare(p)
	lpPositions.Set(coin+":"+caller, &lpPos{shares: minted, entryRKPS: rk, depositTs: now})
	chain.Emit("LiquidityAdded", "coin", coin, "who", caller,
		"coinIn", u(coinAmt), "grinIn", u(grinAmt), "shares", u(minted))
	return minted
}

// SetPoolPaused stops new swaps and deposits on one pool. Withdrawals stay open.
func SetPoolPaused(cur realm, coin string, p bool) {
	requireAdmin(cur)
	getPool(coin).paused = p
	chain.Emit("PoolPaused", "coin", coin, "paused", strconv.FormatBool(p))
}

// AddLiquidity deposits up to coinMax of `coin` and grinMax grin. The first
// deposit sets the price (open economy: any ratio) and burns minLiquidity
// shares; later deposits take the current ratio (never more than either cap).
// Reverts unless at least minShares are minted.
func AddLiquidity(cur realm, coin string, coinMax uint64, grinMax uint64, minShares uint64, deadline int64) uint64 {
	caller := exchangeCaller(cur)
	requireMarketOpen(caller)
	requireDeadline(deadline)
	requireAmount("coinMax", coinMax)
	requireAmount("grinMax", grinMax)
	p := getPool(coin)
	if p.paused {
		panic("pool paused")
	}
	var aCoin, aHub, minted uint64
	if p.shares == 0 {
		aCoin, aHub = coinMax, grinMax
		s := isqrt128(aCoin, aHub)
		if s <= minLiquidity {
			panic("first deposit too small: sqrt(coin×grin) must exceed 1000")
		}
		minted = s - minLiquidity
	} else {
		aHub = grinMax
		aCoin = mulDivUp(aHub, p.rCoin, p.rHub)
		if aCoin > coinMax {
			aCoin = coinMax
			aHub = mulDivUp(aCoin, p.rHub, p.rCoin)
		}
		s1 := mulDiv(aCoin, p.shares, p.rCoin)
		s2 := mulDiv(aHub, p.shares, p.rHub)
		minted = s1
		if s2 < minted {
			minted = s2
		}
		if minted == 0 {
			panic("deposit too small for one share")
		}
	}
	if minted < minShares {
		panic("slippage: shares below minimum")
	}
	requireBalance(caller, coin, aCoin)
	requireBalance(caller, hubCoin, aHub)
	// ── all checks passed; writes start here ──
	if p.shares == 0 {
		p.shares = addChk(minted, minLiquidity) // minLiquidity shares belong to nobody (burned)
	} else {
		p.shares = addChk(p.shares, minted)
	}
	debitBal(caller, coin, aCoin)
	debitBal(caller, hubCoin, aHub)
	p.rCoin = addChk(p.rCoin, aCoin)
	p.rHub = addChk(p.rHub, aHub)

	key := coin + ":" + caller
	now := time.Now().Unix()
	rk := rootKPerShare(p)
	if lpPositions.Has(key) {
		pos := lpPositions.Get(key).(*lpPos)
		tot := addChk(pos.shares, minted)
		pos.entryRKPS = addChk(mulDiv(pos.entryRKPS, pos.shares, tot), mulDivUp(rk, minted, tot))
		// share-weighted deposit time: a top-up restarts the warm-up in proportion.
		pos.depositTs = int64(addChk(mulDiv(uint64(pos.depositTs), pos.shares, tot), mulDivUp(uint64(now), minted, tot)))
		pos.shares = tot
	} else {
		lpPositions.Set(key, &lpPos{shares: minted, entryRKPS: rk, depositTs: now})
	}
	chain.Emit("LiquidityAdded", "coin", coin, "who", caller,
		"coinIn", u(aCoin), "grinIn", u(aHub), "shares", u(minted))
	return minted
}

// lpPayout computes what `shares` of a position withdraw right now:
// pro-rata of CURRENT reserves (floor). Within the warm-up the fee growth
// since entry (√k/share above entry) stays in the pool for the other LPs;
// principal is never cut below its entry-value share.
func lpPayout(p *pool, pos *lpPos, shares uint64, now int64) (uint64, uint64) {
	outCoin := mulDiv(shares, p.rCoin, p.shares)
	outHub := mulDiv(shares, p.rHub, p.shares)
	if now-pos.depositTs < warmupSecs {
		rk := rootKPerShare(p)
		if rk > pos.entryRKPS {
			outCoin = mulDiv(outCoin, pos.entryRKPS, rk)
			outHub = mulDiv(outHub, pos.entryRKPS, rk)
		}
	}
	return outCoin, outHub
}

// RemoveLiquidity is instant and ALWAYS available: it works while the
// exchange or the pool is paused, before or after a ban, and needs no tool.
// Nobody but the position owner can call it for that position.
func RemoveLiquidity(cur realm, coin string, shares uint64, minCoin uint64, minGrin uint64, deadline int64) (uint64, uint64) {
	caller := exchangeCaller(cur)
	requireDeadline(deadline)
	p := getPool(coin)
	key := coin + ":" + caller
	if !lpPositions.Has(key) {
		panic("no liquidity position in " + coin)
	}
	pos := lpPositions.Get(key).(*lpPos)
	if shares == 0 || shares > pos.shares {
		panic("invalid shares")
	}
	outCoin, outHub := lpPayout(p, pos, shares, time.Now().Unix())
	if outCoin < minCoin || outHub < minGrin {
		panic("slippage: output below minimum")
	}
	p.rCoin = subChk(p.rCoin, outCoin)
	p.rHub = subChk(p.rHub, outHub)
	p.shares = subChk(p.shares, shares)
	pos.shares = subChk(pos.shares, shares)
	if pos.shares == 0 {
		lpPositions.Remove(key)
	}
	creditBal(caller, coin, outCoin)
	creditBal(caller, hubCoin, outHub)
	chain.Emit("LiquidityRemoved", "coin", coin, "who", caller,
		"coinOut", u(outCoin), "grinOut", u(outHub), "shares", u(shares))
	return outCoin, outHub
}

// poolQuote returns (out, protoFee) for amountIn of the input side; no writes.
func poolQuote(p *pool, inIsHub bool, amountIn uint64) (uint64, uint64) {
	rIn, rOut := p.rCoin, p.rHub
	if inIsHub {
		rIn, rOut = p.rHub, p.rCoin
	}
	fee := mulDivUp(amountIn, poolFeeBps, 10000)
	proto := mulDiv(amountIn, protoFeeBps, 10000)
	if fee >= amountIn {
		return 0, 0
	}
	eff := amountIn - fee
	out := mulDiv(rOut, eff, addChk(rIn, eff)) // floor: pool's favor
	return out, proto
}

func poolOpenForSwaps(p *pool) bool {
	return !p.paused && p.rHub >= minOpenDepthGrin && p.rCoin > 0
}

// poolSwap executes one hop (coin↔grin) for `caller`, crediting nothing to
// the caller: it returns the output so routes can chain hops. The caller's
// input must already have been debited.
func poolSwap(p *pool, inIsHub bool, amountIn uint64) uint64 {
	if !poolOpenForSwaps(p) {
		panic("pool " + p.coin + " is not open for swaps (paused or under 2000 grin depth)")
	}
	out, proto := poolQuote(p, inIsHub, amountIn)
	if out == 0 {
		panic("swap too small")
	}
	kBefore := isqrt128(p.rCoin, p.rHub)
	inNet := subChk(amountIn, proto)
	if inIsHub {
		p.rHub = addChk(p.rHub, inNet)
		p.rCoin = subChk(p.rCoin, out)
		accrueProtocolFee(hubCoin, proto)
	} else {
		p.rCoin = addChk(p.rCoin, inNet)
		p.rHub = subChk(p.rHub, out)
		accrueProtocolFee(p.coin, proto)
	}
	if p.rCoin == 0 || p.rHub == 0 {
		panic("swap would empty the pool")
	}
	// Defense in depth: the invariant must hold after every swap.
	if isqrt128(p.rCoin, p.rHub) < kBefore {
		panic("invariant: k decreased")
	}
	return out
}

// SwapExactIn swaps amountIn of coinIn for at least minOut of coinOut through
// one pool (one side must be grin). For X→Y via grin use SwapRoute.
func SwapExactIn(cur realm, coinIn string, coinOut string, amountIn uint64, minOut uint64, deadline int64) uint64 {
	caller := exchangeCaller(cur)
	requireMarketOpen(caller)
	requireDeadline(deadline)
	requireAmount("amountIn", amountIn)
	requireCoin(coinIn)
	requireCoin(coinOut)
	var p *pool
	inIsHub := coinIn == hubCoin
	if inIsHub && coinOut != hubCoin {
		p = getPool(coinOut)
	} else if !inIsHub && coinOut == hubCoin {
		p = getPool(coinIn)
	} else {
		panic("one side must be grin (use SwapRoute for coin→coin)")
	}
	if !poolOpenForSwaps(p) {
		panic("pool " + p.coin + " is not open for swaps (paused or under 2000 grin depth)")
	}
	if q, _ := poolQuote(p, inIsHub, amountIn); q == 0 || q < minOut {
		panic("slippage: output below minimum")
	}
	requireBalance(caller, coinIn, amountIn)
	// ── all checks passed; writes start here ──
	debitBal(caller, coinIn, amountIn)
	out := poolSwap(p, inIsHub, amountIn)
	creditBal(caller, coinOut, out)
	chain.Emit("Swap", "pool", p.coin, "who", caller, "in", coinIn, "out", coinOut,
		"amountIn", u(amountIn), "amountOut", u(out))
	return out
}

// ── views ────────────────────────────────────────────────────────────────────

func poolJSON(p *pool) string {
	return `{"coin":` + jsonStr(p.coin) + `,"rCoin":"` + u(p.rCoin) + `","rGrin":"` + u(p.rHub) +
		`","shares":"` + u(p.shares) + `","paused":` + strconv.FormatBool(p.paused) +
		`,"open":` + strconv.FormatBool(poolOpenForSwaps(p)) + `}`
}

func PoolInfo(coin string) string {
	if !pools.Has(coin) {
		return `{"coin":` + jsonStr(coin) + `,"exists":false}`
	}
	return poolJSON(getPool(coin))
}

// Pools lists pools in coin order (paginated, ≤ 50 per call).
func Pools(limit int, offset int) string {
	if limit <= 0 || limit > maxViewLimit {
		limit = maxViewLimit
	}
	if offset < 0 {
		offset = 0
	}
	out := "["
	n := 0
	pools.IterateByOffset(offset, limit, func(_ string, v any) bool {
		if n > 0 {
			out += ","
		}
		out += poolJSON(v.(*pool))
		n++
		return false
	})
	return out + "]"
}

// QuoteSwap quotes a single-pool swap; "0" if the pool can't take it.
func QuoteSwap(coinIn string, coinOut string, amountIn uint64) string {
	if amountIn == 0 || amountIn > maxAmount {
		return "0"
	}
	c, inIsHub := coinIn, false
	if coinIn == hubCoin {
		c, inIsHub = coinOut, true
	} else if coinOut != hubCoin {
		return "0"
	}
	if !pools.Has(c) {
		return "0"
	}
	p := getPool(c)
	if !poolOpenForSwaps(p) {
		return "0"
	}
	out, _ := poolQuote(p, inIsHub, amountIn)
	return u(out)
}

// LpPosition shows one position and what it would withdraw right now.
func LpPosition(coin string, addr string) string {
	key := coin + ":" + addr
	if !lpPositions.Has(key) || !pools.Has(coin) {
		return `{"coin":` + jsonStr(coin) + `,"shares":"0"}`
	}
	pos := lpPositions.Get(key).(*lpPos)
	p := getPool(coin)
	now := time.Now().Unix()
	oc, oh := lpPayout(p, pos, pos.shares, now)
	warm := pos.depositTs + warmupSecs - now
	if warm < 0 {
		warm = 0
	}
	return `{"coin":` + jsonStr(coin) + `,"shares":"` + u(pos.shares) + `","poolShares":"` + u(p.shares) +
		`","coinOut":"` + u(oc) + `","grinOut":"` + u(oh) + `","warmupLeft":` + strconv.FormatInt(warm, 10) + `}`
}

// LpPositions lists an address's positions (bounded: at most one per pool,
// paginated by pool order, ≤ 50 pools scanned per call).
func LpPositions(addr string, limit int, offset int) string {
	if limit <= 0 || limit > maxViewLimit {
		limit = maxViewLimit
	}
	if offset < 0 {
		offset = 0
	}
	out := "["
	n := 0
	pools.IterateByOffset(offset, limit, func(coin string, _ any) bool {
		if lpPositions.Has(coin + ":" + addr) {
			if n > 0 {
				out += ","
			}
			out += LpPosition(coin, addr)
			n++
		}
		return false
	})
	return out + "]"
}

exchange_route.gno

package game32

// ── P2P exchange: router (book first while it beats the pool, rest via pools)

import (
	"strconv"
	"time"

	"chain"
)

// poolPathOut quotes amountIn of coinIn → coinOut through the grin pools
// (one hop if either side is grin, else coinIn→grin→coinOut). ok=false if a
// needed pool is missing or not open. Read-only.
func poolPathOut(coinIn, coinOut string, amountIn uint64) (uint64, bool) {
	if amountIn == 0 || coinIn == coinOut {
		return 0, false
	}
	if coinIn == hubCoin || coinOut == hubCoin {
		c, inIsHub := coinIn, false
		if coinIn == hubCoin {
			c, inIsHub = coinOut, true
		}
		if !pools.Has(c) {
			return 0, false
		}
		p := getPool(c)
		if !poolOpenForSwaps(p) {
			return 0, false
		}
		out, _ := poolQuote(p, inIsHub, amountIn)
		return out, out > 0
	}
	mid, ok := poolPathOut(coinIn, hubCoin, amountIn)
	if !ok {
		return 0, false
	}
	return poolPathOut(hubCoin, coinOut, mid)
}

// routePlan splits amountIn between book fills (direct pair) and the pool
// path. A book fill is taken while its rate is at least the pool path's
// average rate for the whole remainder; everything else goes to the pools.
func routePlan(caller, coinIn, coinOut string, amountIn uint64, maxFills int, now int64) ([]fillStep, []*order, uint64, uint64, uint64) {
	steps, expired, _, _ := planFills(caller, coinIn, coinOut, amountIn, maxFills, now)
	var take []fillStep
	remaining := amountIn
	bookOut := uint64(0)
	for _, st := range steps {
		cost := addChk(st.x, mulDivUp(st.x, takerFeeBps, 10000))
		if cost > remaining {
			break
		}
		if pOut, ok := poolPathOut(coinIn, coinOut, remaining); ok {
			// book rate g/cost vs pool average rate pOut/remaining (128-bit compare)
			if mulLess(st.g, remaining, pOut, cost) {
				break
			}
		}
		take = append(take, st)
		remaining = subChk(remaining, cost)
		bookOut = addChk(bookOut, st.g)
	}
	poolOut := uint64(0)
	if remaining > 0 {
		if out, ok := poolPathOut(coinIn, coinOut, remaining); ok {
			poolOut = out
		} else {
			remaining = 0 // no pool path: only the book part executes
		}
	}
	return take, expired, remaining, bookOut, poolOut
}

// SwapRoute swaps up to amountIn of coinIn for at least minOut of coinOut,
// using the order book (direct pair) while it beats the pools and the grin
// pools for the rest. Coins not needed are never debited.
func SwapRoute(cur realm, coinIn string, coinOut string, amountIn uint64, minOut uint64, maxFills int, deadline int64) uint64 {
	caller := exchangeCaller(cur)
	requireMarketOpen(caller)
	requireDeadline(deadline)
	requireAmount("amountIn", amountIn)
	requireCoin(coinIn)
	requireCoin(coinOut)
	if coinIn == coinOut {
		panic("coinIn and coinOut must differ")
	}
	take, expired, poolIn, bookOut, poolOut := routePlan(caller, coinIn, coinOut, amountIn, maxFills, time.Now().Unix())
	planned := addChk(bookOut, poolOut)
	if planned == 0 || planned < minOut {
		panic("slippage: output below minimum")
	}
	need := poolIn
	for _, st := range take {
		need = addChk(need, addChk(st.x, mulDivUp(st.x, takerFeeBps, 10000)))
	}
	requireBalance(caller, coinIn, need)
	// ── all checks passed; writes start here ──
	for _, o := range expired {
		closeOrder(o, "expired")
	}
	out := executeFills(caller, coinIn, take)
	if poolIn > 0 {
		debitBal(caller, coinIn, poolIn)
		if coinIn == hubCoin {
			out = addChk(out, poolSwap(getPool(coinOut), true, poolIn))
		} else if coinOut == hubCoin {
			out = addChk(out, poolSwap(getPool(coinIn), false, poolIn))
		} else {
			mid := poolSwap(getPool(coinIn), false, poolIn)
			out = addChk(out, poolSwap(getPool(coinOut), true, mid))
		}
	}
	if out != planned {
		panic("invariant: route plan mismatch")
	}
	creditBal(caller, coinOut, out)
	chain.Emit("SwapRouted", "who", caller, "in", coinIn, "out", coinOut, "amountIn", u(amountIn),
		"bookFills", strconv.Itoa(len(take)), "poolIn", u(poolIn), "amountOut", u(out))
	return out
}

// QuoteRoute previews SwapRoute: how much goes to the book vs the pools and
// the expected output (fees included).
func QuoteRoute(caller string, coinIn string, coinOut string, amountIn uint64, maxFills int) string {
	if amountIn == 0 || amountIn > maxAmount || coinIn == coinOut {
		return `{"out":"0"}`
	}
	if _, ok := coinRarity[coinIn]; !ok {
		return `{"out":"0"}`
	}
	if _, ok := coinRarity[coinOut]; !ok {
		return `{"out":"0"}`
	}
	take, _, poolIn, bookOut, poolOut := routePlan(caller, coinIn, coinOut, amountIn, maxFills, time.Now().Unix())
	bookIn := uint64(0)
	for _, st := range take {
		bookIn = addChk(bookIn, addChk(st.x, mulDivUp(st.x, takerFeeBps, 10000)))
	}
	return `{"bookIn":"` + u(bookIn) + `","bookOut":"` + u(bookOut) + `","bookFills":` + strconv.Itoa(len(take)) +
		`,"poolIn":"` + u(poolIn) + `","poolOut":"` + u(poolOut) + `","out":"` + u(addChk(bookOut, poolOut)) +
		`","unused":"` + u(amountIn-bookIn-poolIn) + `"}`
}

exchange_test.gno

package game32

// Exchange unit, attack and invariant tests. See docs/EXCHANGE_SECURITY_REVIEW.md
// for the threat → code → test map.
//
// gno test caveat: revive() catches a panic but does NOT roll back realm
// state. The exchange validates everything before its first write, so a
// failing call must leave state untouched — several tests assert exactly that
// (snapshot before, compare after).

import (
	"chain"
	"strconv"
	"strings"
	"testing"
	"time"
)

// ── helpers ──────────────────────────────────────────────────────────────────

// exOpen finalizes the migration and unpauses for one test; the returned
// func restores the previous global state (other test files depend on it).
func exOpen() func() {
	setup()
	wasFinal, wasPaused, wasGame := migrationFinalized, exPaused, paused
	migrationFinalized, exPaused, paused = true, false, false
	return func() { migrationFinalized, exPaused, paused = wasFinal, wasPaused, wasGame }
}


// trader: owns wood+stone (can trade, receives up to rarity 3).
func trader(name string) address {
	a := ta(name)
	ownedTools.Set(a.String(), "starter-twig,twig,wood,stone")
	return a
}

func dl() int64 { return time.Now().Unix() + 600 }

// panicMsg runs f and returns its panic message ("" if none). For internal
// (non-crossing) helpers, where revive() does not apply.
func panicMsg(f func()) (msg string) {
	defer func() {
		if r := recover(); r != nil {
			msg = errOf(r)
		}
	}()
	f()
	return ""
}

func errOf(r any) string {
	switch v := r.(type) {
	case nil:
		return ""
	case string:
		return v
	case error:
		return v.Error()
	}
	return "?"
}

// coinTotal = every unit of `coin` the realm accounts for: all balances,
// pool reserves, order escrow, admin fees and the casino pool.
func coinTotal(coin string) uint64 {
	tot := uint64(0)
	balances.Iterate("", "", func(k string, v any) bool {
		if strings.HasSuffix(k, ":"+coin) {
			n, _ := strconv.ParseUint(v.(string), 10, 64)
			tot += n
		}
		return false
	})
	pools.Iterate("", "", func(_ string, v any) bool {
		p := v.(*pool)
		if p.coin == coin {
			tot += p.rCoin
		}
		if coin == hubCoin {
			tot += p.rHub
		}
		return false
	})
	forEachOrder(func(o *order) {
		if o.give == coin {
			tot += o.remGive
		}
	})
	return tot + getU(&adminFees, coin) + getU(&casinoPool, coin)
}

func lpSum(coin string) uint64 {
	s := uint64(0)
	lpPositions.Iterate(coin+":", coin+";", func(_ string, v any) bool {
		s += v.(*lpPos).shares
		return false
	})
	return s
}

// stateSig is a cheap fingerprint of everything the exchange owns + balances.
func stateSig(coins ...string) string {
	s := ""
	for _, c := range coins {
		s += c + "=" + u(coinTotal(c)) + ";"
		if pools.Has(c) {
			p := getPool(c)
			s += u(p.rCoin) + "/" + u(p.rHub) + "/" + u(p.shares) + ";"
		}
	}
	return s + "orders=" + u(openOrderTotal) + ";book=" + strconv.Itoa(sideTotal()) + ";next=" + u(nextOrderId)
}

func balSig(addrs []address, coins []string) string {
	s := ""
	for _, a := range addrs {
		for _, c := range coins {
			s += u(bal(a, c)) + ","
		}
	}
	return s
}

// ── gates ────────────────────────────────────────────────────────────────────

func TestEx_Gates(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	// seedPool: the caller must already act as `lp` (testing.SetRealm can't be
	// switched from inside a closure). Pools are created by the admin API in
	// TestEx_Gates; here the empty pool record is written directly.
	seedPool := func(coin string, lp address, coinAmt, grinAmt uint64) uint64 {
		if !pools.Has(coin) {
			pools.Set(coin, &pool{coin: coin})
		}
		give(lp, coin, coinAmt)
		give(lp, "grin", grinAmt)
		return AddLiquidity(cross(cur), coin, coinAmt, grinAmt, 0, dl())
	}
	lp := trader("gate-lp")
	testing.SetRealm(testing.NewUserRealm(lp))
	seedPool("joy", lp, 10000, 10000)

	// trading only after FinalizeMigration
	migrationFinalized = false
	testing.SetRealm(testing.NewUserRealm(lp))
	mustAbort(t, "before finalize", revive(func() { SwapExactIn(cross(cur), "grin", "joy", 10, 0, dl()) }), "FinalizeMigration")
	mustAbort(t, "transfer before finalize", revive(func() { Transfer(cross(cur), "grin", ta("x").String(), "1") }), "FinalizeMigration")
	migrationFinalized = true

	// no tool requirement: a Fist-only account (no tools at all) can trade
	noob := ta("gate-noob")
	give(noob, "grin", 100)
	testing.SetRealm(testing.NewUserRealm(noob))
	if got := SwapExactIn(cross(cur), "grin", "joy", 10, 1, dl()); got == 0 || bal(noob, "joy") != got {
		t.Errorf("fist-only swap: got %d", got)
	}


	// deadlines are mandatory and enforced
	mustAbort(t, "no deadline", revive(func() { SwapExactIn(cross(cur), "grin", "joy", 10, 0, 0) }), "deadline required")
	mustAbort(t, "deadline passed", revive(func() { SwapExactIn(cross(cur), "grin", "joy", 10, 0, time.Now().Unix()-1) }), "deadline passed")

	// realm (code) callers are rejected — no cross-realm surface
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/evil/proxy"))
	mustAbort(t, "realm caller swap", revive(func() { SwapExactIn(cross(cur), "grin", "joy", 10, 0, dl()) }), "directly from a user")
	mustAbort(t, "realm caller remove", revive(func() { RemoveLiquidity(cross(cur), "joy", 1, 0, 0, dl()) }), "directly from a user")

	// fake coins and overflow-sized inputs
	testing.SetRealm(testing.NewUserRealm(lp))
	mustAbort(t, "fake coin", revive(func() { SwapExactIn(cross(cur), "grin", "fake-coin", 10, 0, dl()) }), "unknown coin")
	mustAbort(t, "fake give", revive(func() { PlaceOrder(cross(cur), "fake-coin", 100, "grin", 100, 0) }), "unknown coin")
	mustAbort(t, "huge amount", revive(func() { SwapExactIn(cross(cur), "grin", "joy", maxAmount+1, 0, dl()) }), "between 1 and")
	mustAbort(t, "max uint", revive(func() { PlaceOrder(cross(cur), "grin", ^uint64(0), "joy", 1, 0) }), "between 1 and")
	mustAbort(t, "zero", revive(func() { AddLiquidity(cross(cur), "joy", 0, 10, 0, dl()) }), "between 1 and")
	mustAbort(t, "no pool", revive(func() { SwapExactIn(cross(cur), "grin", "cool", 10, 0, dl()) }), "no pool")
	mustAbort(t, "coin→coin needs route", revive(func() { SwapExactIn(cross(cur), "joy", "cool", 10, 0, dl()) }), "one side must be grin")

	// only the admin creates/pauses pools
	mustAbort(t, "player CreatePool", revive(func() { CreatePool(cross(cur), "cool") }), "admin only")
	mustAbort(t, "player pause", revive(func() { SetExchangePaused(cross(cur), true) }), "admin only")
	mustAbort(t, "player fee withdraw", revive(func() { WithdrawProtocolFees(cross(cur), "grin") }), "admin only")
	testing.SetRealm(testing.NewUserRealm(admin))
	mustAbort(t, "grin pool", revive(func() { CreatePool(cross(cur), "grin") }), "hub coin")
	mustAbort(t, "fake pool", revive(func() { CreatePool(cross(cur), "fake-coin") }), "unknown coin")
	mustAbort(t, "dup pool", revive(func() { CreatePool(cross(cur), "joy") }), "pool exists")
}

// ── pools ────────────────────────────────────────────────────────────────────

func TestEx_PoolLifecycleAndFees(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	// seedPool: the caller must already act as `lp` (testing.SetRealm can't be
	// switched from inside a closure). Pools are created by the admin API in
	// TestEx_Gates; here the empty pool record is written directly.
	seedPool := func(coin string, lp address, coinAmt, grinAmt uint64) uint64 {
		if !pools.Has(coin) {
			pools.Set(coin, &pool{coin: coin})
		}
		give(lp, coin, coinAmt)
		give(lp, "grin", grinAmt)
		return AddLiquidity(cross(cur), coin, coinAmt, grinAmt, 0, dl())
	}
	lp, tr := trader("pl-lp"), trader("pl-tr")
	sig0 := u(coinTotal("cool")) + "/" + u(coinTotal("grin"))

	// first deposit: any ratio (open economy), 1000 shares burned
	testing.SetRealm(testing.NewUserRealm(lp))
	minted := seedPool("cool", lp, 1000, 1500) // √(1.5M)=1224
	p := getPool("cool")
	if minted != 224 || p.shares != 1224 || lpSum("cool")+minLiquidity != p.shares {
		t.Errorf("first deposit minted=%d shares=%d lpSum=%d", minted, p.shares, lpSum("cool"))
	}
	// under 2000 grin depth: no swaps yet
	give(tr, "grin", 100000)
	give(tr, "cool", 100000)
	testing.SetRealm(testing.NewUserRealm(tr))
	mustAbort(t, "filling pool", revive(func() { SwapExactIn(cross(cur), "grin", "cool", 10, 0, dl()) }), "not open for swaps")
	if QuoteSwap("grin", "cool", 10) != "0" {
		t.Errorf("quote on filling pool")
	}
	// later deposit at the pool ratio
	give(lp, "cool", 10000)
	give(lp, "grin", 15000)
	testing.SetRealm(testing.NewUserRealm(lp))
	AddLiquidity(cross(cur), "cool", 10000, 15000, 1, dl())
	if p.rHub < minOpenDepthGrin || lpSum("cool")+minLiquidity != p.shares {
		t.Errorf("after add: %s lpSum=%d", PoolInfo("cool"), lpSum("cool"))
	}

	// swap grin→cool: fee 0.5% (ceil), proto 0.15% (floor) split 50/50
	testing.SetRealm(testing.NewUserRealm(tr))
	q, _ := strconv.ParseUint(QuoteSwap("grin", "cool", 1000), 10, 64)
	k0 := isqrt128(p.rCoin, p.rHub)
	adm0, cas0 := getU(&adminFees, "grin"), getU(&casinoPool, "grin")
	out := SwapExactIn(cross(cur), "grin", "cool", 1000, q, dl())
	if out != q || out == 0 {
		t.Errorf("out=%d quote=%d", out, q)
	}
	if getU(&adminFees, "grin")-adm0 != 0 || getU(&casinoPool, "grin")-cas0 != 1 {
		// proto = floor(1000×15/10000) = 1 → admin floor(0.5)=0, casino 1
		t.Errorf("fee split admin+%d casino+%d", getU(&adminFees, "grin")-adm0, getU(&casinoPool, "grin")-cas0)
	}
	if isqrt128(p.rCoin, p.rHub) < k0 {
		t.Errorf("k decreased")
	}
	// bigger swap the other way: proto 15 → admin 7, casino 8
	adm0, cas0 = getU(&adminFees, "cool"), getU(&casinoPool, "cool")
	SwapExactIn(cross(cur), "cool", "grin", 10000, 1, dl())
	if getU(&adminFees, "cool")-adm0 != 7 || getU(&casinoPool, "cool")-cas0 != 8 {
		t.Errorf("fee split cool admin+%d casino+%d", getU(&adminFees, "cool")-adm0, getU(&casinoPool, "cool")-cas0)
	}

	// slippage revert changes nothing (validate-then-write)
	before := stateSig("cool", "grin") + balSig([]address{tr}, []string{"cool", "grin"})
	mustAbort(t, "minOut", revive(func() { SwapExactIn(cross(cur), "grin", "cool", 1000, 1_000_000, dl()) }), "slippage")
	mustAbort(t, "insufficient", revive(func() { SwapExactIn(cross(cur), "grin", "cool", maxAmount, 0, dl()) }), "insufficient")
	if after := stateSig("cool", "grin") + balSig([]address{tr}, []string{"cool", "grin"}); after != before {
		t.Errorf("failed swap changed state:\n%s\n%s", before, after)
	}

	// LP exits fully after warm-up: gets ≥ deposit in value terms thanks to fees
	testing.SkipHeights(200) // > 600 s
	testing.SetRealm(testing.NewUserRealm(lp))
	pos := lpPositions.Get("cool:" + lp.String()).(*lpPos)
	oc, og := RemoveLiquidity(cross(cur), "cool", pos.shares, 0, 0, dl())
	if lpPositions.Has("cool:"+lp.String()) || p.shares != minLiquidity {
		t.Errorf("position not closed, shares=%d", p.shares)
	}
	if oc == 0 || og == 0 || p.rCoin == 0 || p.rHub == 0 {
		t.Errorf("remove out %d/%d, pool left %d/%d", oc, og, p.rCoin, p.rHub)
	}
	// conservation across the whole test
	_ = sig0
	if lpSum("cool")+minLiquidity != p.shares {
		t.Errorf("lp sum")
	}
}

// Instant unstake and cancel must work while paused, and for banned players.
func TestEx_PauseNeverTrapsFunds(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	// seedPool: the caller must already act as `lp` (testing.SetRealm can't be
	// switched from inside a closure). Pools are created by the admin API in
	// TestEx_Gates; here the empty pool record is written directly.
	seedPool := func(coin string, lp address, coinAmt, grinAmt uint64) uint64 {
		if !pools.Has(coin) {
			pools.Set(coin, &pool{coin: coin})
		}
		give(lp, coin, coinAmt)
		give(lp, "grin", grinAmt)
		return AddLiquidity(cross(cur), coin, coinAmt, grinAmt, 0, dl())
	}
	lp := trader("pz-lp")
	testing.SetRealm(testing.NewUserRealm(lp))
	seedPool("think", lp, 5000, 5000)
	give(lp, "grin", 1000)
	testing.SetRealm(testing.NewUserRealm(lp))
	id := PlaceOrder(cross(cur), "grin", 100, "think", 90, 0)

	testing.SetRealm(testing.NewUserRealm(admin))
	SetExchangePaused(cross(cur), true)
	SetPoolPaused(cross(cur), "think", true)
	SetPaused(cross(cur), true) // whole game paused too
	BanAddress(cross(cur), lp.String(), "test", 0)

	testing.SetRealm(testing.NewUserRealm(lp))
	mustAbort(t, "swap paused", revive(func() { SwapExactIn(cross(cur), "grin", "think", 10, 0, dl()) }), "paused")
	mustAbort(t, "add paused", revive(func() { AddLiquidity(cross(cur), "think", 10, 10, 0, dl()) }), "paused")
	mustAbort(t, "order paused", revive(func() { PlaceOrder(cross(cur), "grin", 100, "think", 90, 0) }), "paused")

	g0 := bal(lp, "grin")
	CancelOrder(cross(cur), id) // works paused + banned
	if bal(lp, "grin") != g0+100 {
		t.Errorf("cancel refund %d", bal(lp, "grin")-g0)
	}
	pos := lpPositions.Get("think:" + lp.String()).(*lpPos)
	oc, og := RemoveLiquidity(cross(cur), "think", pos.shares, 1, 1, dl()) // works paused + banned
	if oc == 0 || og == 0 {
		t.Errorf("remove while paused gave %d/%d", oc, og)
	}
	// Transfer is the player's own money: works paused and banned
	Transfer(cross(cur), "grin", trader("pz-friend").String(), "1")

	// fee withdrawal is never blocked either
	testing.SetRealm(testing.NewUserRealm(admin))
	if getU(&adminFees, "grin") > 0 {
		WithdrawProtocolFees(cross(cur), "grin")
	}
	UnbanAddress(cross(cur), lp.String())
	SetPaused(cross(cur), false)
	SetExchangePaused(cross(cur), false)
	SetPoolPaused(cross(cur), "think", false)
}

// Anti-JIT: a deposit that leaves within 600 s gets no fees.
func TestEx_FeeSkimmingJIT(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	// seedPool: the caller must already act as `lp` (testing.SetRealm can't be
	// switched from inside a closure). Pools are created by the admin API in
	// TestEx_Gates; here the empty pool record is written directly.
	seedPool := func(coin string, lp address, coinAmt, grinAmt uint64) uint64 {
		if !pools.Has(coin) {
			pools.Set(coin, &pool{coin: coin})
		}
		give(lp, coin, coinAmt)
		give(lp, "grin", grinAmt)
		return AddLiquidity(cross(cur), coin, coinAmt, grinAmt, 0, dl())
	}
	lp, jit, tr := trader("jit-lp"), trader("jit-jit"), trader("jit-tr")
	testing.SetRealm(testing.NewUserRealm(lp))
	seedPool("sleep", lp, 20000, 20000)
	p := getPool("sleep")

	// JIT adds 2× the pool, a burst of swaps happens, JIT leaves at once
	give(jit, "sleep", 40000)
	give(jit, "grin", 40000)
	testing.SetRealm(testing.NewUserRealm(jit))
	sh := AddLiquidity(cross(cur), "sleep", 40000, 40000, 1, dl())
	give(tr, "grin", 50000)
	give(tr, "sleep", 50000)
	testing.SetRealm(testing.NewUserRealm(tr))
	for i := 0; i < 10; i++ {
		SwapExactIn(cross(cur), "grin", "sleep", 3000, 1, dl())
		SwapExactIn(cross(cur), "sleep", "grin", 3000, 1, dl())
	}
	testing.SetRealm(testing.NewUserRealm(jit))
	oc, og := RemoveLiquidity(cross(cur), "sleep", sh, 0, 0, dl())
	// value at the current pool price, in grin: JIT must not gain
	valOut := og + mulDiv(oc, p.rHub, p.rCoin)
	valIn := 40000 + mulDiv(40000, p.rHub, p.rCoin)
	if valOut > valIn || isqrt128(oc, og) > sh+1 {
		t.Errorf("JIT skimmed fees: out %d > in %d (√ %d vs shares %d)", valOut, valIn, isqrt128(oc, og), sh)
	}
	// the long-term LP (past warm-up) keeps the fees
	testing.SkipHeights(200)
	testing.SetRealm(testing.NewUserRealm(lp))
	pos := lpPositions.Get("sleep:" + lp.String()).(*lpPos)
	oc2, og2 := RemoveLiquidity(cross(cur), "sleep", pos.shares, 0, 0, dl())
	// IL-free measure: √(coin×grin) out vs the 19000 shares' √k at entry (1.0/share)
	if isqrt128(oc2, og2) <= 19000 {
		t.Errorf("LP earned nothing: %d/%d", oc2, og2)
	}
}

// First-depositor share inflation and donation attacks.
func TestEx_InflationAndDonation(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	att, vic := trader("inf-att"), trader("inf-vic")
	testing.SetRealm(testing.NewUserRealm(admin))
	CreatePool(cross(cur), "party")
	give(att, "party", 10_000_000)
	give(att, "grin", 10_000_000)
	testing.SetRealm(testing.NewUserRealm(att))
	mustAbort(t, "dust first deposit", revive(func() { AddLiquidity(cross(cur), "party", 1000, 1000, 0, dl()) }), "too small")
	AddLiquidity(cross(cur), "party", 1001, 1001, 0, dl()) // 1 share for the attacker
	p := getPool("party")
	// donation: Transfer to the realm address only credits a balance entry,
	// reserves are internal counters and don't move.
	realmAddr := chain.PackageAddress(realmPkgPath).String()
	Transfer(cross(cur), "grin", realmAddr, "5000000")
	if p.rHub != 1001 || p.rCoin != 1001 {
		t.Errorf("donation moved reserves: %s", PoolInfo("party"))
	}
	// victim deposits normally and gets a proportional number of shares
	give(vic, "party", 100000)
	give(vic, "grin", 100000)
	testing.SetRealm(testing.NewUserRealm(vic))
	sh := AddLiquidity(cross(cur), "party", 100000, 100000, 1, dl())
	if sh < 99000 {
		t.Errorf("victim got only %d shares for 100k/100k (pool %s)", sh, PoolInfo("party"))
	}
	// the attacker can't extract more than they put in
	testing.SetRealm(testing.NewUserRealm(att))
	testing.SkipHeights(200)
	a0c, a0g := bal(att, "party"), bal(att, "grin")
	RemoveLiquidity(cross(cur), "party", 1, 0, 0, dl())
	if bal(att, "party")-a0c > 1 || bal(att, "grin")-a0g > 1 {
		t.Errorf("attacker extracted %d/%d", bal(att, "party")-a0c, bal(att, "grin")-a0g)
	}
}

// Sandwich: the victim's minOut (quote − 1%) makes the front-run revert the victim.
func TestEx_SandwichWithMinOut(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	// seedPool: the caller must already act as `lp` (testing.SetRealm can't be
	// switched from inside a closure). Pools are created by the admin API in
	// TestEx_Gates; here the empty pool record is written directly.
	seedPool := func(coin string, lp address, coinAmt, grinAmt uint64) uint64 {
		if !pools.Has(coin) {
			pools.Set(coin, &pool{coin: coin})
		}
		give(lp, coin, coinAmt)
		give(lp, "grin", grinAmt)
		return AddLiquidity(cross(cur), coin, coinAmt, grinAmt, 0, dl())
	}
	lp, att, vic := trader("sw-lp"), trader("sw-att"), trader("sw-vic")
	testing.SetRealm(testing.NewUserRealm(lp))
	seedPool("hot", lp, 100000, 100000)
	give(vic, "grin", 10000)
	give(att, "grin", 1_000_000)
	testing.SetRealm(testing.NewUserRealm(vic))
	q, _ := strconv.ParseUint(QuoteSwap("grin", "hot", 5000), 10, 64)
	minOut := q * 99 / 100
	// attacker front-runs with a big buy
	testing.SetRealm(testing.NewUserRealm(att))
	SwapExactIn(cross(cur), "grin", "hot", 50000, 1, dl())
	testing.SetRealm(testing.NewUserRealm(vic))
	before := stateSig("hot", "grin") + balSig([]address{vic}, []string{"hot", "grin"})
	mustAbort(t, "sandwiched victim", revive(func() { SwapExactIn(cross(cur), "grin", "hot", 5000, minOut, dl()) }), "slippage")
	if stateSig("hot", "grin")+balSig([]address{vic}, []string{"hot", "grin"}) != before {
		t.Errorf("victim's failed swap changed state")
	}
	// open economy: the big trade itself is allowed (no impact cap)
	testing.SetRealm(testing.NewUserRealm(att))
	give(att, "hot", 1_000_000)
	SwapExactIn(cross(cur), "hot", "grin", 1_000_000, 1, dl()) // dump 10× the pool
}

// Round trips and add→remove never profit (rounding favors the pool).
func TestEx_RoundingFavorsPool(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	// seedPool: the caller must already act as `lp` (testing.SetRealm can't be
	// switched from inside a closure). Pools are created by the admin API in
	// TestEx_Gates; here the empty pool record is written directly.
	seedPool := func(coin string, lp address, coinAmt, grinAmt uint64) uint64 {
		if !pools.Has(coin) {
			pools.Set(coin, &pool{coin: coin})
		}
		give(lp, coin, coinAmt)
		give(lp, "grin", grinAmt)
		return AddLiquidity(cross(cur), coin, coinAmt, grinAmt, 0, dl())
	}
	lp, tr := trader("rd-lp"), trader("rd-tr")
	testing.SetRealm(testing.NewUserRealm(lp))
	seedPool("wow", lp, 50000, 70000)
	testing.SetRealm(testing.NewUserRealm(tr))
	for amt := uint64(1); amt <= 3000; amt = amt*3 + 1 {
		give(tr, "grin", amt)
		g0 := bal(tr, "grin")
		w0 := bal(tr, "wow")
		if q := QuoteSwap("grin", "wow", amt); q == "0" {
			continue
		}
		out := SwapExactIn(cross(cur), "grin", "wow", amt, 1, dl())
		if QuoteSwap("wow", "grin", out) != "0" {
			SwapExactIn(cross(cur), "wow", "grin", out, 0+1, dl())
		}
		if bal(tr, "grin")+bal(tr, "wow") > g0+w0 && bal(tr, "grin") > g0 {
			t.Errorf("round trip of %d profited: grin %d→%d", amt, g0, bal(tr, "grin"))
		}
	}
	// add then remove immediately never returns more than deposited
	give(tr, "wow", 777)
	give(tr, "grin", 999)
	c0, g0 := bal(tr, "wow"), bal(tr, "grin")
	sh := AddLiquidity(cross(cur), "wow", 777, 999, 1, dl())
	RemoveLiquidity(cross(cur), "wow", sh, 0, 0, dl())
	if bal(tr, "wow") > c0 || bal(tr, "grin") > g0 {
		t.Errorf("add/remove profited: %d/%d → %d/%d", c0, g0, bal(tr, "wow"), bal(tr, "grin"))
	}
}

// ── order book ───────────────────────────────────────────────────────────────

func TestEx_OrderBookLifecycle(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	mk, tk, other := trader("ob-mk"), trader("ob-tk"), trader("ob-ot")
	give(mk, "grin", 10000)
	give(mk, "rock", 1000)
	give(tk, "rock", 10000)
	give(tk, "grin", 10000)

	// "I want 10 rock, I pay 100 grin" — escrow + 2 grin post fee (1/1)
	testing.SetRealm(testing.NewUserRealm(mk))
	adm0, cas0 := getU(&adminFees, "grin"), getU(&casinoPool, "grin")
	g0 := bal(mk, "grin")
	id := PlaceOrder(cross(cur), "grin", 100, "rock", 10, 0)
	if bal(mk, "grin") != g0-102 || getU(&adminFees, "grin")-adm0 != 1 || getU(&casinoPool, "grin")-cas0 != 1 {
		t.Errorf("place: grin %d→%d fees %d/%d", g0, bal(mk, "grin"), getU(&adminFees, "grin")-adm0, getU(&casinoPool, "grin")-cas0)
	}
	if !strings.Contains(OrdersOf(mk.String()), `"id":"`+u(id)+`"`) {
		t.Errorf("OrdersOf: %s", OrdersOf(mk.String()))
	}
	mustAbort(t, "too small", revive(func() { PlaceOrder(cross(cur), "grin", 49, "rock", 10, 0) }), "50 grin")
	mustAbort(t, "expiry > 7d", revive(func() { PlaceOrder(cross(cur), "grin", 100, "rock", 10, 8*86400) }), "7 days")
	mustAbort(t, "same coin", revive(func() { PlaceOrder(cross(cur), "grin", 100, "grin", 10, 0) }), "differ")

	// other players can't cancel it
	testing.SetRealm(testing.NewUserRealm(other))
	mustAbort(t, "cancel by other", revive(func() { CancelOrder(cross(cur), id) }), "not your order")

	// self-match: the maker's own order is skipped, so nothing fills
	testing.SetRealm(testing.NewUserRealm(mk))
	mustAbort(t, "self match", revive(func() { FillOrders(cross(cur), "rock", "grin", 5, 1, 0, dl()) }), "slippage")

	// partial fill: taker pays 4 rock (+ceil fee 1) → gets floor(4×100/10)=40 grin
	testing.SetRealm(testing.NewUserRealm(tk))
	r0, tg0 := bal(tk, "rock"), bal(tk, "grin")
	mr0 := bal(mk, "rock")
	got := FillOrders(cross(cur), "rock", "grin", 5, 40, 0, dl())
	if got != 40 || bal(tk, "rock") != r0-5 || bal(tk, "grin") != tg0+40 || bal(mk, "rock") != mr0+4 {
		t.Errorf("partial fill got=%d rock -%d maker +%d", got, r0-bal(tk, "rock"), bal(mk, "rock")-mr0)
	}
	o := findOrder(id)
	if o == nil || o.remGive != 60 || o.remWant != 6 {
		t.Errorf("after partial: %s", Order(mk.String(), id))
	}
	// next fill (6 rock) completes it; remaining 60 grin
	got = FillOrders(cross(cur), "rock", "grin", 100, 1, 0, dl())
	if got != 60 || findOrder(id) != nil {
		t.Errorf("full fill got=%d order=%s", got, Order(mk.String(), id))
	}
	// double cancel / cancel of a filled order
	testing.SetRealm(testing.NewUserRealm(mk))
	mustAbort(t, "cancel filled", revive(func() { CancelOrder(cross(cur), id) }), "no such open order")
	id2 := PlaceOrder(cross(cur), "grin", 200, "rock", 20, 0)
	g1 := bal(mk, "grin")
	CancelOrder(cross(cur), id2)
	if bal(mk, "grin") != g1+200 {
		t.Errorf("cancel refund %d", bal(mk, "grin")-g1)
	}
	mustAbort(t, "double cancel", revive(func() { CancelOrder(cross(cur), id2) }), "no such open order")
}

func TestEx_OrderPriorityExpiryAndSpam(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	a, b, tk := trader("op-a"), trader("op-b"), trader("op-tk")
	give(a, "grin", 100000)
	give(b, "grin", 100000)
	give(tk, "fire", 100000)
	// a asks 2 fire per 100 grin, b asks 1 fire per 100 grin (better for takers)
	testing.SetRealm(testing.NewUserRealm(a))
	ida := PlaceOrder(cross(cur), "grin", 100, "fire", 2, 0)
	testing.SetRealm(testing.NewUserRealm(b))
	idb := PlaceOrder(cross(cur), "grin", 100, "fire", 1, 3600)
	if !strings.HasPrefix(BookDepth("fire", "grin", 10, 0), `[{"id":"`+u(idb)+`"`) {
		t.Errorf("best price not first: %s", BookDepth("fire", "grin", 10, 0))
	}
	// b's order expires: a fill skips it, refunds b, fills a instead
	testing.SkipHeights(721) // > 3600 s
	bg := bal(b, "grin")
	testing.SetRealm(testing.NewUserRealm(tk))
	got := FillOrders(cross(cur), "fire", "grin", 3, 100, 0, dl())
	if got != 100 || findOrder(idb) != nil || bal(b, "grin") != bg+100 || findOrder(ida) != nil {
		t.Errorf("expired handling got=%d b+%d", got, bal(b, "grin")-bg)
	}
	// filling an expired-only book gets nothing and reverts
	testing.SetRealm(testing.NewUserRealm(b))
	idb2 := PlaceOrder(cross(cur), "grin", 100, "fire", 1, 60)
	testing.SkipHeights(20)
	testing.SetRealm(testing.NewUserRealm(tk))
	mustAbort(t, "expired only", revive(func() { FillOrders(cross(cur), "fire", "grin", 3, 1, 0, dl()) }), "slippage")
	if findOrder(idb2) == nil {
		t.Errorf("revert path must not have closed the order")
	}
	SweepExpiredOrders(cross(cur), "fire", "grin")
	if findOrder(idb2) != nil {
		t.Errorf("sweep did not close the expired order")
	}
	// spam: max 20 open orders per maker
	testing.SetRealm(testing.NewUserRealm(a))
	for i := 0; i < 20; i++ {
		PlaceOrder(cross(cur), "grin", 50, "fire", uint64(1+i), 0)
	}
	mustAbort(t, "21st order", revive(func() { PlaceOrder(cross(cur), "grin", 50, "fire", 1, 0) }), "max 20")
	// fills are bounded: ≤ 10 per call even with 20 resting orders
	testing.SetRealm(testing.NewUserRealm(tk))
	n0 := int(openOrderTotal)
	FillOrders(cross(cur), "fire", "grin", 100000, 1, 50, dl())
	if n0-int(openOrderTotal) > maxFillsPerTx {
		t.Errorf("filled %d orders in one call", n0-int(openOrderTotal))
	}
}

// ── router ───────────────────────────────────────────────────────────────────

func TestEx_RouterBookThenPool(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	// seedPool: the caller must already act as `lp` (testing.SetRealm can't be
	// switched from inside a closure). Pools are created by the admin API in
	// TestEx_Gates; here the empty pool record is written directly.
	seedPool := func(coin string, lp address, coinAmt, grinAmt uint64) uint64 {
		if !pools.Has(coin) {
			pools.Set(coin, &pool{coin: coin})
		}
		give(lp, coin, coinAmt)
		give(lp, "grin", grinAmt)
		return AddLiquidity(cross(cur), coin, coinAmt, grinAmt, 0, dl())
	}
	lp, mk, tr := trader("rt-lp"), trader("rt-mk"), trader("rt-tr")
	testing.SetRealm(testing.NewUserRealm(lp))
	seedPool("seedling", lp, 100000, 100000)
	testing.SetRealm(testing.NewUserRealm(lp))
	seedPool("leaves", lp, 100000, 100000)
	// a cheap ask on the book: 1000 seedling for 500 grin (pool price ~1:1)
	give(mk, "seedling", 1000)
	give(mk, "grin", 10)
	testing.SetRealm(testing.NewUserRealm(mk))
	PlaceOrder(cross(cur), "seedling", 1000, "grin", 500, 0)
	give(tr, "grin", 5000)
	q := QuoteRoute(tr.String(), "grin", "seedling", 2000, 0)
	if !strings.Contains(q, `"bookFills":1`) {
		t.Errorf("router ignored the cheaper book: %s", q)
	}
	testing.SetRealm(testing.NewUserRealm(tr))
	outStr := q[strings.Index(q, `"out":"`)+7:]
	want, _ := strconv.ParseUint(outStr[:strings.Index(outStr, `"`)], 10, 64)
	out := SwapRoute(cross(cur), "grin", "seedling", 2000, want, 0, dl())
	if out != want {
		t.Errorf("route out %d != quote %d", out, want)
	}
	// coin → coin through two pools
	give(tr, "leaves", 1000)
	out2 := SwapRoute(cross(cur), "leaves", "seedling", 1000, 1, 0, dl())
	if out2 == 0 || out2 >= 1000 {
		t.Errorf("two-hop out %d", out2)
	}
	before := stateSig("seedling", "leaves", "grin")
	mustAbort(t, "route minOut", revive(func() { SwapRoute(cross(cur), "grin", "seedling", 100, 1000, 0, dl()) }), "slippage")
	if stateSig("seedling", "leaves", "grin") != before {
		t.Errorf("failed route changed state")
	}
}

// ── admin can't touch user funds ─────────────────────────────────────────────

func TestEx_AdminCannotTouchUserFunds(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	// seedPool: the caller must already act as `lp` (testing.SetRealm can't be
	// switched from inside a closure). Pools are created by the admin API in
	// TestEx_Gates; here the empty pool record is written directly.
	seedPool := func(coin string, lp address, coinAmt, grinAmt uint64) uint64 {
		if !pools.Has(coin) {
			pools.Set(coin, &pool{coin: coin})
		}
		give(lp, coin, coinAmt)
		give(lp, "grin", grinAmt)
		return AddLiquidity(cross(cur), coin, coinAmt, grinAmt, 0, dl())
	}
	lp, mk := trader("ad-lp"), trader("ad-mk")
	testing.SetRealm(testing.NewUserRealm(lp))
	seedPool("fallen", lp, 30000, 30000)
	give(mk, "grin", 1000)
	testing.SetRealm(testing.NewUserRealm(mk))
	PlaceOrder(cross(cur), "grin", 300, "fallen", 300, 0)
	users := []address{lp, mk}
	coins := []string{"fallen", "grin"}
	before := stateSig(coins...) + balSig(users, coins)

	// every admin entry point, called by the admin
	testing.SetRealm(testing.NewUserRealm(admin))
	SetExchangePaused(cross(cur), true)
	SetExchangePaused(cross(cur), false)
	SetPoolPaused(cross(cur), "fallen", true)
	SetPoolPaused(cross(cur), "fallen", false)
	SetPaused(cross(cur), true)
	SetPaused(cross(cur), false)
	BanAddress(cross(cur), mk.String(), "x", 0)
	UnbanAddress(cross(cur), mk.String())
	SetVeinMax(cross(cur), "fallen", "999999999999")
	SetPassPrice(cross(cur), 7_000_000)
	mustAbort(t, "migrate after finalize", revive(func() {
		MigrateBatch(cross(cur), "steal", "balance", `[["`+admin.String()+`","grin","999999"]]`)
	}), "finalized")
	if after := stateSig(coins...) + balSig(users, coins); after != before {
		t.Errorf("admin calls changed user funds:\n%s\n%s", before, after)
	}
	// fee withdrawal moves only the admin's own ledger
	if getU(&adminFees, "grin") > 0 {
		c0 := getU(&casinoPool, "grin")
		WithdrawProtocolFees(cross(cur), "grin")
		if getU(&casinoPool, "grin") != c0 || getU(&adminFees, "grin") != 0 {
			t.Errorf("fee withdraw touched the casino pool")
		}
	}
	// WithdrawFunds can't take donated / player GNOT — only unwithdrawn pass revenue
	realmAddr := chain.PackageAddress(realmPkgPath)
	testing.IssueCoins(realmAddr, chain.Coins{chain.NewCoin("ugnot", 50_000_000)})
	owed := WithdrawableFunds()
	mustAbort(t, "withdraw donation", revive(func() { WithdrawFunds(cross(cur), admin.String(), owed+1) }), "unwithdrawn pass revenue")
}

// ── casino pool caps ─────────────────────────────────────────────────────────

func seedCasino(coin string, amt uint64) {
	setU(&casinoPool, coin, amt)
	casinoReserved.Remove(coin)
	casinoDay.Remove(coin)
}


func TestEx_CheckedMath(t *testing.T) {
	if !strings.Contains(panicMsg(func() { addChk(^uint64(0), 1) }), "overflow") {
		t.Errorf("addChk")
	}
	if !strings.Contains(panicMsg(func() { subChk(1, 2) }), "underflow") {
		t.Errorf("subChk")
	}
	if !strings.Contains(panicMsg(func() { mulDiv(^uint64(0), ^uint64(0), 1) }), "overflow") {
		t.Errorf("mulDiv")
	}
	if !strings.Contains(panicMsg(func() { mulDiv(1, 1, 0) }), "division by zero") {
		t.Errorf("mulDiv /0")
	}
	if !strings.Contains(panicMsg(func() { addU(&balances, "x-overflow", ^uint64(0)); addU(&balances, "x-overflow", 1) }), "overflow") {
		t.Errorf("addU must not wrap")
	}
	balances.Remove("x-overflow")
	if isqrt128(^uint64(0), ^uint64(0)) != ^uint64(0)-1 && isqrt128(^uint64(0), ^uint64(0)) != ^uint64(0) {
		t.Errorf("isqrt128 max = %d", isqrt128(^uint64(0), ^uint64(0)))
	}
	for _, c := range [][2]uint64{{1, 1}, {2, 8}, {1000, 1000}, {123456789, 987654321}, {1 << 40, 1 << 40}, {maxAmount, maxAmount}} {
		s := isqrt128(c[0], c[1])
		if mulLess(c[0], c[1], s, s) || !mulLess(c[0], c[1], s+1, s+1) {
			t.Errorf("isqrt128(%d×%d)=%d", c[0], c[1], s)
		}
	}
	if priceKey(1, 2) >= priceKey(1, 1) || priceKey(3, 1) <= priceKey(2, 1) || len(priceKey(maxAmount, 1)) != 24 {
		t.Errorf("priceKey ordering")
	}
}

// ── invariant random walk ────────────────────────────────────────────────────

type xrng struct{ s uint64 }

func (r *xrng) next(n uint64) uint64 {
	r.s = r.s*6364136223846793005 + 1442695040888963407
	return (r.s >> 33) % n
}

func TestEx_InvariantRandomWalk(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	// seedPool: the caller must already act as `lp` (testing.SetRealm can't be
	// switched from inside a closure). Pools are created by the admin API in
	// TestEx_Gates; here the empty pool record is written directly.
	seedPool := func(coin string, lp address, coinAmt, grinAmt uint64) uint64 {
		if !pools.Has(coin) {
			pools.Set(coin, &pool{coin: coin})
		}
		give(lp, coin, coinAmt)
		give(lp, "grin", grinAmt)
		return AddLiquidity(cross(cur), coin, coinAmt, grinAmt, 0, dl())
	}
	coins := []string{"melt", "tear", "grin"}
	names := []string{"iw-0", "iw-1", "iw-2", "iw-3"}
	var us []address
	for _, n := range names {
		a := trader(n)
		us = append(us, a)
		for _, c := range coins {
			give(a, c, 2_000_000)
		}
	}
	testing.SetRealm(testing.NewUserRealm(us[0]))
	seedPool("melt", us[0], 200000, 200000)
	testing.SetRealm(testing.NewUserRealm(us[1]))
	seedPool("tear", us[1], 100000, 300000)
	tot := map[string]uint64{}
	for _, c := range coins {
		tot[c] = coinTotal(c)
	}
	rkps := map[string]uint64{"melt": rootKPerShare(getPool("melt")), "tear": rootKPerShare(getPool("tear"))}
	type res3 struct{ c, h, s uint64 }
	prev := map[string]res3{}
	for _, c := range []string{"melt", "tear"} {
		p := getPool(c)
		prev[c] = res3{p.rCoin, p.rHub, p.shares}
	}
	rng := &xrng{s: 42}
	ok, failed := 0, 0
	for step := 0; step < 400; step++ {
		a := us[rng.next(4)]
		testing.SetRealm(testing.NewUserRealm(a))
		pc := coins[rng.next(2)]
		amt := 1 + rng.next(20000)
		op := rng.next(7)
		isSwap := false
		r := revive(func() {
			switch op {
			case 0:
				SwapExactIn(cross(cur), "grin", pc, amt, 1, dl())
				isSwap = true
			case 1:
				SwapExactIn(cross(cur), pc, "grin", amt, 1, dl())
				isSwap = true
			case 2:
				AddLiquidity(cross(cur), pc, amt, amt*2, 1, dl())
			case 3:
				key := pc + ":" + a.String()
				if lpPositions.Has(key) {
					sh := lpPositions.Get(key).(*lpPos).shares
					RemoveLiquidity(cross(cur), pc, 1+rng.next(sh), 0, 0, dl())
				}
			case 4:
				PlaceOrder(cross(cur), coins[rng.next(3)], 100+amt, coins[rng.next(3)], 1+rng.next(5000), int64(60+rng.next(3600)))
			case 5:
				FillOrders(cross(cur), coins[rng.next(3)], coins[rng.next(3)], amt, 1, int(1+rng.next(10)), dl())
			case 6:
				SwapRoute(cross(cur), coins[rng.next(3)], coins[rng.next(3)], amt, 1, int(rng.next(10)), dl())
			}
		})
		if r != nil {
			failed++
		} else {
			ok++
		}
		testing.SkipHeights(int64(rng.next(30)))
		// I1 conservation per coin (also proves failed calls wrote nothing)
		for _, c := range coins {
			if got := coinTotal(c); got != tot[c] {
				t.Fatalf("step %d op %d (%s): %s total %d != %d", step, op, errOf(r), c, got, tot[c])
			}
		}
		for _, c := range []string{"melt", "tear"} {
			p := getPool(c)
			// I2 LP shares sum to the total (minus the burned 1000)
			if lpSum(c)+minLiquidity != p.shares {
				t.Fatalf("step %d: %s lpSum %d + 1000 != %d", step, c, lpSum(c), p.shares)
			}
			// I3 reserves never empty while shares exist
			if p.rCoin == 0 || p.rHub == 0 {
				t.Fatalf("step %d: %s reserves emptied", step, c)
			}
			// I4 a swap (shares unchanged) never decreases k — exact 128-bit check
			pv := prev[c]
			if p.shares == pv.s && mulLess(p.rCoin, p.rHub, pv.c, pv.h) {
				t.Fatalf("step %d op %d: %s k decreased on a swap", step, op, c)
			}
			// I4b √k per share never decreases beyond isqrt's floor (≤ 1e9/S + 1 units)
			now := rootKPerShare(p)
			if now+rootKScale/p.shares+1 < rkps[c] {
				t.Fatalf("step %d op %d swap=%t: %s √k/share fell %d → %d", step, op, isSwap, c, rkps[c], now)
			}
			rkps[c] = now
			prev[c] = res3{p.rCoin, p.rHub, p.shares}
		}
		// I5 no open order is empty (can't overfill)
		nOrders, nSide := 0, 0
		forEachOrder(func(o *order) {
			nOrders++
			if o.remGive == 0 || o.remWant == 0 {
				t.Fatalf("step %d: empty open order %d", step, o.id)
			}
			// I6 every open order has exactly its book entry
			s := sideStr(sideKey(o.want, o.give))
			e := sideEntry(o)
			i := sideSearch(s, e[:sideSortLen]) * sideEntryLen
			if i+sideEntryLen > len(s) || s[i:i+sideEntryLen] != e {
				t.Fatalf("step %d: order %d missing from its book side", step, o.id)
			}
		})
		sides.Iterate("", "", func(_ string, v any) bool {
			s := v.(string)
			nSide += len(s) / sideEntryLen
			// I7 each side is strictly sorted (price, then id)
			for i := sideEntryLen; i < len(s); i += sideEntryLen {
				if s[i-sideEntryLen:i-sideEntryLen+sideSortLen] >= s[i:i+sideSortLen] {
					t.Fatalf("step %d: book side out of order", step)
				}
			}
			return false
		})
		if nOrders != nSide || uint64(nOrders) != openOrderTotal {
			t.Fatalf("step %d: orders %d, book entries %d, counter %d", step, nOrders, nSide, openOrderTotal)
		}
	}
	if ok < 100 {
		t.Errorf("random walk too degenerate: %d ok, %d failed", ok, failed)
	}
}

// ── order storage test helpers (production looks orders up per maker) ──────

func forEachOrder(fn func(o *order)) {
	makerBooks.Iterate("", "", func(maker string, _ any) bool {
		for _, r := range makerRecs(maker) {
			fn(decodeOrder(maker, r))
		}
		return false
	})
}

func findOrder(id uint64) *order {
	var found *order
	forEachOrder(func(o *order) {
		if o.id == id {
			found = o
		}
	})
	return found
}

func sideTotal() int {
	n := 0
	sides.Iterate("", "", func(_ string, v any) bool {
		n += len(v.(string)) / sideEntryLen
		return false
	})
	return n
}

// A book side holds ≤ maxSideOrders. When full, a worse-or-equal price is
// refused and a better one evicts the worst order, refunding only its maker.
// Storage stays bounded and nobody can lock a side with absurd prices.
func TestEx_BookSideCapAndEviction(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	var worstMaker address
	var worstId uint64
	n := 0
	for m := 0; n < maxSideOrders; m++ {
		mk := trader("cap-" + strconv.Itoa(m))
		give(mk, "grin", 1000000)
		testing.SetRealm(testing.NewUserRealm(mk))
		for i := 0; i < int(maxOpenOrders) && n < maxSideOrders; i++ {
			// price rises with n: the last one placed is the worst for takers
			id := PlaceOrder(cross(cur), "grin", 100, "joy", uint64(100+n), 0)
			worstMaker, worstId = mk, id
			n++
		}
	}
	if sideCount("joy", "grin") != maxSideOrders {
		t.Fatalf("side count %d", sideCount("joy", "grin"))
	}
	late := trader("cap-late")
	give(late, "grin", 10000)
	testing.SetRealm(testing.NewUserRealm(late))
	sig := stateSig("grin", "joy")
	mustAbort(t, "worse price on full side", revive(func() { PlaceOrder(cross(cur), "grin", 100, "joy", 100000, 0) }), "book side full")
	mustAbort(t, "equal-to-worst price", revive(func() { PlaceOrder(cross(cur), "grin", 100, "joy", uint64(100+maxSideOrders-1), 0) }), "book side full")
	if stateSig("grin", "joy") != sig {
		t.Errorf("refused order changed state")
	}
	wg := bal(worstMaker, "grin")
	id := PlaceOrder(cross(cur), "grin", 100, "joy", 50, 0)
	if sideCount("joy", "grin") != maxSideOrders || findOrder(worstId) != nil || findOrder(id) == nil {
		t.Errorf("eviction failed: count=%d", sideCount("joy", "grin"))
	}
	if bal(worstMaker, "grin") != wg+100 {
		t.Errorf("evicted maker refund %d", bal(worstMaker, "grin")-wg)
	}
	if !strings.HasPrefix(BookDepth("joy", "grin", 1, 0), `[{"id":"`+u(id)+`"`) {
		t.Errorf("new best order not first: %s", BookDepth("joy", "grin", 1, 0))
	}
}

func mustPanicEx(t *testing.T, what string, f func(), want string) {
	msg := panicMsg(f)
	if msg == "" || !strings.Contains(msg, want) {
		t.Errorf("%s: want panic containing %q, got %q", what, want, msg)
	}
}

// No receive cap (Simion, 2026-10-11): every coin is freely transferable and
// tradable. A Fist-only player (hands, no tools) receives an r6 coin by Send,
// sends it on and swaps for more; stone traders (formerly capped at r3) buy r6
// by swap, list an order that WANTS r6 and receive r6 by fill.
func TestEx_NoReceiveCap(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	r6 := "dragon"
	if coinRarity[r6] != 6 {
		t.Fatalf("%s is not r6", r6)
	}
	lp := trader("free-lp")
	if !pools.Has(r6) {
		pools.Set(r6, &pool{coin: r6})
	}
	give(lp, r6, 200)
	give(lp, "grin", 20100) // 20000 staked + posting fees
	testing.SetRealm(testing.NewUserRealm(lp))
	AddLiquidity(cross(cur), r6, 100, 20000, 0, dl())

	// Send: Fist-only player receives r6 and sends some back
	fist := ta("free-fist")
	Transfer(cross(cur), r6, fist.String(), "10")
	if bal(fist, r6) != 10 {
		t.Errorf("fist got %d %s, want 10", bal(fist, r6), r6)
	}
	testing.SetRealm(testing.NewUserRealm(fist))
	Transfer(cross(cur), r6, lp.String(), "3")
	if bal(fist, r6) != 7 {
		t.Errorf("fist after send-on: %d", bal(fist, r6))
	}
	// no tool gate either: the Fist-only player buys more r6 by swap
	give(fist, "grin", 1000)
	if got := SwapExactIn(cross(cur), "grin", r6, 500, 1, dl()); got == 0 {
		t.Errorf("fist-only swap into r6 returned 0")
	}

	// Swap: stone-only trader buys r6
	st := trader("free-stone")
	give(st, "grin", 5000)
	testing.SetRealm(testing.NewUserRealm(st))
	if got := SwapExactIn(cross(cur), "grin", r6, 1000, 1, dl()); got == 0 || bal(st, r6) != got {
		t.Errorf("stone swap into r6: got %d bal %d", got, bal(st, r6))
	}
	// Order that wants r6 is accepted
	PlaceOrder(cross(cur), "grin", 600, r6, 1, 0)

	// Fill: lp lists r6 for grin; another stone-only trader fills and receives r6
	testing.SetRealm(testing.NewUserRealm(lp))
	PlaceOrder(cross(cur), r6, 2, "grin", 500, 0)
	st2 := trader("free-stone2")
	give(st2, "grin", 1000)
	testing.SetRealm(testing.NewUserRealm(st2))
	if got := FillOrders(cross(cur), "grin", r6, 600, 1, 5, dl()); got != 2 || bal(st2, r6) != 2 {
		t.Errorf("fill into r6: got %d bal %d", got, bal(st2, r6))
	}
}

// Trading is open to every account (Simion, 2026-10-11): a Fist-only player
// (no tools at all) swaps, posts an order, fills an order, stakes and unstakes.
func TestEx_FistOnlyTrades(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()
	lp := ta("fo-lp") // no tools either
	if !pools.Has("joy") {
		pools.Set("joy", &pool{coin: "joy"})
	}
	give(lp, "joy", 10200)
	give(lp, "grin", 10100)
	testing.SetRealm(testing.NewUserRealm(lp))
	AddLiquidity(cross(cur), "joy", 10000, 10000, 1, dl())
	PlaceOrder(cross(cur), "joy", 100, "grin", 120, 0) // for the Fist-only player to fill

	fist := ta("fo-fist")
	if ownedTools.Has(fist.String()) {
		t.Fatalf("test player must own no tools")
	}
	give(fist, "grin", 5000)
	testing.SetRealm(testing.NewUserRealm(fist))
	// swap
	if got := SwapExactIn(cross(cur), "grin", "joy", 500, 1, dl()); got == 0 || bal(fist, "joy") != got {
		t.Errorf("swap: got %d bal %d", got, bal(fist, "joy"))
	}
	// post (other side of the book, so no self-match with the fill below)
	if id := PlaceOrder(cross(cur), "grin", 300, "joy", 100, 0); id == 0 || openOrderCount(fist.String()) != 1 {
		t.Errorf("post: id %d open %d", id, openOrderCount(fist.String()))
	}
	// fill lp's joy order
	j0 := bal(fist, "joy")
	if got := FillOrders(cross(cur), "grin", "joy", 125, 1, 5, dl()); got == 0 || bal(fist, "joy")-j0 != got {
		t.Errorf("fill: got %d", got)
	}
	// stake and unstake
	sh := AddLiquidity(cross(cur), "joy", 200, 1000, 1, dl())
	if sh == 0 {
		t.Errorf("stake minted 0 shares")
	}
	c, g := RemoveLiquidity(cross(cur), "joy", sh, 1, 1, dl())
	if c == 0 || g == 0 {
		t.Errorf("unstake returned %d joy %d grin", c, g)
	}
}

exploit_test.gno

package game32

// The 12 game27/game28 exploit PoCs (SECURITY_GAME28.md), ported to game29.
// Convention here is the reverse of the audit copy: a test PASSES when the
// exploit is BLOCKED.

import (
	"chain"
	"strconv"
	"strings"
	"testing"
)

const forgedSig = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"

// H1a: forged dust bank with zero clicks + free Gnome Pass.
func TestH1a_ForgeDustBankWithFreePass(cur realm, t *testing.T) {
	setup()
	bot := ta("h1a-bot")
	testing.SetRealm(testing.NewUserRealm(bot))
	mustAbort(t, "free pass", revive(func() { ActivateGnomePass(cross(cur), 3650) }), "")
	mustAbort(t, "free pass 30d", revive(func() { ActivateGnomePass(cross(cur), 30) }), "attach exactly")
	if HasActivePass(bot.String()) {
		t.Errorf("pass still free")
	}
	// No server voucher → no claim, whatever the signature.
	mustAbort(t, "unvouchered claim", revive(func() {
		ClaimAndMint(cross(cur), `[["grin","1440"]]`, 1, 1234567890+600, forgedSig)
	}), "invalid voucher signature")
	if bal(bot, "grin") != 0 {
		t.Errorf("bot forged %d grin", bal(bot, "grin"))
	}
}

// H1b: dust refilling forever for a bot. A voucher is single use, so the bot
// can't reuse one after the bucket refills.
func TestH1b_DustRefillsForever(cur realm, t *testing.T) {
	setup()
	bot := ta("h1b-bot")
	payload := `[["grin","100"]]`
	n, e, s := voucher(t, "claim", bot, payload)
	testing.SetRealm(testing.NewUserRealm(bot))
	ClaimAndMint(cross(cur), payload, n, e, s) // one legit, vouchered claim
	testing.SkipHeights(720)                   // 1 h later the bucket is full again…
	mustAbort(t, "replay after refill", revive(func() { ClaimAndMint(cross(cur), payload, n, e, s) }), "")
	if bal(bot, "grin") != 100 {
		t.Errorf("grin=%d, want 100", bal(bot, "grin"))
	}
}

// H1c: made-up coin ids, even with a valid voucher.
func TestH1c_FakeCoinId(cur realm, t *testing.T) {
	setup()
	bot := ta("h1c-bot")
	payload := `[["fake-coin","50000"]]`
	n, e, s := voucher(t, "claim", bot, payload)
	testing.SetRealm(testing.NewUserRealm(bot))
	mustAbort(t, "fake coin", revive(func() { ClaimAndMint(cross(cur), payload, n, e, s) }), "unknown coin id")
}

// H1d: Fist mining mythic coins, even with a valid voucher.
func TestH1d_FistForgesMythic(cur realm, t *testing.T) {
	setup()
	bot := ta("h1d-bot")
	payload := `[["dragon","1"]]`
	n, e, s := voucher(t, "claim", bot, payload)
	testing.SetRealm(testing.NewUserRealm(bot))
	mustAbort(t, "fist→mythic", revive(func() { ClaimAndMint(cross(cur), payload, n, e, s) }), "cannot mine rarity")
	if bal(bot, "dragon") != 0 {
		t.Errorf("dragon minted")
	}
}

// H1e: zero-click tool climb. Without vouchers a script claims nothing, and a
// fresh bucket only holds 5 min of allowance (game28: a full hour).
func TestH1e_ZeroClickToolClimb(cur realm, t *testing.T) {
	setup()
	bot := ta("h1e-bot")
	testing.SetRealm(testing.NewUserRealm(bot))
	for i := 0; i < 5; i++ {
		_ = revive(func() { ClaimAndMint(cross(cur), `[["grin","24"]]`, int64(i+1), 1234567890+600, forgedSig) })
		testing.SkipHeights(13)
	}
	if bal(bot, "grin") != 0 {
		t.Errorf("zero-click bot got %d grin", bal(bot, "grin"))
	}
	mustAbort(t, "buy starter-twig", revive(func() { BuyTool(cross(cur), "starter-twig") }), "insufficient")
	fresh := ta("h1e-fresh")
	if a := allowanceFor(fresh, 0); a != 210 {
		t.Errorf("fresh dust allowance = %d, want 210 (5 min @ 42/min, year-plan dust headroom 1.75)", a)
	}
	// Even a vouchered claim can't exceed the 5-min grace bank.
	payload := `[["grin","1440"]]`
	n, e, s := voucher(t, "claim", fresh, payload)
	testing.SetRealm(testing.NewUserRealm(fresh))
	mustAbort(t, "1h bank on fresh wallet", revive(func() { ClaimAndMint(cross(cur), payload, n, e, s) }), "rate limit")
	if bal(fresh, "grin") != 0 {
		t.Errorf("fresh wallet got %d", bal(fresh, "grin"))
	}
}

// H1f: sybil funnel. Sybils can't mint without vouchers, so there's nothing
// to funnel; a voucher for one wallet doesn't work for another.
func TestH1f_SybilFunnel(cur realm, t *testing.T) {
	setup()
	main := ta("h1f-main")
	payload := `[["grin","100"]]`
	n, e, s := voucher(t, "claim", main, payload) // a real voucher for main
	for i := 0; i < 10; i++ {
		sy := ta("h1f-sybil-" + strconv.Itoa(i))
		testing.SetRealm(testing.NewUserRealm(sy))
		_ = revive(func() { ActivateGnomePass(cross(cur), 3650) })
		_ = revive(func() { ClaimAndMint(cross(cur), payload, n, e, s) }) // stolen voucher
		_ = revive(func() { Transfer(cross(cur), "grin", main.String(), "100") })
		if bal(sy, "grin") != 0 {
			t.Errorf("sybil %d minted", i)
		}
	}
	if bal(main, "grin") != 0 {
		t.Errorf("main received %d grin from sybils", bal(main, "grin"))
	}
}

// H2a: PvP reveal never checked against the commit.
func TestH2a_PvpRevealIgnoresCommit(cur realm, t *testing.T) {
	setup()
	alice, bob := ta("h2a-alice"), ta("h2a-bob")
	give(alice, "grin", 1000)
	give(bob, "grin", 1000)
	testing.SetRealm(testing.NewUserRealm(alice))
	lobby := CreatePvpLobby(cross(cur), "rps", "grin", "0")
	testing.SetRealm(testing.NewUserRealm(bob))
	JoinPvpLobby(cross(cur), lobby)
	testing.SetRealm(testing.NewUserRealm(alice))
	CommitPvpMove(cross(cur), lobby, h("rock", "a-salt"))
	testing.SetRealm(testing.NewUserRealm(bob))
	mustAbort(t, "non-hash commit", revive(func() { CommitPvpMove(cross(cur), lobby, "garbage") }), "64 hex")
	CommitPvpMove(cross(cur), lobby, h("scissors", "b-salt"))
	testing.SetRealm(testing.NewUserRealm(alice))
	RevealPvpMove(cross(cur), lobby, "rock", "a-salt")
	testing.SetRealm(testing.NewUserRealm(bob))
	mustAbort(t, "reveal different move", revive(func() { RevealPvpMove(cross(cur), lobby, "paper", "b-salt") }), "does not match")
	if strings.Contains(PvpLobby(lobby), `"status":"finished"`) {
		t.Errorf("a cheat reveal settled the lobby")
	}
}

// H2b: commits overwritable by anyone, any time, on any lobby id.
func TestH2b_CommitOverwrite(cur realm, t *testing.T) {
	setup()
	eve := ta("h2b-eve")
	testing.SetRealm(testing.NewUserRealm(eve))
	mustAbort(t, "commit on missing lobby", revive(func() { CommitPvpMove(cross(cur), "pvp-nonexistent-1", h("rock", "x")) }), "not in progress")
	a, b := ta("h2b-a"), ta("h2b-b")
	testing.SetRealm(testing.NewUserRealm(a))
	lobby := CreatePvpLobby(cross(cur), "rps", "grin", "0")
	testing.SetRealm(testing.NewUserRealm(b))
	JoinPvpLobby(cross(cur), lobby)
	testing.SetRealm(testing.NewUserRealm(eve))
	mustAbort(t, "outsider commit", revive(func() { CommitPvpMove(cross(cur), lobby, h("rock", "x")) }), "not a lobby participant")
	testing.SetRealm(testing.NewUserRealm(a))
	CommitPvpMove(cross(cur), lobby, h("rock", "1"))
	mustAbort(t, "overwrite", revive(func() { CommitPvpMove(cross(cur), lobby, h("paper", "2")) }), "already committed")
	if pvpLobbies.Get(lobby+":commit:"+a.String()).(string) != h("rock", "1") {
		t.Errorf("commit overwritten")
	}
}



// H2e: two lobbies in one block got the same id (escrow wiped).
func TestH2e_LobbyIdCollision(cur realm, t *testing.T) {
	setup()
	a, c := ta("coll-alice"), ta("coll-carol")
	give(a, "grin", 100)
	give(c, "grin", 100)
	testing.SetRealm(testing.NewUserRealm(a))
	id1 := CreatePvpLobby(cross(cur), "rps", "grin", "0")
	testing.SetRealm(testing.NewUserRealm(c))
	id2 := CreatePvpLobby(cross(cur), "rps", "grin", "0")
	if id1 == id2 {
		t.Errorf("lobby id collision: %s", id1)
	}
	if !strings.Contains(PvpLobby(id1), a.String()) {
		t.Errorf("alice's lobby record lost")
	}
}

// NEW (game28): any medal id claimable, tasks completable by anyone.
func TestNew_AnyMedalClaimable(cur realm, t *testing.T) {
	setup()
	p := ta("medal-farmer")
	payload := `["mythic-legend","made-up-medal"]`
	testing.SetRealm(testing.NewUserRealm(p))
	mustAbort(t, "unvouchered medals", revive(func() { BatchClaimAchievements(cross(cur), payload, 1, 1234567890+600, forgedSig) }), "invalid voucher")
	n, e, s := voucher(t, "ach", p, payload)
	testing.SetRealm(testing.NewUserRealm(p))
	got := BatchClaimAchievements(cross(cur), payload, n, e, s) // even with a voucher
	mustAbort(t, "CompleteTask", revive(func() { CompleteTask(cross(cur), "any-task") }), "operator-only")
	mustAbort(t, "CreateTask", revive(func() { CreateTask(cross(cur), "any-task", "x") }), "operator only")
	m := GetMedals(p.String())
	if got != 0 || strings.Contains(m, "made-up-medal") || strings.Contains(m, "mythic-legend") {
		t.Errorf("non-allowlisted medal claimed: %s", m)
	}
}

var _ = chain.NewCoin

// H2c: no casino refund once the server seed is revealed (two-sided commit/reveal).
func TestH2c_CasinoRefundAfterReveal(cur realm, t *testing.T) {
	adm := setup()
	seedCasino("joy", 1000000)
	p := ta("h2c-gambler")
	give(p, "joy", 100)
	testing.SetRealm(testing.NewUserRealm(adm))
	CommitCasinoSeed(cross(cur), "round-1", p.String(), h0("serverseed"))
	testing.SetRealm(testing.NewUserRealm(p))
	PlaceCasinoBet(cross(cur), "round-1", "coin_flip", "joy", "100", "heads", h0("cs"))
	testing.SetRealm(testing.NewUserRealm(adm))
	RevealCasinoSeed(cross(cur), "round-1", "serverseed")
	after := bal(p, "joy")
	testing.SkipHeights(2000)
	testing.SetRealm(testing.NewUserRealm(p))
	mustAbort(t, "refund after reveal", revive(func() { RefundCasinoBet(cross(cur), "round-1") }), "no refunds")
	if bal(p, "joy") != after {
		t.Errorf("refund after reveal paid out")
	}
}

// H2d: one bet per round, bound to its player; no bet after the reveal.
func TestH2d_BetAfterRevealAndOverwrite(cur realm, t *testing.T) {
	adm := setup()
	seedCasino("joy", 1000000)
	p, q := ta("h2d-gambler"), ta("h2d-other")
	give(p, "joy", 100)
	give(q, "joy", 100)
	testing.SetRealm(testing.NewUserRealm(adm))
	CommitCasinoSeed(cross(cur), "round-2", p.String(), h0("s2"))
	testing.SetRealm(testing.NewUserRealm(q))
	mustAbort(t, "other player's round", revive(func() { PlaceCasinoBet(cross(cur), "round-2", "coin_flip", "joy", "10", "heads", h0("x")) }), "another player")
	testing.SetRealm(testing.NewUserRealm(p))
	PlaceCasinoBet(cross(cur), "round-2", "coin_flip", "joy", "40", "heads", h0("cs"))
	mustAbort(t, "second bet", revive(func() { PlaceCasinoBet(cross(cur), "round-2", "coin_flip", "joy", "60", "tails", h0("cs")) }), "")
	testing.SetRealm(testing.NewUserRealm(adm))
	RevealCasinoSeed(cross(cur), "round-2", "s2")
	testing.SetRealm(testing.NewUserRealm(p))
	mustAbort(t, "bet after reveal", revive(func() { PlaceCasinoBet(cross(cur), "round-2", "coin_flip", "joy", "10", "heads", h0("cs")) }), "")
	b := casinoBets.Get("round-2:" + p.String()).(*casinoBet)
	if b.amount != 40 {
		t.Errorf("first bet overwritten: %d", b.amount)
	}
}

features_test.gno

package game32

import (
	"chain"
	"strconv"
	"strings"
	"testing"
	"time"
)

// ── Vouchers & replay ────────────────────────────────────────────────────────

func TestVoucher_ValidAndReplay(cur realm, t *testing.T) {
	setup()
	p := ta("v-player")
	payload := `[["grin","50"]]`
	n, e, s := voucher(t, "claim", p, payload)
	testing.SetRealm(testing.NewUserRealm(p))
	out := ClaimAndMint(cross(cur), payload, n, e, s)
	if bal(p, "grin") != 50 || out != `{"grin":50}` {
		t.Errorf("claim: bal=%d out=%s", bal(p, "grin"), out)
	}
	if LastNonce(p.String()) != n {
		t.Errorf("nonce not recorded")
	}
	testing.SkipHeights(13)
	mustAbort(t, "replay", revive(func() { ClaimAndMint(cross(cur), payload, n, e, s) }), "already used")
	if bal(p, "grin") != 50 {
		t.Errorf("replay credited")
	}
}

func TestVoucher_Rejections(cur realm, t *testing.T) {
	adm := setup()
	p, q := ta("v-p"), ta("v-q")
	payload := `[["grin","10"]]`
	now := time.Now().Unix()

	// voucher for p used by q
	n, e, s := voucher(t, "claim", p, payload)
	testing.SetRealm(testing.NewUserRealm(q))
	mustAbort(t, "other player", revive(func() { ClaimAndMint(cross(cur), payload, n, e, s) }), "invalid voucher signature")
	// tampered payload
	testing.SetRealm(testing.NewUserRealm(p))
	mustAbort(t, "tampered", revive(func() { ClaimAndMint(cross(cur), `[["grin","99"]]`, n, e, s) }), "invalid voucher signature")
	// wrong kind (an achievement voucher can't be used to claim)
	sa := sigFor(t, "ach", p, n, e, payload)
	mustAbort(t, "wrong kind", revive(func() { ClaimAndMint(cross(cur), payload, n, e, sa) }), "invalid voucher signature")
	// expired
	se := sigFor(t, "claim", p, n, now-1, payload)
	mustAbort(t, "expired", revive(func() { ClaimAndMint(cross(cur), payload, n, now-1, se) }), "expired")
	// expiry too far out
	sf := sigFor(t, "claim", p, n, now+3600, payload)
	mustAbort(t, "far expiry", revive(func() { ClaimAndMint(cross(cur), payload, n, now+3600, sf) }), "too far")
	// kill switch
	testing.SetRealm(testing.NewUserRealm(adm))
	SetClaimSigner(cross(cur), "")
	testing.SetRealm(testing.NewUserRealm(p))
	mustAbort(t, "signer disabled", revive(func() { ClaimAndMint(cross(cur), payload, n, e, s) }), "no claim signer")
	testing.SetRealm(testing.NewUserRealm(p))
	mustAbort(t, "non-admin SetClaimSigner", revive(func() { SetClaimSigner(cross(cur), testSignerPub) }), "admin only")
	testing.SetRealm(testing.NewUserRealm(adm))
	SetClaimSigner(cross(cur), testSignerPub)
	testing.SetRealm(testing.NewUserRealm(p))
	ClaimAndMint(cross(cur), payload, n, e, s)
	if bal(p, "grin") != 10 || bal(q, "grin") != 0 {
		t.Errorf("p=%d q=%d", bal(p, "grin"), bal(q, "grin"))
	}
}

// ── Rate caps ────────────────────────────────────────────────────────────────

func TestRateCap_RefillAndCooldown(cur realm, t *testing.T) {
	setup()
	p := ta("rate-p")
	// hands dust rate = 12 × 2.00 (dmg) × 1.75 (year-plan dust headroom) = 42/min;
	// a fresh wallet starts with a 5-min bank = 210.
	payload := `[["grin","200"]]`
	n, e, s := voucher(t, "claim", p, payload)
	testing.SetRealm(testing.NewUserRealm(p))
	ClaimAndMint(cross(cur), payload, n, e, s)

	payload = `[["grin","1"]]`
	n, e, s = voucher(t, "claim", p, payload)
	mustAbort(t, "cooldown", revive(func() { ClaimAndMint(cross(cur), payload, n, e, s) }), "too fast")
	testing.SkipHeights(13) // +65 s → 10 + 45 = 55 available
	payload = `[["grin","60"]]`
	n, e, s = voucher(t, "claim", p, payload)
	mustAbort(t, "over cap", revive(func() { ClaimAndMint(cross(cur), payload, n, e, s) }), "rate limit")
	testing.SkipHeights(13) // +65 s → 10 + 91 = 101
	payload = `[["grin","90"]]`
	n, e, s = voucher(t, "claim", p, payload)
	ClaimAndMint(cross(cur), payload, n, e, s)
	if bal(p, "grin") != 290 {
		t.Errorf("grin=%d want 290", bal(p, "grin"))
	}
	// the bank never exceeds 1 h of the tool's rate
	testing.SkipHeights(2000)
	if a := allowanceFor(p, 0); a != 2520 {
		t.Errorf("bank cap = %d, want 2520", a)
	}
}

func TestRateCap_VeinCap(cur realm, t *testing.T) {
	adm := setup()
	p := ta("vein-p")
	testing.SetRealm(testing.NewUserRealm(adm))
	SetVeinMax(cross(cur), "joy", strconv.FormatUint(veinMintedOf("joy")+30, 10))
	payload := `[["joy","100"]]`
	n, e, s := voucher(t, "claim", p, payload)
	testing.SetRealm(testing.NewUserRealm(p))
	out := ClaimAndMint(cross(cur), payload, n, e, s)
	if bal(p, "joy") != 30 || out != `{"joy":30}` {
		t.Errorf("vein cap not applied: %d %s", bal(p, "joy"), out)
	}
	testing.SetRealm(testing.NewUserRealm(adm))
	mustAbort(t, "vein below minted", revive(func() { SetVeinMax(cross(cur), "joy", "1") }), "below")
}

// ── Gnome Pass payment ───────────────────────────────────────────────────────

func TestPass_PaymentAndWithdraw(cur realm, t *testing.T) {
	adm := setup()
	p := ta("pass-buyer")
	price := PassPrice()
	testing.SetRealm(testing.NewUserRealm(p))
	testing.SetOriginSend(chain.Coins{chain.NewCoin("ugnot", 1)})
	mustAbort(t, "underpay", revive(func() { ActivateGnomePass(cross(cur), 30) }), "attach exactly")
	testing.SetOriginSend(chain.Coins{chain.NewCoin("ugnot", price*2)})
	mustAbort(t, "overpay", revive(func() { ActivateGnomePass(cross(cur), 30) }), "attach exactly")
	mustAbort(t, "bad duration", revive(func() { ActivateGnomePass(cross(cur), 45) }), "durationDays")
	testing.SetOriginSend(chain.Coins{chain.NewCoin("ugnot", price)})
	ActivateGnomePass(cross(cur), 30)
	now := time.Now().Unix()
	if GnomePassExpiry(p.String()) != now+30*86400 {
		t.Errorf("expiry %d", GnomePassExpiry(p.String()))
	}
	testing.SetOriginSend(chain.Coins{chain.NewCoin("ugnot", price*2)})
	ActivateGnomePass(cross(cur), 60) // stacks
	if GnomePassExpiry(p.String()) != now+90*86400 {
		t.Errorf("stacked expiry %d", GnomePassExpiry(p.String()))
	}
	if PassRevenue() != price*3 {
		t.Errorf("revenue %d", PassRevenue())
	}
	testing.SetOriginSend(nil)

	// Withdraw (the bank deposited the attached ugnot into the realm account).
	realmAddr := chain.PackageAddress(realmPkgPath)
	testing.IssueCoins(realmAddr, chain.Coins{chain.NewCoin("ugnot", price*3)})
	mustAbort(t, "non-admin withdraw", revive(func() { WithdrawFunds(cross(cur), p.String(), 1) }), "admin only")
	testing.SetRealm(testing.NewUserRealm(adm))
	out := ta("treasury-out")
	WithdrawFunds(cross(cur), out.String(), price*3)
	if TreasuryBalance() != 0 {
		t.Errorf("realm balance after withdraw %d", TreasuryBalance())
	}
	mustAbort(t, "overdraw", revive(func() { WithdrawFunds(cross(cur), out.String(), 1) }), "unwithdrawn pass revenue")
}

// TestWithdrawFunds_CannotExceedPassRevenue verifies that WithdrawFunds is
// strictly capped at passRevenueUgnot − adminGnotWithdrawn and cannot drain
// any ugnot that arrived through other means (e.g. donations or future
// features that hold player funds).
func TestWithdrawFunds_CannotExceedPassRevenue(cur realm, t *testing.T) {
	adm := setup()
	realmAddr := chain.PackageAddress(realmPkgPath)

	// Issue coins directly to the realm to simulate a "donation" beyond pass revenue.
	// passRevenueUgnot starts at 0 (no passes sold in this sub-test).
	donationAmount := int64(10000000) // 10 GNOT — not pass revenue
	testing.IssueCoins(realmAddr, chain.Coins{chain.NewCoin("ugnot", donationAmount)})

	// Admin must NOT be able to withdraw the donation — it exceeds pass revenue.
	testing.SetRealm(testing.NewUserRealm(adm))
	dst := ta("wd-dst")
	mustAbort(t, "withdraw donation beyond revenue",
		revive(func() { WithdrawFunds(cross(cur), dst.String(), 1) }),
		"unwithdrawn pass revenue")

	// Buy exactly one pass period so there is legitimate withdrawable revenue.
	price := PassPrice()
	buyer := ta("wd-buyer")
	testing.SetRealm(testing.NewUserRealm(buyer))
	testing.SetOriginSend(chain.Coins{chain.NewCoin("ugnot", price)})
	ActivateGnomePass(cross(cur), 30)
	testing.SetOriginSend(nil)
	testing.IssueCoins(realmAddr, chain.Coins{chain.NewCoin("ugnot", price)})

	// Withdrawing exactly the pass revenue must succeed.
	testing.SetRealm(testing.NewUserRealm(adm))
	WithdrawFunds(cross(cur), dst.String(), price)

	// A second withdraw of even 1 ugnot must fail (revenue exhausted).
	mustAbort(t, "second withdraw after full drain",
		revive(func() { WithdrawFunds(cross(cur), dst.String(), 1) }),
		"unwithdrawn pass revenue")

	// Withdrawable() must report 0.
	if got := WithdrawableFunds(); got != 0 {
		t.Errorf("WithdrawableFunds after drain = %d, want 0", got)
	}
}

// TestWithdrawProtocolFees_IsolatedFromCasinoAndPlayers verifies that
// WithdrawProtocolFees can only move the admin's own accrued share of
// protocol fees (adminFees[coin]) and cannot touch casinoPool or any player
// balance, even when those are substantially funded.
func TestWithdrawProtocolFees_IsolatedFromCasinoAndPlayers(cur realm, t *testing.T) {
	restore := exOpen()
	defer restore()

	adm := setup()
	player := ta("wpf-player")

	// Seed the player with coins and the casino pool with grin via accrueProtocolFee.
	give(player, "grin", 50000)
	casinoGrinBefore := getU(&casinoPool, "grin")

	// Accrue a known fee: accrueProtocolFee("grin", 200) splits 100 to adminFees,
	// 100 (or 99 due to integer div) to casinoPool.
	accrueProtocolFee("grin", 200)
	adminShare := getU(&adminFees, "grin")
	casinoShare := getU(&casinoPool, "grin") - casinoGrinBefore
	if adminShare == 0 {
		t.Fatal("expected non-zero adminFees after accrueProtocolFee")
	}

	// Non-admin must not be able to call WithdrawProtocolFees.
	testing.SetRealm(testing.NewUserRealm(player))
	mustAbort(t, "player fee withdraw",
		revive(func() { WithdrawProtocolFees(cross(cur), "grin") }),
		"admin only")

	// Snapshot player and casino balances before admin withdrawal.
	playerBalBefore := bal(player, "grin")
	casinoAfterAccrue := getU(&casinoPool, "grin")
	adminBalBefore := bal(adm, "grin")

	// Admin withdraws their protocol fees.
	testing.SetRealm(testing.NewUserRealm(adm))
	withdrawn := WithdrawProtocolFees(cross(cur), "grin")

	// Withdrawn amount must equal exactly the admin's accrued share.
	if withdrawn != adminShare {
		t.Errorf("withdrawn=%d, want adminShare=%d", withdrawn, adminShare)
	}

	// Admin balance must have increased by exactly withdrawn.
	if got := bal(adm, "grin"); got != adminBalBefore+withdrawn {
		t.Errorf("admin bal after = %d, want %d", got, adminBalBefore+withdrawn)
	}

	// Casino pool must be unchanged (not touched by the withdrawal).
	if got := getU(&casinoPool, "grin"); got != casinoAfterAccrue {
		t.Errorf("casinoPool after admin withdraw = %d, want %d (unchanged)", got, casinoAfterAccrue)
	}

	// Casino's incremental share must still be present.
	if casinoShare > 0 && getU(&casinoPool, "grin") < casinoGrinBefore+casinoShare {
		t.Errorf("casino lost coins during protocol fee withdrawal")
	}

	// Player balance must be unchanged.
	if got := bal(player, "grin"); got != playerBalBefore {
		t.Errorf("player bal after admin fee withdraw = %d, want %d (unchanged)", got, playerBalBefore)
	}

	// adminFees must now be zero for grin.
	if got := getU(&adminFees, "grin"); got != 0 {
		t.Errorf("adminFees[grin] after withdraw = %d, want 0", got)
	}

	// A second withdraw must panic (nothing to withdraw).
	mustAbort(t, "double withdraw",
		revive(func() { WithdrawProtocolFees(cross(cur), "grin") }),
		"no fees to withdraw")
}

// ── PvP ──────────────────────────────────────────────────────────────────────

func newMatch(cur realm, a, b address, game string, bet string) string {
	testing.SetRealm(testing.NewUserRealm(a))
	id := CreatePvpLobby(cross(cur), game, "grin", bet)
	testing.SetRealm(testing.NewUserRealm(b))
	JoinPvpLobby(cross(cur), id)
	return id
}

// legacyLobby builds a lobby that escrowed a wager before wagers were switched off.
func legacyLobby(cur realm, a address, bet uint64) string {
	testing.SetRealm(testing.NewUserRealm(a))
	id := CreatePvpLobby(cross(cur), "rps", "grin", "0")
	debitBal(a.String(), "grin", bet)
	lset(id, "bet", strconv.FormatUint(bet, 10))
	pvpWagers.Set(id, "grin:"+strconv.FormatUint(bet, 10)+":"+a.String()+":")
	return id
}

func winnerIs(id string, w address) bool {
	return strings.Contains(PvpLobby(id), `"winner":"`+w.String()+`"`)
}

// Decision 5: PvP wagers are off until rewritten. A bet is refused; a lobby
// escrowed before the switch can't be joined or revealed, only refunded.
func TestPvp_WagersOff(cur realm, t *testing.T) {
	setup()
	a, b := ta("pvpw-a"), ta("pvpw-b")
	give(a, "grin", 1000)
	give(b, "grin", 1000)
	testing.SetRealm(testing.NewUserRealm(a))
	mustAbort(t, "wager lobby", revive(func() { CreatePvpLobby(cross(cur), "rps", "grin", "100") }), "wagers are off")
	if bal(a, "grin") != 1000 {
		t.Errorf("refused wager moved coins: %d", bal(a, "grin"))
	}
	id := legacyLobby(cur, a, 100)
	testing.SetRealm(testing.NewUserRealm(b))
	mustAbort(t, "join wagered lobby", revive(func() { JoinPvpLobby(cross(cur), id) }), "wagers are off")
	// a legacy lobby that was already joined: reveal refused, timeout refunds both
	id2 := legacyLobby(cur, a, 100)
	debitBal(b.String(), "grin", 100)
	pvpWagers.Set(id2, "grin:100:"+a.String()+":"+b.String())
	lset(id2, "challenger", b.String())
	lset(id2, "status", "joined")
	testing.SetRealm(testing.NewUserRealm(a))
	CommitPvpMove(cross(cur), id2, h("rock", "1"))
	testing.SetRealm(testing.NewUserRealm(b))
	CommitPvpMove(cross(cur), id2, h("paper", "2"))
	mustAbort(t, "reveal wagered lobby", revive(func() { RevealPvpMove(cross(cur), id2, "paper", "2") }), "wagers are off")
	testing.SkipHeights(121)
	ClaimPvpTimeout(cross(cur), id2)
	if bal(a, "grin") != 900 || bal(b, "grin") != 1000 {
		t.Errorf("timeout refund: a=%d b=%d", bal(a, "grin"), bal(b, "grin"))
	}
	testing.SetRealm(testing.NewUserRealm(a))
	CancelPvpLobby(cross(cur), id)
	if bal(a, "grin") != 1000 {
		t.Errorf("cancel refund: a=%d", bal(a, "grin"))
	}
}

func TestPvp_HashedRoundPaysWinner(cur realm, t *testing.T) {
	adm := setup()
	a, b := ta("pvp-a"), ta("pvp-b")
	give(a, "grin", 1000)
	give(b, "grin", 1000)
	_ = adm
	id := newMatch(cur, a, b, "rps", "0")
	if strings.Contains(OpenLobbies(), id) {
		t.Errorf("joined lobby still listed as open")
	}
	testing.SetRealm(testing.NewUserRealm(a))
	CommitPvpMove(cross(cur), id, h("rock", "sa"))
	testing.SetRealm(testing.NewUserRealm(b))
	mustAbort(t, "reveal before both commit", revive(func() { RevealPvpMove(cross(cur), id, "scissors", "sb") }), "both players")
	CommitPvpMove(cross(cur), id, h("scissors", "sb"))
	RevealPvpMove(cross(cur), id, "scissors", "sb")
	testing.SetRealm(testing.NewUserRealm(a))
	RevealPvpMove(cross(cur), id, "rock", "sa")
	if !winnerIs(id, a) || bal(a, "grin") != 1000 || bal(b, "grin") != 1000 {
		t.Errorf("winner/balances: %s a=%d b=%d", PvpLobby(id), bal(a, "grin"), bal(b, "grin"))
	}
	if !strings.Contains(PvpLobby(id), `"status":"finished"`) || !strings.Contains(PvpLobby(id), a.String()) {
		t.Errorf("lobby %s", PvpLobby(id))
	}
}

func TestPvp_InvalidChoiceForfeits(cur realm, t *testing.T) {
	setup()
	a, b := ta("pvpf-a"), ta("pvpf-b")
	give(a, "grin", 100)
	give(b, "grin", 100)
	id := newMatch(cur, a, b, "rps", "0")
	testing.SetRealm(testing.NewUserRealm(a))
	CommitPvpMove(cross(cur), id, h("lizard", "x")) // not an rps move
	testing.SetRealm(testing.NewUserRealm(b))
	CommitPvpMove(cross(cur), id, h("rock", "y"))
	testing.SetRealm(testing.NewUserRealm(a))
	RevealPvpMove(cross(cur), id, "lizard", "x")
	if !winnerIs(id, b) {
		t.Errorf("forfeit: %s", PvpLobby(id))
	}
}

func TestPvp_Timeouts(cur realm, t *testing.T) {
	setup()
	a, b, c, d := ta("pvpt-a"), ta("pvpt-b"), ta("pvpt-c"), ta("pvpt-d")
	for _, x := range []address{a, b, c, d} {
		give(x, "grin", 100)
	}
	// 1) only a commits, b stalls → a wins after the timeout
	id := newMatch(cur, a, b, "rps", "0")
	testing.SetRealm(testing.NewUserRealm(a))
	CommitPvpMove(cross(cur), id, h("rock", "1"))
	mustAbort(t, "early timeout", revive(func() { ClaimPvpTimeout(cross(cur), id) }), "not yet")
	testing.SkipHeights(121)
	ClaimPvpTimeout(cross(cur), id)
	if !winnerIs(id, a) {
		t.Errorf("committer timeout win: %s", PvpLobby(id))
	}
	// 2) nobody commits → refund both
	id2 := newMatch(cur, c, d, "coin_flip", "0")
	testing.SkipHeights(121)
	testing.SetRealm(testing.NewUserRealm(d))
	ClaimPvpTimeout(cross(cur), id2)
	if bal(c, "grin") != 100 || bal(d, "grin") != 100 {
		t.Errorf("refund: c=%d d=%d", bal(c, "grin"), bal(d, "grin"))
	}
	// 3) open lobby nobody joins → creator cancels and is refunded
	id3 := legacyLobby(cur, c, 40)
	testing.SetRealm(testing.NewUserRealm(d))
	mustAbort(t, "cancel by other", revive(func() { CancelPvpLobby(cross(cur), id3) }), "only the creator")
	testing.SetRealm(testing.NewUserRealm(c))
	CancelPvpLobby(cross(cur), id3)
	if bal(c, "grin") != 100 {
		t.Errorf("cancel refund: c=%d", bal(c, "grin"))
	}
	testing.SetRealm(testing.NewUserRealm(d))
	mustAbort(t, "join cancelled", revive(func() { JoinPvpLobby(cross(cur), id3) }), "not open")
}

func TestPvp_CoinFlipFairBit(cur realm, t *testing.T) {
	setup()
	a, b := ta("pvpc-a"), ta("pvpc-b")
	give(a, "grin", 10)
	give(b, "grin", 10)
	id := newMatch(cur, a, b, "coin_flip", "0")
	testing.SetRealm(testing.NewUserRealm(a))
	CommitPvpMove(cross(cur), id, h("heads", "s1"))
	testing.SetRealm(testing.NewUserRealm(b))
	CommitPvpMove(cross(cur), id, h("tails", "s2"))
	RevealPvpMove(cross(cur), id, "tails", "s2")
	testing.SetRealm(testing.NewUserRealm(a))
	RevealPvpMove(cross(cur), id, "heads", "s1")
	x := sha256Sum("s1:s2")
	outcome := "heads"
	if (hexNibble(x[1]) & 1) == 1 {
		outcome = "tails"
	}
	winner := a
	if outcome == "tails" {
		winner = b
	}
	if !winnerIs(id, winner) {
		t.Errorf("outcome %s, winner bal %d (a=%d b=%d)", outcome, bal(winner, "grin"), bal(a, "grin"), bal(b, "grin"))
	}
}

func hexNibble(c byte) byte {
	if c >= 'a' {
		return c - 'a' + 10
	}
	return c - '0'
}

// ── Casino ───────────────────────────────────────────────────────────────────



// ── Achievements ─────────────────────────────────────────────────────────────

func TestAchievements_AllowlistAndFixedRewards(cur realm, t *testing.T) {
	setup()
	p := ta("ach-p")
	pl := `["blocks_1"]`
	n, e, s := voucher(t, "ach", p, pl)
	testing.SetRealm(testing.NewUserRealm(p))
	ClaimAchievement(cross(cur), "blocks_1", n, e, s)
	if bal(p, "grin") != 4 || !HasAchievement(p.String(), "blocks_1") {
		t.Errorf("blocks_1 reward: grin=%d", bal(p, "grin"))
	}
	n, e, s = voucher(t, "ach", p, pl)
	testing.SetRealm(testing.NewUserRealm(p))
	mustAbort(t, "claim twice", revive(func() { ClaimAchievement(cross(cur), "blocks_1", n, e, s) }), "already claimed")
	// grind medal needs real lifetime mining
	gp := `["g.grin.10"]`
	n, e, s = voucher(t, "ach", p, gp)
	testing.SetRealm(testing.NewUserRealm(p))
	mustAbort(t, "unearned grind", revive(func() { ClaimAchievement(cross(cur), "g.grin.10", n, e, s) }), "not earned")
	cp := `[["grin","20"]]`
	n, e, s = voucher(t, "claim", p, cp)
	testing.SetRealm(testing.NewUserRealm(p))
	ClaimAndMint(cross(cur), cp, n, e, s)
	bp := `["g.grin.10","g.grin.100","nope"]`
	n, e, s = voucher(t, "ach", p, bp)
	testing.SetRealm(testing.NewUserRealm(p))
	if got := BatchClaimAchievements(cross(cur), bp, n, e, s); got != 1 {
		t.Errorf("batch claimed %d, want 1 (g.grin.10 only)", got)
	}
	if bal(p, "grin") != 4+20+10 {
		t.Errorf("grin=%d want 34", bal(p, "grin"))
	}
	// medal credits: claiming g.grin.10 (and blocks_1) does NOT change
	// LifetimeMined or the miners leaderboard; rewards have their own counter.
	if got := getU(&lifetimeMined, p.String()+":grin"); got != 20 {
		t.Errorf("lifetimeMined grin=%d want 20 (real claims only)", got)
	}
	if got := getU(&rewarded, p.String()+":grin"); got != 14 {
		t.Errorf("rewarded grin=%d want 14", got)
	}
	if got := getU(&miners, p.String()); got != 20 {
		t.Errorf("miners=%d want 20", got)
	}
	if !strings.Contains(LifetimeMined(p.String()), `"grin":20`) || !strings.Contains(Rewarded(p.String()), `"grin":14`) {
		t.Errorf("views: %s / %s", LifetimeMined(p.String()), Rewarded(p.String()))
	}
}

// Vein sizes follow the year-plan rule; crossing 50% is exposed/emitted;
// exhaustion caps credits (the client reports the shortfall).
func TestVein_ResizedAndHalfFlag(cur realm, t *testing.T) {
	adm := setup()
	var r1, r6 string
	for c, r := range coinRarity {
		if r == 1 && r1 == "" && c != "grin" {
			r1 = c
		}
		if r == 6 && r6 == "" {
			r6 = c
		}
	}
	if veinMax(r1) != 82_000_000 || veinMax(r6) != 85_000_000 || veinMax("grin") != 102_000_000 {
		t.Errorf("vein sizes r1 %d r6 %d grin %d", veinMax(r1), veinMax(r6), veinMax("grin"))
	}
	testing.SetRealm(testing.NewUserRealm(adm))
	SetVeinMax(cross(cur), "joy", strconv.FormatUint(veinMintedOf("joy")+100, 10))
	if strings.Contains(VeinSupply("joy"), `"exhausted":true`) {
		t.Errorf("fresh vein exhausted: %s", VeinSupply("joy"))
	}
	takeFromVein("joy", 60)
	if !strings.Contains(VeinSupply("joy"), `"exhausted":false`) {
		t.Errorf("not exhausted yet: %s", VeinSupply("joy"))
	}
	if got := takeFromVein("joy", 60); got != 40 {
		t.Errorf("overflow credited %d want 40", got)
	}
	if !strings.Contains(VeinSupply("joy"), `"halfMinted":true`) || !strings.Contains(VeinSupply("joy"), `"exhausted":true`) {
		t.Errorf("flags: %s", VeinSupply("joy"))
	}
}

// ── Migration ────────────────────────────────────────────────────────────────

func TestMigration_IdempotentAndFinal(cur realm, t *testing.T) {
	adm := setup()
	u := ta("mig-user").String()
	rows := `[["` + u + `","coffee","500"],["` + u + `","bogus","9"]]`
	testing.SetRealm(testing.NewUserRealm(ta("mig-eve")))
	mustAbort(t, "non-admin migrate", revive(func() { MigrateBatch(cross(cur), "b1", "balance", rows) }), "admin only")
	testing.SetRealm(testing.NewUserRealm(adm))
	v0 := veinMintedOf("coffee")
	if n := MigrateBatch(cross(cur), "b1", "balance", rows); n != 1 {
		t.Errorf("applied %d rows, want 1", n)
	}
	if n := MigrateBatch(cross(cur), "b1", "balance", rows); n != 0 {
		t.Errorf("re-run applied %d", n)
	}
	MigrateBatch(cross(cur), "b1-again", "balance", rows) // same rows, new id: SET semantics
	if balOf(u, "coffee") != 500 || veinMintedOf("coffee")-v0 != 500 {
		t.Errorf("not idempotent: bal=%d vein+%d", balOf(u, "coffee"), veinMintedOf("coffee")-v0)
	}
	MigrateBatch(cross(cur), "t1", "tools", `[["`+u+`","starter-twig,twig,laser-of-doom"]]`)
	MigrateBatch(cross(cur), "m1", "medal", `[["`+u+`","blocks_1"],["`+u+`","made-up"]]`)
	MigrateBatch(cross(cur), "l1", "lifetime", `[["`+u+`","grin","1000"]]`)
	MigrateBatch(cross(cur), "l2", "lifetime", `[["`+u+`","grin","1000"]]`)
	if OwnedTools(u) != `["starter-twig","twig"]` || !HasAchievement(u, "blocks_1") || HasAchievement(u, "made-up") || getU(&miners, u) != 1000 {
		t.Errorf("tools=%s medals=%s miners=%d", OwnedTools(u), GetMedals(u), getU(&miners, u))
	}
	FinalizeMigration(cross(cur))
	mustAbort(t, "after finalize", revive(func() { MigrateBatch(cross(cur), "b2", "balance", rows) }), "finalized")
	if !strings.Contains(MigrationStatus(), `"finalized":true`) {
		t.Errorf("status %s", MigrationStatus())
	}
}

// ── Misc fixes ───────────────────────────────────────────────────────────────

func TestMisc_BuyToolLifeLeaderboardJsonRender(cur realm, t *testing.T) {
	setup()
	p := ta("misc-p")
	give(p, "grin", 1000)
	testing.SetRealm(testing.NewUserRealm(p))
	BuyTool(cross(cur), "starter-twig")
	for _, c := range toolCosts["twig"] {
		n, _ := strconv.ParseUint(c[1], 10, 64)
		give(p, c[0], n)
	}
	BuyTool(cross(cur), "twig")
	if toolMaxLife["twig"] > 0 && getU(&toolLife, p.String()+":twig") != effectiveMaxLife(p.String(), "twig") {
		t.Errorf("BuyTool did not set toolLife: %s", ToolLife(p.String()))
	}
	mustAbort(t, "buy twice", revive(func() { BuyTool(cross(cur), "twig") }), "already own")

	setU(&miners, ta("lb-small").String(), 5)
	setU(&miners, ta("lb-big").String(), 5_000_000)
	lb := AllMiners(200, 0)
	if !strings.HasPrefix(lb, `[{"address":"`+ta("lb-big").String()) {
		t.Errorf("leaderboard not sorted by score: %s", lb[:120])
	}

	g := ta("misc-guild")
	testing.SetRealm(testing.NewUserRealm(g))
	gid := CreateGuild(cross(cur), `Evil","leader":"x`)
	info := GuildInfo(gid)
	if strings.Contains(info, `"leader":"x"`) {
		t.Errorf("guild JSON injection: %s", info)
	}
	if !strings.Contains(Render(""), "game29") {
		t.Errorf("Render: %s", Render(""))
	}
}

// ── PlayerXp ─────────────────────────────────────────────────────────────────

func TestPlayerXp_AccumulatesOnClaim(cur realm, t *testing.T) {
	setup()
	p := ta("xp-player")

	// Baseline: fresh player has 0 XP.
	if got := PlayerXp(p.String()); got != "0" {
		t.Errorf("initial XP want 0 got %s", got)
	}

	// Claim 10 grin (rarity 0 → 3 XP each) = 30 XP.
	payload := `[["grin","10"]]`
	n, e, s := voucher(t, "claim", p, payload)
	testing.SetRealm(testing.NewUserRealm(p))
	ClaimAndMint(cross(cur), payload, n, e, s)

	wantXp := uint64(10 * 3) // 10 coins × 3 XP (dust rarity)
	gotXp := getU(&playerXp, p.String())
	if gotXp != wantXp {
		t.Errorf("after grin claim: want XP %d got %d (PlayerXp=%s)", wantXp, gotXp, PlayerXp(p.String()))
	}

	// PlayerXp query must return the same value as a decimal string.
	if PlayerXp(p.String()) != strconv.FormatUint(wantXp, 10) {
		t.Errorf("PlayerXp query mismatch: want %d got %s", wantXp, PlayerXp(p.String()))
	}

	// Upgrade to stone tool (maxRarity=2) so the second claim can mine music.
	// Chain: hands → starter-twig → twig → wood → stone.
	testing.SetRealm(testing.NewUserRealm(p))
	for _, cost := range toolCosts["starter-twig"] {
		n, _ := strconv.ParseUint(cost[1], 10, 64)
		give(p, cost[0], n)
	}
	BuyTool(cross(cur), "starter-twig")
	for _, cost := range toolCosts["twig"] {
		n, _ := strconv.ParseUint(cost[1], 10, 64)
		give(p, cost[0], n)
	}
	BuyTool(cross(cur), "twig")
	for _, cost := range toolCosts["wood"] {
		n, _ := strconv.ParseUint(cost[1], 10, 64)
		give(p, cost[0], n)
	}
	BuyTool(cross(cur), "wood")
	for _, cost := range toolCosts["stone"] {
		n, _ := strconv.ParseUint(cost[1], 10, 64)
		give(p, cost[0], n)
	}
	BuyTool(cross(cur), "stone")

	// Second claim: add a higher-rarity coin. music is rarity 2 → 20 XP each.
	testing.SkipHeights(13) // skip cooldown
	payload2 := `[["music","5"]]`
	n2, e2, s2 := voucher(t, "claim", p, payload2)
	testing.SetRealm(testing.NewUserRealm(p))
	ClaimAndMint(cross(cur), payload2, n2, e2, s2)

	wantXp2 := wantXp + uint64(5*20) // +100 XP
	gotXp2 := getU(&playerXp, p.String())
	if gotXp2 != wantXp2 {
		t.Errorf("after music claim: want XP %d got %d", wantXp2, gotXp2)
	}

	// XP accumulates across players independently.
	q := ta("xp-q")
	if PlayerXp(q.String()) != "0" {
		t.Errorf("unrelated player should have 0 XP, got %s", PlayerXp(q.String()))
	}
}

game_admin.gno

package game32

import (
	"encoding/hex"
	"strconv"
	"strings"
	"time"

	"chain"
	"chain/banker"
)

func init(cur realm) {
	// The deployer (tx signer of addpkg) becomes admin and default operator.
	admin = address(cur.Previous().Address())
	operator = admin
}

// ── Roles ────────────────────────────────────────────────────────────────────

func isAdmin(cur realm) bool {
	return admin != address("") && cur.Previous().Address() == admin
}

func requireAdmin(cur realm) {
	if !isAdmin(cur) {
		panic("unauthorized: admin only")
	}
}


// TransferAdmin hands the admin role to another address.
func TransferAdmin(cur realm, newAdmin string) {
	requireAdmin(cur)
	transferAdmin(newAdmin)
}

func transferAdmin(newAdmin string) {
	a := address(newAdmin)
	if !a.IsValid() {
		panic("invalid address")
	}
	admin = a
}

// UpdateConfig is kept for game27/28 API compatibility (= TransferAdmin).
func UpdateConfig(cur realm, newAdmin string) {
	requireAdmin(cur)
	transferAdmin(newAdmin)
}


// SetClaimSigner registers the ed25519 public key (64 hex chars) of the
// server's claim signer. Pass "" to disable all vouchered calls (kill switch).
func SetClaimSigner(cur realm, pubKeyHex string) {
	requireAdmin(cur)
	if pubKeyHex == "" {
		claimSignerPubKey = nil
		return
	}
	b, err := hex.DecodeString(pubKeyHex)
	if err != nil || len(b) != 32 {
		panic("claim signer must be a 32-byte ed25519 public key in hex")
	}
	claimSignerPubKey = b
}

func ClaimSigner() string { return hex.EncodeToString(claimSignerPubKey) }
func Admin() string       { return admin.String() }

func SetPaused(cur realm, p bool) {
	requireAdmin(cur)
	paused = p
}

func IsPaused() bool { return paused }

func requireNotPaused() {
	if paused {
		panic("game is paused")
	}
}

// ── Blacklist ─────────────────────────────────────────────────────────────────

// BanAddress bans a player address. durationSecs=0 means permanent.
func BanAddress(cur realm, targetAddr string, reason string, durationSecs int64) {
	requireAdmin(cur)
	if !address(targetAddr).IsValid() {
		panic("invalid address")
	}
	expiry := int64(0)
	if durationSecs > 0 {
		expiry = time.Now().Unix() + durationSecs
	}
	blacklist.Set(targetAddr, strings.ReplaceAll(reason, ":", " ")+":"+strconv.FormatInt(time.Now().Unix(), 10))
	banExpiries.Set(targetAddr, strconv.FormatInt(expiry, 10))
}

func UnbanAddress(cur realm, targetAddr string) {
	requireAdmin(cur)
	blacklist.Remove(targetAddr)
	banExpiries.Remove(targetAddr)
}

func BlacklistStatus(addr string) string {
	if !blacklist.Has(addr) {
		return `{"banned":false}`
	}
	entry := blacklist.Get(addr).(string)
	expiry, _ := strconv.ParseInt(banExpiries.Get(addr).(string), 10, 64)
	now := time.Now().Unix()
	if expiry > 0 && now >= expiry {
		return `{"banned":false}`
	}
	reason := strings.SplitN(entry, ":", 2)[0]
	if expiry == 0 {
		return `{"banned":true,"reason":` + jsonStr(reason) + `,"permanent":true}`
	}
	return `{"banned":true,"reason":` + jsonStr(reason) + `,"permanent":false,"remainingSecs":` + strconv.FormatInt(expiry-now, 10) + `}`
}

func isBlacklisted(addr string) bool {
	if !blacklist.Has(addr) {
		return false
	}
	expiry, _ := strconv.ParseInt(banExpiries.Get(addr).(string), 10, 64)
	if expiry == 0 {
		return true
	}
	return time.Now().Unix() < expiry
}

func requirePlayer(cur realm) string {
	requireNotPaused()
	caller := cur.Previous().Address().String()
	if isBlacklisted(caller) {
		panic("address banned")
	}
	return caller
}

// ── Veins ────────────────────────────────────────────────────────────────────

func veinMax(coinId string) uint64 {
	// FIX 2B: skip AVL read when no overrides have ever been set.
	if veinOverrideActive && veinMaxOverride.Has(coinId) {
		v, _ := strconv.ParseUint(veinMaxOverride.Get(coinId).(string), 10, 64)
		return v
	}
	r, ok := coinRarity[coinId]
	if !ok {
		return 0
	}
	if v, ok := veinCoinDefault[coinId]; ok {
		return v
	}
	return veinDefaultMax[r]
}

func veinMintedOf(coinId string) uint64 {
	if !veinMinted.Has(coinId) {
		return 0
	}
	v, _ := strconv.ParseUint(veinMinted.Get(coinId).(string), 10, 64)
	return v
}

// takeFromVein returns how much of amt can still be minted for coinId and
// records it as minted.
func takeFromVein(coinId string, amt uint64) uint64 {
	mx := veinMax(coinId)
	mi := veinMintedOf(coinId)
	if mi >= mx {
		return 0
	}
	if amt > mx-mi {
		amt = mx - mi
	}
	veinMinted.Set(coinId, strconv.FormatUint(mi+amt, 10))
	if half := mx / 2; mi < half && mi+amt >= half {
		chain.Emit("VeinHalfMinted", "coin", coinId,
			"minted", strconv.FormatUint(mi+amt, 10), "max", strconv.FormatUint(mx, 10))
	}
	if mi+amt == mx {
		chain.Emit("VeinExhausted", "coin", coinId, "max", strconv.FormatUint(mx, 10))
	}
	return amt
}

// SetVeinMax overrides a coin's vein size. It can't go below what was minted.
func SetVeinMax(cur realm, coinId string, maxSupply string) {
	requireAdmin(cur)
	setVeinMax(coinId, maxSupply)
}

func setVeinMax(coinId string, maxSupply string) {
	if _, ok := coinRarity[coinId]; !ok {
		panic("unknown coin id: " + coinId)
	}
	mx, err := strconv.ParseUint(maxSupply, 10, 64)
	if err != nil {
		panic("invalid max supply")
	}
	if mx < veinMintedOf(coinId) {
		panic("vein max below already-minted supply")
	}
	veinMaxOverride.Set(coinId, strconv.FormatUint(mx, 10))
	veinOverrideActive = true
}

// RegisterVein is the game28 name for SetVeinMax.
func RegisterVein(cur realm, coinId string, maxSupply string) {
	requireAdmin(cur)
	setVeinMax(coinId, maxSupply)
}

func VeinSupply(coinId string) string {
	if _, ok := coinRarity[coinId]; !ok {
		return `{"remaining":"0","max":"0"}`
	}
	mx := veinMax(coinId)
	mi := veinMintedOf(coinId)
	rem := uint64(0)
	if mx > mi {
		rem = mx - mi
	}
	return `{"remaining":"` + strconv.FormatUint(rem, 10) + `","max":"` + strconv.FormatUint(mx, 10) + `","minted":"` + strconv.FormatUint(mi, 10) + `","halfMinted":` + strconv.FormatBool(mx > 0 && mi >= mx/2) + `,"exhausted":` + strconv.FormatBool(mx > 0 && mi >= mx) + `}`
}

// ── Gnome Pass (paid) ────────────────────────────────────────────────────────

// SetPassPrice sets the ugnot price per 30-day period.
func SetPassPrice(cur realm, ugnotPer30Days int64) {
	requireAdmin(cur)
	if ugnotPer30Days <= 0 {
		panic("price must be > 0")
	}
	passPriceUgnot = ugnotPer30Days
}

func PassPrice() int64 { return passPriceUgnot }

// ActivateGnomePass buys durationDays (30..360, multiple of 30) of Gnome Pass.
// The tx must attach exactly passPrice × durationDays/30 ugnot (MsgCall send).
func ActivateGnomePass(cur realm, durationDays int64) {
	caller := requirePlayer(cur)
	// Payment verification must only trust the origin envelope when the
	// caller is the signer itself (no intermediate realm can consume it).
	if cur.Previous().PkgPath() != "" {
		panic("Gnome Pass must be bought directly by the player")
	}
	if durationDays <= 0 || durationDays%30 != 0 || durationDays > 360 {
		panic("durationDays must be 30, 60, ... 360")
	}
	periods := durationDays / 30
	required := passPriceUgnot * periods
	sent := banker.NewBanker(banker.BankerTypeOriginSend, cur).GetCoins(cur.Address())
	if len(sent) != 1 || sent[0].Denom != "ugnot" || sent[0].Amount != required {
		panic("Gnome Pass costs " + strconv.FormatInt(required, 10) + "ugnot for " + strconv.FormatInt(durationDays, 10) + " days — attach exactly that amount")
	}
	passRevenueUgnot += required

	now := time.Now().Unix()
	base := now
	if gnomePasses.Has(caller) {
		existing, _ := strconv.ParseInt(gnomePasses.Get(caller).(string), 10, 64)
		if existing > now {
			base = existing
		}
	}
	gnomePasses.Set(caller, strconv.FormatInt(base+durationDays*86400, 10))
}

func GnomePassExpiry(addr string) int64 {
	if !gnomePasses.Has(addr) {
		return 0
	}
	expiry, _ := strconv.ParseInt(gnomePasses.Get(addr).(string), 10, 64)
	return expiry
}

func HasActivePass(addr string) bool { return GnomePassExpiry(addr) > time.Now().Unix() }

func GnomePassCount() int {
	count := 0
	now := time.Now().Unix()
	gnomePasses.Iterate("", "", func(_ string, val any) bool {
		e, _ := strconv.ParseInt(val.(string), 10, 64)
		if e > now {
			count++
		}
		return false
	})
	return count
}

func PassRevenue() int64 { return passRevenueUgnot }

// TreasuryBalance returns the ugnot held by this realm (pass revenue not yet withdrawn).
func TreasuryBalance(cur realm) int64 {
	realmAddr := chain.PackageAddress("gno.land/r/g138gdmwj6heduu3st796lw6qqdwylgaxf7ty5gz/game32")
	coins := banker.NewBanker(banker.BankerTypeReadonly, cur).GetCoins(realmAddr)
	for _, c := range coins {
		if c.Denom == "ugnot" {
			return c.Amount
		}
	}
	return 0
}

// WithdrawFunds sends GNOT the admin is OWED — Gnome Pass revenue not yet
// withdrawn — to `to`. It can never touch other ugnot the realm holds
// (donations, anything a future feature would hold for players).
func WithdrawFunds(cur realm, to string, amountUgnot int64) {
	requireAdmin(cur)
	dst := address(to)
	if !dst.IsValid() {
		panic("invalid address")
	}
	if amountUgnot <= 0 {
		panic("amount must be > 0")
	}
	if amountUgnot > passRevenueUgnot-adminGnotWithdrawn {
		panic("can only withdraw unwithdrawn pass revenue: " + strconv.FormatInt(passRevenueUgnot-adminGnotWithdrawn, 10) + "ugnot")
	}
	adminGnotWithdrawn += amountUgnot
	b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	b.SendCoins(cur.Address(), dst, chain.Coins{chain.NewCoin("ugnot", amountUgnot)})
	chain.Emit("FundsWithdrawn", "to", to, "ugnot", strconv.FormatInt(amountUgnot, 10))
}

// WithdrawableFunds = pass revenue the admin may still withdraw (ugnot).
func WithdrawableFunds() int64 { return passRevenueUgnot - adminGnotWithdrawn }

// ── Migration (game31 → game32) ──────────────────────────────────────────────
//
// MigrateBatch(batchId, kind, rowsJson) imports one batch. rowsJson is a JSON
// array of string arrays. Kinds and row shapes:
//   balance  [addr, coinId, amount]       → balances (SET, not add)
//   lifetime [addr, coinId, amount]       → lifetimeMined (SET) + miners total
//   tools    [addr, "t1,t2,..."]          → ownedTools (SET, unknown ids dropped)
//   toollife [addr, toolId, life]         → toolLife (SET, clamped to max)
//   skill    [addr, skillId, rank]        → skillRanks (SET, clamped to max)
//   medal    [addr, achievementId]        → achievements (allowlisted ids only)
//   pass     [addr, expiryUnix]           → gnomePasses (SET)
//   guild    [guildId, name, leader, "m1,m2,..."] → guilds + members
//   ban      [addr, reason, expiryUnix]   → blacklist (expiry 0 = permanent)
// A batchId that was already applied is skipped, and every write is a SET, so
// re-running a whole migration is a no-op. FinalizeMigration locks it forever.
// Every unique player address in a batch is recorded in migrationAddrs so that
// MigrationStatus can report how many distinct players were migrated.
func MigrateBatch(cur realm, batchId string, kind string, rowsJson string) int {
	requireAdmin(cur)
	if migrationFinalized {
		panic("migration is finalized")
	}
	if batchId == "" {
		panic("batchId required")
	}
	if migrationBatches.Has(batchId) {
		return 0
	}
	rows := parseStringRows(rowsJson)
	n := 0
	for _, r := range rows {
		if migrateRow(kind, r) {
			n++
			// Track the player address for the migrated-count in MigrationStatus.
			// For player-scoped kinds the address is always r[0]; guild rows use a
			// guild ID, not a player address, so we skip them.
			if kind != "guild" && len(r) > 0 && validAddr(r[0]) {
				migrationAddrs.Set(r[0], "1")
			}
		}
	}
	migrationBatches.Set(batchId, kind+":"+strconv.Itoa(n))
	return n
}

func FinalizeMigration(cur realm) {
	requireAdmin(cur)
	migrationFinalized = true
}

// MigrationStatus returns a JSON object with:
//   - finalized: bool   — true once FinalizeMigration has been called
//   - batches:   int    — number of distinct batch IDs applied
//   - addresses: int    — number of distinct player addresses migrated across all batches
func MigrationStatus() string {
	return `{"finalized":` + strconv.FormatBool(migrationFinalized) +
		`,"batches":` + strconv.Itoa(migrationBatches.Size()) +
		`,"addresses":` + strconv.Itoa(migrationAddrs.Size()) + `}`
}

func MigrationBatch(batchId string) string {
	if !migrationBatches.Has(batchId) {
		return ""
	}
	return migrationBatches.Get(batchId).(string)
}

func validAddr(s string) bool { return address(s).IsValid() }

func migrateRow(kind string, r []string) bool {
	switch kind {
	case "balance", "lifetime":
		if len(r) != 3 || !validAddr(r[0]) {
			return false
		}
		if _, ok := coinRarity[r[1]]; !ok {
			return false
		}
		amt, err := strconv.ParseUint(r[2], 10, 64)
		if err != nil {
			return false
		}
		key := r[0] + ":" + r[1]
		if kind == "balance" {
			old := getU(&balances, key)
			// Imported balances count against the vein (delta on re-run).
			if amt > old {
				mi := veinMintedOf(r[1])
				veinMinted.Set(r[1], strconv.FormatUint(mi+(amt-old), 10))
			}
			setU(&balances, key, amt)
		} else {
			old := getU(&lifetimeMined, key)
			setU(&lifetimeMined, key, amt)
			tot := getU(&miners, r[0])
			if tot >= old {
				tot -= old
			} else {
				tot = 0
			}
			setU(&miners, r[0], tot+amt)
		}
		return true
	case "tools":
		if len(r) != 2 || !validAddr(r[0]) {
			return false
		}
		var keep []string
		seen := map[string]bool{}
		for _, t := range strings.Split(r[1], ",") {
			t = strings.TrimSpace(t)
			if t == "" || t == "hands" || seen[t] {
				continue
			}
			if _, ok := toolCosts[t]; !ok {
				continue
			}
			seen[t] = true
			keep = append(keep, t)
		}
		if len(keep) == 0 {
			ownedTools.Remove(r[0])
		} else {
			ownedTools.Set(r[0], strings.Join(keep, ","))
		}
		return true
	case "toollife":
		if len(r) != 3 || !validAddr(r[0]) {
			return false
		}
		mx, ok := toolMaxLife[r[1]]
		if !ok || mx == 0 {
			return false
		}
		life, err := strconv.ParseUint(r[2], 10, 64)
		if err != nil {
			return false
		}
		if em := effectiveMaxLife(r[0], r[1]); life > em {
			life = em
		}
		setU(&toolLife, r[0]+":"+r[1], life)
		return true
	case "skill":
		if len(r) != 3 || !validAddr(r[0]) {
			return false
		}
		mx, ok := skillMaxRanks[r[1]]
		if !ok {
			return false
		}
		rank, err := strconv.ParseUint(r[2], 10, 64)
		if err != nil {
			return false
		}
		if rank > mx {
			rank = mx
		}
		setU(&skillRanks, r[0]+":"+r[1], rank)
		return true
	case "medal":
		if len(r) != 2 || !validAddr(r[0]) || !isValidAchievementId(r[1]) {
			return false
		}
		achievements.Set(r[0]+":"+r[1], "1")
		return true
	case "pass":
		if len(r) != 2 || !validAddr(r[0]) {
			return false
		}
		e, err := strconv.ParseInt(r[1], 10, 64)
		if err != nil || e <= 0 {
			return false
		}
		gnomePasses.Set(r[0], strconv.FormatInt(e, 10))
		return true
	case "guild":
		if len(r) != 4 || r[0] == "" || !validAddr(r[2]) {
			return false
		}
		name := sanitizeName(r[1])
		if len(name) < 3 {
			return false
		}
		members := []string{}
		for _, m := range strings.Split(r[3], ",") {
			m = strings.TrimSpace(m)
			if validAddr(m) && len(members) < maxGuildMembers {
				members = append(members, m)
			}
		}
		if len(members) == 0 {
			return false
		}
		// Drop stale membership rows of this guild, then write fresh ones.
		var stale []string
		guildMembers.Iterate(r[0]+":", r[0]+";", func(k string, _ any) bool {
			stale = append(stale, k)
			return false
		})
		for _, k := range stale {
			guildMembers.Remove(k)
		}
		for _, m := range members {
			guildMembers.Set(r[0]+":"+m, "1")
			playerGuild.Set(m, r[0])
		}
		guildMetas[r[0]] = guildMeta{name: name, leader: r[2], createdAt: time.Now().Unix()}
		rewriteGuild(r[0])
		return true
	case "ban":
		if len(r) != 3 || !validAddr(r[0]) {
			return false
		}
		e, err := strconv.ParseInt(r[2], 10, 64)
		if err != nil || e < 0 {
			return false
		}
		blacklist.Set(r[0], strings.ReplaceAll(r[1], ":", " ")+":"+strconv.FormatInt(time.Now().Unix(), 10))
		banExpiries.Set(r[0], strconv.FormatInt(e, 10))
		return true
	}
	panic("unknown migration kind: " + kind)
}

game_casino.gno

package game32

import (
	"crypto/sha256"
	"encoding/hex"
	"math/bits"
	"strconv"
	"strings"
	"time"

	"chain"

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

// ── Casino: two-sided commit–reveal, settled and paid on chain ──────────────
//
// One round = one bet by one player:
//   1. CommitCasinoSeed(roundId, player, sha256(s))        operator
//        s is 32 fresh random bytes for this round, kept by the server.
//   2. PlaceCasinoBet(roundId, game, coin, amt, choice, sha256(c))   the player
//        c is the player's secret (made and kept by the browser). The stake is
//        debited and the bet's largest possible net win is reserved in the pool.
//   3. RevealCasinoSeed(roundId, s)                        operator
//        s must hash to the commit. The operator still doesn't know c, so it
//        doesn't know the result when it reveals.
//   4. RevealCasinoSecret(roundId, c)                      anyone (a preimage)
//        c must hash to the bet's hash; the realm rolls and settles the bet.
// Timeouts (nobody can profit from withholding):
//   - s not revealed 30 min after the bet → RefundCasinoBet (full stake back).
//   - s revealed but c not revealed within 24 h → ForfeitCasinoBet (anyone):
//     the bet settles as a loss; only the player could have known the result.
//   No refund once s is revealed.
//
// Results (the only rules; the client re-derives and shows them):
//   roll = uint32(sha256(s:c:roundId:game)[0:4]) % 100
//   coin_flip:    0..48 heads, 51..99 tails, 49/50 edge (house)      win pays 2×
//   higher_lower: 51..99 higher, 0..48 lower, 49/50 house              win pays 2×
//   rps:          0..32 player wins (2×), 33..64 push (stake back), 65..99 house
//                 wins; the house move shown is derived from that. RTP 98%.
//   slots:        reels/lines/scatters/Hold & Spin from the stream in game_slots.gno;
//                 free spins and MAJOR/GRAND jackpots in game_casino_bonus.gno.
//
// Pool safety (fixed in code):
//   coin_flip / wheel / rps bet ≤ 0.5% of the free pool; slots bet ≤ 0.004%
//   (its 500× max win then reserves ≤ 2% of the pool); every open bet reserves
//   its largest net win; open reservations ≤ 20% of the pool; net paid today +
//   reservations ≤ 10% of the pool at 00:00 UTC; opens at ≥ 20,000 grin-eq and
//   ≥ 200 units. Coins only move between players and the pool: nothing is
//   minted, and the admin can't withdraw the pool.

var (
	casinoBets     avl.Tree // roundId+":"+addr → *casinoBet
	casinoReserved avl.Tree // coin → largest net payouts of unsettled bets (string)
	casinoDay      avl.Tree // coin → "day:snapshot:paid:received" (UTC day)
)

const (
	casinoWinRange         = uint64(49)       // winning rolls per pick (of 100) for flip/wheel
	rpsWinBelow            = uint64(33)       // rps: roll < 33 player wins
	rpsPushBelow           = uint64(65)       // rps: 33..64 push
	casinoBetWindowSec     = int64(3600)      // a committed round takes its bet within 1 h
	casinoSeedTimeoutSec   = int64(1800)      // refunds open 30 min after the bet if s is never revealed
	casinoSecretTimeoutSec = int64(86400)     // the bet forfeits 24 h after s if c is never revealed
	casinoMaxBetBps        = uint64(50)       // flip / wheel / rps bet ≤ 0.5% of the free pool
	slotsMaxBetPPM         = uint64(40)       // slots bet ≤ 0.004% of the free pool
	casinoOpenBps          = uint64(2000)     // open reservations on a coin ≤ 20% of the pool
	casinoDayBps           = uint64(1000)     // daily net payout ≤ 10% of the day's snapshot
	casinoMinPoolMilli     = uint64(20000000) // ≥ 20,000 grin-equivalent …
	casinoMinPoolUnits     = uint64(200)      // … and ≥ 200 units of the coin
	casinoMaxAmount        = uint64(1000000000)
)

// Reference value per unit by rarity, in milli-grin (same table as the
// exchange plan): only used for the pool's opening threshold.
var casinoRefMilli = [7]uint64{1000, 3200, 11000, 40000, 160000, 720000, 3600000}

type casinoRound struct {
	player      string
	seedHash    string
	serverSeed  string
	status      string // committed | bet | seeded | settled | refunded | closed
	committedAt int64
	betAt       int64
	seededAt    int64
	bets        int
}

type casinoBet struct {
	addr, game, coin, choice string
	clientHash, clientSecret string
	amount, exposure         uint64
	settled, won, refunded   bool
	forfeited                bool
	roll, payout             uint64
	outcome                  string
	// slots only
	grid       string
	lineMult   uint64
	lines      int
	scatters   int
	freeSpin   bool   // a free spin from a grant (no stake)
	capped     bool   // the round's win hit the 500× cap
	fsGranted  uint64 // free spins this spin granted
	hsTiles    string // Hold & Spin tiles ("." separated, 0 = empty)
	hsRespins  int
	hsMult     uint64 // Hold & Spin win in bets (MINI/MINOR included)
	jackpots   string // "major", "grand", "major+grand" or ""
	jackpotWin uint64 // paid from the jackpot pools (outside the cap)
}

// ── roles ────────────────────────────────────────────────────────────────────

// isOperator: the casino operator key commits and reveals server seeds. Once an
// operator is set, only that key can; the admin (treasury) key only stands in
// while no operator has been named yet (bootstrap and tests).
func isOperator(cur realm) bool {
	c := cur.Previous().Address()
	if operator != address("") {
		return c == operator
	}
	return admin != address("") && c == admin
}

// SetOperator lets the admin name the server account that commits and
// reveals casino seeds. It must be its own key, never the admin/treasury key.
// The operator can't move anyone's coins.
func SetOperator(cur realm, addr string) {
	if cur.Previous().Address() != admin {
		panic("unauthorized: admin only")
	}
	a := address(addr)
	if !a.IsValid() {
		panic("invalid address")
	}
	if a == admin {
		panic("the casino operator must be a separate key, not the admin/treasury key")
	}
	operator = a
	chain.Emit("CasinoOperatorSet", "operator", addr)
}

func Operator() string { return operator.String() }

// ── casino accounting (monitoring) ──────────────────────────────────────────
//
// Per coin: pool + MAJOR + GRAND == seeded + staked − paid, always. Per coin and
// game: rounds, staked, paid (free spins and jackpots count as slots pay), so
// realized RTP = paid / staked. Updated on every settlement; read by CasinoStats.

var casinoStats avl.Tree // coin:field or coin:game:field → uint (string)

func casStat(coin, game, field string, add uint64) {
	k := coin + ":" + field
	if game != "" {
		k = coin + ":" + game + ":" + field
	}
	casSet(&casinoStats, k, casAdd(casGet(&casinoStats, k), add))
}

func casRecord(coin, game string, staked, paid uint64) {
	casStat(coin, game, "rounds", 1)
	casStat(coin, game, "staked", staked)
	casStat(coin, game, "paid", paid)
	casStat(coin, "", "staked", staked)
	casStat(coin, "", "paid", paid)
}

// CasinoStats reports a coin's accounting: pool, reserved, jackpots, seeded,
// staked, paid, the conservation check and per-game rounds/staked/paid.
func CasinoStats(coinId string) string {
	pool := casGet(&casinoPool, coinId)
	major := casGet(&casinoJackpot, jpKey(coinId, "major"))
	grand := casGet(&casinoJackpot, jpKey(coinId, "grand"))
	seeded := casGet(&casinoStats, coinId+":seeded")
	staked := casGet(&casinoStats, coinId+":staked")
	paid := casGet(&casinoStats, coinId+":paid")
	fees := casGet(&casinoStats, coinId+":fees") // exchange protocol-fee inflow
	ok := pool+major+grand+paid == seeded+staked+fees
	out := `{"coin":"` + coinId + `","pool":"` + casU(pool) + `","reserved":"` + casU(casGet(&casinoReserved, coinId)) +
		`","major":"` + casU(major) + `","grand":"` + casU(grand) + `","seeded":"` + casU(seeded) +
		`","staked":"` + casU(staked) + `","paid":"` + casU(paid) + `","fees":"` + casU(fees) + `","conserved":` + strconv.FormatBool(ok) +
		`,"freeSpinsOpen":` + strconv.Itoa(casinoGrants.Size()) + `,"games":{`
	for i, g := range []string{"coin_flip", "higher_lower", "rps", "slots"} {
		if i > 0 {
			out += ","
		}
		out += `"` + g + `":{"rounds":` + casU(casGet(&casinoStats, coinId+":"+g+":rounds")) +
			`,"staked":"` + casU(casGet(&casinoStats, coinId+":"+g+":staked")) +
			`","paid":"` + casU(casGet(&casinoStats, coinId+":"+g+":paid")) + `"}`
	}
	return out + `}}`
}

// ── uint helpers (balances and pool values are decimal strings) ─────────────

func casGet(t *avl.Tree, key string) uint64 {
	if !t.Has(key) {
		return 0
	}
	v, _ := strconv.ParseUint(t.Get(key).(string), 10, 64)
	return v
}

func casSet(t *avl.Tree, key string, v uint64) { t.Set(key, strconv.FormatUint(v, 10)) }

func casAdd(a, b uint64) uint64 {
	s, carry := bits.Add64(a, b, 0)
	if carry != 0 {
		panic("math overflow")
	}
	return s
}

func casSub(a, b uint64) uint64 {
	if b > a {
		panic("math underflow")
	}
	return a - b
}

// casMulDiv = floor(a*b/c) with a 128-bit product.
func casMulDiv(a, b, c uint64) uint64 {
	hi, lo := bits.Mul64(a, b)
	if hi >= c {
		panic("math overflow")
	}
	q, _ := bits.Div64(hi, lo, c)
	return q
}

func casMul(a, b uint64) uint64 {
	hi, lo := bits.Mul64(a, b)
	if hi != 0 {
		panic("math overflow")
	}
	return lo
}

func casU(n uint64) string { return strconv.FormatUint(n, 10) }

func casBalOf(addr, coin string) uint64 { return casGet(&balances, addr+":"+coin) }

func casCredit(addr, coin string, amt uint64) {
	if amt > 0 {
		casSet(&balances, addr+":"+coin, casAdd(casBalOf(addr, coin), amt))
	}
}

func casDebit(addr, coin string, amt uint64) {
	have := casBalOf(addr, coin)
	if have < amt {
		panic("insufficient balance: need " + casU(amt) + " " + coin + ", have " + casU(have))
	}
	casSet(&balances, addr+":"+coin, have-amt)
}

func casGrinValueMilli(coin string, amt uint64) uint64 {
	r, ok := coinRarity[coin]
	if !ok || r < 0 || r > 6 {
		return 0
	}
	hi, lo := bits.Mul64(amt, casinoRefMilli[r])
	if hi != 0 {
		return ^uint64(0)
	}
	return lo
}

func casIsHex64(s string) bool {
	if len(s) != 64 {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
			return false
		}
	}
	return true
}

// casSafe: a short [A-Za-z0-9_.-] token (no quotes, so it is JSON-safe).
func casSafe(s string, maxLen int) bool {
	if s == "" || len(s) > maxLen {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.') {
			return false
		}
	}
	return true
}

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

// ── outcome rules (the only ones; the client just re-derives them) ──────────

// CasinoRoll is the on-chain roll: uint32(sha256(s:c:roundId:game)[0:4]) % 100.
func CasinoRoll(serverSeed, clientSecret, roundId, game string) uint64 {
	h := sha256.Sum256([]byte(serverSeed + ":" + clientSecret + ":" + roundId + ":" + game))
	v := uint64(h[0])<<24 | uint64(h[1])<<16 | uint64(h[2])<<8 | uint64(h[3])
	return v % 100
}

// CasinoOutcome maps a roll to what landed. For rps the outcome is
// "win" | "push" | "lose" (see rpsHouseMove for the move shown).
func CasinoOutcome(game string, roll uint64) string {
	switch game {
	case "coin_flip":
		if roll < casinoWinRange {
			return "heads"
		}
		if roll >= 100-casinoWinRange {
			return "tails"
		}
		return "edge"
	case "higher_lower":
		if roll >= 100-casinoWinRange {
			return "higher"
		}
		if roll < casinoWinRange {
			return "lower"
		}
		return "house"
	case "rps":
		if roll < rpsWinBelow {
			return "win"
		}
		if roll < rpsPushBelow {
			return "push"
		}
		return "lose"
	}
	return ""
}

// rpsHouseMove: the house move that produces the outcome against the player's move.
func rpsHouseMove(choice, outcome string) string {
	beats := map[string]string{"rock": "scissors", "paper": "rock", "scissors": "paper"} // key beats value
	switch outcome {
	case "win":
		return beats[choice]
	case "push":
		return choice
	}
	for k, v := range beats {
		if v == choice {
			return k
		}
	}
	return ""
}

func validCasinoChoice(game, choice string) bool {
	switch game {
	case "coin_flip":
		return choice == "heads" || choice == "tails"
	case "higher_lower":
		return choice == "higher" || choice == "lower"
	case "rps":
		return choice == "rock" || choice == "paper" || choice == "scissors"
	case "slots":
		return casSafe(choice, 32)
	}
	return false
}

// casinoExposure: the largest net amount a bet can take from the pool.
func casinoExposure(game string, amt uint64) uint64 {
	if game == "slots" {
		return casMul(amt, slotsMaxWinMult-1)
	}
	return amt // flip / wheel / rps win pays 2× = net +amt
}

// ── pool ────────────────────────────────────────────────────────────────────

func casDayNow() int64 { return time.Now().Unix() / 86400 }

func casinoDayState(coin string) (int64, uint64, uint64, uint64) {
	day := casDayNow()
	if casinoDay.Has(coin) {
		f := strings.Split(casinoDay.Get(coin).(string), ":")
		d, _ := strconv.ParseInt(f[0], 10, 64)
		if d == day && len(f) == 4 {
			snap, _ := strconv.ParseUint(f[1], 10, 64)
			paid, _ := strconv.ParseUint(f[2], 10, 64)
			recv, _ := strconv.ParseUint(f[3], 10, 64)
			return day, snap, paid, recv
		}
	}
	return day, casGet(&casinoPool, coin), 0, 0 // first touch of the day: snapshot the pool
}

func setCasinoDay(coin string, day int64, snap, paid, recv uint64) {
	casinoDay.Set(coin, strconv.FormatInt(day, 10)+":"+casU(snap)+":"+casU(paid)+":"+casU(recv))
}

func casinoIsOpen(coin string, pool uint64) bool {
	return pool >= casinoMinPoolUnits && casGrinValueMilli(coin, pool) >= casinoMinPoolMilli
}

func casinoMaxBet(game string, free uint64) uint64 {
	if game == "slots" {
		m := casMulDiv(free, slotsMaxBetPPM, 1000000)
		return m - m%slotsBetStep
	}
	return casMulDiv(free, casinoMaxBetBps, 10000)
}

// casinoCheckBet panics unless the pool can pay the bet's largest win in full (read-only).
func casinoCheckBet(coin, game string, amt uint64) {
	pool := casGet(&casinoPool, coin)
	reserved := casGet(&casinoReserved, coin)
	if !casinoIsOpen(coin, pool) {
		panic("casino closed for " + coin + ": the pool needs at least 20,000 grin-equivalent and 200 " + coin)
	}
	if game == "slots" && (amt < slotsBetStep || amt%slotsBetStep != 0) {
		panic("slots bet must be a multiple of 25")
	}
	free := casSub(pool, reserved)
	maxBet := casinoMaxBet(game, free)
	if amt > maxBet {
		if game == "slots" {
			panic("bet too large: slots max is 0.004 percent of the free casino pool (" + casU(maxBet) + " " + coin + ")")
		}
		panic("bet too large: max is 0.5 percent of the free casino pool (" + casU(maxBet) + " " + coin + ")")
	}
	exp := casinoExposure(game, amt)
	if casAdd(reserved, exp) > casMulDiv(pool, casinoOpenBps, 10000) {
		panic("casino busy: open bets on " + coin + " would exceed 20 percent of the pool")
	}
	_, snap, paid, recv := casinoDayState(coin)
	net := uint64(0)
	if paid > recv {
		net = paid - recv
	}
	if casAdd(casAdd(net, reserved), exp) > casMulDiv(snap, casinoDayBps, 10000) {
		panic("casino daily payout limit reached for " + coin)
	}
}

func casinoReserve(coin string, exp uint64) {
	casSet(&casinoReserved, coin, casAdd(casGet(&casinoReserved, coin), exp))
	day, snap, paid, recv := casinoDayState(coin)
	setCasinoDay(coin, day, snap, paid, recv)
}

// casinoSettle releases the reservation and moves coins: the player receives
// `payout` (0 ≤ payout ≤ stake + exposure) and the pool keeps the rest of the
// stake or pays the difference. Returns payout.
func casinoSettle(addr, coin string, amt, exposure, payout uint64) uint64 {
	if payout > casAdd(amt, exposure) {
		panic("payout above the reservation")
	}
	casSet(&casinoReserved, coin, casSub(casGet(&casinoReserved, coin), exposure))
	day, snap, paid, recv := casinoDayState(coin)
	pool := casGet(&casinoPool, coin)
	if payout >= amt {
		win := payout - amt
		casSet(&casinoPool, coin, casSub(pool, win))
		setCasinoDay(coin, day, snap, casAdd(paid, win), recv)
	} else {
		keep := amt - payout
		casSet(&casinoPool, coin, casAdd(pool, keep))
		setCasinoDay(coin, day, snap, paid, casAdd(recv, keep))
	}
	casCredit(addr, coin, payout)
	return payout
}

// SeedCasinoPool moves the ADMIN'S OWN on-chain coins into a casino pool.
// Only ever the admin's own balance; nobody can withdraw a pool back.
func SeedCasinoPool(cur realm, coinId string, amount string) {
	if cur.Previous().Address() != admin {
		panic("unauthorized: admin only")
	}
	if _, ok := coinRarity[coinId]; !ok {
		panic("unknown coin id: " + coinId)
	}
	amt, err := strconv.ParseUint(amount, 10, 64)
	if err != nil || amt == 0 || amt > casinoMaxAmount {
		panic("invalid amount")
	}
	from := admin.String()
	casDebit(from, coinId, amt)
	casSet(&casinoPool, coinId, casAdd(casGet(&casinoPool, coinId), amt))
	casStat(coinId, "", "seeded", amt)
	chain.Emit("CasinoPoolSeeded", "coin", coinId, "from", from, "amount", amount)
}

// CasinoPool reports a coin's pool, reservation, max bets and daily counters.
func CasinoPool(coinId string) string {
	pool := casGet(&casinoPool, coinId)
	reserved := casGet(&casinoReserved, coinId)
	_, snap, paid, recv := casinoDayState(coinId)
	free := uint64(0)
	if pool > reserved {
		free = pool - reserved
	}
	return `{"coin":"` + coinId + `","pool":"` + casU(pool) + `","reserved":"` + casU(reserved) +
		`","maxBet":"` + casU(casinoMaxBet("coin_flip", free)) + `","slotsMaxBet":"` + casU(casinoMaxBet("slots", free)) +
		`","open":` + strconv.FormatBool(casinoIsOpen(coinId, pool)) +
		`,"daySnapshot":"` + casU(snap) + `","paidToday":"` + casU(paid) + `","receivedToday":"` + casU(recv) + `"}`
}

game_casino_bonus.gno

package game32

import (
	"strconv"
	"time"

	"chain"

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

// ── Slots bonus features, all settled by the realm ──────────────────────────
//
// Free spins: 3/4/5 scatters on a paid spin grant 10/12/15 free spins at that
// spin's bet. The grant is a realm record (one open grant per player). The
// triggering spin keeps its 500× reservation for the whole feature, minus what
// it already paid, so every free spin can always be paid in full. A free spin is
// its own two-sided round (PlaceCasinoFreeSpin takes no stake); its wins are
// doubled, it pays from that reservation, scatters don't retrigger and vaults
// don't start Hold & Spin. The grant never expires for the player.
//
// Hold & Spin: 3+ vaults on a paid spin. Resolved inside that spin's settlement
// from the same seed stream (game_slots.gno). Coin tiles pay 1/2/3/5× the bet,
// MINI 20×, MINOR 75× (all under the 500× cap). The first MAJOR / GRAND tile
// pays that jackpot pool (extra ones pay as MINOR); a full board (20 tiles) also
// awards GRAND.
//
// MAJOR / GRAND jackpots: real pools per coin, fed with 1.0% / 0.5% of every
// paid slots stake (fractions carried exactly). A hit pays
// pool × min(1, bet / refBet); the rest stays. A pool can never pay more than
// it holds. After a hit the pool is topped back up to its reset seed from the
// house pool, only while the free house pool is ≥ 20× that top-up. The admin
// can add its own coins to a jackpot but nobody can withdraw one.

var (
	casinoGrants  avl.Tree // addr → *freeSpinGrant
	casinoJackpot avl.Tree // coin:tier → pool (string)
	casinoJpDust  avl.Tree // coin:tier → contribution remainder in bet×bps units (string)
	casinoJpSeed  avl.Tree // coin:tier → reset seed (string)
	casinoJpRef   avl.Tree // coin → reference bet (string)
)

const (
	freeSpinMult        = uint64(2)
	jpMajorBps          = uint64(100) // 1.0% of each paid slots stake
	jpGrandBps          = uint64(50)  // 0.5%
	jpDefaultRefBet     = uint64(100)
	jpResetFreeMultiple = uint64(20)
	hsMiniMult          = uint64(20)
	hsMinorMult         = uint64(75)
)

type freeSpinGrant struct {
	addr, coin string
	bet        uint64
	left       uint64
	total      uint64
	capLeft    uint64 // still reserved in casinoReserved for this feature
	won        uint64
	inRound    string
	fromRound  string
	grantedAt  int64
}

func getGrant(addr string) *freeSpinGrant {
	if !casinoGrants.Has(addr) {
		return nil
	}
	return casinoGrants.Get(addr).(*freeSpinGrant)
}

func jpKey(coin, tier string) string { return coin + ":" + tier }

func jpRefBet(coin string) uint64 {
	if v := casGet(&casinoJpRef, coin); v > 0 {
		return v
	}
	return jpDefaultRefBet
}

// casinoJackpotContribute moves 1.0% / 0.5% of a paid slots stake from the house
// pool into the MAJOR / GRAND pools (remainders carried, nothing rounded away).
func casinoJackpotContribute(coin string, amt uint64) {
	for _, t := range [2]struct {
		tier string
		bps  uint64
	}{{"major", jpMajorBps}, {"grand", jpGrandBps}} {
		k := jpKey(coin, t.tier)
		dust := casAdd(casGet(&casinoJpDust, k), casMul(amt, t.bps))
		units := dust / 10000
		if units == 0 {
			casSet(&casinoJpDust, k, dust)
			continue
		}
		pool := casGet(&casinoPool, coin)
		if pool < casAdd(casGet(&casinoReserved, coin), units) {
			casSet(&casinoJpDust, k, dust) // house can't spare it right now: keep it owed
			continue
		}
		casSet(&casinoJpDust, k, dust%10000)
		casSet(&casinoPool, coin, pool-units)
		casSet(&casinoJackpot, k, casAdd(casGet(&casinoJackpot, k), units))
		day, snap, paid, recv := casinoDayState(coin)
		setCasinoDay(coin, day, snap, casAdd(paid, units), recv)
	}
}

// casinoJackpotPay pays a jackpot tier to addr: pool × min(1, bet/refBet).
func casinoJackpotPay(addr, coin, tier string, bet uint64) uint64 {
	k := jpKey(coin, tier)
	pool := casGet(&casinoJackpot, k)
	ref := jpRefBet(coin)
	pay := pool
	if bet < ref {
		pay = casMulDiv(pool, bet, ref)
	}
	casSet(&casinoJackpot, k, pool-pay)
	casCredit(addr, coin, pay)
	chain.Emit("CasinoJackpotWon", "player", addr, "coin", coin, "tier", tier, "amount", casU(pay))
	// Top back up to the reset seed from the house pool, only if the house can easily afford it.
	seed := casGet(&casinoJpSeed, k)
	left := pool - pay
	if seed > left {
		need := seed - left
		house := casGet(&casinoPool, coin)
		reserved := casGet(&casinoReserved, coin)
		if house > reserved && house-reserved >= casMul(need, jpResetFreeMultiple) {
			casSet(&casinoPool, coin, house-need)
			casSet(&casinoJackpot, k, seed)
			day, snap, paid, recv := casinoDayState(coin)
			setCasinoDay(coin, day, snap, casAdd(paid, need), recv)
		}
	}
	return pay
}

// slotsHSPayout turns Hold & Spin tiles into bet multiples (under the cap) and
// the jackpot tiers won (paid from their pools).
func slotsHSPayout(tiles *[slotsCells]uint16, full bool) (uint64, bool, bool) {
	mult := uint64(0)
	major, grand := false, false
	for i := 0; i < slotsCells; i++ {
		v := tiles[i]
		switch {
		case v == 0:
		case v < 100:
			mult += uint64(v)
		case v == hsMini:
			mult += hsMiniMult
		case v == hsMinor:
			mult += hsMinorMult
		case v == hsMajor && !major:
			major = true
		case v == hsGrand && !grand:
			grand = true
		default: // a second MAJOR / GRAND in the same bonus pays as MINOR
			mult += hsMinorMult
		}
	}
	if full && !grand {
		grand = true
	}
	return mult, major, grand
}

// PlaceCasinoFreeSpin uses one free spin of the caller's grant in a committed
// round (no stake). One free spin in flight at a time.
func PlaceCasinoFreeSpin(cur realm, roundId string, clientHash string) {
	requireNotPaused()
	caller := cur.Previous().Address().String()
	if isBlacklisted(caller) {
		panic("address banned")
	}
	r := mustCasinoRound(roundId)
	if r.player != caller {
		panic("this round belongs to another player")
	}
	if r.status != "committed" {
		panic("betting is closed for this round")
	}
	if time.Now().Unix()-r.committedAt >= casinoBetWindowSec {
		panic("round expired")
	}
	g := getGrant(caller)
	if g == nil || g.left == 0 {
		panic("no free spins left")
	}
	if g.inRound != "" {
		panic("a free spin is already in progress (round " + g.inRound + ")")
	}
	if !casIsHex64(clientHash) {
		panic("client hash must be sha256 hex")
	}
	g.inRound = roundId
	casinoBets.Set(roundId+":"+caller, &casinoBet{addr: caller, game: "slots", coin: g.coin, choice: "free", clientHash: clientHash, amount: g.bet, freeSpin: true})
	r.status = "bet"
	r.betAt = time.Now().Unix()
	r.bets = 1
}

// settleFreeSpin pays a free spin's win out of its grant's reservation.
func settleFreeSpin(b *casinoBet, win uint64) uint64 {
	g := getGrant(b.addr)
	if g == nil {
		panic("free spin grant missing")
	}
	if win > g.capLeft {
		win = g.capLeft
		b.capped = true
	}
	if win > 0 {
		casSet(&casinoReserved, b.coin, casSub(casGet(&casinoReserved, b.coin), win))
		casSet(&casinoPool, b.coin, casSub(casGet(&casinoPool, b.coin), win))
		day, snap, paid, recv := casinoDayState(b.coin)
		setCasinoDay(b.coin, day, snap, casAdd(paid, win), recv)
		casCredit(b.addr, b.coin, win)
	}
	g.capLeft -= win
	g.won += win
	g.left--
	g.inRound = ""
	if g.left == 0 {
		casSet(&casinoReserved, b.coin, casSub(casGet(&casinoReserved, b.coin), g.capLeft))
		casinoGrants.Remove(b.addr)
		chain.Emit("CasinoFreeSpinsDone", "player", b.addr, "coin", b.coin, "won", casU(g.won))
	}
	return win
}

// FreeSpinGrant reports a player's open free spins (null when none).
func FreeSpinGrant(addr string) string {
	g := getGrant(addr)
	if g == nil {
		return "null"
	}
	return `{"coin":"` + g.coin + `","bet":` + casU(g.bet) + `,"left":` + casU(g.left) + `,"total":` + casU(g.total) +
		`,"mult":` + casU(freeSpinMult) + `,"capLeft":` + casU(g.capLeft) + `,"won":` + casU(g.won) +
		`,"inRound":"` + g.inRound + `","fromRound":"` + g.fromRound + `"}`
}

// CasinoJackpots reports the real MAJOR / GRAND pools and how they pay.
func CasinoJackpots(coinId string) string {
	return `{"coin":"` + coinId + `","major":"` + casU(casGet(&casinoJackpot, jpKey(coinId, "major"))) +
		`","grand":"` + casU(casGet(&casinoJackpot, jpKey(coinId, "grand"))) +
		`","majorSeed":"` + casU(casGet(&casinoJpSeed, jpKey(coinId, "major"))) +
		`","grandSeed":"` + casU(casGet(&casinoJpSeed, jpKey(coinId, "grand"))) +
		`","refBet":"` + casU(jpRefBet(coinId)) + `","miniMult":` + casU(hsMiniMult) + `,"minorMult":` + casU(hsMinorMult) +
		`,"majorBps":` + casU(jpMajorBps) + `,"grandBps":` + casU(jpGrandBps) + `}`
}

func validJpTier(tier string) bool { return tier == "major" || tier == "grand" }

// SeedCasinoJackpot adds the ADMIN'S OWN coins to a jackpot pool (never withdrawable).
func SeedCasinoJackpot(cur realm, coinId, tier, amount string) {
	if cur.Previous().Address() != admin {
		panic("unauthorized: admin only")
	}
	if _, ok := coinRarity[coinId]; !ok {
		panic("unknown coin id: " + coinId)
	}
	if !validJpTier(tier) {
		panic("tier must be major or grand")
	}
	amt, err := strconv.ParseUint(amount, 10, 64)
	if err != nil || amt == 0 || amt > casinoMaxAmount {
		panic("invalid amount")
	}
	casDebit(admin.String(), coinId, amt)
	k := jpKey(coinId, tier)
	casSet(&casinoJackpot, k, casAdd(casGet(&casinoJackpot, k), amt))
	casStat(coinId, "", "seeded", amt)
	chain.Emit("CasinoJackpotSeeded", "coin", coinId, "tier", tier, "amount", amount)
}

// SetCasinoJackpotSeed sets the level a jackpot is topped back up to after a hit.
func SetCasinoJackpotSeed(cur realm, coinId, tier, amount string) {
	if cur.Previous().Address() != admin {
		panic("unauthorized: admin only")
	}
	if !validJpTier(tier) {
		panic("tier must be major or grand")
	}
	amt, err := strconv.ParseUint(amount, 10, 64)
	if err != nil || amt > casinoMaxAmount {
		panic("invalid amount")
	}
	casSet(&casinoJpSeed, jpKey(coinId, tier), amt)
}

// SetCasinoJackpotRefBet sets the bet that wins a full jackpot (smaller bets win
// the same share of the pool as their share of this bet).
func SetCasinoJackpotRefBet(cur realm, coinId, amount string) {
	if cur.Previous().Address() != admin {
		panic("unauthorized: admin only")
	}
	amt, err := strconv.ParseUint(amount, 10, 64)
	if err != nil || amt == 0 || amt > casinoMaxAmount {
		panic("invalid amount")
	}
	casSet(&casinoJpRef, coinId, amt)
}

game_casino_rounds.gno

package game32

import (
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"

	"chain"
)

// ── rounds ──────────────────────────────────────────────────────────────────

func getCasinoRound(id string) *casinoRound {
	if !casinoRounds.Has(id) {
		return nil
	}
	r, ok := casinoRounds.Get(id).(*casinoRound)
	if !ok {
		return nil
	}
	return r
}

func mustCasinoRound(id string) *casinoRound {
	r := getCasinoRound(id)
	if r == nil {
		panic("round not found")
	}
	return r
}

func casinoRoundBet(r *casinoRound, roundId string) *casinoBet {
	key := roundId + ":" + r.player
	if !casinoBets.Has(key) {
		return nil
	}
	return casinoBets.Get(key).(*casinoBet)
}

// CommitCasinoSeed opens a round for one player with sha256(s). Operator only;
// a round id can be used once.
func CommitCasinoSeed(cur realm, roundId string, player string, seedHash string) {
	if !isOperator(cur) {
		panic("unauthorized: casino operator only")
	}
	if !casSafe(roundId, 64) {
		panic("invalid round id")
	}
	if casinoRounds.Has(roundId) {
		panic("round already exists")
	}
	if !address(player).IsValid() {
		panic("invalid player address")
	}
	seedHash = strings.ToLower(seedHash)
	if !casIsHex64(seedHash) {
		panic("seedHash must be sha256 hex")
	}
	casinoRounds.Set(roundId, &casinoRound{player: player, seedHash: seedHash, status: "committed", committedAt: time.Now().Unix()})
}

// PlaceCasinoBet escrows the player's bet with sha256(c): only the round's
// player, only before s is revealed, and only if the pool can pay its largest win.
func PlaceCasinoBet(cur realm, roundId string, game string, coinId string, betAmount string, choice string, clientHash string) {
	requireNotPaused()
	caller := cur.Previous().Address().String()
	if isBlacklisted(caller) {
		panic("address banned")
	}
	r := mustCasinoRound(roundId)
	if r.player != caller {
		panic("this round belongs to another player")
	}
	if r.status != "committed" {
		panic("betting is closed for this round")
	}
	if time.Now().Unix()-r.committedAt >= casinoBetWindowSec {
		panic("round expired")
	}
	if _, ok := coinRarity[coinId]; !ok {
		panic("unknown coin id: " + coinId)
	}
	if !validCasinoChoice(game, choice) {
		panic("invalid game or choice: " + game + "/" + choice)
	}
	clientHash = strings.ToLower(clientHash)
	if !casIsHex64(clientHash) {
		panic("client hash must be sha256 hex")
	}
	amt, err := strconv.ParseUint(betAmount, 10, 64)
	if err != nil || amt == 0 || amt > casinoMaxAmount {
		panic("invalid bet amount")
	}
	if game == "slots" && getGrant(caller) != nil {
		panic("finish your free spins first")
	}
	// Check everything before any write, then debit and reserve the largest win.
	casinoCheckBet(coinId, game, amt)
	exp := casinoExposure(game, amt)
	casDebit(caller, coinId, amt)
	casinoReserve(coinId, exp)
	casinoBets.Set(roundId+":"+caller, &casinoBet{addr: caller, game: game, coin: coinId, choice: choice, clientHash: clientHash, amount: amt, exposure: exp})
	r.status = "bet"
	r.betAt = time.Now().Unix()
	r.bets = 1
}

// RevealCasinoSeed publishes s (it must hash to the commit). It settles nothing:
// the bet settles when the player's secret is revealed.
func RevealCasinoSeed(cur realm, roundId string, serverSeed string) {
	if !isOperator(cur) {
		panic("unauthorized: casino operator only")
	}
	r := mustCasinoRound(roundId)
	if r.status != "committed" && r.status != "bet" {
		panic("round already revealed or closed")
	}
	h := sha256.Sum256([]byte(serverSeed))
	if hex.EncodeToString(h[:]) != r.seedHash {
		panic("server seed does not match the committed hash")
	}
	r.serverSeed = serverSeed
	if r.status == "committed" {
		r.status = "closed" // no bet was placed: the round just ends
		return
	}
	r.status = "seeded"
	r.seededAt = time.Now().Unix()
}

// RevealCasinoSecret publishes the player's secret c (anyone may relay it: it
// must hash to the bet's hash) and settles the bet on chain. Works while paused.
func RevealCasinoSecret(cur realm, roundId string, clientSecret string) {
	r := mustCasinoRound(roundId)
	if r.status != "seeded" {
		panic("round is not waiting for the client secret")
	}
	b := casinoRoundBet(r, roundId)
	if b == nil || b.settled {
		panic("no open bet in this round")
	}
	if !casSafe(clientSecret, 64) {
		panic("invalid client secret")
	}
	if sha256Hex(clientSecret) != b.clientHash {
		panic("client secret does not match the bet's hash")
	}
	b.clientSecret = clientSecret
	casinoResolve(roundId, r, b)
	r.status = "settled"
}

// casinoResolve rolls the bet from s and c, pays it, and records the result.
func casinoResolve(roundId string, r *casinoRound, b *casinoBet) {
	payout := uint64(0)
	switch b.game {
	case "slots":
		s := newSlotsStream(r.serverSeed, b.clientSecret, roundId)
		g := slotsSpinGrid(s)
		mult, lines := slotsLineMult(&g)
		sc := slotsCount(&g, symScatter)
		win := casMul(b.amount/slotsBetStep, mult)
		if sc >= 3 {
			win = casAdd(win, casMul(b.amount, slotsScatterPay[sc]))
		}
		b.grid = slotsGridString(&g)
		b.lineMult = mult
		b.lines = lines
		b.scatters = sc
		if b.freeSpin {
			// ×2, no retrigger, no Hold & Spin; paid from the grant's reservation.
			payout = settleFreeSpin(b, casMul(win, freeSpinMult))
			b.payout = payout
			b.won = payout > 0
			b.outcome = "lose"
			if payout > 0 {
				b.outcome = "win"
			}
			b.settled = true
			casRecord(b.coin, "slots", 0, payout)
			casStat(b.coin, "slots", "freeSpins", 1)
			chain.Emit("CasinoBetSettled", "round", roundId, "player", b.addr, "game", "slots", "coin", b.coin,
				"amount", "0", "freeSpin", "true", "outcome", b.outcome, "won", strconv.FormatBool(b.won), "payout", casU(payout))
			return
		}
		major, grand := false, false
		if slotsCount(&g, symVault) >= 3 {
			tiles, played, full := slotsHoldAndSpin(s, &g)
			hm, mj, gr := slotsHSPayout(&tiles, full)
			b.hsTiles = hsTilesString(&tiles)
			b.hsRespins = played
			b.hsMult = hm
			major, grand = mj, gr
			win = casAdd(win, casMul(b.amount, hm))
		}
		capWin := casMul(b.amount, slotsMaxWinMult)
		if win > capWin {
			win = capWin
			b.capped = true
		}
		payout = casinoSettle(b.addr, b.coin, b.amount, b.exposure, win)
		if sc >= 3 {
			// The rest of this spin's 500× cap stays reserved for its free spins
			// (reserved before anything else leaves the pool, so pool ≥ reserved holds).
			n := slotsFreeSpins[sc]
			capLeft := capWin - win
			casinoReserve(b.coin, capLeft)
			casinoGrants.Set(b.addr, &freeSpinGrant{addr: b.addr, coin: b.coin, bet: b.amount, left: n, total: n, capLeft: capLeft, fromRound: roundId, grantedAt: time.Now().Unix()})
			b.fsGranted = n
			chain.Emit("CasinoFreeSpinsGranted", "player", b.addr, "coin", b.coin, "spins", casU(n), "bet", casU(b.amount))
		}
		casinoJackpotContribute(b.coin, b.amount)
		jw := uint64(0)
		if grand {
			jw = casAdd(jw, casinoJackpotPay(b.addr, b.coin, "grand", b.amount))
			b.jackpots = "grand"
		}
		if major {
			jw = casAdd(jw, casinoJackpotPay(b.addr, b.coin, "major", b.amount))
			if b.jackpots != "" {
				b.jackpots = "major+" + b.jackpots
			} else {
				b.jackpots = "major"
			}
		}
		b.jackpotWin = jw
		b.payout = casAdd(payout, jw)
		b.won = b.payout > b.amount
		b.outcome = "lose"
		if b.payout > 0 {
			b.outcome = "win"
		}
		b.settled = true
		casRecord(b.coin, "slots", b.amount, b.payout)
		chain.Emit("CasinoBetSettled", "round", roundId, "player", b.addr, "game", "slots", "coin", b.coin,
			"amount", casU(b.amount), "outcome", b.outcome, "won", strconv.FormatBool(b.won), "payout", casU(b.payout),
			"jackpots", b.jackpots, "freeSpins", casU(b.fsGranted))
		return
	case "rps":
		b.roll = CasinoRoll(r.serverSeed, b.clientSecret, roundId, b.game)
		res := CasinoOutcome("rps", b.roll)
		b.outcome = rpsHouseMove(b.choice, res)
		switch res {
		case "win":
			payout = casAdd(b.amount, b.amount)
			b.won = true
		case "push":
			payout = b.amount
		}
	default:
		b.roll = CasinoRoll(r.serverSeed, b.clientSecret, roundId, b.game)
		b.outcome = CasinoOutcome(b.game, b.roll)
		if b.outcome == b.choice {
			payout = casAdd(b.amount, b.amount)
			b.won = true
		}
	}
	b.payout = casinoSettle(b.addr, b.coin, b.amount, b.exposure, payout)
	b.settled = true
	casRecord(b.coin, b.game, b.amount, b.payout)
	chain.Emit("CasinoBetSettled", "round", roundId, "player", b.addr, "game", b.game, "coin", b.coin,
		"amount", casU(b.amount), "roll", casU(b.roll), "outcome", b.outcome, "won", strconv.FormatBool(b.won), "payout", casU(b.payout))
}

// RefundCasinoBet returns the stake only if s was never revealed and 30 minutes
// have passed since the bet. Never after s is revealed. Works while paused.
func RefundCasinoBet(cur realm, roundId string) {
	caller := cur.Previous().Address().String()
	r := mustCasinoRound(roundId)
	if r.status == "refunded" {
		panic("bet already settled")
	}
	if r.status != "bet" {
		panic("round already revealed: no refunds")
	}
	if r.player != caller {
		panic("no bet found for this round")
	}
	if time.Now().Unix()-r.betAt < casinoSeedTimeoutSec {
		panic("refund opens 30 minutes after the bet if the server seed is never revealed")
	}
	b := casinoRoundBet(r, roundId)
	b.settled = true
	b.refunded = true
	if b.freeSpin {
		// No stake was taken: the free spin goes back to the grant.
		if g := getGrant(caller); g != nil && g.inRound == roundId {
			g.inRound = ""
		}
	} else {
		casSet(&casinoReserved, b.coin, casSub(casGet(&casinoReserved, b.coin), b.exposure))
		casCredit(caller, b.coin, b.amount)
	}
	r.status = "refunded"
	chain.Emit("CasinoBetRefunded", "round", roundId, "player", caller, "amount", casU(b.amount))
}

// ForfeitCasinoBet settles a bet as a loss when s was revealed but the player's
// secret was not within 24 h (only the player could know the result). Anyone.
func ForfeitCasinoBet(cur realm, roundId string) {
	r := mustCasinoRound(roundId)
	if r.status != "seeded" {
		panic("round is not waiting for the client secret")
	}
	if time.Now().Unix()-r.seededAt < casinoSecretTimeoutSec {
		panic("forfeit opens 24 hours after the server seed is revealed")
	}
	b := casinoRoundBet(r, roundId)
	b.forfeited = true
	b.outcome = "forfeit"
	if b.freeSpin {
		b.payout = settleFreeSpin(b, 0) // the free spin is used, it wins nothing
		casRecord(b.coin, b.game, 0, 0)
	} else {
		b.payout = casinoSettle(b.addr, b.coin, b.amount, b.exposure, 0)
		casRecord(b.coin, b.game, b.amount, 0)
	}
	b.settled = true
	r.status = "settled"
	chain.Emit("CasinoBetForfeited", "round", roundId, "player", b.addr, "amount", casU(b.amount))
}

// ── queries ─────────────────────────────────────────────────────────────────

func CasinoRound(roundId string) string {
	r := getCasinoRound(roundId)
	if r == nil {
		return "null"
	}
	return `{"roundId":"` + roundId + `","player":"` + r.player + `","seedHash":"` + r.seedHash + `","serverSeed":"` + r.serverSeed +
		`","status":"` + r.status + `","committedAt":` + strconv.FormatInt(r.committedAt, 10) +
		`,"betAt":` + strconv.FormatInt(r.betAt, 10) + `,"seededAt":` + strconv.FormatInt(r.seededAt, 10) +
		`,"bets":` + strconv.Itoa(r.bets) + `}`
}

// CasinoBet returns one player's bet and its on-chain result.
func CasinoBet(roundId string, addr string) string {
	key := roundId + ":" + addr
	if !casinoBets.Has(key) {
		return "null"
	}
	b := casinoBets.Get(key).(*casinoBet)
	return `{"addr":"` + b.addr + `","game":"` + b.game + `","coinId":"` + b.coin + `","amount":` + casU(b.amount) +
		`,"exposure":` + casU(b.exposure) + `,"choice":"` + b.choice + `","clientHash":"` + b.clientHash +
		`","clientSecret":"` + b.clientSecret + `","clientSeed":"` + b.clientSecret + `","settled":` + strconv.FormatBool(b.settled) +
		`,"refunded":` + strconv.FormatBool(b.refunded) + `,"forfeited":` + strconv.FormatBool(b.forfeited) +
		`,"won":` + strconv.FormatBool(b.won) + `,"roll":` + casU(b.roll) + `,"outcome":"` + b.outcome +
		`","payout":` + casU(b.payout) + `,"grid":"` + b.grid + `","lineMult":` + casU(b.lineMult) +
		`,"lines":` + strconv.Itoa(b.lines) + `,"scatters":` + strconv.Itoa(b.scatters) +
		`,"freeSpin":` + strconv.FormatBool(b.freeSpin) + `,"capped":` + strconv.FormatBool(b.capped) +
		`,"fsGranted":` + casU(b.fsGranted) + `,"hsTiles":"` + b.hsTiles + `","hsRespins":` + strconv.Itoa(b.hsRespins) +
		`,"hsMult":` + casU(b.hsMult) + `,"jackpots":"` + b.jackpots + `","jackpotWin":` + casU(b.jackpotWin) + `}`
}

// JackpotPool reports the GRAND jackpot pool (the casino bankroll is CasinoPool).
func JackpotPool(coinId string) string {
	return `{"pool":"` + casU(casGet(&casinoJackpot, jpKey(coinId, "grand"))) + `","coinId":"` + coinId + `"}`
}

func CasinoHistory(_ string) string { return "[]" }

game_casino_test.gno

package game32

import (
	"strconv"
	"strings"
	"testing"

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

func casAddr(name string) address { return testutils.TestAddress(name) }

func casSetup() address {
	adm := casAddr("cas-admin")
	admin = adm
	operator = address("")
	return adm
}

func casResetPool(coin string, amt uint64) {
	casSet(&casinoPool, coin, amt)
	casinoReserved.Remove(coin)
	casinoDay.Remove(coin)
}

func casSeedHash(seed string) string { return sha256Hex(seed) }

func casAbort(t *testing.T, what string, abort any, want string) {
	t.Helper()
	if abort == nil {
		t.Errorf("%s: expected abort, got success", what)
		return
	}
	msg := ""
	switch v := abort.(type) {
	case string:
		msg = v
	case error:
		msg = v.Error()
	}
	if want != "" && !strings.Contains(msg, want) {
		t.Errorf("%s: aborted with %q, want %q", what, msg, want)
	}
}

// casTotal = every holder of `coin` the casino can touch: the players' balances,
// the pool and the stakes of open bets. Coins only move between them.
func casTotal(coin string, addrs []address) uint64 {
	tot := casGet(&casinoPool, coin) + casJp(coin)
	for _, a := range addrs {
		tot += casBalOf(a.String(), coin)
	}
	casinoBets.Iterate("", "", func(_ string, v any) bool {
		b := v.(*casinoBet)
		if b.coin == coin && !b.settled {
			tot += b.amount
		}
		return false
	})
	return tot
}

// casJp = coins held in the coin's MAJOR + GRAND jackpot pools.
func casJp(coin string) uint64 {
	return casGet(&casinoJackpot, jpKey(coin, "major")) + casGet(&casinoJackpot, jpKey(coin, "grand"))
}

func casResetBonus() {
	casinoStats = avl.Tree{}
	casinoGrants = avl.Tree{}
	casinoJackpot = avl.Tree{}
	casinoJpDust = avl.Tree{}
	casinoJpSeed = avl.Tree{}
	casinoJpRef = avl.Tree{}
}

// casPlay runs one full round: commit (operator) → bet (player) → reveal s → reveal c.
func casPlay(cur realm, t *testing.T, op, p address, round, game, choice string, amt uint64) *casinoBet {
	t.Helper()
	seed := "s-" + round
	secret := "c-" + round
	testing.SetRealm(testing.NewUserRealm(op))
	CommitCasinoSeed(cross(cur), round, p.String(), casSeedHash(seed))
	testing.SetRealm(testing.NewUserRealm(p))
	PlaceCasinoBet(cross(cur), round, game, "grin", casU(amt), choice, sha256Hex(secret))
	testing.SetRealm(testing.NewUserRealm(op))
	RevealCasinoSeed(cross(cur), round, seed)
	testing.SetRealm(testing.NewUserRealm(casAddr("cas-relayer")))
	RevealCasinoSecret(cross(cur), round, secret)
	return casinoBets.Get(round + ":" + p.String()).(*casinoBet)
}

func TestCasino_OutcomeRules(t *testing.T) {
	for _, gc := range [][2]string{{"coin_flip", "heads"}, {"coin_flip", "tails"}, {"higher_lower", "higher"}, {"higher_lower", "lower"}} {
		n := 0
		for roll := uint64(0); roll < 100; roll++ {
			if CasinoOutcome(gc[0], roll) == gc[1] {
				n++
			}
		}
		if n != 49 {
			t.Errorf("%s/%s wins on %d of 100 rolls, want 49", gc[0], gc[1], n)
		}
	}
	w, p, l := 0, 0, 0
	for roll := uint64(0); roll < 100; roll++ {
		switch CasinoOutcome("rps", roll) {
		case "win":
			w++
		case "push":
			p++
		case "lose":
			l++
		}
	}
	// RTP = 0.33·2 + 0.32·1 = 98%
	if w != 33 || p != 32 || l != 35 {
		t.Errorf("rps table %d/%d/%d", w, p, l)
	}
	cases := [][3]string{{"rock", "win", "scissors"}, {"rock", "push", "rock"}, {"rock", "lose", "paper"},
		{"paper", "win", "rock"}, {"paper", "lose", "scissors"}, {"scissors", "win", "paper"}, {"scissors", "lose", "rock"}}
	for _, c := range cases {
		if m := rpsHouseMove(c[0], c[1]); m != c[2] {
			t.Errorf("rps house move %s/%s = %s, want %s", c[0], c[1], m, c[2])
		}
	}
}

func TestCasino_RolesAndPlayerBinding(cur realm, t *testing.T) {
	adm := casSetup()
	casResetPool("grin", 100000)
	op := casAddr("cas-op")
	p := casAddr("cas-bound")
	other := casAddr("cas-other")
	casSet(&balances, p.String()+":grin", 100)
	casSet(&balances, other.String()+":grin", 100)
	testing.SetRealm(testing.NewUserRealm(other))
	casAbort(t, "outsider commit", revive(func() { CommitCasinoSeed(cross(cur), "cr-r1", p.String(), casSeedHash("s")) }), "operator only")
	casAbort(t, "outsider sets operator", revive(func() { SetOperator(cross(cur), other.String()) }), "admin only")
	casAbort(t, "outsider seeds pool", revive(func() { SeedCasinoPool(cross(cur), "grin", "10") }), "admin only")
	testing.SetRealm(testing.NewUserRealm(adm))
	SetOperator(cross(cur), op.String())
	testing.SetRealm(testing.NewUserRealm(op))
	CommitCasinoSeed(cross(cur), "cr-r1", p.String(), casSeedHash("s"))
	casAbort(t, "recommit", revive(func() { CommitCasinoSeed(cross(cur), "cr-r1", p.String(), casSeedHash("x")) }), "already exists")
	casAbort(t, "bad hash", revive(func() { CommitCasinoSeed(cross(cur), "cr-r2", p.String(), "nothex") }), "sha256")
	casAbort(t, "bad player", revive(func() { CommitCasinoSeed(cross(cur), "cr-r2", "nope", casSeedHash("s")) }), "invalid player")
	// Only the round's player can bet in it.
	testing.SetRealm(testing.NewUserRealm(other))
	casAbort(t, "other player bets", revive(func() {
		PlaceCasinoBet(cross(cur), "cr-r1", "coin_flip", "grin", "10", "heads", sha256Hex("c"))
	}), "another player")
	testing.SetRealm(testing.NewUserRealm(p))
	casAbort(t, "clear seed instead of hash", revive(func() {
		PlaceCasinoBet(cross(cur), "cr-r1", "coin_flip", "grin", "10", "heads", "c")
	}), "client hash")
	PlaceCasinoBet(cross(cur), "cr-r1", "coin_flip", "grin", "10", "heads", sha256Hex("c"))
	casAbort(t, "second bet", revive(func() {
		PlaceCasinoBet(cross(cur), "cr-r1", "coin_flip", "grin", "10", "heads", sha256Hex("c"))
	}), "closed")
	// The secret can't be revealed before s, and only the operator reveals s.
	casAbort(t, "secret before seed", revive(func() { RevealCasinoSecret(cross(cur), "cr-r1", "c") }), "not waiting")
	casAbort(t, "player reveals seed", revive(func() { RevealCasinoSeed(cross(cur), "cr-r1", "s") }), "operator only")
	testing.SetRealm(testing.NewUserRealm(op))
	casAbort(t, "wrong seed", revive(func() { RevealCasinoSeed(cross(cur), "cr-r1", "nope") }), "does not match")
	RevealCasinoSeed(cross(cur), "cr-r1", "s")
	// Revealing s settles nothing: the operator didn't know c.
	if b := casinoBets.Get("cr-r1:" + p.String()).(*casinoBet); b.settled || casBalOf(p.String(), "grin") != 90 {
		t.Fatalf("seed reveal settled the bet")
	}
	casAbort(t, "double seed reveal", revive(func() { RevealCasinoSeed(cross(cur), "cr-r1", "s") }), "already revealed")
	casAbort(t, "wrong secret", revive(func() { RevealCasinoSecret(cross(cur), "cr-r1", "d") }), "does not match")
	testing.SetRealm(testing.NewUserRealm(p))
	casAbort(t, "refund after seed reveal", revive(func() { RefundCasinoBet(cross(cur), "cr-r1") }), "no refunds")
	RevealCasinoSecret(cross(cur), "cr-r1", "c")
	if b := casinoBets.Get("cr-r1:" + p.String()).(*casinoBet); !b.settled {
		t.Fatalf("not settled")
	}
	casAbort(t, "double secret", revive(func() { RevealCasinoSecret(cross(cur), "cr-r1", "c") }), "not waiting")
	// A round with no bet just closes on reveal.
	testing.SetRealm(testing.NewUserRealm(op))
	CommitCasinoSeed(cross(cur), "cr-r3", p.String(), casSeedHash("s3"))
	RevealCasinoSeed(cross(cur), "cr-r3", "s3")
	if getCasinoRound("cr-r3").status != "closed" {
		t.Errorf("empty round not closed")
	}
}

func TestCasino_SettlesAndPaysFromPool(cur realm, t *testing.T) {
	adm := casSetup()
	casResetPool("grin", 0)
	casSet(&balances, adm.String()+":grin", 100000)
	testing.SetRealm(testing.NewUserRealm(adm))
	casAbort(t, "seed more than owned", revive(func() { SeedCasinoPool(cross(cur), "grin", "100001") }), "insufficient")
	SeedCasinoPool(cross(cur), "grin", "100000")
	if casGet(&casinoPool, "grin") != 100000 || casBalOf(adm.String(), "grin") != 0 {
		t.Fatalf("seed: pool=%d admin=%d", casGet(&casinoPool, "grin"), casBalOf(adm.String(), "grin"))
	}
	players := []address{}
	for i := 0; i < 30; i++ {
		players = append(players, casAddr("cas-p"+strconv.Itoa(i)))
		casSet(&balances, players[i].String()+":grin", 1000)
	}
	games := [][2]string{{"coin_flip", "heads"}, {"coin_flip", "tails"}, {"higher_lower", "higher"}, {"higher_lower", "lower"}, {"rps", "rock"}, {"rps", "scissors"}}
	total0 := casTotal("grin", players)
	seen := map[string]int{}
	for i, p := range players {
		g := games[i%len(games)]
		round := "cr-settle-" + strconv.Itoa(i)
		pool0 := casGet(&casinoPool, "grin")
		b := casPlay(cur, t, adm, p, round, g[0], g[1], 100)
		roll := CasinoRoll("s-"+round, "c-"+round, round, g[0])
		want := uint64(0)
		res := CasinoOutcome(g[0], roll)
		if g[0] == "rps" {
			seen["rps-"+res]++
			if res == "win" {
				want = 200
			} else if res == "push" {
				want = 100
			}
			if b.outcome != rpsHouseMove(g[1], res) {
				t.Errorf("rps house move %s for %s/%s", b.outcome, g[1], res)
			}
		} else if res == g[1] {
			want = 200
		}
		if b.payout != want || b.roll != roll || casBalOf(p.String(), "grin") != 900+want {
			t.Errorf("%s round %d: payout %d want %d (bal %d)", g[0], i, b.payout, want, casBalOf(p.String(), "grin"))
		}
		if casGet(&casinoPool, "grin") != pool0+100-want {
			t.Errorf("pool %d → %d with payout %d", pool0, casGet(&casinoPool, "grin"), want)
		}
		if casGet(&casinoReserved, "grin") != 0 {
			t.Errorf("reservation not released")
		}
		if casTotal("grin", players) != total0 {
			t.Fatalf("conservation broken after round %d", i)
		}
		js := CasinoBet(round, p.String())
		if !strings.Contains(js, `"settled":true`) || !strings.Contains(js, `"clientSecret":"c-`+round+`"`) {
			t.Errorf("bet json %s", js)
		}
	}
}

func TestCasino_SlotsSettleOnChain(cur realm, t *testing.T) {
	adm := casSetup()
	casResetPool("grin", 10_000_000) // slots max bet = 0.004% = 400
	p := casAddr("cas-slots")
	casSet(&balances, p.String()+":grin", 1_000_000)
	players := []address{p}
	total0 := casTotal("grin", players)
	wins, paid, staked := 0, uint64(0), uint64(0)
	for i := 0; i < 60; i++ {
		round := "cr-slot-" + strconv.Itoa(i)
		pool0 := casGet(&casinoPool, "grin") + casJp("grin")
		testing.SetRealm(testing.NewUserRealm(adm))
		CommitCasinoSeed(cross(cur), round, p.String(), casSeedHash("s-"+round))
		testing.SetRealm(testing.NewUserRealm(p))
		PlaceCasinoBet(cross(cur), round, "slots", "grin", "100", "spin", sha256Hex("c-"+round))
		if casGet(&casinoReserved, "grin") != 49900 {
			t.Fatalf("slots reserve %d, want 499×100", casGet(&casinoReserved, "grin"))
		}
		testing.SetRealm(testing.NewUserRealm(adm))
		RevealCasinoSeed(cross(cur), round, "s-"+round)
		RevealCasinoSecret(cross(cur), round, "c-"+round)
		b := casinoBets.Get(round + ":" + p.String()).(*casinoBet)
		// Re-derive independently from the stream.
		s := newSlotsStream("s-"+round, "c-"+round, round)
		g := slotsSpinGrid(s)
		mult, _ := slotsLineMult(&g)
		sc := slotsCount(&g, symScatter)
		want := 4 * mult
		if sc >= 3 {
			want += 100 * slotsScatterPay[sc]
		}
		if want > 50000 {
			want = 50000
		}
		if b.grid != slotsGridString(&g) || b.payout != want || b.lineMult != mult || b.scatters != sc {
			t.Errorf("slot %d: grid %s payout %d want %d", i, b.grid, b.payout, want)
		}
		if casGet(&casinoPool, "grin")+casJp("grin")+want != pool0+100 || casGet(&casinoReserved, "grin") != 0 {
			t.Errorf("slot %d pool %d→%d payout %d", i, pool0, casGet(&casinoPool, "grin"), want)
		}
		if want > 0 {
			wins++
		}
		paid += want
		staked += 100
		if casTotal("grin", players) != total0 {
			t.Fatalf("conservation broken at slot %d", i)
		}
	}
	if wins == 0 || wins == 60 {
		t.Errorf("slots wins %d of 60", wins)
	}
	_ = paid
	_ = staked
}

func TestCasino_SlotsEngine(t *testing.T) {
	// strip composition
	cnt := [10]int{}
	for i := 0; i < len(slotsStrip); i++ {
		cnt[slotsStrip[i]-'0']++
	}
	want := [10]int{1, 3, 4, 5, 6, 6, 7, 6, 1, 1}
	if len(slotsStrip) != 40 || cnt != want {
		t.Fatalf("strip %v", cnt)
	}
	// all wilds: every line pays wild ×5
	var g [slotsCells]byte
	if m, l := slotsLineMult(&g); m != 25*1000 || l != 25 {
		t.Errorf("all wilds %d/%d", m, l)
	}
	// row 1 = seven seven wild seven coin, everything else coin/star mix that pays nothing
	for i := range g {
		g[i] = 9 // vault: never pays on a line
	}
	for c, s := range []byte{1, 1, 0, 1, 7} {
		g[c*4+1] = s
	}
	if m, l := slotsLineMult(&g); m != 150 || l != 1 {
		t.Errorf("seven×4 line: %d/%d", m, l)
	}
	// scatter / vault counting
	g[0], g[5] = symScatter, symScatter
	if slotsCount(&g, symScatter) != 2 {
		t.Errorf("scatter count")
	}
	// Vectors shared with src/lib/game/__tests__/slots-engine.test.ts
	s := newSlotsStream("seed-a", "client-a", "cr-vector")
	vg := slotsSpinGrid(s)
	vm, vl := slotsLineMult(&vg)
	if got := slotsGridString(&vg) + "|" + casU(vm) + "|" + strconv.Itoa(vl); got != slotsVectorA {
		t.Errorf("vector a: %s", got)
	}
	hg := [slotsCells]byte{}
	for i := range hg {
		hg[i] = 7
	}
	hg[0], hg[4], hg[8] = symVault, symVault, symVault
	hs := newSlotsStream("seed-h", "client-h", "cr-vector")
	tiles, played, full := slotsHoldAndSpin(hs, &hg)
	if got := hsTilesString(&tiles) + "|" + strconv.Itoa(played) + "|" + strconv.FormatBool(full); got != slotsVectorH {
		t.Errorf("vector h: %s", got)
	}
}

const (
	slotsVectorA = "64573216573221064579|0|0"
	slotsVectorH = "1.0.0.1.1.0.0.0.1.0.0.0.0.0.0.0.0.0.0.0|4|false"
)

func TestCasino_Caps(cur realm, t *testing.T) {
	casSetup()
	casResetPool("grin", 19999)
	mustPanic(t, "casino closed", func() { casinoCheckBet("grin", "coin_flip", 1) })
	casResetPool("joy", 199) // rarity 1: 199 units < 200 units
	mustPanic(t, "casino closed", func() { casinoCheckBet("joy", "coin_flip", 1) })
	casResetPool("grin", 100000)
	mustPanic(t, "bet too large", func() { casinoCheckBet("grin", "coin_flip", 501) })
	casinoCheckBet("grin", "rps", 500)
	// slots: 0.004% of 100,000 = 4 → no slots bet fits (bets are multiples of 25)
	mustPanic(t, "bet too large", func() { casinoCheckBet("grin", "slots", 25) })
	casResetPool("grin", 10_000_000) // 0.004% = 400
	casinoCheckBet("grin", "slots", 400)
	mustPanic(t, "multiple of 25", func() { casinoCheckBet("grin", "slots", 30) })
	mustPanic(t, "bet too large", func() { casinoCheckBet("grin", "slots", 425) })
	// open reservations ≤ 20% of the pool: 400×499 = 199,600 each → 10 fit in 2,000,000 … but the
	// daily 10% (1,000,000) binds first: 5 fit.
	casinoReserve("grin", 199600*5)
	mustPanic(t, "daily payout limit", func() { casinoCheckBet("grin", "slots", 350) })
	casResetPool("grin", 10_000_000)
	casinoReserve("grin", 1_990_000)
	mustPanic(t, "20 percent", func() { casinoCheckBet("grin", "coin_flip", 40_000) })
}

func TestCasino_DailyCap(cur realm, t *testing.T) {
	casResetPool("grin", 100000)
	_, snap, _, _ := casinoDayState("grin")
	setCasinoDay("grin", casDayNow(), snap, 9800, 0)
	mustPanic(t, "daily payout limit", func() { casinoCheckBet("grin", "coin_flip", 201) })
	casinoCheckBet("grin", "coin_flip", 200)
}

func TestCasino_RefundAndForfeitTimeouts(cur realm, t *testing.T) {
	adm := casSetup()
	casResetPool("grin", 100000)
	p := casAddr("cas-refund")
	casSet(&balances, p.String()+":grin", 50)
	// 1) s never revealed → refund after 30 minutes, never earlier.
	testing.SetRealm(testing.NewUserRealm(adm))
	CommitCasinoSeed(cross(cur), "cr-rf-1", p.String(), casSeedHash("r"))
	testing.SetRealm(testing.NewUserRealm(p))
	PlaceCasinoBet(cross(cur), "cr-rf-1", "coin_flip", "grin", "50", "heads", sha256Hex("c"))
	casAbort(t, "early refund", revive(func() { RefundCasinoBet(cross(cur), "cr-rf-1") }), "refund opens")
	testing.SkipHeights(361) // > 30 minutes
	testing.SetRealm(testing.NewUserRealm(casAddr("cas-stranger")))
	casAbort(t, "stranger refund", revive(func() { RefundCasinoBet(cross(cur), "cr-rf-1") }), "no bet")
	testing.SetRealm(testing.NewUserRealm(p))
	RefundCasinoBet(cross(cur), "cr-rf-1")
	if casBalOf(p.String(), "grin") != 50 || casGet(&casinoReserved, "grin") != 0 || casGet(&casinoPool, "grin") != 100000 {
		t.Errorf("refund: bal=%d reserved=%d pool=%d", casBalOf(p.String(), "grin"), casGet(&casinoReserved, "grin"), casGet(&casinoPool, "grin"))
	}
	casAbort(t, "double refund", revive(func() { RefundCasinoBet(cross(cur), "cr-rf-1") }), "already settled")
	testing.SetRealm(testing.NewUserRealm(adm))
	casAbort(t, "reveal after refund", revive(func() { RevealCasinoSeed(cross(cur), "cr-rf-1", "r") }), "closed")

	// 2) s revealed, c withheld → forfeits as a loss after 24 h (anyone can call it).
	CommitCasinoSeed(cross(cur), "cr-rf-2", p.String(), casSeedHash("r2"))
	testing.SetRealm(testing.NewUserRealm(p))
	PlaceCasinoBet(cross(cur), "cr-rf-2", "coin_flip", "grin", "50", "heads", sha256Hex("c2"))
	testing.SetRealm(testing.NewUserRealm(adm))
	RevealCasinoSeed(cross(cur), "cr-rf-2", "r2")
	stranger := casAddr("cas-stranger")
	testing.SetRealm(testing.NewUserRealm(stranger))
	casAbort(t, "early forfeit", revive(func() { ForfeitCasinoBet(cross(cur), "cr-rf-2") }), "forfeit opens")
	testing.SkipHeights(17281) // > 24 h
	testing.SetRealm(testing.NewUserRealm(p))
	casAbort(t, "refund instead of forfeit", revive(func() { RefundCasinoBet(cross(cur), "cr-rf-2") }), "no refunds")
	testing.SetRealm(testing.NewUserRealm(stranger))
	ForfeitCasinoBet(cross(cur), "cr-rf-2")
	if casBalOf(p.String(), "grin") != 0 || casGet(&casinoPool, "grin") != 100050 || casGet(&casinoReserved, "grin") != 0 {
		t.Errorf("forfeit: bal=%d pool=%d reserved=%d", casBalOf(p.String(), "grin"), casGet(&casinoPool, "grin"), casGet(&casinoReserved, "grin"))
	}
	casAbort(t, "secret after forfeit", revive(func() { RevealCasinoSecret(cross(cur), "cr-rf-2", "c2") }), "not waiting")
	// 3) betting window: a commit older than 1 h takes no bet.
	testing.SetRealm(testing.NewUserRealm(adm))
	CommitCasinoSeed(cross(cur), "cr-rf-3", p.String(), casSeedHash("r3"))
	testing.SkipHeights(721)
	casSet(&balances, p.String()+":grin", 5)
	testing.SetRealm(testing.NewUserRealm(p))
	casAbort(t, "expired round", revive(func() {
		PlaceCasinoBet(cross(cur), "cr-rf-3", "coin_flip", "grin", "5", "heads", sha256Hex("c3"))
	}), "expired")
}

// Same vectors as src/lib/game/__tests__/casino-outcome.test.ts: realm and client roll alike.
func TestCasino_RollVectors(t *testing.T) {
	if r := CasinoRoll("seed-a", "client-a", "cr-vector", "higher_lower"); r != 23 {
		t.Errorf("vector a: %d", r)
	}
	if r := CasinoRoll("seed-b", "client-b", "cr-vector", "coin_flip"); r != 65 {
		t.Errorf("vector b: %d", r)
	}
}

// Seeds ground offline with the same engine (.bot-notes/casino, engine mirror):
//   cr-g-25    3 scatters → 10 free spins, base win 240 at bet 100
//   cr-g-212   4 vaults → Hold & Spin 6× (+ lines 55 units) = 820 at bet 100
//   cr-g-8273  Hold & Spin with MAJOR (+ 28× incl. a MINI) = 2800 at bet 100
//   cr-g-29989 Hold & Spin with GRAND (9×) = 450 at bet 50
func TestCasino_FreeSpinsGrant(cur realm, t *testing.T) {
	adm := casSetup()
	casResetBonus()
	casResetPool("grin", 10_000_000)
	p := casAddr("cas-fs")
	casSet(&balances, p.String()+":grin", 100_000)
	players := []address{p, adm}
	total0 := casTotal("grin", players)

	b := casPlay(cur, t, adm, p, "cr-g-25", "slots", "spin", 100)
	if b.payout != 240 || b.scatters != 3 || b.fsGranted != 10 {
		t.Fatalf("trigger spin payout %d scatters %d granted %d", b.payout, b.scatters, b.fsGranted)
	}
	g := getGrant(p.String())
	if g == nil || g.left != 10 || g.bet != 100 || g.capLeft != 50000-240 {
		t.Fatalf("grant %s", FreeSpinGrant(p.String()))
	}
	if casGet(&casinoReserved, "grin") != 50000-240 {
		t.Fatalf("grant reservation %d", casGet(&casinoReserved, "grin"))
	}
	bal0 := casBalOf(p.String(), "grin")

	// A paid slots spin waits until the free spins are used.
	testing.SetRealm(testing.NewUserRealm(adm))
	CommitCasinoSeed(cross(cur), "cr-f-paid", p.String(), casSeedHash("s-cr-f-paid"))
	testing.SetRealm(testing.NewUserRealm(p))
	casAbort(t, "paid spin during grant", revive(func() {
		PlaceCasinoBet(cross(cur), "cr-f-paid", "slots", "grin", "100", "spin", sha256Hex("c-cr-f-paid"))
	}), "finish your free spins")

	// Only the grant owner can spin; refund of a stuck free spin gives the spin back.
	testing.SetRealm(testing.NewUserRealm(adm))
	CommitCasinoSeed(cross(cur), "cr-f-r", p.String(), casSeedHash("s-cr-f-r"))
	testing.SetRealm(testing.NewUserRealm(p))
	PlaceCasinoFreeSpin(cross(cur), "cr-f-r", sha256Hex("c-cr-f-r"))
	testing.SetRealm(testing.NewUserRealm(adm))
	CommitCasinoSeed(cross(cur), "cr-f-x", p.String(), casSeedHash("s-cr-f-x"))
	testing.SetRealm(testing.NewUserRealm(p))
	casAbort(t, "two free spins in flight", revive(func() {
		PlaceCasinoFreeSpin(cross(cur), "cr-f-x", sha256Hex("c-cr-f-x"))
	}), "already in progress")
	testing.SkipHeights(361)
	RefundCasinoBet(cross(cur), "cr-f-r")
	if g.left != 10 || g.inRound != "" || casBalOf(p.String(), "grin") != bal0 {
		t.Fatalf("free spin refund: %s bal %d", FreeSpinGrant(p.String()), casBalOf(p.String(), "grin"))
	}

	wants := []uint64{896, 0, 216, 0, 0, 0, 1640, 80, 0}
	for j, want := range wants {
		round := "cr-f-" + strconv.Itoa(j)
		testing.SetRealm(testing.NewUserRealm(adm))
		CommitCasinoSeed(cross(cur), round, p.String(), casSeedHash("s-"+round))
		testing.SetRealm(testing.NewUserRealm(p))
		before := casBalOf(p.String(), "grin")
		PlaceCasinoFreeSpin(cross(cur), round, sha256Hex("c-"+round))
		if casBalOf(p.String(), "grin") != before {
			t.Fatalf("free spin took a stake")
		}
		testing.SetRealm(testing.NewUserRealm(adm))
		RevealCasinoSeed(cross(cur), round, "s-"+round)
		RevealCasinoSecret(cross(cur), round, "c-"+round)
		fb := casinoBets.Get(round + ":" + p.String()).(*casinoBet)
		if !fb.freeSpin || fb.payout != want || casBalOf(p.String(), "grin") != before+want || fb.fsGranted != 0 || fb.hsTiles != "" {
			t.Errorf("free spin %d payout %d want %d", j, fb.payout, want)
		}
		if casTotal("grin", players) != total0 {
			t.Fatalf("conservation broken at free spin %d", j)
		}
		if casGet(&casinoReserved, "grin") != g.capLeft {
			t.Fatalf("reservation %d != capLeft %d", casGet(&casinoReserved, "grin"), g.capLeft)
		}
	}
	if g.left != 1 || g.won != 2832 || g.capLeft != 50000-240-2832 {
		t.Fatalf("grant after 9: %s", FreeSpinGrant(p.String()))
	}
	// The last free spin is never revealed by the player: forfeited after 24h, wins 0, grant closes.
	testing.SetRealm(testing.NewUserRealm(adm))
	CommitCasinoSeed(cross(cur), "cr-f-9", p.String(), casSeedHash("s-cr-f-9"))
	testing.SetRealm(testing.NewUserRealm(p))
	PlaceCasinoFreeSpin(cross(cur), "cr-f-9", sha256Hex("c-cr-f-9"))
	testing.SetRealm(testing.NewUserRealm(adm))
	RevealCasinoSeed(cross(cur), "cr-f-9", "s-cr-f-9")
	testing.SkipHeights(17281)
	testing.SetRealm(testing.NewUserRealm(casAddr("cas-anyone")))
	ForfeitCasinoBet(cross(cur), "cr-f-9")
	if getGrant(p.String()) != nil || FreeSpinGrant(p.String()) != "null" || casGet(&casinoReserved, "grin") != 0 {
		t.Fatalf("grant not closed: %s reserved %d", FreeSpinGrant(p.String()), casGet(&casinoReserved, "grin"))
	}
	if casTotal("grin", players) != total0 {
		t.Fatalf("conservation broken after the feature")
	}
	// Paid spins are open again.
	testing.SetRealm(testing.NewUserRealm(adm))
	CommitCasinoSeed(cross(cur), "cr-f-after", p.String(), casSeedHash("s-cr-f-after"))
	testing.SetRealm(testing.NewUserRealm(p))
	PlaceCasinoBet(cross(cur), "cr-f-after", "slots", "grin", "100", "spin", sha256Hex("c-cr-f-after"))
	testing.SetRealm(testing.NewUserRealm(casAddr("cas-nogrant")))
	casAbort(t, "free spin without grant", revive(func() {
		PlaceCasinoFreeSpin(cross(cur), "cr-f-x", sha256Hex("c-cr-f-x"))
	}), "another player")
}

func TestCasino_HoldAndSpinJackpots(cur realm, t *testing.T) {
	adm := casSetup()
	casResetBonus()
	casResetPool("grin", 10_000_000)
	p := casAddr("cas-hs")
	casSet(&balances, p.String()+":grin", 100_000)
	casSet(&balances, adm.String()+":grin", 50_000)
	players := []address{p, adm}

	// Only the admin seeds, from its own balance; seeds and ref bet are admin-only.
	testing.SetRealm(testing.NewUserRealm(p))
	casAbort(t, "non-admin seed", revive(func() { SeedCasinoJackpot(cross(cur), "grin", "major", "10") }), "admin only")
	casAbort(t, "non-admin reset", revive(func() { SetCasinoJackpotSeed(cross(cur), "grin", "major", "10") }), "admin only")
	testing.SetRealm(testing.NewUserRealm(adm))
	casAbort(t, "bad tier", revive(func() { SeedCasinoJackpot(cross(cur), "grin", "mega", "10") }), "tier")
	casAbort(t, "seed above balance", revive(func() { SeedCasinoJackpot(cross(cur), "grin", "grand", "60000") }), "")
	SeedCasinoJackpot(cross(cur), "grin", "major", "5000")
	SeedCasinoJackpot(cross(cur), "grin", "grand", "20000")
	SetCasinoJackpotSeed(cross(cur), "grin", "major", "3000")
	SetCasinoJackpotSeed(cross(cur), "grin", "grand", "10000")
	if casBalOf(adm.String(), "grin") != 25000 || casJp("grin") != 25000 {
		t.Fatalf("seeding moved %d", casJp("grin"))
	}
	if !strings.Contains(JackpotPool("grin"), `"pool":"20000"`) {
		t.Errorf("JackpotPool should report GRAND: %s", JackpotPool("grin"))
	}
	total0 := casTotal("grin", players)

	// Plain Hold & Spin: coins only, inside the 500× cap.
	b := casPlay(cur, t, adm, p, "cr-g-212", "slots", "spin", 100)
	if b.payout != 820 || b.hsMult != 6 || b.hsRespins != 3 || b.jackpots != "" || b.hsTiles != "0.1.0.0.3.0.0.0.0.0.0.0.0.0.0.1.0.0.1.0" {
		t.Errorf("hold&spin payout %d mult %d respins %d tiles %s", b.payout, b.hsMult, b.hsRespins, b.hsTiles)
	}
	// Each paid spin feeds MAJOR 1% and GRAND 0.5% (remainders carried).
	if casGet(&casinoJackpot, jpKey("grin", "major")) != 5001 || casGet(&casinoJpDust, jpKey("grin", "grand")) != 5000 {
		t.Errorf("contribution major %d grand dust %d", casGet(&casinoJackpot, jpKey("grin", "major")), casGet(&casinoJpDust, jpKey("grin", "grand")))
	}
	if casTotal("grin", players) != total0 {
		t.Fatalf("conservation broken after hold&spin")
	}

	// MAJOR at the reference bet: the whole pool (incl. this spin's 1), then reset to its seed from the house.
	bal := casBalOf(p.String(), "grin")
	house := casGet(&casinoPool, "grin")
	b = casPlay(cur, t, adm, p, "cr-g-8273", "slots", "spin", 100)
	if b.jackpots != "major" || b.jackpotWin != 5002 || b.payout != 2800+5002 || b.hsMult != 28 {
		t.Errorf("major: jackpots %q win %d payout %d mult %d", b.jackpots, b.jackpotWin, b.payout, b.hsMult)
	}
	if casBalOf(p.String(), "grin") != bal-100+b.payout {
		t.Errorf("major paid %d", casBalOf(p.String(), "grin")-bal)
	}
	if casGet(&casinoJackpot, jpKey("grin", "major")) != 3000 {
		t.Errorf("major not reset to its seed: %d", casGet(&casinoJackpot, jpKey("grin", "major")))
	}
	// house: +100 stake −2800 win −1 major −1 grand(dust 5000+5000) −3000 reset
	if casGet(&casinoPool, "grin") != house+100-2800-1-1-3000 {
		t.Errorf("house after major %d → %d", house, casGet(&casinoPool, "grin"))
	}
	if casTotal("grin", players) != total0 {
		t.Fatalf("conservation broken after major")
	}

	// GRAND at half the reference bet pays half the pool.
	grand0 := casGet(&casinoJackpot, jpKey("grin", "grand"))
	b = casPlay(cur, t, adm, p, "cr-g-29989", "slots", "spin", 50)
	if b.jackpots != "grand" || b.jackpotWin != grand0/2 || b.payout != 450+grand0/2 {
		t.Errorf("grand: jackpots %q win %d (pool %d) payout %d", b.jackpots, b.jackpotWin, grand0, b.payout)
	}
	if casGet(&casinoJackpot, jpKey("grin", "grand")) != 10001 {
		// half stays (10000 + the 1 contributed) → above the 10000 seed, no top-up
		t.Errorf("grand after hit %d", casGet(&casinoJackpot, jpKey("grin", "grand")))
	}
	if casTotal("grin", players) != total0 {
		t.Fatalf("conservation broken after grand")
	}
	if !strings.Contains(CasinoJackpots("grin"), `"major":"3000"`) || !strings.Contains(CasinoBet("cr-g-29989", p.String()), `"jackpots":"grand"`) {
		t.Errorf("queries: %s", CasinoJackpots("grin"))
	}
	if casGet(&casinoReserved, "grin") != 0 {
		t.Errorf("reservations left %d", casGet(&casinoReserved, "grin"))
	}
}

func TestCasino_HSPayoutRules(t *testing.T) {
	var tiles [slotsCells]uint16
	tiles[0], tiles[1], tiles[2], tiles[3] = 5, hsMini, hsMinor, hsMajor
	tiles[4], tiles[5] = hsMajor, hsGrand
	m, mj, gr := slotsHSPayout(&tiles, false)
	if m != 5+20+75+75 || !mj || !gr {
		t.Errorf("hs payout %d %v %v", m, mj, gr)
	}
	var full [slotsCells]uint16
	for i := range full {
		full[i] = 1
	}
	m, mj, gr = slotsHSPayout(&full, true)
	if m != 20 || mj || !gr {
		t.Errorf("blackout %d %v %v", m, mj, gr)
	}
}


func TestCasino_OperatorIsSeparateKey(cur realm, t *testing.T) {
	adm := casSetup()
	casResetPool("grin", 100000)
	op := casAddr("cas-op2")
	p := casAddr("cas-op-player")
	testing.SetRealm(testing.NewUserRealm(adm))
	casAbort(t, "operator = admin", revive(func() { SetOperator(cross(cur), adm.String()) }), "separate key")
	// bootstrap: no operator yet → the admin may commit
	CommitCasinoSeed(cross(cur), "cr-op-boot", p.String(), casSeedHash("s"))
	SetOperator(cross(cur), op.String())
	casAbort(t, "admin after operator set", revive(func() {
		CommitCasinoSeed(cross(cur), "cr-op-adm", p.String(), casSeedHash("s"))
	}), "operator")
	testing.SetRealm(testing.NewUserRealm(op))
	CommitCasinoSeed(cross(cur), "cr-op-ok", p.String(), casSeedHash("s"))
	operator = address("")
}

func TestCasino_StatsConservation(cur realm, t *testing.T) {
	adm := casSetup()
	casResetBonus()
	casinoPool = avl.Tree{}
	casinoReserved = avl.Tree{}
	casinoDay = avl.Tree{}
	casinoRounds = avl.Tree{}
	casinoBets = avl.Tree{}
	casSet(&balances, adm.String()+":grin", 10_100_000)
	testing.SetRealm(testing.NewUserRealm(adm))
	SeedCasinoPool(cross(cur), "grin", "10000000")
	SeedCasinoJackpot(cross(cur), "grin", "major", "5000")
	SeedCasinoJackpot(cross(cur), "grin", "grand", "20000")
	p := casAddr("cas-stats")
	casSet(&balances, p.String()+":grin", 1_000_000)
	casPlay(cur, t, adm, p, "cr-g-25", "slots", "spin", 100) // grants 10 free spins
	for j := 0; j < 9; j++ {
		round := "cr-f-" + strconv.Itoa(j)
		testing.SetRealm(testing.NewUserRealm(adm))
		CommitCasinoSeed(cross(cur), round, p.String(), casSeedHash("s-"+round))
		testing.SetRealm(testing.NewUserRealm(p))
		PlaceCasinoFreeSpin(cross(cur), round, sha256Hex("c-"+round))
		testing.SetRealm(testing.NewUserRealm(adm))
		RevealCasinoSeed(cross(cur), round, "s-"+round)
		RevealCasinoSecret(cross(cur), round, "c-"+round)
	}
	casPlay(cur, t, adm, p, "cr-st-cf", "coin_flip", "heads", 100)
	casPlay(cur, t, adm, p, "cr-st-rps", "rps", "rock", 100)
	st := CasinoStats("grin")
	if !strings.Contains(st, `"conserved":true`) || !strings.Contains(st, `"seeded":"10025000"`) {
		t.Errorf("stats: %s", st)
	}
	if !strings.Contains(st, `"slots":{"rounds":10,"staked":"100","paid":"`+casU(240+2832)+`"}`) {
		t.Errorf("slots stats: %s", st)
	}
	if !strings.Contains(st, `"freeSpinsOpen":1`) {
		t.Errorf("open grant: %s", st)
	}
}

game_daily_test.gno

package game32

import (
	"strconv"
	"testing"
	"time"
)

// ── DailyCheckin helpers ──────────────────────────────────────────────────────

// resetDailyCheckin removes any stored check-in state for the address.
func resetDailyCheckin(addr string) {
	dailyCheckins.Remove(addr)
}

// setDailyCheckinRaw directly writes a raw value into dailyCheckins.
// Use this to seed "yesterday", "old format", etc. without going through
// the DailyCheckin transaction path.
func setDailyCheckinRaw(addr, raw string) {
	dailyCheckins.Set(addr, raw)
}

// getDailyCheckinRaw reads the raw stored value (for assertions).
func getDailyCheckinRaw(addr string) string {
	if !dailyCheckins.Has(addr) {
		return ""
	}
	return dailyCheckins.Get(addr).(string)
}

// ── parseDailyCheckin tests ───────────────────────────────────────────────────

func TestParseDailyCheckinNewFormat(t *testing.T) {
	lastDay, streak := parseDailyCheckin("20000:5")
	if lastDay != 20000 {
		t.Errorf("lastDay: got %d, want 20000", lastDay)
	}
	if streak != 5 {
		t.Errorf("streak: got %d, want 5", streak)
	}
}

func TestParseDailyCheckinLegacyFormat(t *testing.T) {
	// Old format: raw unix seconds.  day 19000 = 19000 * 86400 = 1641600000
	seconds := int64(19000 * 86400)
	raw := strconv.FormatInt(seconds, 10)
	lastDay, streak := parseDailyCheckin(raw)
	if lastDay != 19000 {
		t.Errorf("lastDay: got %d, want 19000", lastDay)
	}
	if streak != 1 {
		t.Errorf("legacy format must give streak=1, got %d", streak)
	}
}

func TestParseDailyCheckinEmpty(t *testing.T) {
	// Edge: value "0" (no prior check-in default)
	lastDay, streak := parseDailyCheckin("0")
	if lastDay != 0 {
		t.Errorf("lastDay: got %d, want 0", lastDay)
	}
	if streak != 1 {
		t.Errorf("streak: got %d, want 1", streak)
	}
}

// ── DailyCheckin streak logic tests ──────────────────────────────────────────

func TestDailyCheckinFirstCheckin(t *testing.T) {
	addr := "g1dailytest001"
	resetDailyCheckin(addr)

	today := time.Now().Unix() / 86400

	// Simulate first check-in: no prior state → DailyCheckin writes today:1
	// We call the logic inline (mirrors BuyToolDirect approach) since DailyCheckin
	// requires a cur realm that isn't available in unit tests.
	// Precondition: nothing stored
	if dailyCheckins.Has(addr) {
		t.Fatal("precondition: must have no prior check-in")
	}

	// Perform the streak update logic directly (same as DailyCheckin body)
	var lastDay, streak int64
	// No entry → both stay 0
	_ = lastDay
	_ = streak
	// today != 0 and 0 != today-1 → streak = 1
	newStreak := int64(1)
	val := strconv.FormatInt(today, 10) + ":" + strconv.FormatInt(newStreak, 10)
	dailyCheckins.Set(addr, val)

	// Verify
	stored := getDailyCheckinRaw(addr)
	gotDay, gotStreak := parseDailyCheckin(stored)
	if gotDay != today {
		t.Errorf("lastDay: got %d, want %d", gotDay, today)
	}
	if gotStreak != 1 {
		t.Errorf("streak after first check-in: got %d, want 1", gotStreak)
	}
}

func TestDailyCheckinConsecutiveDays(t *testing.T) {
	addr := "g1dailytest002"
	resetDailyCheckin(addr)

	today := time.Now().Unix() / 86400
	yesterday := today - 1

	// Seed: player checked in yesterday with streak=3
	setDailyCheckinRaw(addr, strconv.FormatInt(yesterday, 10)+":3")

	// Now simulate today's check-in
	raw := getDailyCheckinRaw(addr)
	lastDay, streak := parseDailyCheckin(raw)

	if lastDay == today {
		t.Fatal("test setup error: lastDay should be yesterday")
	}
	var newStreak int64
	if lastDay == today-1 {
		newStreak = streak + 1 // should be 4
	} else {
		newStreak = 1
	}

	val := strconv.FormatInt(today, 10) + ":" + strconv.FormatInt(newStreak, 10)
	dailyCheckins.Set(addr, val)

	gotDay, gotStreak := parseDailyCheckin(getDailyCheckinRaw(addr))
	if gotDay != today {
		t.Errorf("lastDay: got %d, want %d", gotDay, today)
	}
	if gotStreak != 4 {
		t.Errorf("streak after consecutive day: got %d, want 4", gotStreak)
	}
}

func TestDailyCheckinSkippedDay(t *testing.T) {
	addr := "g1dailytest003"
	resetDailyCheckin(addr)

	today := time.Now().Unix() / 86400
	twoDaysAgo := today - 2

	// Seed: player last checked in 2 days ago with a long streak
	setDailyCheckinRaw(addr, strconv.FormatInt(twoDaysAgo, 10)+":42")

	raw := getDailyCheckinRaw(addr)
	lastDay, streak := parseDailyCheckin(raw)
	_ = streak

	var newStreak int64
	if lastDay == today {
		t.Fatal("same-day check detected unexpectedly")
	} else if lastDay == today-1 {
		newStreak = streak + 1
	} else {
		newStreak = 1 // streak resets
	}

	val := strconv.FormatInt(today, 10) + ":" + strconv.FormatInt(newStreak, 10)
	dailyCheckins.Set(addr, val)

	_, gotStreak := parseDailyCheckin(getDailyCheckinRaw(addr))
	if gotStreak != 1 {
		t.Errorf("streak after missed day: got %d, want 1", gotStreak)
	}
}

func TestDailyCheckinSameDayPanics(t *testing.T) {
	addr := "g1dailytest004"
	resetDailyCheckin(addr)

	today := time.Now().Unix() / 86400

	// Seed: already checked in today
	setDailyCheckinRaw(addr, strconv.FormatInt(today, 10)+":7")

	// The DailyCheckin function should panic with "already checked in today"
	// when lastDay == today. We replicate the same panic condition here.
	mustPanic(t, "already checked in today", func() {
		raw := getDailyCheckinRaw(addr)
		lastDay, _ := parseDailyCheckin(raw)
		if lastDay == today {
			panic("already checked in today")
		}
	})
}

func TestDailyCheckinOldUnixSecondsFormat(t *testing.T) {
	addr := "g1dailytest005"
	resetDailyCheckin(addr)

	today := time.Now().Unix() / 86400
	yesterdaySeconds := (today - 1) * 86400

	// Seed: old format — raw unix seconds for yesterday
	setDailyCheckinRaw(addr, strconv.FormatInt(yesterdaySeconds, 10))

	// parseDailyCheckin must interpret this as lastDay = yesterdaySeconds/86400 = today-1, streak=1
	raw := getDailyCheckinRaw(addr)
	lastDay, streak := parseDailyCheckin(raw)

	if lastDay != today-1 {
		t.Errorf("old format lastDay: got %d, want %d", lastDay, today-1)
	}
	if streak != 1 {
		t.Errorf("old format streak: got %d, want 1", streak)
	}

	// Checking in today from old-format yesterday → streak becomes 2
	var newStreak int64
	if lastDay == today-1 {
		newStreak = streak + 1
	} else {
		newStreak = 1
	}
	if newStreak != 2 {
		t.Errorf("streak after old-format yesterday: got %d, want 2", newStreak)
	}
}

// ── DailyCheckinStatus tests ──────────────────────────────────────────────────

func TestDailyCheckinStatusNeverCheckedIn(t *testing.T) {
	addr := "g1statustest001"
	resetDailyCheckin(addr)

	status := DailyCheckinStatus(addr)
	if !strContains(status, `"ok":true`) {
		t.Errorf("expected ok:true, got %s", status)
	}
	if !strContains(status, `"done":false`) {
		t.Errorf("expected done:false for no check-in, got %s", status)
	}
	if !strContains(status, `"streak":0`) {
		t.Errorf("expected streak:0 for no check-in, got %s", status)
	}
}

func TestDailyCheckinStatusCheckedInToday(t *testing.T) {
	addr := "g1statustest002"
	resetDailyCheckin(addr)

	today := time.Now().Unix() / 86400
	// Simulate checked in today with streak=5
	setDailyCheckinRaw(addr, strconv.FormatInt(today, 10)+":5")

	status := DailyCheckinStatus(addr)
	if !strContains(status, `"done":true`) {
		t.Errorf("expected done:true when checked in today, got %s", status)
	}
	if !strContains(status, `"streak":5`) {
		t.Errorf("expected streak:5, got %s", status)
	}
}

func TestDailyCheckinStatusCheckedInYesterday(t *testing.T) {
	addr := "g1statustest003"
	resetDailyCheckin(addr)

	today := time.Now().Unix() / 86400
	yesterday := today - 1
	// Checked in yesterday — streak is still live (not broken yet)
	setDailyCheckinRaw(addr, strconv.FormatInt(yesterday, 10)+":12")

	status := DailyCheckinStatus(addr)
	if !strContains(status, `"done":false`) {
		t.Errorf("expected done:false (not checked in today), got %s", status)
	}
	// Streak is still live (lastDay == today-1)
	if !strContains(status, `"streak":12`) {
		t.Errorf("expected streak:12 (live streak), got %s", status)
	}
}

func TestDailyCheckinStatusStreakBrokenAfterMissedDay(t *testing.T) {
	addr := "g1statustest004"
	resetDailyCheckin(addr)

	today := time.Now().Unix() / 86400
	twoDaysAgo := today - 2
	// Last check-in was 2 days ago — streak is broken
	setDailyCheckinRaw(addr, strconv.FormatInt(twoDaysAgo, 10)+":30")

	status := DailyCheckinStatus(addr)
	if !strContains(status, `"done":false`) {
		t.Errorf("expected done:false, got %s", status)
	}
	// Streak must report 0 when broken
	if !strContains(status, `"streak":0`) {
		t.Errorf("expected streak:0 after missed day, got %s", status)
	}
}

func TestDailyCheckinStatusNextMidnight(t *testing.T) {
	addr := "g1statustest005"
	resetDailyCheckin(addr)

	today := time.Now().Unix() / 86400
	setDailyCheckinRaw(addr, strconv.FormatInt(today, 10)+":1")

	status := DailyCheckinStatus(addr)
	// next field must be (today+1)*86400
	wantNext := (today + 1) * 86400
	wantStr := `"next":` + strconv.FormatInt(wantNext, 10)
	if !strContains(status, wantStr) {
		t.Errorf("expected %s in status, got %s", wantStr, status)
	}
}

func TestDailyCheckinStatusOldFormat(t *testing.T) {
	addr := "g1statustest006"
	resetDailyCheckin(addr)

	today := time.Now().Unix() / 86400
	// Seed yesterday in old unix-seconds format
	yesterdaySeconds := (today - 1) * 86400
	setDailyCheckinRaw(addr, strconv.FormatInt(yesterdaySeconds, 10))

	status := DailyCheckinStatus(addr)
	// Old format is yesterday → streak lives at 1, not yet done today
	if !strContains(status, `"done":false`) {
		t.Errorf("expected done:false (old format, yesterday), got %s", status)
	}
	if !strContains(status, `"streak":1`) {
		t.Errorf("expected streak:1 (old format gives streak=1), got %s", status)
	}
}

// ── helpers (from the game28 test suite) ──
func mustPanic(t *testing.T, wantSubstr string, f func()) {
	t.Helper()
	var msg string
	panicked := false
	func() {
		defer func() {
			r := recover()
			if r != nil {
				panicked = true
				switch v := r.(type) {
				case string:
					msg = v
				case error:
					msg = v.Error()
				default:
					msg = "non-string panic"
				}
			}
		}()
		f()
	}()
	if !panicked {
		t.Errorf("expected panic containing %q, but no panic occurred", wantSubstr)
		return
	}
	if wantSubstr != "" && !strContains(msg, wantSubstr) {
		t.Errorf("panic message %q does not contain %q", msg, wantSubstr)
	}
}

func strContains(s, sub string) bool {
	if len(sub) == 0 {
		return true
	}
	if len(sub) > len(s) {
		return false
	}
	for i := 0; i <= len(s)-len(sub); i++ {
		if s[i:i+len(sub)] == sub {
			return true
		}
	}
	return false
}


func TestRepairCostCeil30Pct(t *testing.T) {
	type tc struct {
		toolId   string
		coinId   string
		base     uint64
		expected uint64 // ceil(base × 30%) = (base×30 + 99) / 100
	}
	cases := []tc{
		// wood: seedling:19 → ceil(5.7) = 6
		{"wood", "seedling", 19, 6},
		// wood: party:8 → ceil(2.4) = 3
		{"wood", "party", 8, 3},
		// iron: gear:42 → ceil(12.6) = 13
		{"iron", "gear", 42, 13},
		// iron: magnet:4 → ceil(1.2) = 2
		{"iron", "magnet", 4, 2},
		// quasar: lotus:3510 → ceil(1053.0) = 1053
		{"quasar", "lotus", 3510, 1053},
		// omega: lotus:26970 → ceil(8091.0) = 8091
		{"omega", "lotus", 26970, 8091},
		// stone: cactus:15 → ceil(4.5) = 5
		{"stone", "cactus", 15, 5},
	}
	for _, c := range cases {
		costs, hasCosts := toolCosts[c.toolId]
		if !hasCosts {
			t.Errorf("toolCosts missing for %s", c.toolId)
			continue
		}
		found := false
		for _, pair := range costs {
			if pair[0] != c.coinId {
				continue
			}
			found = true
			base, _ := strconv.ParseUint(pair[1], 10, 64)
			if base != c.base {
				t.Errorf("%s[%s]: expected base=%d, got %d", c.toolId, c.coinId, c.base, base)
			}
			got := (base*30 + 99) / 100
			if got != c.expected {
				t.Errorf("%s[%s]: ceil(30%%)=%d expected, got %d", c.toolId, c.coinId, c.expected, got)
			}
			break
		}
		if !found {
			t.Errorf("%s does not contain ingredient %s", c.toolId, c.coinId)
		}
	}
}

game_data.gno

// GnoMoji — Main Game Realm (game32)
// gno.land/r/g138gdmwj6heduu3st796lw6qqdwylgaxf7ty5gz/game32
//
// game29 closes the game28 audit holes (see SECURITY_GAME28.md):
//   - claims and achievements need an ed25519 voucher from the server's claim
//     signer (a dedicated key, never the treasury), with per-player nonces;
//   - per-rarity rate caps still apply on chain, plus per-coin vein caps;
//   - the Gnome Pass costs real ugnot (OriginSend), withdrawable by admin;
//   - PvP commit/reveal is hash-checked, casino bets settle on chain;
//   - player state can be imported once from game27/game28, then locked.

package game32

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

const realmPkgPath = "gno.land/r/g138gdmwj6heduu3st796lw6qqdwylgaxf7ty5gz/game32"

// ── State ────────────────────────────────────────────────────────────────────

var (
	admin    address // deployer; can set roles, prices, veins, migrate, withdraw
	operator address // server hot account for casino seeds (defaults to admin)

	// claimSignerPubKey is the ed25519 public key (32 bytes) whose signatures
	// authorise ClaimAndMint / achievement vouchers. Empty = claims disabled.
	claimSignerPubKey []byte
	claimNonces       avl.Tree // addr → last used voucher nonce (decimal string)

	balances      avl.Tree // addr+":"+coinId → amount string
	claimBuckets  avl.Tree // addr → "m0:t0|m1:t1|m2:t2|m3:t3|m4:t4|m5:t5|m6:t6" (packed; lazy-migrated from old addr:r keys)
	veinMinted    avl.Tree // coinId → total ever credited by claims/rewards/migration
	veinMaxOverride avl.Tree // coinId → admin-set max (overrides the rarity default)
	veinOverrideActive bool   // true once any SetVeinMax has been called; gates the veinMaxOverride AVL read
	casinoRounds  avl.Tree // roundId → *casinoRound
	pvpLobbies    avl.Tree // lobbyId and lobbyId+":field" → string (see game_pvp.gno)
	pvpWagers     avl.Tree // lobbyId → "coinId:amount:creator:challenger"
	ownedTools    avl.Tree // addr → comma-separated tool IDs
	toolLife      avl.Tree // addr+":"+toolId → remaining life string
	lifetimeMined avl.Tree // addr+":"+coinId → total mined string (real claims only)
	rewarded      avl.Tree // addr+":"+coinId → total credited by rewards (medals etc.)
	achievements  avl.Tree // addr+":"+achId → "1"
	dailyCheckins avl.Tree // addr → unix seconds string
	skillRanks    avl.Tree // addr+":"+skillId → rank string
	miners        avl.Tree // addr → total mined all-time string
	playerXp      avl.Tree // addr → cumulative rarity-weighted XP (uint64 string)
	lastClaim     avl.Tree // addr → unix timestamp of last ClaimAndMint
	blacklist     avl.Tree // addr → "reason:timestamp"
	banExpiries   avl.Tree // addr → unix expiry (0 = permanent)
	guilds        avl.Tree // guildId → JSON{name, leader, memberCount, createdAt}
	guildMembers  avl.Tree // guildId+":"+addr → "1"
	playerGuild   avl.Tree // addr → guildId
	gnomePasses   avl.Tree // addr → unix expiry timestamp string

	paused bool

	// Gnome Pass price in ugnot per 30 days (admin-settable).
	passPriceUgnot = int64(5000000)
	passRevenueUgnot int64 // lifetime ugnot received for passes (accounting only)

	pvpCounter   uint64 // monotonically increasing lobby number
	guildCounter uint64 // monotonically increasing guild number

	// Relay (game32): treasury wallet address authorised to call RelayBuyTool
	// and RelayTrainSkill on behalf of players (gasless tool purchases).
	// Set by SetRelayAddress (admin only). Zero value = relay disabled.
	relayAddress address
	// relayNonces tracks per-player relay nonces (shared sequence across all
	// relay kinds) to prevent replay attacks on gasless calls.
	relayNonces avl.Tree // addr → last nonce (decimal string)

	// Migration (game31 → game32). Batches are idempotent (set semantics +
	// batch registry); FinalizeMigration locks imports forever.
	// migrationAddrs tracks every unique player address imported via
	// MigrateBatch so MigrationStatus can report migrated-address count.
	migrationFinalized bool
	migrationBatches   avl.Tree // batchId → "kind:count"
	migrationAddrs     avl.Tree // addr → "1" (deduplicates across batch re-runs)
)

// ── Tool Tables (game29) ──────────────────────────────────────────────────────
// One ID scheme shared with src/lib/game/catalog.ts. Every ingredient is
// mineable by the previous tool (rarity ≤ prev maxRarity). Repair = ceil(30%
// of cost). See REPORT.md §4 for the full progression table and §5 for the
// claim-rate cap table.

// toolOrder is the canonical upgrade path from hands to omega.
var toolOrder = []string{
	"hands", "starter-twig", "twig", "wood", "stone", "iron", "gold",
	"diamond", "cosmic", "plasma", "neutron", "quasar", "void", "genesis", "omega",
}

// toolRequires: BuyTool must panic unless the caller owns the prerequisite tool.
var toolRequires = map[string]string{
	"starter-twig": "hands",
	"twig":         "starter-twig",
	"wood":         "twig",
	"stone":        "wood",
	"iron":         "stone",
	"gold":         "iron",
	"diamond":      "gold",
	"cosmic":       "diamond",
	"plasma":       "cosmic",
	"neutron":      "plasma",
	"quasar":       "neutron",
	"void":         "quasar",
	"genesis":      "void",
	"omega":        "genesis",
}

// toolMaxRarity: highest coin rarity each tool can mine (used by the claim rate cap).
var toolMaxRarity = map[string]int{
	"hands":        0,
	"starter-twig": 0,
	"twig":         0,
	"wood":         1,
	"stone":        2,
	"iron":         3,
	"gold":         4,
	"diamond":      5,
	"cosmic":       6,
	"plasma":       6,
	"neutron":      6,
	"quasar":       6,
	"void":         6,
	"genesis":      6,
	"omega":        6,
}

// toolCosts maps toolId → slice of [coinId, amount] pairs.
// Matches catalog.ts TOOLS array exactly. Amounts are for qty=1.
var toolCosts = map[string][][2]string{
	"starter-twig": {
		{"grin", "13"},
	},
	"twig": {
		{"grin", "14"}, {"joy", "9"}, {"cool", "7"},
	},
	"wood": {
		{"seedling", "19"}, {"leaves", "16"}, {"fallen", "13"}, {"think", "11"}, {"sleep", "10"}, {"party", "8"},
	},
	"stone": {
		{"rock", "50"}, {"log", "45"}, {"evergreen", "40"}, {"brick", "35"}, {"mushroom", "30"}, {"heart", "25"},
		{"deciduous", "20"}, {"cactus", "15"},
	},
	"iron": {
		{"gear", "42"}, {"chains", "42"}, {"wrench", "38"}, {"hammer", "34"}, {"anchor", "34"}, {"pick", "29"},
		{"nut", "21"}, {"saw", "8"}, {"hammer-wrench", "17"}, {"magnet", "4"},
	},
	"gold": {
		{"gold-medal", "150"}, {"crown", "140"}, {"trophy", "130"}, {"money-bag", "120"}, {"bolt", "120"}, {"sword", "110"},
		{"dagger", "10"}, {"bow", "10"}, {"bullseye", "30"}, {"mahjong", "10"}, {"hanafuda", "10"}, {"fireworks", "10"},
	},
	"diamond": {
		{"gem", "220"}, {"coin", "200"}, {"ring", "190"}, {"disco", "180"}, {"kite", "180"}, {"dodo", "160"},
		{"scope", "10"}, {"xray", "10"}, {"tube", "10"}, {"dish", "10"}, {"lock", "40"}, {"key-lock", "30"},
		{"eight", "20"}, {"puzzle", "30"},
	},
	"cosmic": {
		{"galaxy", "336"}, {"moai", "320"}, {"hamsa", "320"}, {"mirror", "304"}, {"atom", "288"}, {"ufo", "256"},
		{"whale-spout", "16"}, {"whale", "16"}, {"sun", "16"}, {"radioactive", "16"}, {"cyclone", "16"}, {"tornado", "16"},
		{"sat", "16"}, {"castle", "16"}, {"liberty", "16"}, {"castle-jp", "16"},
	},
	"plasma": {
		{"galaxy", "1003"}, {"atom", "935"}, {"moai", "935"}, {"comet", "867"}, {"jelly", "799"}, {"peacock", "799"},
		{"om", "17"}, {"yin", "17"}, {"ophiuchus", "17"}, {"fleur", "17"}, {"trident", "17"}, {"radioactive", "17"},
		{"biohazard", "17"}, {"castle-jp", "34"}, {"sun-face", "17"}, {"dragon-face", "17"}, {"sauropod", "17"}, {"moon-word", "34"},
	},
	"neutron": {
		{"jelly", "2040"}, {"peacock", "1870"}, {"unicorn", "1870"}, {"galaxy", "1700"}, {"hamsa", "1700"}, {"dna", "1496"},
		{"genie", "17"}, {"heart-organ", "34"}, {"mage", "34"}, {"monarch", "51"}, {"ninja", "34"}, {"brain", "17"},
		{"lotus-sit", "34"}, {"lion", "51"}, {"tiger", "51"}, {"eagle", "51"}, {"wolf", "68"}, {"shark", "85"},
	},
	"quasar": {
		{"unicorn", "4590"}, {"peacock", "4590"}, {"jelly", "4590"}, {"lotus", "3510"}, {"galaxy", "3780"}, {"dragon", "3510"},
		{"fireworks", "54"}, {"medal", "27"}, {"sports-medal", "54"}, {"silver-medal", "81"}, {"bronze-medal", "81"}, {"tower", "108"},
		{"hot-spring", "135"}, {"pirate", "81"}, {"fairy", "108"}, {"vampire", "108"}, {"heli", "54"}, {"bullet", "81"},
		{"race", "108"},
	},
	"void": {
		{"lotus", "8990"}, {"unicorn", "10850"}, {"dragon", "10540"}, {"peacock", "10850"}, {"jelly", "11470"}, {"galaxy", "3720"},
		{"om", "31"}, {"yin", "31"}, {"trident", "62"}, {"fleur", "62"}, {"ophiuchus", "31"}, {"shooting", "62"},
		{"sun-face", "62"}, {"dragon-face", "93"}, {"rex", "93"}, {"sauropod", "93"}, {"mammoth", "124"}, {"new-face", "93"},
		{"kaaba", "31"}, {"witness", "31"}, {"genie", "31"},
	},
	"genesis": {
		{"lotus", "18000"}, {"dragon", "18000"}, {"unicorn", "17520"}, {"peacock", "16560"}, {"jelly", "16080"}, {"infinity", "14160"},
		{"genie", "48"}, {"witness", "48"}, {"sun-face", "144"}, {"shooting", "96"}, {"dragon-face", "168"}, {"om", "72"},
		{"yin", "72"}, {"trident", "72"}, {"fleur", "72"}, {"kaaba", "72"}, {"rex", "144"}, {"sauropod", "144"},
		{"mammoth", "168"}, {"new-face", "144"}, {"lion", "264"}, {"shark", "504"},
	},
	"omega": {
		{"lotus", "26970"}, {"dragon", "25110"}, {"unicorn", "24180"}, {"peacock", "23250"}, {"jelly", "23250"}, {"infinity", "22320"},
		{"genie", "65"}, {"witness", "74"}, {"sun-face", "195"}, {"shooting", "158"}, {"dragon-face", "233"}, {"om", "93"},
		{"yin", "93"}, {"trident", "112"}, {"fleur", "112"}, {"ophiuchus", "93"}, {"kaaba", "93"}, {"rex", "195"},
		{"sauropod", "214"}, {"mammoth", "233"}, {"new-face", "195"}, {"mage", "307"}, {"heart-organ", "233"}, {"sat", "381"},
	},
}

// skillBaseCosts maps skillId → base cost at rank 0.
// Actual cost at rank N = base × 2^N (doubles per rank).
var skillBaseCosts = map[string][][2]string{
	// STRIKE branch
	"wrist":               {{"grin", "80"}, {"joy", "20"}},
	"palm_strike":         {{"cool", "60"}, {"think", "40"}},
	"follow":              {{"fire", "40"}, {"up", "40"}},
	"knuckle_wrap":        {{"rock", "45"}, {"log", "40"}},
	"heavy_swing":         {{"brick", "35"}, {"evergreen", "30"}},
	"stone_breaker":       {{"rock", "70"}, {"hammer", "25"}, {"gear", "20"}},
	"anvil_force":         {{"chains", "35"}, {"wrench", "30"}, {"brick", "60"}},
	"point_drive":         {{"pick", "35"}, {"gear", "40"}, {"log", "90"}},
	"kinetic_thrust":      {{"rocket", "20"}, {"bolt", "12"}, {"fire", "70"}},
	"crushing_blow":       {{"crown", "10"}, {"trophy", "12"}, {"hammer", "45"}, {"bolt", "15"}},
	"shatter_spike":       {{"sword", "18"}, {"pick", "45"}, {"chains", "45"}, {"gold-medal", "12"}},
	"ironclad_cleave":     {{"anchor", "40"}, {"gear", "60"}, {"wrench", "50"}, {"money-bag", "15"}},
	"thunder_jab":         {{"bolt", "25"}, {"rocket", "30"}, {"fire", "120"}, {"wand", "15"}},
	"titan_hammer":        {{"gem", "14"}, {"coin", "18"}, {"crown", "22"}, {"trophy", "22"}, {"sword", "28"}},
	"diamond_cleave":      {{"gem", "20"}, {"ring", "12"}, {"disco", "15"}, {"pick", "70"}, {"gold-medal", "24"}},
	"hyper_drive":         {{"kite", "15"}, {"dodo", "12"}, {"bolt", "35"}, {"rocket", "45"}, {"gear", "70"}},
	"quasar_impact":       {{"galaxy", "18"}, {"moai", "18"}, {"atom", "20"}, {"ufo", "16"}, {"comet", "18"}},
	"black_hole_crush":    {{"galaxy", "30"}, {"atom", "28"}, {"moai", "24"}, {"gem", "35"}, {"ring", "28"}, {"comet", "22"}},
	"mythic_annihilation": {{"dragon", "8"}, {"unicorn", "10"}, {"jelly", "12"}, {"peacock", "12"}, {"galaxy", "35"}, {"moai", "30"}},
	"singularity_fist":    {{"infinity", "6"}, {"lotus", "8"}, {"dragon", "10"}, {"unicorn", "12"}, {"jelly", "14"}, {"galaxy", "40"}},
	// FORTUNE branch
	"fortune":             {{"clover", "16"}, {"heart", "40"}},
	"four_leaf":           {{"seedling", "60"}, {"leaves", "50"}},
	"edge":                {{"pizza", "20"}, {"spark", "30"}},
	"glint":               {{"spark", "50"}, {"star", "12"}},
	"spark_chaser":        {{"fire", "45"}, {"tada", "25"}},
	"razor_focus":         {{"coffee", "25"}, {"game", "25"}, {"hundred", "30"}},
	"precision_cut":       {{"eyes", "40"}, {"skull", "35"}, {"flutter", "18"}},
	"aurora_gaze":         {{"rainbow", "15"}, {"spark", "60"}, {"moon", "20"}},
	"starlight_gleam":     {{"star", "25"}, {"clover", "20"}, {"heart", "80"}},
	"double_haul":         {{"gear", "30"}, {"anchor", "20"}, {"up", "70"}},
	"twin_strike":         {{"chains", "25"}, {"wrench", "25"}, {"pick", "20"}},
	"executioner":         {{"skull", "60"}, {"sword", "18"}, {"crown", "10"}, {"orb", "8"}},
	"celestial_sight":     {{"planet", "10"}, {"moon", "30"}, {"star", "30"}, {"bead", "8"}},
	"helix_harmony":       {{"dna", "12"}, {"spark", "80"}, {"rainbow", "25"}, {"orb", "10"}},
	"fortune_split":       {{"money-bag", "15"}, {"gold-medal", "12"}, {"clover", "35"}, {"chains", "40"}},
	"critical_surge":      {{"gem", "15"}, {"disco", "14"}, {"ring", "12"}, {"orb", "20"}, {"planet", "18"}},
	"astral_scintillation": {{"ring", "14"}, {"gem", "16"}, {"dna", "20"}, {"star", "60"}, {"moon", "50"}},
	"plunder_frenzy":      {{"coin", "25"}, {"money-bag", "30"}, {"gem", "12"}, {"crown", "25"}, {"trophy", "25"}},
	"singularity_edge":    {{"lotus", "6"}, {"dragon", "8"}, {"galaxy", "25"}, {"hamsa", "20"}, {"atom", "22"}, {"mirror", "20"}},
	"cosmic_fortune":      {{"peacock", "10"}, {"unicorn", "8"}, {"comet", "25"}, {"disco", "30"}, {"galaxy", "30"}, {"gem", "35"}},
	// POCKET branch
	"dustbag":             {{"grin", "200"}, {"sleep", "40"}},
	"rhythm":              {{"music", "16"}, {"clap", "30"}},
	"pocket_expansion":    {{"fallen", "45"}, {"herb", "35"}},
	"steady_tempo":        {{"party", "40"}, {"wow", "30"}},
	"cadence":             {{"music", "30"}, {"coffee", "20"}, {"clap", "50"}},
	"deep_pouch":          {{"log", "70"}, {"rock", "60"}, {"mushroom", "35"}},
	"vein_resonator":      {{"flutter", "20"}, {"rainbow", "15"}, {"tada", "40"}},
	"cart_bed":            {{"log", "120"}, {"rock", "100"}, {"brick", "80"}, {"money-bag", "10"}},
	"bounty_overflow":     {{"trophy", "15"}, {"crown", "12"}, {"pick", "45"}, {"game", "35"}},
	"fracture_pulse":      {{"bolt", "25"}, {"wand", "15"}, {"hammer", "50"}, {"rocket", "25"}},
	"metro_pulse":         {{"music", "45"}, {"coffee", "35"}, {"raise", "30"}, {"bolt", "15"}},
	"hoarders_tote":       {{"coin", "22"}, {"gem", "10"}, {"money-bag", "35"}, {"rock", "150"}, {"log", "150"}},
	"shatter_strike":      {{"gem", "14"}, {"bolt", "35"}, {"wand", "25"}, {"sword", "30"}, {"hammer", "60"}},
	"super_conductor":     {{"coin", "20"}, {"ring", "12"}, {"music", "60"}, {"bolt", "30"}, {"coffee", "50"}},
	"dodo_instinct":       {{"dodo", "14"}, {"kite", "14"}, {"crown", "22"}, {"trophy", "22"}, {"eyes", "80"}},
	"void_rend":           {{"infinity", "6"}, {"jelly", "12"}, {"dragon", "8"}, {"atom", "30"}, {"comet", "25"}, {"bolt", "60"}},
	"celestial_duplication": {{"infinity", "5"}, {"lotus", "6"}, {"dragon", "8"}, {"peacock", "10"}, {"coin", "40"}, {"gem", "35"}},
	"eternity_flow":       {{"infinity", "5"}, {"lotus", "6"}, {"peacock", "8"}, {"hamsa", "25"}, {"mirror", "25"}, {"music", "100"}},
	"abyssal_reserve":     {{"unicorn", "6"}, {"jelly", "10"}, {"moai", "25"}, {"ufo", "25"}, {"money-bag", "50"}, {"rock", "300"}},
	"singularity_snap":    {{"infinity", "8"}, {"lotus", "8"}, {"dragon", "10"}, {"galaxy", "40"}, {"moai", "30"}, {"bolt", "80"}},

	// ── Phase 5: Nature branch (level 20) ────────────────────────────────────
	"deep_root":       {{"bear", "60"}, {"fox", "40"}},
	"stone_sense":     {{"turtle", "30"}, {"coral", "15"}},
	"bloom_tide":      {{"sakura", "20"}, {"bee", "50"}, {"deciduous", "80"}},
	"thorn_hide":      {{"boar", "40"}, {"snake", "30"}, {"scorpion", "20"}},
	"old_growth":      {{"elephant", "25"}, {"gorilla", "20"}, {"whale-spout", "15"}},
	"storm_surge":     {{"storm", "25"}, {"lightning-cloud", "20"}, {"tornado", "15"}},
	"predator_sense":  {{"tiger", "20"}, {"lion", "20"}, {"wolf", "20"}, {"eagle", "15"}},
	"world_tree":      {{"rex", "12"}, {"mammoth", "10"}, {"dragon-face", "8"}, {"shooting", "8"}},

	// ── Phase 5: Food branch (level 30) ──────────────────────────────────────
	"hot_meal":     {{"ramen", "50"}, {"stew", "40"}},
	"sugar_rush":   {{"candy", "60"}, {"cupcake", "40"}, {"donut", "30"}},
	"second_wind":  {{"burger", "50"}, {"bacon", "40"}, {"cheese", "30"}},
	"caffeinated":  {{"boba", "40"}, {"tea", "30"}, {"sake", "25"}},
	"feast_mode":   {{"sushi", "30"}, {"curry", "40"}, {"pasta", "40"}, {"paella", "25"}},
	"night_shift":  {{"honey", "30"}, {"pie", "25"}, {"cake", "20"}},
	"brew_mastery": {{"beer", "40"}, {"wine", "30"}, {"cocktail", "20"}, {"champagne", "15"}},
	"mythic_feast": {{"tropical-drink", "20"}, {"cheers", "15"}, {"toast", "12"}, {"mate", "12"}},

	// ── Phase 5: People branch (level 40) ────────────────────────────────────
	"mentor":        {{"baby", "60"}, {"child", "50"}},
	"crowd_favor":   {{"clap", "80"}, {"heart-hands", "60"}},
	"team_spirit":   {{"shake", "40"}, {"pray", "30"}, {"hug-pair", "30"}},
	"athlete_heart": {{"surf", "30"}, {"swim", "30"}, {"run", "40"}, {"lift", "25"}},
	"warrior_code":  {{"ninja", "20"}, {"fencer", "15"}, {"juggle", "15"}},
	"elder_wisdom":  {{"monarch", "15"}, {"mage", "15"}, {"fairy", "12"}},
	"hero_legend":   {{"hero", "12"}, {"vampire", "10"}, {"merfolk", "10"}},
	"genie_wish":    {{"genie", "8"}, {"heart-organ", "12"}},

	// ── Phase 5: Things branch (level 50) ────────────────────────────────────
	"tempered_grip":   {{"gloves", "80"}, {"hammer", "60"}},
	"field_repair":    {{"hammer-wrench", "40"}, {"saw", "30"}, {"nut", "50"}},
	"master_craft":    {{"wrench", "60"}, {"driver", "50"}, {"clamp", "30"}},
	"workshop_lore":   {{"toolbox", "30"}, {"abacus", "25"}, {"scroll", "20"}},
	"iron_discipline": {{"axe", "30"}, {"dagger", "20"}, {"bow", "15"}},
	"vault_keeper":    {{"lock", "40"}, {"key-lock", "30"}, {"old-key", "15"}},
	"precision_forge": {{"scope", "20"}, {"telescope", "15"}, {"tube", "18"}, {"dish", "15"}},
	"deep_science":    {{"alembic", "12"}, {"shield", "15"}, {"hammer-pick", "15"}, {"scale", "12"}},

	// ── Phase 5: Travel branch (level 65) ────────────────────────────────────
	"long_haul":      {{"car", "80"}, {"bus", "60"}},
	"vein_compass":   {{"plane", "50"}, {"sail", "30"}},
	"nomad_pace":     {{"moto", "40"}, {"cycle", "50"}, {"scooter", "40"}},
	"deep_sea":       {{"ship", "30"}, {"whale-spout", "15"}, {"dolphin", "25"}},
	"sky_route":      {{"rocket", "30"}, {"heli", "20"}, {"depart", "20"}},
	"monument_seal":  {{"tower", "20"}, {"castle", "15"}, {"liberty", "12"}},
	"orbital_drift":  {{"sat", "15"}, {"castle-jp", "12"}},
	"sacred_ground":  {{"kaaba", "8"}, {"shrine", "10"}, {"temple", "10"}, {"mosque", "10"}},

	// ── Phase 5: Signs branch (level 80) ─────────────────────────────────────
	"amplify":       {{"sparkle", "80"}, {"eight-star", "60"}},
	"resonance":     {{"recycle", "60"}, {"medical", "50"}},
	"sigil_power":   {{"worship", "40"}, {"peace-sign", "30"}},
	"zodiac_edge":   {{"aries", "20"}, {"taurus", "20"}, {"gemini", "20"}, {"cancer", "15"}},
	"star_david":    {{"star-david", "15"}, {"dharma", "15"}, {"cross", "15"}, {"menorah", "12"}},
	"hazard_forge":  {{"radioactive", "12"}, {"biohazard", "12"}},
	"cosmic_sigil":  {{"trident", "10"}, {"fleur", "10"}, {"ophiuchus", "8"}},
	"infinite_mark": {{"om", "8"}, {"yin", "8"}, {"witness", "6"}},
}

// skillMaxRanks maps skillId → maximum rank allowed.
// Most skills cap at 3 or 4 — see catalog.ts SKILLS[*].max.
var skillMaxRanks = map[string]uint64{
	// Strike branch
	"wrist": 5, "palm_strike": 4, "follow": 3, "knuckle_wrap": 4, "heavy_swing": 4,
	"stone_breaker": 4, "anvil_force": 4, "point_drive": 4, "kinetic_thrust": 4,
	"crushing_blow": 4, "shatter_spike": 4, "ironclad_cleave": 3, "thunder_jab": 3,
	"titan_hammer": 3, "diamond_cleave": 3, "hyper_drive": 3, "quasar_impact": 3,
	"black_hole_crush": 3, "mythic_annihilation": 3, "singularity_fist": 3,
	// Fortune branch
	"fortune": 4, "four_leaf": 3, "edge": 3, "glint": 3, "spark_chaser": 3,
	"razor_focus": 3, "precision_cut": 3, "aurora_gaze": 3, "starlight_gleam": 3,
	"double_haul": 3, "twin_strike": 3, "executioner": 3, "celestial_sight": 3,
	"helix_harmony": 3, "fortune_split": 3, "critical_surge": 3,
	"astral_scintillation": 3, "plunder_frenzy": 3, "singularity_edge": 3, "cosmic_fortune": 3,
	// Pocket branch
	"dustbag": 3, "rhythm": 3, "pocket_expansion": 3, "steady_tempo": 3, "cadence": 3,
	"deep_pouch": 3, "vein_resonator": 3, "cart_bed": 3, "bounty_overflow": 3,
	"fracture_pulse": 3, "metro_pulse": 3, "hoarders_tote": 3, "shatter_strike": 3,
	"super_conductor": 3, "dodo_instinct": 3, "void_rend": 3, "celestial_duplication": 3,
	"eternity_flow": 3, "abyssal_reserve": 3, "singularity_snap": 3,
	// Phase 5 — Nature branch (unlocks level 20)
	"deep_root": 3, "stone_sense": 3, "bloom_tide": 3, "thorn_hide": 3,
	"old_growth": 3, "storm_surge": 3, "predator_sense": 3, "world_tree": 3,
	// Phase 5 — Food branch (unlocks level 30)
	"hot_meal": 3, "sugar_rush": 3, "second_wind": 3, "caffeinated": 3,
	"feast_mode": 3, "night_shift": 3, "brew_mastery": 3, "mythic_feast": 3,
	// Phase 5 — People branch (unlocks level 40)
	"mentor": 3, "crowd_favor": 3, "team_spirit": 3, "athlete_heart": 3,
	"warrior_code": 3, "elder_wisdom": 3, "hero_legend": 3, "genie_wish": 3,
	// Phase 5 — Things branch (unlocks level 50)
	"tempered_grip": 3, "field_repair": 3, "master_craft": 3, "workshop_lore": 3,
	"iron_discipline": 3, "vault_keeper": 3, "precision_forge": 3, "deep_science": 3,
	// Phase 5 — Travel branch (unlocks level 65)
	"long_haul": 3, "vein_compass": 3, "nomad_pace": 3, "deep_sea": 3,
	"sky_route": 3, "monument_seal": 3, "orbital_drift": 3, "sacred_ground": 3,
	// Phase 5 — Signs branch (unlocks level 80)
	"amplify": 3, "resonance": 3, "sigil_power": 3, "zodiac_edge": 3,
	"star_david": 3, "hazard_forge": 3, "cosmic_sigil": 3, "infinite_mark": 3,
}

// toolMaxLife maps toolId → maximum durability in blocks broken.
// 0 = indestructible (hands, starter-twig, twig). Matches catalog.ts tool.life.
var toolMaxLife = map[string]uint64{
	"hands": 0, "starter-twig": 0, "twig": 0,
	"wood": 300, "stone": 900, "iron": 940, "gold": 4900, "diamond": 5300, "cosmic": 4500,
	"plasma": 15000, "neutron": 15000, "quasar": 23000, "void": 30000, "genesis": 36000, "omega": 54000,
}

// ── Coin allowlist and rarity lookup ─────────────────────────────────────────
// coinRarity maps every valid coin id → its rarity (0=dust .. 6=mythic).
// ClaimMine and ClaimAndMint panic on any id not present here.
// Generated from src/lib/game/catalog.ts COINS (1262 entries).
// Populated across two init() functions in game_data_coins.gno and game_data_coins2.gno
// to keep each file under the 594-line Onyx parser limit.

var coinRarity map[string]int

game_data_catalog.gno

package game32

// ── Claim-rate skill headroom factors (game29 caps, §5 of REPORT.md) ─────────
// When on-chain skillRanks are available these are computed from actual ranks.
// Until then we use fixed conservative headroom = client-side cap maximums.
// The effective rate for rarity r = base_rate[r] × skillHeadroom[r].
const (
	// dust: +4 yield cap, double drop and hardening -> sim max 1.70x of the 1.01 cap; 1.75 gives margin.
	skillDustHeadroom = uint64(175) // ×175/100

	// Maximum damage multiplier: ≤ 2× → twice as many blocks per minute.
	skillDmgHeadroom = uint64(200) // ×200/100

	// Maximum drop-rate bonus: +30% → 1.30×.
	skillDropHeadroom = uint64(130) // ×130/100
)

// toolLifeSkillIds lists the on-chain skills that grant toolLifeBonus.
// Covers the Things branch (level 50) and the Nature-branch skills that also
// affect tool wear. Must stay in sync with catalog.ts SKILLS[*].toolLifeBonus.
var toolLifeSkillIds = []string{
	"tempered_grip",   // +10%/rank   (Things)
	"stone_sense",     // +0.5%/rank  (Nature)
	"master_craft",    // +15%/rank   (Things)
	"thorn_hide",      // +1%/rank    (Nature)
	"storm_surge",     // +1.5%/rank  (Nature)
	"workshop_lore",   // +15%/rank   (Things)
	"iron_discipline", // +20%/rank   (Things)
	"vault_keeper",    // +20%/rank   (Things)
	"precision_forge", // +25%/rank   (Things)
	"field_repair",    // +10%/rank   (Things)
	"deep_science",    // +25%/rank   (Things)
}

// toolLifeSkillBonus maps each skill to its per-rank life bonus fraction × 1000.
// e.g. "tempered_grip" → 100 means +10.0% per rank (100/1000 = 0.10).
var toolLifeSkillBonus = map[string]uint64{
	"tempered_grip":   100, // +10%/rank
	"stone_sense":       5, // +0.5%/rank
	"master_craft":    150, // +15%/rank
	"thorn_hide":       10, // +1%/rank
	"storm_surge":      15, // +1.5%/rank
	"workshop_lore":   150, // +15%/rank
	"iron_discipline": 200, // +20%/rank
	"vault_keeper":    200, // +20%/rank
	"precision_forge": 250, // +25%/rank
	"field_repair":    100, // +10%/rank
	"deep_science":    250, // +25%/rank
}

// ── Claim rate cap tables (REPORT.md §5) ─────────────────────────────────────
// claimBucketSecs: how many seconds of allowance the bucket can bank (1 hour).
const claimBucketSecs = int64(3600)

// claimRatePerMin[toolId][rarity] = max coins/min of that rarity the caller may
// claim (before skill headroom). Indexed 0=dust..6=mythic.
var claimRatePerMin = map[string][7]uint64{
	"hands":        {12, 0, 0, 0, 0, 0, 0},
	"starter-twig": {16, 0, 0, 0, 0, 0, 0},
	"twig":         {23, 0, 0, 0, 0, 0, 0},
	"wood":         {32, 9, 0, 0, 0, 0, 0},
	"stone":        {69, 20, 6, 0, 0, 0, 0},
	"iron":         {184, 55, 15, 5, 0, 0, 0},
	"gold":         {422, 140, 40, 13, 4, 0, 0},
	"diamond":      {783, 333, 112, 36, 12, 3, 0},
	"cosmic":       {1406, 658, 296, 110, 36, 8, 2},
	"plasma":       {1422, 919, 393, 171, 59, 13, 4},
	"neutron":      {1449, 1207, 513, 263, 94, 22, 7},
	"quasar":       {1476, 1233, 654, 385, 147, 34, 10},
	"void":         {1503, 1255, 853, 489, 220, 55, 16},
	"genesis":      {1544, 1289, 1083, 610, 341, 90, 26},
	"omega":        {1598, 1334, 1124, 769, 516, 145, 42},
}

// ── Vein caps (game29) ───────────────────────────────────────────────────────
// Every coin in coinRarity has a vein from deploy: its max is the default for
// its rarity unless the admin overrides it. No per-coin init writes needed.
// Defaults: ≈1 year of demand per core coin × 1.5 headroom (see REPORT §6).
var veinDefaultMax = [7]uint64{
	50000000, // r0 dust
	82000000, // r1 common
	25000000, // r2 uncommon
	25000000, // r3 rare
	20000000, // r4 epic
	25000000, // r5 legendary
	85000000, // r6 mythic
}

// Per-coin default overrides (static: no deploy-time writes).
var veinCoinDefault = map[string]uint64{
	"grin": 102000000,
}

// ── Achievement allowlist (game29) ───────────────────────────────────────────
// Static ids with FIXED rewards. Grind ids "g.<coin>.<need>" are valid for any
// allowlisted coin and need ∈ grindRungs. The client can never choose a reward.
type coinAmt struct {
	coin string
	amt  uint64
}

var achievementRewards = map[string][]coinAmt{
	"ad_1":         {{"grin", 10}},
	"ad_5":         {{"coffee", 6}},
	"blocks_1":     {{"grin", 4}},
	"blocks_10":    {{"seedling", 6}},
	"blocks_25k":   {{"pick", 2}},
	"blocks_50":    {{"seedling", 12}},
	"blocks_500":   {{"log", 6}, {"rock", 10}},
	"blocks_5k":    {{"gear", 4}},
	"combo_12":     {{"grin", 12}},
	"cosmic_own":   {{"moon", 4}},
	"diamond_own":  {{"spark", 8}},
	"dj":           {{"music", 6}},
	"era_1":        {{"bolt", 3}},
	"first-clash":  {{"rock", 10}},
	"first_tap":    {{"grin", 8}},
	"gem":          {{"spark", 6}},
	"genesis_own":  {{"dragon", 1}},
	"gold_own":     {{"pick", 3}},
	"iron_own":     {{"gold-medal", 2}},
	"miner-1":      {{"seedling", 10}},
	"mythic":       {{"galaxy", 1}},
	"neutron_own":  {{"dna", 2}},
	"omega_own":    {{"lotus", 1}},
	"pioneer":      {{"grin", 50}},
	"plasma_own":   {{"bolt", 3}},
	"quasar_own":   {{"comet", 2}},
	"rarity_0":     {{"grin", 6}},
	"rarity_1":     {{"seedling", 6}},
	"rarity_2":     {{"rock", 5}},
	"rarity_3":     {{"fire", 4}},
	"rarity_4":     {{"spark", 6}},
	"rarity_5":     {{"star", 2}},
	"send":         {{"heart", 4}},
	"shiny":        {{"spark", 6}},
	"slot-roller":  {{"gold-medal", 1}},
	"starter-twig": {{"grin", 20}},
	"stone_own":    {{"gear", 4}},
	"swap":         {{"up", 6}},
	"twig_own":     {{"grin", 50}},
	"unique_1":     {{"grin", 40}},
	"unique_10":    {{"fire", 20}},
	"unique_100":   {{"lotus", 3}, {"peacock", 2}},
	"unique_15":    {{"rock", 24}},
	"unique_25":    {{"clover", 12}},
	"unique_3":     {{"seedling", 24}},
	"unique_40":    {{"pizza", 16}},
	"unique_5":     {{"leaves", 24}},
	"unique_50":    {{"star", 10}},
	"unique_60":    {{"bolt", 10}},
	"unique_75":    {{"crown", 6}},
	"unique_80":    {{"gem", 4}},
	"unique_85":    {{"planet", 3}},
	"unique_90":    {{"galaxy", 2}},
	"unique_95":    {{"lotus", 2}},
	"unique_99":    {{"unicorn", 2}},
	"void_own":     {{"new-moon", 4}},
	"wood_own":     {{"rock", 8}},
}

var grindRungs = []uint64{10, 100, 1000, 10000, 100000}

func grindPay(need uint64) uint64 {
	switch {
	case need >= 100000:
		return 480
	case need >= 10000:
		return 140
	case need >= 1000:
		return 56
	case need >= 100:
		return 20
	}
	return 10
}

// ── PvP / casino allowlists ──────────────────────────────────────────────────
var pvpGames = map[string][]string{
	"rps":          {"rock", "paper", "scissors"},
	"coin_flip":    {"heads", "tails"},
	"higher_lower": {"higher", "lower"},
}

const (
	pvpTimeoutSec        = int64(600) // AFK window before ClaimPvpTimeout
	pvpRakePct           = uint64(2)  // to admin balance
	voucherMaxTTL        = int64(900) // vouchers must expire within 15 min
	claimCooldownSec     = int64(60)  // min seconds between ClaimAndMint
	claimInitialGraceSec = int64(300) // a new rarity bucket starts with 5 min of allowance
)

game_data_coins.gno

package game32

// ── coinRarity part 1 of 2 ────────────────────────────────────────────────────
// Entries "grin" through "chocolate" (first ~590 coins).
// Part 2 continues in game_data_coins2.gno.
// Split to keep each file under the 594-line Onyx v1.5.0 parser limit.

func init() {
	coinRarity = make(map[string]int, 1264)
	coinRarity["grin"] = 0
	coinRarity["joy"] = 0
	coinRarity["cool"] = 0
	coinRarity["think"] = 0
	coinRarity["sleep"] = 0
	coinRarity["party"] = 0
	coinRarity["hot"] = 0
	coinRarity["wow"] = 0
	coinRarity["seedling"] = 0
	coinRarity["leaves"] = 0
	coinRarity["fallen"] = 0
	coinRarity["heart"] = 1
	coinRarity["up"] = 1
	coinRarity["fire"] = 1
	coinRarity["spark"] = 1
	coinRarity["clap"] = 1
	coinRarity["tada"] = 1
	coinRarity["hundred"] = 1
	coinRarity["skull"] = 1
	coinRarity["eyes"] = 1
	coinRarity["raise"] = 1
	coinRarity["log"] = 1
	coinRarity["rock"] = 1
	coinRarity["herb"] = 1
	coinRarity["brick"] = 1
	coinRarity["evergreen"] = 1
	coinRarity["mushroom"] = 1
	coinRarity["pizza"] = 2
	coinRarity["game"] = 2
	coinRarity["music"] = 2
	coinRarity["coffee"] = 2
	coinRarity["rainbow"] = 2
	coinRarity["clover"] = 2
	coinRarity["moon"] = 2
	coinRarity["star"] = 2
	coinRarity["flutter"] = 2
	coinRarity["rocket"] = 2
	coinRarity["gear"] = 2
	coinRarity["chains"] = 2
	coinRarity["wrench"] = 2
	coinRarity["hammer"] = 2
	coinRarity["anchor"] = 2
	coinRarity["pick"] = 2
	coinRarity["crown"] = 3
	coinRarity["trophy"] = 3
	coinRarity["bolt"] = 3
	coinRarity["orb"] = 3
	coinRarity["dna"] = 3
	coinRarity["planet"] = 3
	coinRarity["bead"] = 3
	coinRarity["gold-medal"] = 3
	coinRarity["money-bag"] = 3
	coinRarity["sword"] = 3
	coinRarity["wand"] = 3
	coinRarity["gem"] = 4
	coinRarity["coin"] = 4
	coinRarity["disco"] = 4
	coinRarity["kite"] = 4
	coinRarity["ring"] = 4
	coinRarity["dodo"] = 4
	coinRarity["galaxy"] = 5
	coinRarity["moai"] = 5
	coinRarity["hamsa"] = 5
	coinRarity["mirror"] = 5
	coinRarity["atom"] = 5
	coinRarity["ufo"] = 5
	coinRarity["comet"] = 5
	coinRarity["unicorn"] = 6
	coinRarity["jelly"] = 6
	coinRarity["peacock"] = 6
	coinRarity["lotus"] = 6
	coinRarity["dragon"] = 6
	coinRarity["infinity"] = 6
	coinRarity["melt"] = 0
	coinRarity["tear"] = 0
	coinRarity["wink"] = 0
	coinRarity["blush"] = 0
	coinRarity["halo"] = 0
	coinRarity["slight"] = 0
	coinRarity["yum"] = 0
	coinRarity["tongue"] = 0
	coinRarity["silly"] = 0
	coinRarity["zany"] = 0
	coinRarity["squint"] = 0
	coinRarity["money"] = 0
	coinRarity["hug"] = 0
	coinRarity["oops"] = 0
	coinRarity["shh"] = 0
	coinRarity["salute"] = 0
	coinRarity["zip"] = 0
	coinRarity["raise2"] = 0
	coinRarity["flat"] = 0
	coinRarity["blank"] = 0
	coinRarity["mute"] = 0
	coinRarity["dotted"] = 0
	coinRarity["smirk"] = 0
	coinRarity["unamused"] = 0
	coinRarity["roll"] = 0
	coinRarity["grimace"] = 0
	coinRarity["lie"] = 0
	coinRarity["relief"] = 0
	coinRarity["pensive"] = 0
	coinRarity["sleepy"] = 0
	coinRarity["drool"] = 0
	coinRarity["mask"] = 0
	coinRarity["sick"] = 0
	coinRarity["hurt"] = 0
	coinRarity["sickly"] = 0
	coinRarity["puke"] = 0
	coinRarity["sneeze"] = 0
	coinRarity["cold"] = 0
	coinRarity["woozy"] = 0
	coinRarity["dizzy"] = 0
	coinRarity["mind"] = 0
	coinRarity["cowboy"] = 1
	coinRarity["disguise"] = 1
	coinRarity["nerd"] = 0
	coinRarity["monocle"] = 1
	coinRarity["confused"] = 0
	coinRarity["worried"] = 0
	coinRarity["frown"] = 0
	coinRarity["open"] = 0
	coinRarity["hush"] = 0
	coinRarity["astonish"] = 0
	coinRarity["flush"] = 0
	coinRarity["plead"] = 1
	coinRarity["hold"] = 1
	coinRarity["gape"] = 0
	coinRarity["anguish"] = 0
	coinRarity["fear"] = 0
	coinRarity["cold-sweat"] = 0
	coinRarity["sad"] = 0
	coinRarity["cry"] = 0
	coinRarity["sob"] = 0
	coinRarity["confound"] = 0
	coinRarity["persevere"] = 0
	coinRarity["disappoint"] = 0
	coinRarity["down"] = 0
	coinRarity["weary"] = 0
	coinRarity["tired"] = 0
	coinRarity["yawn"] = 0
	coinRarity["huff"] = 0
	coinRarity["pout"] = 0
	coinRarity["angry"] = 0
	coinRarity["censor"] = 1
	coinRarity["imp"] = 2
	coinRarity["devil"] = 2
	coinRarity["bones"] = 4
	coinRarity["poo"] = 1
	coinRarity["clown"] = 2
	coinRarity["ogre"] = 4
	coinRarity["goblin"] = 4
	coinRarity["ghost"] = 3
	coinRarity["alien"] = 5
	coinRarity["invader"] = 5
	coinRarity["robot"] = 4
	coinRarity["cat-grin"] = 1
	coinRarity["cat-joy"] = 1
	coinRarity["cat-tear"] = 1
	coinRarity["cat-heart"] = 1
	coinRarity["cat-wry"] = 1
	coinRarity["cat-kiss"] = 1
	coinRarity["cat-wow"] = 1
	coinRarity["cat-cry"] = 1
	coinRarity["cat-mad"] = 1
	coinRarity["see-not"] = 1
	coinRarity["hear-not"] = 1
	coinRarity["speak-not"] = 1
	coinRarity["kiss"] = 1
	coinRarity["love-letter"] = 1
	coinRarity["cupid"] = 2
	coinRarity["ribbon-heart"] = 2
	coinRarity["spark-heart"] = 2
	coinRarity["grow-heart"] = 1
	coinRarity["beat"] = 1
	coinRarity["revolving"] = 1
	coinRarity["two-hearts"] = 1
	coinRarity["heart-deco"] = 1
	coinRarity["heart-exclaim"] = 1
	coinRarity["broken"] = 2
	coinRarity["heart-fire"] = 5
	coinRarity["orange-heart"] = 1
	coinRarity["yellow-heart"] = 1
	coinRarity["green-heart"] = 1
	coinRarity["blue-heart"] = 1
	coinRarity["purple-heart"] = 1
	coinRarity["black-heart"] = 1
	coinRarity["white-heart"] = 1
	coinRarity["brown-heart"] = 1
	coinRarity["pink-heart"] = 1
	coinRarity["light-heart"] = 1
	coinRarity["grey-heart"] = 1
	coinRarity["zzz"] = 0
	coinRarity["anger"] = 0
	coinRarity["speech"] = 0
	coinRarity["witness"] = 6
	coinRarity["left-bubble"] = 0
	coinRarity["anger-bubble"] = 1
	coinRarity["thought"] = 0
	coinRarity["wave"] = 0
	coinRarity["stop"] = 0
	coinRarity["palm"] = 0
	coinRarity["hand"] = 0
	coinRarity["vulcan"] = 1
	coinRarity["right"] = 0
	coinRarity["left"] = 0
	coinRarity["ok"] = 0
	coinRarity["pinch"] = 0
	coinRarity["tiny"] = 0
	coinRarity["peace"] = 0
	coinRarity["luck-fingers"] = 1
	coinRarity["heart-hand"] = 1
	coinRarity["love-you"] = 0
	coinRarity["horns"] = 0
	coinRarity["call"] = 0
	coinRarity["left-point"] = 0
	coinRarity["right-point"] = 0
	coinRarity["up-point"] = 0
	coinRarity["down-point"] = 0
	coinRarity["index"] = 0
	coinRarity["you"] = 0
	coinRarity["down2"] = 0
	coinRarity["fist"] = 0
	coinRarity["punch"] = 0
	coinRarity["left-fist"] = 0
	coinRarity["right-fist"] = 0
	coinRarity["heart-hands"] = 1
	coinRarity["open-hands"] = 0
	coinRarity["palms"] = 0
	coinRarity["shake"] = 1
	coinRarity["pray"] = 1
	coinRarity["write"] = 0
	coinRarity["nails"] = 1
	coinRarity["selfie"] = 0
	coinRarity["flex"] = 1
	coinRarity["arm-mech"] = 4
	coinRarity["leg-mech"] = 4
	coinRarity["leg"] = 0
	coinRarity["foot"] = 0
	coinRarity["ear"] = 0
	coinRarity["aid"] = 1
	coinRarity["nose"] = 0
	coinRarity["brain"] = 4
	coinRarity["heart-organ"] = 5
	coinRarity["lungs"] = 2
	coinRarity["tooth"] = 1
	coinRarity["bone"] = 1
	coinRarity["eye"] = 1
	coinRarity["tongue-out"] = 0
	coinRarity["mouth"] = 0
	coinRarity["bite"] = 1
	coinRarity["baby"] = 1
	coinRarity["girl"] = 0
	coinRarity["child"] = 0
	coinRarity["boy"] = 0
	coinRarity["woman"] = 0
	coinRarity["person"] = 0
	coinRarity["man"] = 0
	coinRarity["grandma"] = 0
	coinRarity["elder"] = 0
	coinRarity["grandpa"] = 0
	coinRarity["skullcap"] = 1
	coinRarity["turban"] = 1
	coinRarity["cop"] = 1
	coinRarity["detective"] = 2
	coinRarity["guard"] = 1
	coinRarity["ninja"] = 4
	coinRarity["builder"] = 1
	coinRarity["monarch"] = 5
	coinRarity["prince"] = 2
	coinRarity["princess"] = 2
	coinRarity["hero"] = 4
	coinRarity["villain"] = 4
	coinRarity["mage"] = 5
	coinRarity["fairy"] = 5
	coinRarity["vampire"] = 5
	coinRarity["merfolk"] = 5
	coinRarity["elf"] = 5
	coinRarity["genie"] = 6
	coinRarity["zombie"] = 3
	coinRarity["troll"] = 3
	coinRarity["massage"] = 1
	coinRarity["haircut"] = 0
	coinRarity["walk"] = 0
	coinRarity["stand"] = 0
	coinRarity["kneel"] = 0
	coinRarity["run"] = 0
	coinRarity["dance"] = 1
	coinRarity["groove"] = 1
	coinRarity["hover-suit"] = 5
	coinRarity["bunnies"] = 1
	coinRarity["sauna"] = 1
	coinRarity["climb"] = 1
	coinRarity["fencer"] = 3
	coinRarity["jockey"] = 3
	coinRarity["ski"] = 1
	coinRarity["snowboard"] = 1
	coinRarity["golf"] = 1
	coinRarity["surf"] = 1
	coinRarity["row"] = 1
	coinRarity["swim"] = 1
	coinRarity["baller"] = 1
	coinRarity["lift"] = 1
	coinRarity["bike"] = 1
	coinRarity["mountain"] = 1
	coinRarity["cartwheel"] = 1
	coinRarity["wrestle"] = 1
	coinRarity["water-polo"] = 1
	coinRarity["handball"] = 1
	coinRarity["juggle"] = 3
	coinRarity["lotus-sit"] = 4
	coinRarity["bath"] = 0
	coinRarity["bed"] = 0
	coinRarity["women"] = 0
	coinRarity["couple"] = 0
	coinRarity["men"] = 0
	coinRarity["kiss-pair"] = 1
	coinRarity["love-pair"] = 1
	coinRarity["family"] = 1
	coinRarity["speak"] = 1
	coinRarity["bust"] = 0
	coinRarity["busts"] = 0
	coinRarity["hug-pair"] = 1
	coinRarity["prints"] = 0
	coinRarity["dog"] = 1
	coinRarity["cat"] = 1
	coinRarity["mouse"] = 1
	coinRarity["hamster"] = 1
	coinRarity["bunny"] = 1
	coinRarity["fox"] = 2
	coinRarity["bear"] = 2
	coinRarity["panda"] = 2
	coinRarity["polar"] = 2
	coinRarity["koala"] = 2
	coinRarity["tiger"] = 4
	coinRarity["lion"] = 4
	coinRarity["cow"] = 1
	coinRarity["pig"] = 1
	coinRarity["frog"] = 1
	coinRarity["monkey"] = 1
	coinRarity["chicken"] = 1
	coinRarity["penguin"] = 1
	coinRarity["bird"] = 1
	coinRarity["chick"] = 1
	coinRarity["duck"] = 1
	coinRarity["eagle"] = 4
	coinRarity["owl"] = 4
	coinRarity["bat"] = 2
	coinRarity["wolf"] = 4
	coinRarity["boar"] = 2
	coinRarity["horse"] = 2
	coinRarity["bee"] = 2
	coinRarity["worm"] = 1
	coinRarity["bug"] = 1
	coinRarity["snail"] = 1
	coinRarity["ladybug"] = 1
	coinRarity["ant"] = 1
	coinRarity["fly"] = 0
	coinRarity["beetle"] = 1
	coinRarity["roach"] = 0
	coinRarity["mosquito"] = 0
	coinRarity["cricket"] = 1
	coinRarity["spider"] = 1
	coinRarity["web"] = 1
	coinRarity["scorpion"] = 2
	coinRarity["turtle"] = 2
	coinRarity["snake"] = 2
	coinRarity["lizard"] = 2
	coinRarity["rex"] = 6
	coinRarity["sauropod"] = 6
	coinRarity["octopus"] = 2
	coinRarity["squid"] = 2
	coinRarity["shrimp"] = 1
	coinRarity["lobster"] = 2
	coinRarity["crab"] = 1
	coinRarity["blowfish"] = 1
	coinRarity["tropical"] = 1
	coinRarity["fish"] = 1
	coinRarity["dolphin"] = 2
	coinRarity["whale-spout"] = 5
	coinRarity["whale"] = 5
	coinRarity["shark"] = 4
	coinRarity["croc"] = 2
	coinRarity["tiger-full"] = 4
	coinRarity["leopard"] = 2
	coinRarity["zebra"] = 2
	coinRarity["gorilla"] = 2
	coinRarity["orangutan"] = 2
	coinRarity["elephant"] = 2
	coinRarity["mammoth"] = 6
	coinRarity["rhino"] = 2
	coinRarity["hippo"] = 2
	coinRarity["dromedary"] = 1
	coinRarity["camel"] = 1
	coinRarity["giraffe"] = 2
	coinRarity["roo"] = 2
	coinRarity["bison"] = 2
	coinRarity["buffalo"] = 1
	coinRarity["ox"] = 1
	coinRarity["cow-full"] = 1
	coinRarity["racehorse"] = 1
	coinRarity["pig-full"] = 1
	coinRarity["ram"] = 1
	coinRarity["sheep"] = 1
	coinRarity["llama"] = 1
	coinRarity["goat"] = 1
	coinRarity["deer"] = 1
	coinRarity["dog-full"] = 1
	coinRarity["poodle"] = 1
	coinRarity["guide"] = 1
	coinRarity["cat-full"] = 1
	coinRarity["black-cat"] = 2
	coinRarity["feather"] = 1
	coinRarity["rooster"] = 1
	coinRarity["turkey"] = 1
	coinRarity["parrot"] = 2
	coinRarity["swan"] = 2
	coinRarity["flamingo"] = 2
	coinRarity["dove"] = 2
	coinRarity["rabbit"] = 1
	coinRarity["raccoon"] = 1
	coinRarity["skunk"] = 1
	coinRarity["badger"] = 1
	coinRarity["beaver"] = 1
	coinRarity["otter"] = 1
	coinRarity["sloth"] = 2
	coinRarity["mouse-full"] = 1
	coinRarity["rat"] = 1
	coinRarity["chipmunk"] = 1
	coinRarity["hedgehog"] = 2
	coinRarity["paws"] = 0
	coinRarity["dragon-face"] = 6
	coinRarity["cactus"] = 1
	coinRarity["xmas"] = 1
	coinRarity["deciduous"] = 1
	coinRarity["palm2"] = 1
	coinRarity["shamrock"] = 2
	coinRarity["pine-deco"] = 1
	coinRarity["potted"] = 1
	coinRarity["tanabata"] = 1
	coinRarity["maple"] = 1
	coinRarity["shell"] = 1
	coinRarity["coral"] = 3
	coinRarity["sheaf"] = 1
	coinRarity["bouquet"] = 1
	coinRarity["tulip"] = 1
	coinRarity["rose"] = 1
	coinRarity["wilt"] = 1
	coinRarity["hibiscus"] = 1
	coinRarity["sunflower"] = 1
	coinRarity["blossom"] = 1
	coinRarity["sakura"] = 3
	coinRarity["white-flower"] = 3
	coinRarity["americas"] = 2
	coinRarity["africa"] = 2
	coinRarity["asia"] = 2
	coinRarity["meridian"] = 2
	coinRarity["new-moon"] = 4
	coinRarity["wax-crescent"] = 1
	coinRarity["first-quarter"] = 1
	coinRarity["wax-gibbous"] = 1
	coinRarity["full-moon"] = 4
	coinRarity["wane-gibbous"] = 1
	coinRarity["last-quarter"] = 1
	coinRarity["wane-crescent"] = 1
	coinRarity["new-face"] = 6
	coinRarity["first-face"] = 1
	coinRarity["last-face"] = 1
	coinRarity["sun"] = 5
	coinRarity["full-face"] = 1
	coinRarity["sun-face"] = 6
	coinRarity["glow-star"] = 4
	coinRarity["shooting"] = 6
	coinRarity["cloud"] = 0
	coinRarity["sun-cloud"] = 0
	coinRarity["storm"] = 2
	coinRarity["sun-small-cloud"] = 0
	coinRarity["cloud-sun"] = 0
	coinRarity["rain-sun"] = 2
	coinRarity["rain"] = 2
	coinRarity["snow-cloud"] = 2
	coinRarity["lightning-cloud"] = 4
	coinRarity["tornado"] = 5
	coinRarity["fog"] = 2
	coinRarity["blow"] = 2
	coinRarity["cyclone"] = 5
	coinRarity["closed-umbrella"] = 0
	coinRarity["umbrella"] = 0
	coinRarity["rain-umbrella"] = 0
	coinRarity["snowflake"] = 3
	coinRarity["snowman"] = 1
	coinRarity["frosty"] = 1
	coinRarity["drop"] = 0
	coinRarity["wave2"] = 2
	coinRarity["grapes"] = 1
	coinRarity["melon"] = 1
	coinRarity["watermelon"] = 1
	coinRarity["tangerine"] = 1
	coinRarity["lemon"] = 1
	coinRarity["banana"] = 1
	coinRarity["pineapple"] = 1
	coinRarity["mango"] = 1
	coinRarity["red-apple"] = 1
	coinRarity["green-apple"] = 1
	coinRarity["pear"] = 1
	coinRarity["peach"] = 1
	coinRarity["cherries"] = 1
	coinRarity["strawberry"] = 1
	coinRarity["blueberry"] = 1
	coinRarity["kiwi"] = 1
	coinRarity["tomato"] = 1
	coinRarity["olive"] = 1
	coinRarity["coconut"] = 1
	coinRarity["avocado"] = 1
	coinRarity["eggplant"] = 1
	coinRarity["potato"] = 1
	coinRarity["carrot"] = 1
	coinRarity["corn"] = 1
	coinRarity["chili"] = 1
	coinRarity["pepper"] = 1
	coinRarity["cucumber"] = 1
	coinRarity["greens"] = 1
	coinRarity["broccoli"] = 1
	coinRarity["garlic"] = 1
	coinRarity["onion"] = 1
	coinRarity["peanut"] = 1
	coinRarity["beans"] = 1
	coinRarity["chestnut"] = 1
	coinRarity["bread"] = 1
	coinRarity["croissant"] = 1
	coinRarity["baguette"] = 1
	coinRarity["flatbread"] = 1
	coinRarity["pretzel"] = 1
	coinRarity["bagel"] = 1
	coinRarity["pancakes"] = 1
	coinRarity["waffle"] = 1
	coinRarity["cheese"] = 1
	coinRarity["meat"] = 1
	coinRarity["drumstick"] = 1
	coinRarity["cut"] = 1
	coinRarity["bacon"] = 1
	coinRarity["burger"] = 1
	coinRarity["fries"] = 1
	coinRarity["hotdog"] = 1
	coinRarity["sandwich"] = 1
	coinRarity["taco"] = 1
	coinRarity["burrito"] = 1
	coinRarity["tamale"] = 1
	coinRarity["pita"] = 1
	coinRarity["falafel"] = 1
	coinRarity["egg"] = 0
	coinRarity["pan"] = 1
	coinRarity["paella"] = 1
	coinRarity["stew"] = 1
	coinRarity["fondue"] = 1
	coinRarity["bowl"] = 0
	coinRarity["salad"] = 1
	coinRarity["popcorn"] = 1
	coinRarity["butter"] = 0
	coinRarity["salt"] = 0
	coinRarity["can"] = 0
	coinRarity["bento"] = 1
	coinRarity["cracker"] = 1
	coinRarity["onigiri"] = 1
	coinRarity["rice"] = 1
	coinRarity["curry"] = 1
	coinRarity["ramen"] = 1
	coinRarity["pasta"] = 1
	coinRarity["yam"] = 1
	coinRarity["oden"] = 1
	coinRarity["sushi"] = 2
	coinRarity["fry-shrimp"] = 1
	coinRarity["naruto"] = 1
	coinRarity["mooncake"] = 2
	coinRarity["dango"] = 1
	coinRarity["dumpling"] = 1
	coinRarity["fortune"] = 1
	coinRarity["takeout"] = 0
	coinRarity["soft-serve"] = 1
	coinRarity["shaved"] = 1
	coinRarity["ice-cream"] = 1
	coinRarity["donut"] = 1
}

game_data_coins2.gno

package game32

// ── coinRarity part 2 of 2 ────────────────────────────────────────────────────
// Entries "candy" through end (remaining ~670 coins).
// Part 1 is in game_data_coins.gno (allocates the map).
// Split to keep each file under the 594-line Onyx v1.5.0 parser limit.

func init() {
	coinRarity["cookie"] = 1
	coinRarity["cake"] = 1
	coinRarity["shortcake"] = 1
	coinRarity["cupcake"] = 1
	coinRarity["pie"] = 1
	coinRarity["chocolate"] = 1
	coinRarity["candy"] = 0
	coinRarity["lollipop"] = 0
	coinRarity["custard"] = 1
	coinRarity["honey"] = 1
	coinRarity["bottle"] = 0
	coinRarity["milk"] = 0
	coinRarity["teapot"] = 1
	coinRarity["tea"] = 1
	coinRarity["sake"] = 1
	coinRarity["champagne"] = 2
	coinRarity["wine"] = 1
	coinRarity["cocktail"] = 1
	coinRarity["tropical-drink"] = 1
	coinRarity["beer"] = 1
	coinRarity["cheers"] = 1
	coinRarity["toast"] = 1
	coinRarity["tumbler"] = 1
	coinRarity["pour"] = 0
	coinRarity["cup"] = 0
	coinRarity["boba"] = 1
	coinRarity["juice"] = 0
	coinRarity["mate"] = 1
	coinRarity["ice"] = 0
	coinRarity["chopsticks"] = 0
	coinRarity["place"] = 0
	coinRarity["fork-knife"] = 0
	coinRarity["spoon"] = 0
	coinRarity["knife"] = 1
	coinRarity["jar"] = 0
	coinRarity["soccer"] = 1
	coinRarity["baseball"] = 1
	coinRarity["softball"] = 1
	coinRarity["basketball"] = 1
	coinRarity["volleyball"] = 1
	coinRarity["football"] = 1
	coinRarity["rugby"] = 1
	coinRarity["tennis"] = 1
	coinRarity["disc"] = 1
	coinRarity["bowl2"] = 1
	coinRarity["cricket-bat"] = 1
	coinRarity["field-hockey"] = 1
	coinRarity["ice-hockey"] = 1
	coinRarity["lacrosse"] = 1
	coinRarity["ping-pong"] = 1
	coinRarity["badminton"] = 1
	coinRarity["glove"] = 1
	coinRarity["gi"] = 1
	coinRarity["goal"] = 1
	coinRarity["flag-hole"] = 1
	coinRarity["skate"] = 1
	coinRarity["fish-rod"] = 1
	coinRarity["dive"] = 1
	coinRarity["singlet"] = 0
	coinRarity["skis"] = 1
	coinRarity["sled"] = 1
	coinRarity["curling"] = 1
	coinRarity["bullseye"] = 1
	coinRarity["yo-yo"] = 0
	coinRarity["kite-fly"] = 1
	coinRarity["eight"] = 1
	coinRarity["stick"] = 2
	coinRarity["slots"] = 4
	coinRarity["dice"] = 1
	coinRarity["puzzle"] = 1
	coinRarity["teddy"] = 1
	coinRarity["pinata"] = 1
	coinRarity["nesting"] = 1
	coinRarity["spade"] = 1
	coinRarity["heart-suit"] = 1
	coinRarity["diamond-suit"] = 1
	coinRarity["club"] = 1
	coinRarity["pawn"] = 1
	coinRarity["joker"] = 4
	coinRarity["mahjong"] = 3
	coinRarity["hanafuda"] = 3
	coinRarity["masks"] = 1
	coinRarity["frame"] = 1
	coinRarity["palette"] = 1
	coinRarity["thread"] = 0
	coinRarity["needle"] = 0
	coinRarity["yarn"] = 0
	coinRarity["knot"] = 0
	coinRarity["glasses"] = 0
	coinRarity["dark-glasses"] = 1
	coinRarity["goggles"] = 1
	coinRarity["coat"] = 0
	coinRarity["vest"] = 0
	coinRarity["tie"] = 0
	coinRarity["shirt"] = 0
	coinRarity["jeans"] = 0
	coinRarity["scarf"] = 0
	coinRarity["gloves"] = 0
	coinRarity["jacket"] = 0
	coinRarity["socks"] = 0
	coinRarity["dress"] = 0
	coinRarity["kimono"] = 1
	coinRarity["sari"] = 1
	coinRarity["swim-one"] = 0
	coinRarity["briefs"] = 0
	coinRarity["shorts"] = 0
	coinRarity["bikini"] = 0
	coinRarity["blouse"] = 0
	coinRarity["purse"] = 1
	coinRarity["bag"] = 0
	coinRarity["clutch"] = 0
	coinRarity["shopping"] = 0
	coinRarity["pack"] = 0
	coinRarity["flipflop"] = 0
	coinRarity["shoe"] = 0
	coinRarity["sneaker"] = 0
	coinRarity["boot"] = 0
	coinRarity["flat2"] = 0
	coinRarity["heel"] = 0
	coinRarity["sandal"] = 0
	coinRarity["ballet"] = 1
	coinRarity["tall-boot"] = 0
	coinRarity["hat"] = 0
	coinRarity["top-hat"] = 1
	coinRarity["cap"] = 1
	coinRarity["billed"] = 0
	coinRarity["helmet"] = 1
	coinRarity["rescue"] = 1
	coinRarity["beads"] = 1
	coinRarity["lipstick"] = 0
	coinRarity["mute-speaker"] = 0
	coinRarity["speaker"] = 0
	coinRarity["quiet"] = 0
	coinRarity["loud"] = 0
	coinRarity["loudspeaker"] = 0
	coinRarity["megaphone"] = 0
	coinRarity["post-horn"] = 1
	coinRarity["bell"] = 0
	coinRarity["no-bell"] = 0
	coinRarity["score"] = 1
	coinRarity["notes"] = 1
	coinRarity["studio"] = 2
	coinRarity["slider"] = 1
	coinRarity["knobs"] = 1
	coinRarity["mic"] = 1
	coinRarity["cans"] = 1
	coinRarity["radio"] = 1
	coinRarity["sax"] = 1
	coinRarity["accordion"] = 1
	coinRarity["guitar"] = 2
	coinRarity["keys"] = 2
	coinRarity["trumpet"] = 1
	coinRarity["violin"] = 1
	coinRarity["banjo"] = 1
	coinRarity["drum"] = 1
	coinRarity["long-drum"] = 1
	coinRarity["phone"] = 0
	coinRarity["call-out"] = 0
	coinRarity["handset"] = 0
	coinRarity["receiver"] = 0
	coinRarity["pager"] = 1
	coinRarity["fax"] = 1
	coinRarity["battery"] = 0
	coinRarity["low-batt"] = 0
	coinRarity["plug"] = 0
	coinRarity["laptop"] = 2
	coinRarity["desktop"] = 2
	coinRarity["printer"] = 0
	coinRarity["keyboard"] = 0
	coinRarity["mouse-pc"] = 0
	coinRarity["trackball"] = 1
	coinRarity["minidisc"] = 1
	coinRarity["floppy"] = 1
	coinRarity["disc2"] = 1
	coinRarity["dvd"] = 1
	coinRarity["abacus"] = 1
	coinRarity["cam"] = 2
	coinRarity["frames"] = 1
	coinRarity["projector"] = 1
	coinRarity["slate"] = 2
	coinRarity["tv"] = 1
	coinRarity["camera"] = 2
	coinRarity["flash-cam"] = 1
	coinRarity["video"] = 1
	coinRarity["vhs"] = 1
	coinRarity["search-left"] = 0
	coinRarity["search-right"] = 0
	coinRarity["candle"] = 1
	coinRarity["bulb"] = 1
	coinRarity["torch"] = 0
	coinRarity["lantern"] = 2
	coinRarity["diya"] = 1
	coinRarity["decor-book"] = 0
	coinRarity["closed-book"] = 0
	coinRarity["open-book"] = 0
	coinRarity["green-book"] = 0
	coinRarity["blue-book"] = 0
	coinRarity["orange-book"] = 0
	coinRarity["books"] = 2
	coinRarity["notebook"] = 0
	coinRarity["ledger"] = 0
	coinRarity["page-curl"] = 0
	coinRarity["scroll"] = 2
	coinRarity["page"] = 0
	coinRarity["news"] = 0
	coinRarity["rolled-news"] = 0
	coinRarity["bookmark-tabs"] = 0
	coinRarity["bookmark"] = 0
	coinRarity["tag"] = 0
	coinRarity["yen"] = 1
	coinRarity["dollar"] = 1
	coinRarity["euro"] = 1
	coinRarity["pound"] = 1
	coinRarity["wings"] = 1
	coinRarity["card"] = 1
	coinRarity["receipt"] = 0
	coinRarity["chart-up"] = 1
	coinRarity["envelope"] = 0
	coinRarity["email"] = 0
	coinRarity["incoming"] = 0
	coinRarity["outgoing"] = 0
	coinRarity["outbox"] = 0
	coinRarity["inbox"] = 0
	coinRarity["package"] = 0
	coinRarity["mailbox"] = 0
	coinRarity["closed-box"] = 0
	coinRarity["open-mail"] = 0
	coinRarity["empty-mail"] = 0
	coinRarity["post"] = 0
	coinRarity["ballot"] = 1
	coinRarity["pencil"] = 0
	coinRarity["nib"] = 0
	coinRarity["fountain"] = 0
	coinRarity["pen"] = 0
	coinRarity["brush"] = 0
	coinRarity["crayon"] = 0
	coinRarity["memo"] = 0
	coinRarity["briefcase"] = 0
	coinRarity["folder"] = 0
	coinRarity["open-folder"] = 0
	coinRarity["dividers"] = 0
	coinRarity["date"] = 0
	coinRarity["tearcal"] = 0
	coinRarity["pad"] = 0
	coinRarity["spiral-cal"] = 0
	coinRarity["card-index"] = 0
	coinRarity["trend-up"] = 1
	coinRarity["trend-down"] = 1
	coinRarity["bars"] = 1
	coinRarity["clipboard"] = 0
	coinRarity["pin"] = 0
	coinRarity["round-pin"] = 0
	coinRarity["clip"] = 0
	coinRarity["linked"] = 0
	coinRarity["ruler"] = 0
	coinRarity["triangle"] = 0
	coinRarity["scissors"] = 0
	coinRarity["file-box"] = 0
	coinRarity["cabinet"] = 0
	coinRarity["waste"] = 0
	coinRarity["lock"] = 2
	coinRarity["unlock"] = 1
	coinRarity["ink-lock"] = 1
	coinRarity["key-lock"] = 2
	coinRarity["key"] = 1
	coinRarity["old-key"] = 4
	coinRarity["axe"] = 3
	coinRarity["hammer-pick"] = 4
	coinRarity["hammer-wrench"] = 1
	coinRarity["dagger"] = 3
	coinRarity["water-gun"] = 1
	coinRarity["boomerang"] = 1
	coinRarity["bow"] = 3
	coinRarity["shield"] = 4
	coinRarity["saw"] = 1
	coinRarity["driver"] = 0
	coinRarity["nut"] = 0
	coinRarity["clamp"] = 1
	coinRarity["scale"] = 4
	coinRarity["cane"] = 0
	coinRarity["link"] = 0
	coinRarity["hook"] = 1
	coinRarity["toolbox"] = 1
	coinRarity["magnet"] = 2
	coinRarity["ladder"] = 0
	coinRarity["alembic"] = 5
	coinRarity["tube"] = 3
	coinRarity["dish"] = 3
	coinRarity["scope"] = 4
	coinRarity["telescope"] = 5
	coinRarity["dish-sat"] = 4
	coinRarity["syringe"] = 1
	coinRarity["blood"] = 1
	coinRarity["pill"] = 1
	coinRarity["bandage"] = 0
	coinRarity["crutch"] = 0
	coinRarity["steth"] = 1
	coinRarity["xray"] = 4
	coinRarity["door"] = 0
	coinRarity["lift2"] = 0
	coinRarity["window"] = 0
	coinRarity["bed-full"] = 0
	coinRarity["couch"] = 0
	coinRarity["chair"] = 0
	coinRarity["toilet"] = 0
	coinRarity["plunger"] = 0
	coinRarity["shower"] = 0
	coinRarity["tub"] = 0
	coinRarity["trap"] = 1
	coinRarity["razor"] = 0
	coinRarity["lotion"] = 0
	coinRarity["safety"] = 0
	coinRarity["broom"] = 0
	coinRarity["basket"] = 0
	coinRarity["roll2"] = 0
	coinRarity["bucket"] = 0
	coinRarity["soap"] = 0
	coinRarity["bubbles"] = 0
	coinRarity["brush-teeth"] = 0
	coinRarity["sponge"] = 0
	coinRarity["extinguish"] = 1
	coinRarity["cart"] = 0
	coinRarity["smoke"] = 0
	coinRarity["coffin"] = 3
	coinRarity["headstone"] = 3
	coinRarity["urn"] = 3
	coinRarity["placard"] = 0
	coinRarity["id"] = 1
	coinRarity["atm"] = 0
	coinRarity["litter"] = 0
	coinRarity["water"] = 0
	coinRarity["access"] = 0
	coinRarity["men2"] = 0
	coinRarity["women2"] = 0
	coinRarity["restroom"] = 0
	coinRarity["baby-sign"] = 0
	coinRarity["wc"] = 0
	coinRarity["control"] = 0
	coinRarity["customs"] = 0
	coinRarity["baggage"] = 0
	coinRarity["left-luggage"] = 0
	coinRarity["warn"] = 0
	coinRarity["children"] = 0
	coinRarity["no-entry"] = 0
	coinRarity["prohibited"] = 0
	coinRarity["no-bike"] = 0
	coinRarity["no-smoke"] = 0
	coinRarity["no-litter"] = 0
	coinRarity["no-water"] = 0
	coinRarity["no-walk"] = 0
	coinRarity["no-phone"] = 0
	coinRarity["eighteen"] = 0
	coinRarity["radioactive"] = 5
	coinRarity["biohazard"] = 5
	coinRarity["north"] = 0
	coinRarity["northeast"] = 0
	coinRarity["east"] = 0
	coinRarity["southeast"] = 0
	coinRarity["south"] = 0
	coinRarity["southwest"] = 0
	coinRarity["west"] = 0
	coinRarity["northwest"] = 0
	coinRarity["up-down"] = 0
	coinRarity["left-right"] = 0
	coinRarity["right-hook"] = 0
	coinRarity["left-hook"] = 0
	coinRarity["up-right"] = 0
	coinRarity["down-right"] = 0
	coinRarity["cw"] = 0
	coinRarity["ccw"] = 0
	coinRarity["back"] = 0
	coinRarity["end"] = 0
	coinRarity["on"] = 0
	coinRarity["soon"] = 0
	coinRarity["top"] = 0
	coinRarity["worship"] = 1
	coinRarity["om"] = 6
	coinRarity["star-david"] = 3
	coinRarity["dharma"] = 3
	coinRarity["yin"] = 6
	coinRarity["cross"] = 3
	coinRarity["orthodox"] = 3
	coinRarity["star-crescent"] = 3
	coinRarity["peace-sign"] = 1
	coinRarity["menorah"] = 3
	coinRarity["dotted-star"] = 3
	coinRarity["aries"] = 3
	coinRarity["taurus"] = 3
	coinRarity["gemini"] = 3
	coinRarity["cancer"] = 3
	coinRarity["leo"] = 3
	coinRarity["virgo"] = 3
	coinRarity["libra"] = 3
	coinRarity["scorpio"] = 3
	coinRarity["sagittarius"] = 3
	coinRarity["capricorn"] = 3
	coinRarity["aquarius"] = 3
	coinRarity["pisces"] = 3
	coinRarity["ophiuchus"] = 6
	coinRarity["shuffle"] = 0
	coinRarity["repeat"] = 0
	coinRarity["repeat-one"] = 0
	coinRarity["play"] = 0
	coinRarity["fast"] = 0
	coinRarity["next"] = 0
	coinRarity["pause-play"] = 0
	coinRarity["reverse"] = 0
	coinRarity["rewind"] = 0
	coinRarity["prev"] = 0
	coinRarity["up-tri"] = 0
	coinRarity["double-up"] = 0
	coinRarity["down-tri"] = 0
	coinRarity["double-down"] = 0
	coinRarity["pause"] = 0
	coinRarity["stop2"] = 0
	coinRarity["rec"] = 0
	coinRarity["eject"] = 0
	coinRarity["cinema"] = 0
	coinRarity["dim"] = 0
	coinRarity["bright"] = 0
	coinRarity["bars-sig"] = 0
	coinRarity["vibrate"] = 0
	coinRarity["phone-off"] = 0
	coinRarity["female"] = 0
	coinRarity["male"] = 0
	coinRarity["trans"] = 0
	coinRarity["times"] = 0
	coinRarity["plus"] = 0
	coinRarity["minus"] = 0
	coinRarity["divide"] = 0
	coinRarity["bang-bang"] = 0
	coinRarity["bang-query"] = 0
	coinRarity["question"] = 0
	coinRarity["white-query"] = 0
	coinRarity["white-bang"] = 0
	coinRarity["bang"] = 0
	coinRarity["wave-dash"] = 0
	coinRarity["fx"] = 1
	coinRarity["heavy-dollar"] = 1
	coinRarity["medical"] = 1
	coinRarity["recycle"] = 1
	coinRarity["fleur"] = 6
	coinRarity["trident"] = 6
	coinRarity["name"] = 0
	coinRarity["beginner"] = 1
	coinRarity["hollow"] = 0
	coinRarity["check"] = 0
	coinRarity["ballot-check"] = 0
	coinRarity["heavy-check"] = 0
	coinRarity["cross-mark"] = 0
	coinRarity["cross-box"] = 0
	coinRarity["curl"] = 0
	coinRarity["double-curl"] = 0
	coinRarity["part"] = 0
	coinRarity["eight-star"] = 1
	coinRarity["eight-black"] = 1
	coinRarity["sparkle"] = 1
	coinRarity["copy"] = 1
	coinRarity["reg"] = 1
	coinRarity["tm"] = 1
	coinRarity["hash"] = 0
	coinRarity["asterisk"] = 0
	coinRarity["zero"] = 0
	coinRarity["one"] = 0
	coinRarity["two"] = 0
	coinRarity["three"] = 0
	coinRarity["four"] = 0
	coinRarity["five"] = 0
	coinRarity["six"] = 0
	coinRarity["seven"] = 0
	coinRarity["eight2"] = 0
	coinRarity["nine"] = 0
	coinRarity["ten"] = 0
	coinRarity["abcd"] = 0
	coinRarity["abcd-small"] = 0
	coinRarity["1234"] = 0
	coinRarity["symbols"] = 0
	coinRarity["abc"] = 0
	coinRarity["a-blood"] = 1
	coinRarity["ab-blood"] = 1
	coinRarity["b-blood"] = 1
	coinRarity["cl"] = 0
	coinRarity["cool-word"] = 0
	coinRarity["free"] = 0
	coinRarity["info"] = 0
	coinRarity["id-word"] = 0
	coinRarity["m-circ"] = 0
	coinRarity["new"] = 0
	coinRarity["ng"] = 0
	coinRarity["o-blood"] = 1
	coinRarity["ok-word"] = 0
	coinRarity["p"] = 0
	coinRarity["sos"] = 1
	coinRarity["up-word"] = 0
	coinRarity["vs"] = 0
	coinRarity["koko"] = 1
	coinRarity["sa"] = 1
	coinRarity["moon-word"] = 1
	coinRarity["not-free"] = 1
	coinRarity["reserved"] = 1
	coinRarity["bargain"] = 1
	coinRarity["discount"] = 1
	coinRarity["free-jp"] = 1
	coinRarity["prohibited-jp"] = 1
	coinRarity["accept"] = 1
	coinRarity["apply"] = 1
	coinRarity["passing"] = 1
	coinRarity["vacancy"] = 1
	coinRarity["congrats"] = 1
	coinRarity["secret"] = 2
	coinRarity["open2"] = 1
	coinRarity["full"] = 1
	coinRarity["red"] = 0
	coinRarity["orange"] = 0
	coinRarity["yellow"] = 0
	coinRarity["green"] = 0
	coinRarity["blue"] = 0
	coinRarity["purple"] = 0
	coinRarity["black"] = 0
	coinRarity["white"] = 0
	coinRarity["brown"] = 0
	coinRarity["red-up"] = 0
	coinRarity["red-down"] = 0
	coinRarity["radio-on"] = 0
	coinRarity["white-square"] = 0
	coinRarity["black-square"] = 0
	coinRarity["chequered"] = 1
	coinRarity["tri-flag"] = 0
	coinRarity["crossed"] = 1
	coinRarity["black-flag"] = 1
	coinRarity["white-flag"] = 1
	coinRarity["pride"] = 2
	coinRarity["trans-flag"] = 2
	coinRarity["pirate"] = 3
	coinRarity["car"] = 1
	coinRarity["taxi"] = 1
	coinRarity["suv"] = 1
	coinRarity["bus"] = 1
	coinRarity["trolley"] = 1
	coinRarity["race"] = 3
	coinRarity["police-car"] = 1
	coinRarity["ambulance"] = 1
	coinRarity["engine"] = 1
	coinRarity["van"] = 1
	coinRarity["pickup"] = 1
	coinRarity["truck"] = 1
	coinRarity["lorry"] = 1
	coinRarity["tractor"] = 1
	coinRarity["moto"] = 1
	coinRarity["scooter"] = 1
	coinRarity["manual-chair"] = 1
	coinRarity["motor-chair"] = 1
	coinRarity["tuk"] = 1
	coinRarity["cycle"] = 1
	coinRarity["kick"] = 0
	coinRarity["skateboard"] = 1
	coinRarity["roller"] = 1
	coinRarity["stop-bus"] = 0
	coinRarity["motorway"] = 1
	coinRarity["rails"] = 1
	coinRarity["oil"] = 1
	coinRarity["fuel"] = 1
	coinRarity["beacon"] = 1
	coinRarity["h-lights"] = 0
	coinRarity["v-lights"] = 0
	coinRarity["halt"] = 0
	coinRarity["work"] = 0
	coinRarity["ring-buoy"] = 1
	coinRarity["sail"] = 2
	coinRarity["canoe"] = 1
	coinRarity["speed"] = 2
	coinRarity["passenger"] = 2
	coinRarity["ferry"] = 1
	coinRarity["motorboat"] = 1
	coinRarity["ship"] = 1
	coinRarity["plane"] = 1
	coinRarity["small-plane"] = 1
	coinRarity["depart"] = 2
	coinRarity["arrive"] = 2
	coinRarity["chute"] = 3
	coinRarity["seat"] = 0
}

game_data_coins3.gno

package game32

// ── coinRarity part 3 of 3 ────────────────────────────────────────────────────
// Entries from "bellhop" through end (remaining ~94 coins).
// Split to keep each file under the 594-line Onyx v1.5.0 parser limit.

func init() {
	coinRarity["heli"] = 3
	coinRarity["suspension"] = 1
	coinRarity["gondola"] = 1
	coinRarity["aerial"] = 1
	coinRarity["sat"] = 5
	coinRarity["bellhop"] = 1
	coinRarity["luggage"] = 0
	coinRarity["done-sand"] = 1
	coinRarity["sand"] = 1
	coinRarity["watch"] = 0
	coinRarity["alarm"] = 0
	coinRarity["stopwatch"] = 1
	coinRarity["timer"] = 1
	coinRarity["mantel"] = 1
	coinRarity["twelve"] = 0
	coinRarity["one-hour"] = 0
	coinRarity["two-hour"] = 0
	coinRarity["three-hour"] = 0
	coinRarity["four-hour"] = 0
	coinRarity["five-hour"] = 0
	coinRarity["six-hour"] = 0
	coinRarity["seven-hour"] = 0
	coinRarity["eight-hour"] = 0
	coinRarity["nine-hour"] = 0
	coinRarity["ten-hour"] = 0
	coinRarity["eleven-hour"] = 0
	coinRarity["house"] = 0
	coinRarity["garden-house"] = 0
	coinRarity["office"] = 0
	coinRarity["jp-post"] = 1
	coinRarity["post-office"] = 0
	coinRarity["hospital"] = 0
	coinRarity["bank"] = 1
	coinRarity["hotel"] = 0
	coinRarity["love-hotel"] = 1
	coinRarity["convenience"] = 0
	coinRarity["school"] = 0
	coinRarity["dept"] = 0
	coinRarity["factory"] = 1
	coinRarity["castle-jp"] = 5
	coinRarity["castle"] = 5
	coinRarity["wedding"] = 1
	coinRarity["tower"] = 3
	coinRarity["liberty"] = 5
	coinRarity["church"] = 1
	coinRarity["mosque"] = 4
	coinRarity["temple"] = 4
	coinRarity["synagogue"] = 4
	coinRarity["shrine"] = 4
	coinRarity["kaaba"] = 6
	coinRarity["fountain2"] = 1
	coinRarity["tent"] = 1
	coinRarity["foggy"] = 1
	coinRarity["night"] = 1
	coinRarity["cityscape"] = 1
	coinRarity["sunrise-mtn"] = 1
	coinRarity["sunrise"] = 1
	coinRarity["dusk"] = 1
	coinRarity["sunset"] = 1
	coinRarity["bridge"] = 1
	coinRarity["hot-spring"] = 3
	coinRarity["carousel"] = 1
	coinRarity["slide"] = 0
	coinRarity["wheel"] = 2
	coinRarity["coaster"] = 2
	coinRarity["barber"] = 0
	coinRarity["circus"] = 2
	coinRarity["loco"] = 1
	coinRarity["railcar"] = 1
	coinRarity["shinkansen"] = 1
	coinRarity["bullet"] = 3
	coinRarity["train"] = 1
	coinRarity["metro"] = 1
	coinRarity["light-rail"] = 1
	coinRarity["station"] = 0
	coinRarity["tram"] = 1
	coinRarity["mono"] = 1
	coinRarity["mountain-rail"] = 1
	coinRarity["tramcar"] = 1
	coinRarity["pumpkin"] = 1
	coinRarity["fireworks"] = 3
	coinRarity["sparkler"] = 2
	coinRarity["cracker-pop"] = 2
	coinRarity["balloon"] = 0
	coinRarity["confetti"] = 1
	coinRarity["dolls"] = 1
	coinRarity["carp"] = 1
	coinRarity["wind-bell"] = 1
	coinRarity["moon-view"] = 1
	coinRarity["envelope-red"] = 2
	coinRarity["bow2"] = 0
	coinRarity["gift"] = 2
	coinRarity["reminder"] = 1
	coinRarity["tickets"] = 1
	coinRarity["ticket"] = 0
	coinRarity["medal"] = 3
	coinRarity["sports-medal"] = 3
	coinRarity["silver-medal"] = 3
	coinRarity["bronze-medal"] = 3
}

game_guilds.gno

package game32

import (
	"sort"
	"strconv"
	"strings"
	"time"

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

// ── Guilds ───────────────────────────────────────────────────────────────────

const maxGuildMembers = 10
const maxGuildNameLen = 24

func guildJSON(guildId, name, leader string, members int, createdAt int64) string {
	return `{"guildId":` + jsonStr(guildId) + `,"name":` + jsonStr(name) + `,"leader":` + jsonStr(leader) +
		`,"memberCount":` + strconv.Itoa(members) + `,"createdAt":` + strconv.FormatInt(createdAt, 10) + `}`
}

func guildMemberCount(gid string) int {
	n := 0
	guildMembers.Iterate(gid+":", gid+";", func(string, any) bool {
		n++
		return false
	})
	return n
}

type guildMeta struct {
	name, leader string
	createdAt    int64
}

// guild meta is stored alongside the JSON so it can be re-rendered safely.
var guildMetas = map[string]guildMeta{}

func rewriteGuild(gid string) {
	m, ok := guildMetas[gid]
	if !ok {
		return
	}
	guilds.Set(gid, guildJSON(gid, m.name, m.leader, guildMemberCount(gid), m.createdAt))
}

func CreateGuild(cur realm, name string) string {
	caller := requirePlayer(cur)
	if playerGuild.Has(caller) {
		panic("already in a guild")
	}
	name = sanitizeName(name)
	if len(name) < 3 {
		panic("guild name too short (min 3 chars)")
	}
	if len(name) > maxGuildNameLen {
		panic("guild name too long (max 24 chars)")
	}
	guildCounter++
	gid := "guild-" + zeroPad(guildCounter, 6)
	now := time.Now().Unix()
	guildMetas[gid] = guildMeta{name: name, leader: caller, createdAt: now}
	guildMembers.Set(gid+":"+caller, "1")
	playerGuild.Set(caller, gid)
	rewriteGuild(gid)
	return gid
}

func JoinGuild(cur realm, guildId string) {
	caller := requirePlayer(cur)
	if playerGuild.Has(caller) {
		panic("already in a guild — leave current guild first")
	}
	if !guilds.Has(guildId) {
		panic("guild not found")
	}
	if guildMemberCount(guildId) >= maxGuildMembers {
		panic("guild is full (max 10 members)")
	}
	guildMembers.Set(guildId+":"+caller, "1")
	playerGuild.Set(caller, guildId)
	rewriteGuild(guildId)
}

func LeaveGuild(cur realm) {
	requireNotPaused()
	caller := cur.Previous().Address().String()
	if !playerGuild.Has(caller) {
		panic("not in a guild")
	}
	gid := playerGuild.Get(caller).(string)
	guildMembers.Remove(gid + ":" + caller)
	playerGuild.Remove(caller)
	if guildMemberCount(gid) == 0 {
		guilds.Remove(gid)
		delete(guildMetas, gid)
		return
	}
	if m, ok := guildMetas[gid]; ok && m.leader == caller {
		// hand leadership to the first remaining member
		guildMembers.Iterate(gid+":", gid+";", func(k string, _ any) bool {
			m.leader = strings.TrimPrefix(k, gid+":")
			return true
		})
		guildMetas[gid] = m
	}
	rewriteGuild(gid)
}

func PlayerGuild(addr string) string {
	if !playerGuild.Has(addr) {
		return ""
	}
	gid := playerGuild.Get(addr).(string)
	if !guilds.Has(gid) {
		return ""
	}
	return guilds.Get(gid).(string)
}

func GuildInfo(guildId string) string {
	if !guilds.Has(guildId) {
		return ""
	}
	return guilds.Get(guildId).(string)
}

func TopGuilds(limit int) string {
	if limit <= 0 || limit > 50 {
		limit = 20
	}
	var all guildRows
	guilds.Iterate("", "", func(k string, v any) bool {
		all = append(all, guildRow{v.(string), guildMemberCount(k)})
		return false
	})
	sort.Stable(all)
	var parts []string
	for i := 0; i < len(all) && i < limit; i++ {
		parts = append(parts, all[i].js)
	}
	return "[" + strings.Join(parts, ",") + "]"
}

// ── Queries ──────────────────────────────────────────────────────────────────

func kvJSON(prefixAddr string, t *avl.Tree) string {
	var parts []string
	t.Iterate(prefixAddr+":", prefixAddr+";", func(key string, val any) bool {
		parts = append(parts, jsonStr(strings.TrimPrefix(key, prefixAddr+":"))+":"+val.(string))
		return false
	})
	return "{" + strings.Join(parts, ",") + "}"
}

func AllBalances(playerAddr string) string   { return kvJSON(playerAddr, &balances) }
func LifetimeMined(playerAddr string) string { return kvJSON(playerAddr, &lifetimeMined) }

// PlayerXp returns the caller's cumulative rarity-weighted XP earned from
// ClaimAndMint calls as a plain decimal string (e.g. "12345"). Returns "0"
// for players who have not yet minted anything on this realm version.
func PlayerXp(playerAddr string) string {
	return strconv.FormatUint(getU(&playerXp, playerAddr), 10)
}

// Rewarded returns what rewards (medals etc.) credited, per coin. Separate
// from LifetimeMined.
func Rewarded(playerAddr string) string { return kvJSON(playerAddr, &rewarded) }
func SkillRanks(playerAddr string) string    { return kvJSON(playerAddr, &skillRanks) }
func ToolLife(playerAddr string) string      { return kvJSON(playerAddr, &toolLife) }

func OwnedTools(playerAddr string) string {
	if !ownedTools.Has(playerAddr) || ownedTools.Get(playerAddr).(string) == "" {
		return `["hands"]`
	}
	var quoted []string
	for _, id := range strings.Split(ownedTools.Get(playerAddr).(string), ",") {
		quoted = append(quoted, jsonStr(id))
	}
	return "[" + strings.Join(quoted, ",") + "]"
}

func PlayerProfile(playerAddr string) string {
	return `{"address":` + jsonStr(playerAddr) + `,"bestTool":` + jsonStr(bestOwnedTool(playerAddr)) +
		`,"total":` + strconv.FormatUint(getU(&miners, playerAddr), 10) + `,"passExpiry":` + strconv.FormatInt(GnomePassExpiry(playerAddr), 10) + `}`
}

// AllMiners returns the leaderboard sorted by total mined (desc), paginated.
// (game28 returned it in address order.)
func AllMiners(limit int, offset int) string {
	if limit <= 0 || limit > 200 {
		limit = 100
	}
	if offset < 0 {
		offset = 0
	}
	var rows minerRows
	miners.Iterate("", "", func(k string, v any) bool {
		t, _ := strconv.ParseUint(v.(string), 10, 64)
		rows = append(rows, minerRow{k, t})
		return false
	})
	sort.Sort(rows)
	var parts []string
	for i := offset; i < len(rows) && i < offset+limit; i++ {
		d := rows[i].addr
		if len(d) > 12 {
			d = d[:8] + "..."
		}
		parts = append(parts, `{"address":`+jsonStr(rows[i].addr)+`,"display":`+jsonStr(d)+`,"total":`+strconv.FormatUint(rows[i].total, 10)+`,"rank":`+strconv.Itoa(i+1)+`}`)
	}
	return "[" + strings.Join(parts, ",") + "]"
}

func GetMedals(playerAddr string) string {
	var claimed []string
	achievements.Iterate(playerAddr+":", playerAddr+";", func(key string, _ any) bool {
		claimed = append(claimed, jsonStr(strings.TrimPrefix(key, playerAddr+":")))
		return false
	})
	return `{"medals":[` + strings.Join(claimed, ",") + `]}`
}

func DailyCheckinStatus(playerAddr string) string {
	today := time.Now().Unix() / 86400
	var lastDay, streak int64
	if dailyCheckins.Has(playerAddr) {
		raw := dailyCheckins.Get(playerAddr).(string)
		lastDay, streak = parseDailyCheckin(raw)
	}
	done := lastDay == today
	// Streak is live only if the player checked in today or yesterday.
	// If they missed a day, report 0 so the client knows the streak is broken.
	liveStreak := streak
	if lastDay < today-1 {
		liveStreak = 0
	}
	nextMidnight := (today + 1) * 86400
	return ufmt.Sprintf(`{"ok":true,"done":%t,"streak":%d,"next":%d}`, done, liveStreak, nextMidnight)
}

func ListTasks(_ string) string {
	var parts []string
	achievements.Iterate("task:", "task;", func(k string, v any) bool {
		if strings.HasSuffix(k, ":desc") {
			id := strings.TrimSuffix(strings.TrimPrefix(k, "task:"), ":desc")
			parts = append(parts, `{"id":`+jsonStr(id)+`,"desc":`+jsonStr(v.(string))+`}`)
		}
		return false
	})
	return `{"ok":true,"tasks":[` + strings.Join(parts, ",") + `]}`
}

// ── Render ───────────────────────────────────────────────────────────────────

func Render(_ string) string {
	return ufmt.Sprintf("# GnoMoji Game Realm — game32\n\nAdmin: `%s`\n\nPath: `%s`\n\nClaims: server-vouchered (%s)\n\nMigration finalized: %t\n\nMine emoji coins on Gno.land!\n",
		admin.String(), realmPkgPath, func() string {
			if len(claimSignerPubKey) == 32 {
				return "signer set"
			}
			return "disabled — no signer"
		}(), migrationFinalized)
}

// ── Helpers ──────────────────────────────────────────────────────────────────

// deductBalances checks all balances, then deducts (no partial deductions).
func deductBalances(caller string, costs [][2]string) {
	for _, pair := range costs {
		required, err := strconv.ParseUint(pair[1], 10, 64)
		if err != nil || required == 0 {
			continue
		}
		if have := balOf(caller, pair[0]); have < required {
			panic("insufficient " + pair[0] + ": need " + pair[1] + " have " + strconv.FormatUint(have, 10))
		}
	}
	for _, pair := range costs {
		required, err := strconv.ParseUint(pair[1], 10, 64)
		if err != nil || required == 0 {
			continue
		}
		debitBal(caller, pair[0], required)
	}
}

type guildRow struct {
	js string
	n  int
}
type guildRows []guildRow

func (g guildRows) Len() int           { return len(g) }
func (g guildRows) Less(i, j int) bool { return g[i].n > g[j].n }
func (g guildRows) Swap(i, j int)      { g[i], g[j] = g[j], g[i] }

type minerRow struct {
	addr  string
	total uint64
}
type minerRows []minerRow

func (m minerRows) Len() int { return len(m) }
func (m minerRows) Less(i, j int) bool {
	if m[i].total != m[j].total {
		return m[i].total > m[j].total
	}
	return m[i].addr < m[j].addr
}
func (m minerRows) Swap(i, j int) { m[i], m[j] = m[j], m[i] }

game_migration_test.gno

package game32

import (
	"strconv"
	"testing"
	"time"
)

// TestClaimBuckets_LazyMigration verifies that a player whose claimBuckets
// entries are in the old per-rarity format (addr+":"+r) are automatically
// migrated to the packed format on the next ClaimAndMint.
func TestClaimBuckets_LazyMigration(cur realm, t *testing.T) {
	setup()
	p := ta("migrate-player")

	// Write old-format per-rarity bucket entries directly.
	nowTs := time.Now().Unix()
	for r := 0; r < 7; r++ {
		oldKey := p.String() + ":" + strconv.Itoa(r)
		// Write a non-default value so we can verify it survived migration.
		claimBuckets.Set(oldKey, "9999:"+strconv.FormatInt(nowTs-100, 10))
	}

	// Confirm old keys exist.
	for r := 0; r < 7; r++ {
		if !claimBuckets.Has(p.String() + ":" + strconv.Itoa(r)) {
			t.Fatalf("setup: old key r=%d missing", r)
		}
	}

	// Trigger a ClaimAndMint — this calls loadPackedBuckets which lazy-migrates.
	n, e, s := voucher(t, "claim", p, `[["grin","1"]]`)
	testing.SetRealm(testing.NewUserRealm(p))
	ClaimAndMint(cross(cur), `[["grin","1"]]`, n, e, s)

	// Old keys must be gone.
	for r := 0; r < 7; r++ {
		if claimBuckets.Has(p.String() + ":" + strconv.Itoa(r)) {
			t.Errorf("old key r=%d still exists after migration", r)
		}
	}

	// New packed key must exist.
	if !claimBuckets.Has(p.String()) {
		t.Error("packed key missing after migration")
	}
}

// TestClaimBuckets_NewPlayerSingleKey verifies a brand-new player creates
// exactly one claimBuckets key (the packed format) on first ClaimAndMint.
func TestClaimBuckets_NewPlayerSingleKey(cur realm, t *testing.T) {
	setup()
	p := ta("new-player-bucket")

	// Confirm no bucket state exists yet.
	if claimBuckets.Has(p.String()) {
		t.Fatal("setup: packed key should not exist yet")
	}
	for r := 0; r < 7; r++ {
		if claimBuckets.Has(p.String() + ":" + strconv.Itoa(r)) {
			t.Fatalf("setup: old key r=%d should not exist", r)
		}
	}

	// First claim.
	n, e, s := voucher(t, "claim", p, `[["grin","1"]]`)
	testing.SetRealm(testing.NewUserRealm(p))
	ClaimAndMint(cross(cur), `[["grin","1"]]`, n, e, s)

	// Exactly one key for this player in claimBuckets.
	if !claimBuckets.Has(p.String()) {
		t.Error("packed key missing after first claim")
	}
	for r := 0; r < 7; r++ {
		if claimBuckets.Has(p.String() + ":" + strconv.Itoa(r)) {
			t.Errorf("old-format key r=%d unexpectedly created", r)
		}
	}
}

game_mining.gno

package game32

import (
	"crypto/ed25519"
	"encoding/hex"
	"sort"
	"strconv"
	"strings"
	"time"

	"chain/runtime"

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

// ── Vouchers ─────────────────────────────────────────────────────────────────
//
// The server's claim signer (ed25519) signs (v2 format):
//
//   gnomoji-voucher-v2|<chainId>|<kind>|<player>|<nonce>|<expiry>|<compactPayload>
//
// compactPayload for kind="claim": coinId:amount pairs sorted alphabetically by
//   coinId, comma-joined. e.g. "cool:7,grin:100,joy:50"
// compactPayload for kind="ach": achievement IDs sorted alphabetically,
//   comma-joined. e.g. "blocks_1,g.grin.10"
//
// The realm reconstructs compactPayload from the coinsJson/idsJson argument
// before calling ed25519.Verify, then uses coinsJson/idsJson for actual logic.
//
// v2 changes from v1: realmPkgPath removed; payload is now compact (not raw JSON).
// Replay protection is retained via per-player on-chain nonces (claimNonces) and
// chain ID — a voucher cannot be replayed on game30 (different nonce tree state).
//
// nonce must be strictly greater than the player's last nonce (one shared
// sequence for all kinds), expiry is unix seconds and at most voucherMaxTTL
// in the future. A voucher is single-use and bound to one player and chain.

// VoucherMessage builds the canonical message that the server signs and the
// realm verifies. Format: gnomoji-voucher-v2|chainId|kind|player|nonce|expiry|compactPayload
//
// v2 changes from v1: realmPkgPath removed; payload is now compact (not raw JSON).
// For kind="claim": compactPayload = coinId:amount pairs sorted by coinId, comma-joined.
//   e.g. [["grin","100"],["joy","50"]] → "grin:100,joy:50"
// For kind="ach": compactPayload = achievement IDs sorted, comma-joined.
//   e.g. ["blocks_1","g.grin.10"] → "blocks_1,g.grin.10"
func VoucherMessage(kind, player string, nonce, expiry int64, payload string) string {
	return "gnomoji-voucher-v2|" + runtime.ChainID() + "|" + kind + "|" + player + "|" +
		strconv.FormatInt(nonce, 10) + "|" + strconv.FormatInt(expiry, 10) + "|" + payload
}

// compactClaimPayload builds the canonical compact payload for a "claim" voucher
// from a coinsJson string: [["coinId","amount"],...].
// Output: "coinId:amount" pairs sorted alphabetically by coinId, comma-joined.
// Must produce the same output as the TypeScript claimVoucherPayload() function
// in src/lib/game/claim-voucher.ts.
func compactClaimPayload(coinsJson string) string {
	rows := parseStringRows(coinsJson)
	// Collect unique coinId:amount pairs (duplicate coinIds summed).
	sums := map[string]uint64{}
	var order []string
	for _, row := range rows {
		if len(row) != 2 {
			continue
		}
		amt, _ := strconv.ParseUint(row[1], 10, 64)
		if _, seen := sums[row[0]]; !seen {
			order = append(order, row[0])
		}
		sums[row[0]] += amt
	}
	// Sort alphabetically by coinId.
	sort.Strings(order)
	parts := make([]string, 0, len(order))
	for _, coinId := range order {
		parts = append(parts, coinId+":"+strconv.FormatUint(sums[coinId], 10))
	}
	return strings.Join(parts, ",")
}

// compactAchPayload builds the canonical compact payload for an "ach" voucher
// from an idsJson string: ["achId",...].
// Output: achievement IDs sorted alphabetically, comma-joined.
func compactAchPayload(idsJson string) string {
	rows := parseStringList(idsJson)
	sort.Strings(rows)
	return strings.Join(rows, ",")
}

// LastNonce returns the last voucher nonce used by addr (0 if none).
func LastNonce(addr string) int64 {
	if !claimNonces.Has(addr) {
		return 0
	}
	n, _ := strconv.ParseInt(claimNonces.Get(addr).(string), 10, 64)
	return n
}

func useVoucher(kind, player string, nonce, expiry int64, payload, sigHex string) {
	if len(claimSignerPubKey) != 32 {
		panic("claims are disabled: no claim signer set")
	}
	now := time.Now().Unix()
	if expiry < now {
		panic("voucher expired")
	}
	if expiry > now+voucherMaxTTL {
		panic("voucher expiry too far in the future")
	}
	// FIX 1D: cache lastN to avoid calling LastNonce (2 AVL reads) twice.
	lastN := LastNonce(player)
	if nonce <= lastN {
		panic("voucher already used (nonce " + strconv.FormatInt(nonce, 10) + " ≤ last " + strconv.FormatInt(lastN, 10) + ")")
	}
	sig, err := hex.DecodeString(sigHex)
	if err != nil || len(sig) != 64 {
		panic("invalid voucher signature encoding")
	}
	compact := payload
	if kind == "claim" {
		compact = compactClaimPayload(payload)
	} else if kind == "ach" {
		compact = compactAchPayload(payload)
	}
	if !ed25519.Verify(claimSignerPubKey, []byte(VoucherMessage(kind, player, nonce, expiry, compact)), sig) {
		panic("invalid voucher signature")
	}
	claimNonces.Set(player, strconv.FormatInt(nonce, 10))
}

// ── Claim-rate helpers ────────────────────────────────────────────────────────

// bestOwnedTool returns the highest-tier tool the caller owns that still has
// durability (or is indestructible). "hands" if none.
func bestOwnedTool(callerAddr string) string {
	if !ownedTools.Has(callerAddr) {
		return "hands"
	}
	ownedSet := map[string]bool{}
	for _, t := range strings.Split(ownedTools.Get(callerAddr).(string), ",") {
		if t = strings.TrimSpace(t); t != "" {
			ownedSet[t] = true
		}
	}
	for i := len(toolOrder) - 1; i >= 0; i-- {
		tid := toolOrder[i]
		if !ownedSet[tid] {
			continue
		}
		maxLife, hasMax := toolMaxLife[tid]
		if !hasMax || maxLife == 0 {
			return tid
		}
		lifeKey := callerAddr + ":" + tid
		if !toolLife.Has(lifeKey) || getU(&toolLife, lifeKey) > 0 {
			return tid
		}
	}
	return "hands"
}

func effectiveRateFor(tool string, r int) uint64 {
	rates, ok := claimRatePerMin[tool]
	if !ok {
		rates = claimRatePerMin["hands"]
	}
	base := rates[r]
	var eff uint64
	if r == 0 {
		eff = (base * skillDmgHeadroom * skillDustHeadroom) / 10000
	} else {
		eff = (base * skillDmgHeadroom) / 100
	}
	if eff == 0 {
		eff = base
	}
	return eff
}

// loadPackedBuckets reads the packed claimBuckets entry for addr, or creates
// a fresh one. Returns [7][2]uint64 where [r][0]=accruedMillis, [r][1]=lastTs.
// Lazy-migrates from the old per-rarity key format (addr+":"+r) on first read
// after an upgrade.
func loadPackedBuckets(addr string, nowTs int64) [7][2]uint64 {
	var buckets [7][2]uint64
	// Set default initial values (will be overwritten if stored data exists).
	for r := 0; r < 7; r++ {
		buckets[r][0] = 0 // accruedMillis: start at zero, will refill on next bucketState call
		buckets[r][1] = uint64(nowTs)
	}

	// Try new packed format first.
	if claimBuckets.Has(addr) {
		packed := claimBuckets.Get(addr).(string)
		parts := strings.Split(packed, "|")
		for r := 0; r < 7 && r < len(parts); r++ {
			sub := strings.SplitN(parts[r], ":", 2)
			if len(sub) == 2 {
				buckets[r][0], _ = strconv.ParseUint(sub[0], 10, 64)
				ts, _ := strconv.ParseInt(sub[1], 10, 64)
				buckets[r][1] = uint64(ts)
			}
		}
		return buckets
	}

	// Lazy migration: check for old per-rarity keys.
	foundOld := false
	for r := 0; r < 7; r++ {
		oldKey := addr + ":" + strconv.Itoa(r)
		if claimBuckets.Has(oldKey) {
			foundOld = true
			parts := strings.SplitN(claimBuckets.Get(oldKey).(string), ":", 2)
			if len(parts) == 2 {
				buckets[r][0], _ = strconv.ParseUint(parts[0], 10, 64)
				ts, _ := strconv.ParseInt(parts[1], 10, 64)
				buckets[r][1] = uint64(ts)
			}
			claimBuckets.Remove(oldKey)
		}
	}
	if foundOld {
		// Write the migrated packed entry immediately so future reads are fast.
		claimBuckets.Set(addr, formatPackedBuckets(buckets))
	}
	return buckets
}

// formatPackedBuckets serializes [7][2]uint64 to "m0:t0|m1:t1|...|m6:t6".
func formatPackedBuckets(buckets [7][2]uint64) string {
	parts := make([]string, 7)
	for r := 0; r < 7; r++ {
		parts[r] = strconv.FormatUint(buckets[r][0], 10) + ":" + strconv.FormatInt(int64(buckets[r][1]), 10)
	}
	return strings.Join(parts, "|")
}

// bucketState returns (accruedMillis, capMillis) for rarity r at nowTs.
// allBuckets is the result of loadPackedBuckets — pass it in to avoid
// re-reading the AVL entry for each rarity check.
func bucketState(allBuckets [7][2]uint64, r int, tool string, nowTs int64) (uint64, uint64) {
	eff := effectiveRateFor(tool, r)
	capMillis := eff * uint64(claimBucketSecs) * 1000 / 60
	stored := allBuckets[r][0]
	lastTs := int64(allBuckets[r][1])
	// A new rarity bucket defaults to lastTs=nowTs, stored=0.
	// Give it the initial grace allowance so first-ever claims aren't blocked.
	if lastTs == nowTs && stored == 0 {
		stored = eff * uint64(claimInitialGraceSec) * 1000 / 60
	}
	if elapsed := nowTs - lastTs; elapsed > 0 {
		stored += uint64(elapsed) * eff * 1000 / 60
	}
	if stored > capMillis {
		stored = capMillis
	}
	return stored, capMillis
}

// enforceClaimRate checks every rarity first, then deducts (no partial writes).
// FIX 2A: reads claimBuckets once (packed format) instead of once per rarity.
func enforceClaimRate(callerAddr string, byRarity [7]uint64, nowTs int64, tool string) {
	maxR, ok := toolMaxRarity[tool]
	if !ok {
		maxR = 0
	}
	// Load all 7 rarity buckets in one AVL read (or lazy-migrate from old format).
	allBuckets := loadPackedBuckets(callerAddr, nowTs)
	var after [7]uint64
	for r := 0; r < 7; r++ {
		claimed := byRarity[r]
		if claimed == 0 {
			continue
		}
		if r > maxR {
			panic(ufmt.Sprintf("rate limit: %s tool cannot mine rarity %d coins", tool, r))
		}
		stored, capMillis := bucketState(allBuckets, r, tool, nowTs)
		if claimed*1000 > stored {
			panic(ufmt.Sprintf("rate limit rarity %d: tried %d, allowed %d (refills at %d/min, max bank %d)",
				r, claimed, stored/1000, effectiveRateFor(tool, r), capMillis/1000))
		}
		after[r] = stored - claimed*1000
	}
	// Compute new packed state and write once.
	var newBuckets [7][2]uint64
	for r := 0; r < 7; r++ {
		if byRarity[r] > 0 {
			newBuckets[r][0] = after[r]
			newBuckets[r][1] = uint64(nowTs)
		} else {
			newBuckets[r][0] = allBuckets[r][0]
			newBuckets[r][1] = allBuckets[r][1]
		}
	}
	claimBuckets.Set(callerAddr, formatPackedBuckets(newBuckets))
}

// decrementToolLife wears the best tool by the number of non-dust coins.
// FIX 1A: accepts pre-computed tool to avoid a second bestOwnedTool call.
func decrementToolLife(callerAddr string, totalCoins uint64, tool string) {
	if totalCoins == 0 {
		return
	}
	maxLife, hasMax := toolMaxLife[tool]
	if !hasMax || maxLife == 0 {
		return
	}
	lifeKey := callerAddr + ":" + tool
	current := effectiveMaxLife(callerAddr, tool)
	if toolLife.Has(lifeKey) {
		current = getU(&toolLife, lifeKey)
	}
	if totalCoins >= current {
		setU(&toolLife, lifeKey, 0)
	} else {
		setU(&toolLife, lifeKey, current-totalCoins)
	}
}

// parseCoinClaims parses [["coinId","amount"],...]. Unknown ids panic
// (allowlist); duplicate ids are summed; at most 20 entries.
func parseCoinClaims(coinsJson string) ([]string, map[string]uint64, [7]uint64) {
	coinMap := map[string]uint64{}
	var order []string
	var byRarity [7]uint64
	rows := parseStringRows(coinsJson)
	if len(rows) == 0 {
		panic("no coins to claim")
	}
	if len(rows) > 20 {
		panic("too many coin entries (max 20)")
	}
	for _, row := range rows {
		if len(row) != 2 {
			panic("each claim entry must be [coinId, amount]")
		}
		rarity, known := coinRarity[row[0]]
		if !known {
			panic("unknown coin id: " + row[0])
		}
		amt, err := strconv.ParseUint(row[1], 10, 64)
		if err != nil || amt == 0 || amt > 1000000 {
			panic("invalid amount for " + row[0])
		}
		if _, seen := coinMap[row[0]]; !seen {
			order = append(order, row[0])
		}
		coinMap[row[0]] += amt
		byRarity[rarity] += amt
	}
	return order, coinMap, byRarity
}

func guildBonusPct(addr string) uint64 {
	if !playerGuild.Has(addr) {
		return 0
	}
	gid := playerGuild.Get(addr).(string)
	n := 0
	guildMembers.Iterate(gid+":", gid+";", func(string, any) bool {
		n++
		return false
	})
	if n <= 1 {
		return 0
	}
	if n-1 > 9 {
		return 9
	}
	return uint64(n - 1)
}

// creditMined credits a mined/reward amount to addr, capped by the vein, and
// records lifetime total. Returns the amount credited.
// FIX 1B: miners update removed — caller must addU(&miners, addr, total) after the loop.
func creditMined(addr, coinId string, amt uint64) uint64 {
	amt = takeFromVein(coinId, amt)
	if amt == 0 {
		return 0
	}
	creditBal(addr, coinId, amt)
	addU(&lifetimeMined, addr+":"+coinId, amt)
	return amt
}

// creditReward credits a reward (medal/achievement or any future event). It
// still draws from the vein (so rewards can't exceed supply caps) but is
// tracked in its own counter: it never touches lifetimeMined or the miners
// leaderboard, so rewards can't unlock grind medals or inflate rankings.
func creditReward(addr, coinId string, amt uint64) uint64 {
	amt = takeFromVein(coinId, amt)
	if amt == 0 {
		return 0
	}
	creditBal(addr, coinId, amt)
	addU(&rewarded, addr+":"+coinId, amt)
	return amt
}

// ── Claims ───────────────────────────────────────────────────────────────────

// ClaimAndMint credits mined coins to the caller's on-chain balance.
// coinsJson: [["coinId","amount"],...]. Requires a server voucher
// (see VoucherMessage) for exactly this coinsJson, plus the on-chain rate cap
// for the caller's best tool, the coin allowlist and the vein caps.
// Returns a JSON object of what was actually credited (after bonuses/veins).
func ClaimAndMint(cur realm, coinsJson string, nonce int64, expiry int64, sigHex string) string {
	caller := requirePlayer(cur)
	now := time.Now().Unix()
	// Voucher first (clear errors for forged/replayed vouchers); a failed tx
	// reverts, so a valid voucher isn't burned by the cooldown below.
	useVoucher("claim", caller, nonce, expiry, coinsJson, sigHex)
	if lastClaim.Has(caller) {
		last, _ := strconv.ParseInt(lastClaim.Get(caller).(string), 10, 64)
		if now-last < claimCooldownSec {
			panic("too fast — " + strconv.FormatInt(claimCooldownSec-(now-last), 10) + "s remaining (1 min cooldown)")
		}
	}
	lastClaim.Set(caller, strconv.FormatInt(now, 10))

	order, coinMap, byRarity := parseCoinClaims(coinsJson)

	// FIX 1A: compute tool once and pass to both functions.
	tool := bestOwnedTool(caller)
	enforceClaimRate(caller, byRarity, now, tool)

	nonDust := uint64(0)
	for r := 1; r < 7; r++ {
		nonDust += byRarity[r]
	}
	decrementToolLife(caller, nonDust, tool)

	bonus := guildBonusPct(caller)
	pass := HasActivePass(caller)
	// rarityXpWeights maps rarity index (0=dust … 6=mythic) to XP per credited coin.
	// Matches the client-side rarityXp() table in store/helpers.ts exactly.
	rarityXpWeights := [7]uint64{3, 8, 20, 50, 120, 300, 800}
	var out []string
	sessionXp := uint64(0)
	// FIX 1B: accumulate miners total outside the loop.
	totalCredited := uint64(0)
	for _, coinId := range order {
		amt := coinMap[coinId]
		if bonus > 0 {
			amt += amt * bonus / 100
		}
		if pass {
			amt += amt / 2
		}
		got := creditMined(caller, coinId, amt)
		totalCredited += got
		out = append(out, jsonStr(coinId)+":"+strconv.FormatUint(got, 10))
		// Accumulate rarity-weighted XP for each credited coin.
		r := coinRarity[coinId]
		if r < 0 {
			r = 0
		} else if r > 6 {
			r = 6
		}
		sessionXp += got * rarityXpWeights[r]
	}
	// FIX 1B: single miners write after loop instead of N writes inside loop.
	if totalCredited > 0 {
		addU(&miners, caller, totalCredited)
	}
	if sessionXp > 0 {
		addU(&playerXp, caller, sessionXp)
	}
	return "{" + strings.Join(out, ",") + "}"
}

// ClaimMine (game27/28 two-step flow) is retired: pending mints are gone.
func ClaimMine(cur realm, coinsJson string) {
	panic("ClaimMine is retired in game29 — use ClaimAndMint with a server voucher")
}

// PendingMints is kept for client compatibility; game29 has no pending step.
func PendingMints(playerAddr string) string { return `{"pending":[]}` }

// ClaimAllowance returns the current per-rarity allowance for addr.
func ClaimAllowance(playerAddr string) string {
	tool := bestOwnedTool(playerAddr)
	now := time.Now().Unix()
	// Load packed buckets once for all 7 rarities.
	allBuckets := loadPackedBuckets(playerAddr, now)
	var parts []string
	for r := 0; r < 7; r++ {
		stored, _ := bucketState(allBuckets, r, tool, now)
		maxR, ok := toolMaxRarity[tool]
		if !ok || r > maxR {
			stored = 0
		}
		parts = append(parts, `"r`+strconv.Itoa(r)+`":`+strconv.FormatUint(stored/1000, 10))
	}
	return "{" + strings.Join(parts, ",") + `,"tool":` + jsonStr(tool) + `,"nextNonce":` + strconv.FormatInt(LastNonce(playerAddr)+1, 10) + "}"
}

game_pvp.gno

package game32

import (
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"

)

// ── PvP lobbies ──────────────────────────────────────────────────────────────
//
// Storage (pvpLobbies, string values — PvpLobby(key) can read any of them):
//   <id>                → lobby JSON (re-rendered on every change)
//   <id>:creator / :challenger / :game / :coin / :bet / :status / :createdAt / :last
//   <id>:commit:<addr>  → sha256(choice+":"+salt) hex, written once
//   <id>:reveal:<addr>  → choice (after the hash matched)
//   <id>:salt:<addr>    → salt
//   <id>:winner         → addr | "draw"
// Lobby ids come from a counter, so two lobbies can never collide.
// Status: open → joined → finished | cancelled.

func lget(id, f string) string {
	k := id + ":" + f
	if !pvpLobbies.Has(k) {
		return ""
	}
	return pvpLobbies.Get(k).(string)
}

func lset(id, f, v string) { pvpLobbies.Set(id+":"+f, v) }

func renderLobby(id string) {
	bet := lget(id, "bet")
	if bet == "" {
		bet = "0"
	}
	js := `{"lobbyId":` + jsonStr(id) + `,"creator":` + jsonStr(lget(id, "creator")) +
		`,"challenger":` + jsonStr(lget(id, "challenger")) + `,"game":` + jsonStr(lget(id, "game")) +
		`,"coinId":` + jsonStr(lget(id, "coin")) + `,"betAmount":` + bet +
		`,"status":` + jsonStr(lget(id, "status")) + `,"winner":` + jsonStr(lget(id, "winner")) +
		`,"round":1,"createdAt":` + lget(id, "createdAt") + `}`
	pvpLobbies.Set(id, js)
}

func touch(id string) { lset(id, "last", strconv.FormatInt(time.Now().Unix(), 10)) }

func lastAction(id string) int64 {
	v, _ := strconv.ParseInt(lget(id, "last"), 10, 64)
	return v
}

// CreatePvpLobby escrows the creator's wager and opens a lobby.
func CreatePvpLobby(cur realm, game string, coinId string, betAmount string) string {
	caller := requirePlayer(cur)
	if _, ok := pvpGames[game]; !ok {
		panic("unknown PvP game: " + game)
	}
	if _, ok := coinRarity[coinId]; !ok {
		panic("unknown coin id: " + coinId)
	}
	wager, err := strconv.ParseUint(betAmount, 10, 64)
	if err != nil || wager > 1000000000 {
		panic("invalid bet amount")
	}
	if wager > 0 {
		panic("PvP wagers are off until they are rewritten; create a lobby with bet 0")
	}
	pvpCounter++
	id := "pvp-" + zeroPad(pvpCounter, 10)
	now := strconv.FormatInt(time.Now().Unix(), 10)
	lset(id, "creator", caller)
	lset(id, "game", game)
	lset(id, "coin", coinId)
	lset(id, "bet", strconv.FormatUint(wager, 10))
	lset(id, "status", "open")
	lset(id, "createdAt", now)
	lset(id, "last", now)
	if wager > 0 {
		pvpWagers.Set(id, coinId+":"+strconv.FormatUint(wager, 10)+":"+caller+":")
	}
	renderLobby(id)
	return id
}

func JoinPvpLobby(cur realm, lobbyId string) {
	caller := requirePlayer(cur)
	if lget(lobbyId, "status") != "open" {
		panic("lobby not open")
	}
	creator := lget(lobbyId, "creator")
	if caller == creator {
		panic("cannot join your own lobby")
	}
	if pvpWagered(lobbyId) {
		panic("PvP wagers are off: this wagered lobby can only be refunded")
	}
	wager, _ := strconv.ParseUint(lget(lobbyId, "bet"), 10, 64)
	coin := lget(lobbyId, "coin")
	if wager > 0 {
		debitBal(caller, coin, wager)
		pvpWagers.Set(lobbyId, coin+":"+strconv.FormatUint(wager, 10)+":"+creator+":"+caller)
	}
	lset(lobbyId, "challenger", caller)
	lset(lobbyId, "status", "joined")
	touch(lobbyId)
	renderLobby(lobbyId)
}

// pvpWagered: a lobby that escrowed coins before wagers were switched off.
// It can only be cancelled or refunded after the timeout.
func pvpWagered(id string) bool { b := lget(id, "bet"); return b != "" && b != "0" }

// CancelPvpLobby lets the creator close an open lobby nobody joined (refund).
// Works while paused: a refund of the player's own escrow is never blocked.
func CancelPvpLobby(cur realm, lobbyId string) {
	caller := cur.Previous().Address().String()
	if lget(lobbyId, "status") != "open" || lget(lobbyId, "creator") != caller {
		panic("only the creator can cancel an open lobby")
	}
	settlePvp(lobbyId, "refund")
	lset(lobbyId, "status", "cancelled")
	renderLobby(lobbyId)
}

func memberOf(lobbyId, addr string) bool {
	return addr != "" && (addr == lget(lobbyId, "creator") || addr == lget(lobbyId, "challenger"))
}

// CommitPvpMove stores sha256(choice+":"+salt) for the caller. Members only,
// once per player per lobby, only while the lobby is joined.
func CommitPvpMove(cur realm, lobbyId string, moveHash string) {
	caller := requirePlayer(cur)
	if lget(lobbyId, "status") != "joined" {
		panic("lobby is not in progress")
	}
	if !memberOf(lobbyId, caller) {
		panic("not a lobby participant")
	}
	if lget(lobbyId, "commit:"+caller) != "" {
		panic("move already committed")
	}
	moveHash = strings.ToLower(moveHash)
	if !isHex64(moveHash) {
		panic("moveHash must be sha256(choice:salt) as 64 hex chars")
	}
	lset(lobbyId, "commit:"+caller, moveHash)
	touch(lobbyId)
}

func validChoice(game, choice string) bool {
	for _, c := range pvpGames[game] {
		if c == choice {
			return true
		}
	}
	return false
}

func moveHash(choice, salt string) string {
	h := sha256.Sum256([]byte(choice + ":" + salt))
	return hex.EncodeToString(h[:])
}

// RevealPvpMove reveals a committed move. The tx fails unless
// sha256(choice+":"+salt) equals the stored commit. A matching reveal of an
// invalid choice forfeits the match. When both have revealed, it settles.
func RevealPvpMove(cur realm, lobbyId string, choice string, salt string) {
	caller := requirePlayer(cur)
	if lget(lobbyId, "status") != "joined" {
		panic("lobby is not in progress")
	}
	if !memberOf(lobbyId, caller) {
		panic("not a lobby participant")
	}
	if pvpWagered(lobbyId) {
		panic("PvP wagers are off: this wagered lobby can only be refunded after the timeout")
	}
	creator, challenger := lget(lobbyId, "creator"), lget(lobbyId, "challenger")
	if lget(lobbyId, "commit:"+creator) == "" || lget(lobbyId, "commit:"+challenger) == "" {
		panic("both players must commit moves before revealing")
	}
	if lget(lobbyId, "reveal:"+caller) != "" {
		panic("already revealed")
	}
	if moveHash(choice, salt) != lget(lobbyId, "commit:"+caller) {
		panic("reveal does not match your commit")
	}
	lset(lobbyId, "reveal:"+caller, choice)
	lset(lobbyId, "salt:"+caller, salt)
	touch(lobbyId)

	game := lget(lobbyId, "game")
	if !validChoice(game, choice) {
		// Committed garbage: forfeit to the opponent.
		opp := creator
		if caller == creator {
			opp = challenger
		}
		settlePvp(lobbyId, opp)
		return
	}
	cr, chr := lget(lobbyId, "reveal:"+creator), lget(lobbyId, "reveal:"+challenger)
	if cr == "" || chr == "" {
		renderLobby(lobbyId)
		return
	}
	settlePvp(lobbyId, pvpWinner(game, creator, challenger, cr, chr, lget(lobbyId, "salt:"+creator), lget(lobbyId, "salt:"+challenger)))
}

// pvpWinner: rps uses the usual rules. coin_flip / higher_lower flip a coin
// from sha256(creatorSalt:challengerSalt) — neither player controls it alone —
// and whoever alone called it wins (both or neither right = draw).
func pvpWinner(game, creator, challenger, cChoice, chChoice, cSalt, chSalt string) string {
	if game == "rps" {
		if cChoice == chChoice {
			return "draw"
		}
		if (cChoice == "rock" && chChoice == "scissors") || (cChoice == "scissors" && chChoice == "paper") || (cChoice == "paper" && chChoice == "rock") {
			return creator
		}
		return challenger
	}
	h := sha256.Sum256([]byte(cSalt + ":" + chSalt))
	outcome := pvpGames[game][int(h[0]&1)]
	cOk, chOk := cChoice == outcome, chChoice == outcome
	if cOk && !chOk {
		return creator
	}
	if chOk && !cOk {
		return challenger
	}
	return "draw"
}

// settlePvp pays out the escrow. result = winner addr, "draw" or "refund".
func settlePvp(lobbyId, result string) {
	if pvpWagers.Has(lobbyId) {
		parts := strings.SplitN(pvpWagers.Get(lobbyId).(string), ":", 4)
		if len(parts) == 4 {
			coin := parts[0]
			wager, _ := strconv.ParseUint(parts[1], 10, 64)
			payers := []string{}
			for _, a := range parts[2:] {
				if a != "" {
					payers = append(payers, a)
				}
			}
			if result == "draw" || result == "refund" || len(payers) < 2 {
				for _, a := range payers {
					creditBal(a, coin, wager)
				}
			} else {
				pot := wager * uint64(len(payers))
				rake := pot * pvpRakePct / 100
				creditBal(result, coin, pot-rake)
				creditBal(admin.String(), coin, rake)
			}
		}
		pvpWagers.Remove(lobbyId)
	}
	if result != "refund" {
		lset(lobbyId, "winner", result)
	}
	lset(lobbyId, "status", "finished")
	renderLobby(lobbyId)
}

// ClaimPvpTimeout resolves a stuck match after pvpTimeoutSec without action:
//   - only one player committed → that player wins;
//   - both committed, only one revealed → the revealer wins;
//   - otherwise → both refunded.
// Any lobby member may call it. Escrow can never stay locked.
func ClaimPvpTimeout(cur realm, lobbyId string) {
	caller := cur.Previous().Address().String()
	st := lget(lobbyId, "status")
	if st != "joined" && st != "open" {
		panic("lobby already settled")
	}
	if !memberOf(lobbyId, caller) {
		panic("not a lobby participant")
	}
	if time.Now().Unix()-lastAction(lobbyId) < pvpTimeoutSec {
		panic("timeout not yet claimable — 10 minutes must pass without a move")
	}
	if st == "open" || pvpWagered(lobbyId) {
		settlePvp(lobbyId, "refund")
		lset(lobbyId, "status", "cancelled")
		renderLobby(lobbyId)
		return
	}
	cr, ch := lget(lobbyId, "creator"), lget(lobbyId, "challenger")
	cc, chc := lget(lobbyId, "commit:"+cr) != "", lget(lobbyId, "commit:"+ch) != ""
	rv, chv := lget(lobbyId, "reveal:"+cr) != "", lget(lobbyId, "reveal:"+ch) != ""
	switch {
	case cc && !chc:
		settlePvp(lobbyId, cr)
	case chc && !cc:
		settlePvp(lobbyId, ch)
	case cc && chc && rv && !chv:
		settlePvp(lobbyId, cr)
	case cc && chc && chv && !rv:
		settlePvp(lobbyId, ch)
	default:
		settlePvp(lobbyId, "refund")
	}
}

// ExpireLobbies is a no-op kept for API compatibility (timeouts are per lobby).
func ExpireLobbies(cur realm) {}

func PvpLobby(lobbyId string) string {
	if !pvpLobbies.Has(lobbyId) {
		return "null"
	}
	return pvpLobbies.Get(lobbyId).(string)
}

func OpenLobbies() string {
	var parts []string
	pvpLobbies.Iterate("pvp-", "pvp.", func(key string, val any) bool {
		if !strings.Contains(key, ":") && lget(key, "status") == "open" {
			parts = append(parts, val.(string))
		}
		return len(parts) >= 100
	})
	return "[" + strings.Join(parts, ",") + "]"
}

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

// zeroPad formats n with leading zeros to width w (ufmt has no %0Nd).
func zeroPad(n uint64, w int) string {
	s := strconv.FormatUint(n, 10)
	for len(s) < w {
		s = "0" + s
	}
	return s
}

game_queries.gno

package game32

import (
	"strconv"
	"strings"
	"time"

	"chain"
)

// ── Tool-life helpers ─────────────────────────────────────────────────────────

// effectiveMaxLife = toolMaxLife × (1000 + Σ rank × bonus‰) / 1000.
// FIX 1C: fast-path for players with no tool-life skills trained (the common
// case), avoiding 22 AVL reads (11 skills × Has+Get) that all return 0.
func effectiveMaxLife(callerAddr string, toolId string) uint64 {
	base, ok := toolMaxLife[toolId]
	if !ok || base == 0 {
		return 0
	}
	// Fast path: check the first skill only. Skills must be trained in order
	// (toolLifeSkillIds[0] = "tempered_grip" is always the entry-level skill).
	// If the player has no rank in it, they have no rank in any of the 11.
	if !skillRanks.Has(callerAddr + ":" + toolLifeSkillIds[0]) {
		return base
	}
	bonus := uint64(0)
	for _, skillId := range toolLifeSkillIds {
		if rank := getU(&skillRanks, callerAddr+":"+skillId); rank > 0 {
			bonus += rank * toolLifeSkillBonus[skillId]
		}
	}
	return base * (1000 + bonus) / 1000
}

func ownsTool(addr, toolId string) bool {
	if toolId == "hands" {
		return true
	}
	if !ownedTools.Has(addr) {
		return false
	}
	for _, t := range strings.Split(ownedTools.Get(addr).(string), ",") {
		if strings.TrimSpace(t) == toolId {
			return true
		}
	}
	return false
}

// ── Coin Transfer ────────────────────────────────────────────────────────────

// Transfer sends coins to another player. It is a player's own money, so the
// admin can't stop it: it works while the game is paused and for banned
// addresses (bans only stop earning). It needs a finalized migration
// (MigrateBatch SETs balances). There is no receive cap: any coin can be sent
// to any player, whatever tools they own.
func Transfer(cur realm, coinId string, toAddr string, amountStr string) {
	caller := cur.Previous().Address().String()
	if !migrationFinalized {
		panic("transfers open after FinalizeMigration")
	}
	if !address(toAddr).IsValid() {
		panic("invalid destination address")
	}
	if caller == toAddr {
		panic("cannot transfer to yourself")
	}
	if _, ok := coinRarity[coinId]; !ok {
		panic("unknown coin id: " + coinId)
	}
	amount, err := strconv.ParseUint(amountStr, 10, 64)
	if err != nil || amount == 0 || amount > maxAmount {
		panic("invalid amount")
	}
	debitBal(caller, coinId, amount)
	creditBal(toAddr, coinId, amount)
	chain.Emit("Transferred", "coin", coinId, "from", caller, "to", toAddr, "amount", u(amount))
}

// ── Tools ────────────────────────────────────────────────────────────────────

func BuyTool(cur realm, toolId string) {
	caller := requirePlayer(cur)
	costs, hasCost := toolCosts[toolId]
	if !hasCost {
		panic("unknown tool: " + toolId)
	}
	if ownsTool(caller, toolId) {
		panic("already own " + toolId + " — use RepairTool to restore durability")
	}
	if prereq, ok := toolRequires[toolId]; ok && !ownsTool(caller, prereq) {
		panic("must own " + prereq + " before buying " + toolId)
	}
	deductBalances(caller, costs)

	if !ownedTools.Has(caller) || ownedTools.Get(caller).(string) == "" {
		ownedTools.Set(caller, toolId)
	} else {
		ownedTools.Set(caller, ownedTools.Get(caller).(string)+","+toolId)
	}
	// Always initialise durability at purchase (skill-boosted max).
	if mx, ok := toolMaxLife[toolId]; ok && mx > 0 {
		setU(&toolLife, caller+":"+toolId, effectiveMaxLife(caller, toolId))
	}
}

func RepairTool(cur realm, toolId string) {
	caller := requirePlayer(cur)
	maxLife, ok := toolMaxLife[toolId]
	if !ok || maxLife == 0 {
		panic("tool cannot be repaired: " + toolId)
	}
	if !ownsTool(caller, toolId) {
		panic("you don't own " + toolId)
	}
	var repairCosts [][2]string
	for _, pair := range toolCosts[toolId] {
		baseAmt, _ := strconv.ParseUint(pair[1], 10, 64)
		if amt := (baseAmt*30 + 99) / 100; amt > 0 {
			repairCosts = append(repairCosts, [2]string{pair[0], strconv.FormatUint(amt, 10)})
		}
	}
	deductBalances(caller, repairCosts)
	setU(&toolLife, caller+":"+toolId, effectiveMaxLife(caller, toolId))
}

// ── Progression ──────────────────────────────────────────────────────────────

func TrainSkill(cur realm, skillId string) {
	caller := requirePlayer(cur)
	key := caller + ":" + skillId
	rank := getU(&skillRanks, key)
	maxRank, ok := skillMaxRanks[skillId]
	if !ok {
		panic("unknown skill: " + skillId)
	}
	if rank >= maxRank {
		panic("skill already at maximum rank")
	}
	baseCosts, ok := skillBaseCosts[skillId]
	if !ok {
		panic("unknown skill: " + skillId)
	}
	mult := uint64(1) << rank
	var scaled [][2]string
	for _, pair := range baseCosts {
		baseAmt, _ := strconv.ParseUint(pair[1], 10, 64)
		if s := baseAmt * mult; s > 0 {
			scaled = append(scaled, [2]string{pair[0], strconv.FormatUint(s, 10)})
		}
	}
	deductBalances(caller, scaled)
	setU(&skillRanks, key, rank+1)
}

// ── Achievements (allowlisted, fixed rewards, vouchered) ─────────────────────

func parseGrindId(id string) (string, uint64, bool) {
	if !strings.HasPrefix(id, "g.") {
		return "", 0, false
	}
	rest := id[2:]
	dot := strings.LastIndex(rest, ".")
	if dot <= 0 {
		return "", 0, false
	}
	coin := rest[:dot]
	need, err := strconv.ParseUint(rest[dot+1:], 10, 64)
	if err != nil {
		return "", 0, false
	}
	if _, ok := coinRarity[coin]; !ok {
		return "", 0, false
	}
	for _, r := range grindRungs {
		if r == need {
			return coin, need, true
		}
	}
	return "", 0, false
}

func isValidAchievementId(id string) bool {
	if _, ok := achievementRewards[id]; ok {
		return true
	}
	_, _, ok := parseGrindId(id)
	return ok
}

// achievementReward returns the fixed reward for id, checking any on-chain
// predicate (grind: lifetimeMined ≥ need; "<tool>_own": tool owned).
// ok=false means the id is unknown or not earned on chain.
func achievementReward(addr, id string) ([]coinAmt, string) {
	if coin, need, isGrind := parseGrindId(id); isGrind {
		if getU(&lifetimeMined, addr+":"+coin) < need {
			return nil, "not earned: mined " + strconv.FormatUint(getU(&lifetimeMined, addr+":"+coin), 10) + "/" + strconv.FormatUint(need, 10) + " " + coin
		}
		return []coinAmt{{coin, grindPay(need)}}, ""
	}
	rw, ok := achievementRewards[id]
	if !ok {
		return nil, "unknown achievement: " + id
	}
	if strings.HasSuffix(id, "_own") {
		tool := strings.TrimSuffix(id, "_own")
		if _, isTool := toolCosts[tool]; isTool && !ownsTool(addr, tool) {
			return nil, "not earned: you don't own " + tool
		}
	}
	return rw, ""
}

// claimAchievementsFor claims ids for addr. strict=true panics on any bad id;
// otherwise bad/claimed ids are skipped. Returns the number claimed.
func claimAchievementsFor(addr string, ids []string, strict bool) int {
	if len(ids) > 200 {
		panic("too many achievements in one call (max 200)")
	}
	n := 0
	for _, id := range ids {
		key := addr + ":" + id
		if achievements.Has(key) {
			if strict {
				panic("already claimed")
			}
			continue
		}
		rw, why := achievementReward(addr, id)
		if why != "" {
			if strict {
				panic(why)
			}
			continue
		}
		achievements.Set(key, "1")
		for _, ca := range rw {
			creditReward(addr, ca.coin, ca.amt)
		}
		n++
	}
	return n
}

// ClaimAchievement claims one allowlisted achievement and credits its fixed
// reward. Needs a server voucher of kind "ach" with payload = `["<id>"]`.
func ClaimAchievement(cur realm, achievementId string, nonce int64, expiry int64, sigHex string) {
	caller := requirePlayer(cur)
	payload := `[` + jsonStr(achievementId) + `]`
	useVoucher("ach", caller, nonce, expiry, payload, sigHex)
	claimAchievementsFor(caller, []string{achievementId}, true)
}

// BatchClaimAchievements claims several ids (already-claimed / not-earned ids
// are skipped). idsJson must be exactly the voucher payload.
func BatchClaimAchievements(cur realm, idsJson string, nonce int64, expiry int64, sigHex string) int {
	caller := requirePlayer(cur)
	useVoucher("ach", caller, nonce, expiry, idsJson, sigHex)
	return claimAchievementsFor(caller, parseStringList(idsJson), false)
}

func HasAchievement(addr, id string) bool { return achievements.Has(addr + ":" + id) }

// parseDailyCheckin reads the stored value for an address and returns
// (lastDay, streak). It handles both the new "<lastDay>:<streak>" format
// and the legacy "<unix seconds>" format (which stores raw epoch seconds;
// treated as lastDay = seconds/86400, streak = 1).
func parseDailyCheckin(raw string) (int64, int64) {
	for i := 0; i < len(raw); i++ {
		if raw[i] == ':' {
			lastDay, errD := strconv.ParseInt(raw[:i], 10, 64)
			streak, errS := strconv.ParseInt(raw[i+1:], 10, 64)
			if errD == nil && errS == nil {
				return lastDay, streak
			}
			break
		}
	}
	// Legacy format: raw is a plain unix-seconds timestamp
	seconds, err := strconv.ParseInt(raw, 10, 64)
	if err != nil {
		return 0, 0
	}
	return seconds / 86400, 1
}

func DailyCheckin(cur realm) {
	caller := requirePlayer(cur)
	today := time.Now().Unix() / 86400

	var lastDay, streak int64
	if dailyCheckins.Has(caller) {
		raw := dailyCheckins.Get(caller).(string)
		lastDay, streak = parseDailyCheckin(raw)
	}

	if lastDay == today {
		panic("already checked in today")
	}
	if lastDay == today-1 {
		streak = streak + 1
	} else {
		streak = 1
	}

	val := strconv.FormatInt(today, 10) + ":" + strconv.FormatInt(streak, 10)
	dailyCheckins.Set(caller, val)
}

// Tasks: game28 let anyone mark any task done. In game29 tasks are created
// and completed for a player only by the operator (server) — no free medals.
func CreateTask(cur realm, taskId string, desc string) {
	if !isOperator(cur) {
		panic("unauthorized: operator only")
	}
	if !isSafeId(taskId, 64) {
		panic("invalid task id")
	}
	achievements.Set("task:"+taskId+":desc", sanitizeName(desc))
}

func CompleteTask(cur realm, taskId string) {
	panic("CompleteTask is operator-only in game29 — use CompleteTaskFor")
}

func CompleteTaskFor(cur realm, player string, taskId string) {
	if !isOperator(cur) {
		panic("unauthorized: operator only")
	}
	if !achievements.Has("task:" + taskId + ":desc") {
		panic("unknown task")
	}
	achievements.Set(player+":task."+taskId, "1")
}

game_relay.gno

package game32

// ── Gasless relay: treasury pays gas for BuyTool and TrainSkill ──────────────
//
// The treasury server calls RelayBuyTool / RelayTrainSkill from the relay
// address (set by SetRelayAddress). Effects are recorded against `player`,
// not against the relay caller.
//
// Security model:
//   - relayAddress is the ONLY caller that may use these functions.
//   - Each call requires an ed25519 signature from the same claimSignerPubKey
//     used for claim vouchers. The server signs with MOJI_CLAIM_SIGNER_SEED.
//   - Replay protection: relayNonces[player] must increase monotonically.
//   - Expiry: relay vouchers expire within relayMaxTTL seconds.
//   - The relay cannot grant tools the player cannot normally buy (same
//     prerequisite and balance checks as BuyTool/TrainSkill).
//
// Relay voucher message (signed by the server, verified on-chain):
//   gnomoji-relay-v1|<chainId>|<kind>|<player>|<extra>|<nonce>|<expiry>
//
// Where:
//   kind  = "BuyTool" | "TrainSkill"
//   extra = toolId   (BuyTool) | skillId (TrainSkill)

import (
	"crypto/ed25519"
	"encoding/hex"
	"strconv"
	"time"

	"chain/runtime"

	"chain"
)

const relayMaxTTL = int64(300) // 5 minutes — relay vouchers are short-lived

// relayVoucherMessage builds the canonical message the server signs.
func relayVoucherMessage(kind, player, extra string, nonce, expiry int64) string {
	return "gnomoji-relay-v1|" + runtime.ChainID() + "|" + kind + "|" + player + "|" +
		extra + "|" + strconv.FormatInt(nonce, 10) + "|" + strconv.FormatInt(expiry, 10)
}

// lastRelayNonce returns the last relay nonce for player (0 if none).
func lastRelayNonce(player string) int64 {
	if !relayNonces.Has(player) {
		return 0
	}
	n, _ := strconv.ParseInt(relayNonces.Get(player).(string), 10, 64)
	return n
}

// useRelayVoucher verifies and consumes a relay voucher for player.
// Panics on any failure so the entire tx is rolled back.
func useRelayVoucher(kind, player, extra string, nonce, expiry int64, sigHex string) {
	if len(claimSignerPubKey) != 32 {
		panic("relay disabled: no claim signer configured")
	}
	now := time.Now().Unix()
	if expiry < now {
		panic("relay voucher expired")
	}
	if expiry > now+relayMaxTTL {
		panic("relay voucher expiry too far in the future")
	}
	lastN := lastRelayNonce(player)
	if nonce <= lastN {
		panic("relay voucher already used (nonce " + strconv.FormatInt(nonce, 10) + " ≤ last " + strconv.FormatInt(lastN, 10) + ")")
	}
	sig, err := hex.DecodeString(sigHex)
	if err != nil || len(sig) != 64 {
		panic("invalid relay voucher signature encoding")
	}
	msg := relayVoucherMessage(kind, player, extra, nonce, expiry)
	if !ed25519.Verify(claimSignerPubKey, []byte(msg), sig) {
		panic("invalid relay voucher signature")
	}
	relayNonces.Set(player, strconv.FormatInt(nonce, 10))
}

// requireRelay panics unless the caller is the registered relay address.
func requireRelay(cur realm) {
	if relayAddress == address("") {
		panic("relay not configured: SetRelayAddress first")
	}
	if cur.Previous().Address() != relayAddress {
		panic("unauthorized: relay calls must come from the registered relay address")
	}
}

// ── Admin ─────────────────────────────────────────────────────────────────────

// SetRelayAddress registers the treasury wallet address as the relay.
// Pass "" to disable the relay.
func SetRelayAddress(cur realm, addr string) {
	requireAdmin(cur)
	if addr == "" {
		relayAddress = address("")
		return
	}
	a := address(addr)
	if !a.IsValid() {
		panic("invalid relay address")
	}
	relayAddress = a
	chain.Emit("RelayAddressSet", "relay", addr)
}

func RelayAddress() string { return relayAddress.String() }

// ── RelayBuyTool ──────────────────────────────────────────────────────────────

// RelayBuyTool executes BuyTool logic on behalf of `player` (the relay pays
// gas). The server must sign a relay voucher with MOJI_CLAIM_SIGNER_SEED:
//
//	gnomoji-relay-v1|<chainId>|BuyTool|<player>|<toolId>|<nonce>|<expiry>
//
// All prerequisites (coin balance, tool chain, existing ownership) are checked
// the same as BuyTool — the relay cannot bypass them.
func RelayBuyTool(cur realm, player string, toolId string, nonce int64, expiry int64, sigHex string) {
	requireRelay(cur)
	requireNotPaused()
	if isBlacklisted(player) {
		panic("player address is banned")
	}
	if !address(player).IsValid() {
		panic("invalid player address")
	}
	useRelayVoucher("BuyTool", player, toolId, nonce, expiry, sigHex)

	// ── BuyTool logic (identical to BuyTool but acts on `player`, not caller) ──
	costs, hasCost := toolCosts[toolId]
	if !hasCost {
		panic("unknown tool: " + toolId)
	}
	if ownsTool(player, toolId) {
		panic("already own " + toolId + " — use RepairTool to restore durability")
	}
	if prereq, ok := toolRequires[toolId]; ok && !ownsTool(player, prereq) {
		panic("must own " + prereq + " before buying " + toolId)
	}
	deductBalances(player, costs)

	if !ownedTools.Has(player) || ownedTools.Get(player).(string) == "" {
		ownedTools.Set(player, toolId)
	} else {
		ownedTools.Set(player, ownedTools.Get(player).(string)+","+toolId)
	}
	if mx, ok := toolMaxLife[toolId]; ok && mx > 0 {
		setU(&toolLife, player+":"+toolId, effectiveMaxLife(player, toolId))
	}
	chain.Emit("RelayedBuyTool", "player", player, "tool", toolId, "relay", cur.Previous().Address().String())
}

// ── RelayTrainSkill ───────────────────────────────────────────────────────────

// RelayTrainSkill executes TrainSkill logic on behalf of `player`.
// Relay voucher message:
//
//	gnomoji-relay-v1|<chainId>|TrainSkill|<player>|<skillId>|<nonce>|<expiry>
//
// Same checks as TrainSkill; max rank and coin deduction apply normally.
func RelayTrainSkill(cur realm, player string, skillId string, nonce int64, expiry int64, sigHex string) {
	requireRelay(cur)
	requireNotPaused()
	if isBlacklisted(player) {
		panic("player address is banned")
	}
	if !address(player).IsValid() {
		panic("invalid player address")
	}
	useRelayVoucher("TrainSkill", player, skillId, nonce, expiry, sigHex)

	// ── TrainSkill logic (identical to TrainSkill but acts on `player`) ──────
	key := player + ":" + skillId
	rank := getU(&skillRanks, key)
	maxRank, ok := skillMaxRanks[skillId]
	if !ok {
		panic("unknown skill: " + skillId)
	}
	if rank >= maxRank {
		panic("skill already at maximum rank")
	}
	baseCosts, ok := skillBaseCosts[skillId]
	if !ok {
		panic("unknown skill: " + skillId)
	}
	mult := uint64(1) << rank
	var scaled [][2]string
	for _, pair := range baseCosts {
		baseAmt, _ := strconv.ParseUint(pair[1], 10, 64)
		if s := baseAmt * mult; s > 0 {
			scaled = append(scaled, [2]string{pair[0], strconv.FormatUint(s, 10)})
		}
	}
	deductBalances(player, scaled)
	setU(&skillRanks, key, rank+1)
	chain.Emit("RelayedTrainSkill", "player", player, "skill", skillId, "relay", cur.Previous().Address().String())
}

// LastRelayNonce returns the last relay nonce used by addr (0 if none).
// Used by the server to compute the next nonce.
func LastRelayNonce(addr string) int64 { return lastRelayNonce(addr) }

game_slots.gno

package game32

import (
	"crypto/sha256"
	"strconv"
)

// ── Slots engine: every reel, line, scatter and Hold & Spin tile comes from the
// round's combined seed. The client renders what the realm stored and re-derives
// it with the same rules (src/lib/game/slots-engine.ts mirrors this file).
//
// Stream: block i = sha256(serverSeed ":" clientSecret ":" roundId ":slots:" i),
// bytes consumed in order. Reel c stops at uint32(next 4 bytes) % 40 and shows
// strip[(stop+r) % 40] for rows r = 0..3. Grid cells are indexed c*4+r.
//
// Paytable (see the RTP math in .bot-notes/casino/CASINO_100_PLAN.md):
//   25 lines pay left to right in units of the line bet (bet/25; bets are a
//   multiple of 25 so nothing is rounded); wild substitutes; the anchor is the
//   first symbol that is not wild/scatter/vault (an all-wild line pays wild).
//   3/4/5 scatters anywhere pay 2/10/50× the bet and grant 10/12/15 free spins.
//   3+ vaults start Hold & Spin. Every win of a round is capped at 500× the bet.

const (
	slotsReels      = 5
	slotsRows       = 4
	slotsCells      = 20
	slotsStripLen   = 40
	slotsBetStep    = uint64(25) // bet must be a multiple of the 25 lines
	slotsMaxWinMult = uint64(500)

	symWild    = byte(0)
	symScatter = byte(8)
	symVault   = byte(9)

	// Hold & Spin
	hsLandBelow = byte(8) // a free cell lands a coin when its byte < 8 (3.125%)
	hsRespins   = 3

	// Hold & Spin tile codes (anything < 100 is a multiple of the bet)
	hsMini  = uint16(101)
	hsMinor = uint16(102)
	hsMajor = uint16(103)
	hsGrand = uint16(104)
)

// One strip for all reels: wild 1, seven 3, diamond 4, trophy 5, star 6,
// clover 6, flame 7, coin 6, scatter 1, vault 1 (digits = symbol ids).
const slotsStrip = "8645732106457321645793216457326457364576"

var slotsSymbolNames = [10]string{"wild", "seven", "diamond", "trophy", "star", "clover", "flame", "coin", "scatter", "vault"}

// line-bet multiples for 3/4/5 of a kind, symbols 0..7
var slotsPays = [8][3]uint64{
	{60, 250, 1000}, // wild
	{40, 150, 500},  // seven
	{30, 100, 300},  // diamond
	{25, 75, 200},   // trophy
	{15, 40, 100},   // star
	{12, 30, 80},    // clover
	{10, 25, 60},    // flame
	{8, 20, 50},     // coin
}

// same 25 lines as src/lib/game/slots.ts PAYLINES (row per reel)
var slotsPaylines = [25][5]byte{
	{1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {0, 0, 0, 0, 0}, {3, 3, 3, 3, 3},
	{0, 1, 2, 1, 0}, {3, 2, 1, 2, 3}, {0, 1, 3, 1, 0}, {3, 2, 0, 2, 3},
	{0, 1, 2, 3, 3}, {3, 2, 1, 0, 0}, {0, 0, 1, 2, 3}, {3, 3, 2, 1, 0},
	{1, 2, 1, 2, 1}, {2, 1, 2, 1, 2}, {1, 0, 1, 2, 1}, {2, 3, 2, 1, 2},
	{1, 0, 0, 0, 1}, {2, 3, 3, 3, 2}, {0, 2, 3, 2, 0}, {3, 1, 0, 1, 3},
	{1, 1, 2, 1, 1}, {2, 2, 1, 2, 2}, {0, 1, 0, 1, 0}, {3, 2, 3, 2, 3},
	{0, 3, 0, 3, 0},
}

var (
	slotsScatterPay = [6]uint64{0, 0, 0, 2, 10, 50} // × bet, by scatter count
	slotsFreeSpins  = [6]uint64{0, 0, 0, 10, 12, 15}
)

type slotsStream struct {
	prefix string
	ctr    int
	buf    [32]byte
	pos    int
}

func newSlotsStream(serverSeed, clientSecret, roundId string) *slotsStream {
	return &slotsStream{prefix: serverSeed + ":" + clientSecret + ":" + roundId + ":slots:", pos: 32}
}

func (s *slotsStream) next() byte {
	if s.pos >= 32 {
		s.buf = sha256.Sum256([]byte(s.prefix + strconv.Itoa(s.ctr)))
		s.ctr++
		s.pos = 0
	}
	b := s.buf[s.pos]
	s.pos++
	return b
}

func (s *slotsStream) u32() uint32 {
	return uint32(s.next())<<24 | uint32(s.next())<<16 | uint32(s.next())<<8 | uint32(s.next())
}

// slotsSpinGrid draws the 5 reel stops and returns the 20 visible symbols.
func slotsSpinGrid(s *slotsStream) [slotsCells]byte {
	var g [slotsCells]byte
	for c := 0; c < slotsReels; c++ {
		stop := int(s.u32() % slotsStripLen)
		for r := 0; r < slotsRows; r++ {
			g[c*slotsRows+r] = slotsStrip[(stop+r)%slotsStripLen] - '0'
		}
	}
	return g
}

// slotsLineMult = Σ line pays in line-bet units, and how many lines paid.
func slotsLineMult(g *[slotsCells]byte) (uint64, int) {
	total := uint64(0)
	lines := 0
	for l := 0; l < 25; l++ {
		var sym [5]byte
		anchor := byte(255)
		for c := 0; c < 5; c++ {
			sym[c] = g[c*slotsRows+int(slotsPaylines[l][c])]
			if anchor == 255 && sym[c] != symWild && sym[c] != symScatter && sym[c] != symVault {
				anchor = sym[c]
			}
		}
		if anchor == 255 {
			if sym[0] != symWild {
				continue
			}
			anchor = symWild
		}
		m := 0
		for c := 0; c < 5; c++ {
			if sym[c] == anchor || sym[c] == symWild {
				m++
			} else {
				break
			}
		}
		if m >= 3 {
			total += slotsPays[anchor][m-3]
			lines++
		}
	}
	return total, lines
}

func slotsCount(g *[slotsCells]byte, sym byte) int {
	n := 0
	for i := 0; i < slotsCells; i++ {
		if g[i] == sym {
			n++
		}
	}
	return n
}

// hsDrawValue: 1× 50%, 2× 28%, 3× 12%, 5× 6%, MINI 3%, MINOR 0.9%, MAJOR 0.08%, GRAND 0.02%.
func hsDrawValue(s *slotsStream) uint16 {
	v := s.u32() % 10000
	switch {
	case v < 5000:
		return 1
	case v < 7800:
		return 2
	case v < 9000:
		return 3
	case v < 9600:
		return 5
	case v < 9900:
		return hsMini
	case v < 9990:
		return hsMinor
	case v < 9998:
		return hsMajor
	}
	return hsGrand
}

// slotsHoldAndSpin resolves the whole bonus from the stream: the vault cells
// start locked with a value each; then while respins remain and the board isn't
// full, every empty cell (in index order) lands a coin when its byte < 8, and a
// landing resets the respins to 3. Returns the 20 tiles (0 = empty), how many
// respins were played, and whether the board filled (blackout = GRAND).
func slotsHoldAndSpin(s *slotsStream, g *[slotsCells]byte) ([slotsCells]uint16, int, bool) {
	var tiles [slotsCells]uint16
	locked := 0
	for i := 0; i < slotsCells; i++ {
		if g[i] == symVault {
			tiles[i] = hsDrawValue(s)
			locked++
		}
	}
	respins := hsRespins
	played := 0
	for respins > 0 && locked < slotsCells {
		played++
		landed := false
		for i := 0; i < slotsCells; i++ {
			if tiles[i] != 0 {
				continue
			}
			if s.next() < hsLandBelow {
				tiles[i] = hsDrawValue(s)
				locked++
				landed = true
			}
		}
		if landed {
			respins = hsRespins
		} else {
			respins--
		}
	}
	return tiles, played, locked == slotsCells
}

func slotsGridString(g *[slotsCells]byte) string {
	b := make([]byte, slotsCells)
	for i := 0; i < slotsCells; i++ {
		b[i] = '0' + g[i]
	}
	return string(b)
}

func hsTilesString(t *[slotsCells]uint16) string {
	out := ""
	for i := 0; i < slotsCells; i++ {
		if i > 0 {
			out += "."
		}
		out += strconv.Itoa(int(t[i]))
	}
	return out
}

gnomod.toml

module = "gno.land/r/g138gdmwj6heduu3st796lw6qqdwylgaxf7ty5gz/game32"
gno = "0.9"

[addpkg]
  creator = "g138gdmwj6heduu3st796lw6qqdwylgaxf7ty5gz"
  height = 535714
  max_deposit = "100000000ugnot"

helpers_test.gno

package game32

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

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

// Public key of the deterministic TEST-ONLY signer (scripts/game29-test-vectors.mjs,
// seed = sha256("gnomoji-game29-test-signer")). Not used anywhere but tests.
const testSignerPub = "faec207b91ab599b1e51652602843fcb52275922e8dab39bed3a21034cece6f1"

func setup() address {
	if admin == address("") {
		admin = testutils.TestAddress("deployer")
		operator = admin
	}
	if len(claimSignerPubKey) != 32 {
		claimSignerPubKey, _ = hex.DecodeString(testSignerPub)
	}
	return admin
}

func ta(name string) address { return testutils.TestAddress(name) }

func bal(a address, coin string) uint64 { return balOf(a.String(), coin) }

// voucher returns (nonce, expiry, sigHex) for a server voucher. Signatures
// come from voucherVectors (generated). A missing vector is logged so the
// generator can sign it, and an invalid signature is returned.
func voucher(t *testing.T, kind string, player address, payload string) (int64, int64, string) {
	nonce := LastNonce(player.String()) + 1
	expiry := time.Now().Unix() + 600
	return nonce, expiry, sigFor(t, kind, player, nonce, expiry, payload)
}

// safeCompactAchPayload wraps compactAchPayload with a recover so that
// cross-kind tests (e.g. signing an "ach" voucher over a claim payload) don't
// crash the test helper. An unparseable payload falls back to the raw string —
// the resulting signature will be wrong and the realm will reject it, which is
// exactly what those rejection tests expect.
func safeCompactAchPayload(payload string) (result string) {
	defer func() {
		if r := recover(); r != nil {
			result = payload // fall back to raw payload on parse error
		}
	}()
	return compactAchPayload(payload)
}

func sigFor(t *testing.T, kind string, player address, nonce, expiry int64, payload string) string {
	// Compact the payload to match the v2 VoucherMessage format.
	compact := payload
	if kind == "claim" {
		compact = compactClaimPayload(payload)
	} else if kind == "ach" {
		compact = safeCompactAchPayload(payload)
	}
	msg := VoucherMessage(kind, player.String(), nonce, expiry, compact)
	if s, ok := voucherVectors[msg]; ok {
		return s
	}
	// Regenerate with: node scripts/game29-test-vectors.mjs
	panic("MISSING_VOUCHER " + hex.EncodeToString([]byte(msg)) + " END")
}

func give(a address, coin string, amt uint64) { creditBal(a.String(), coin, amt) }

func allowanceFor(addr address, r int) uint64 {
	js := ClaimAllowance(addr.String())
	key := `"r` + strconv.Itoa(r) + `":`
	i := strings.Index(js, key) + len(key)
	j := i
	for j < len(js) && js[j] >= '0' && js[j] <= '9' {
		j++
	}
	v, _ := strconv.ParseUint(js[i:j], 10, 64)
	return v
}

func mustAbort(t *testing.T, what string, abort any, wantSub string) {
	if abort == nil {
		t.Errorf("%s: expected abort, got success", what)
		return
	}
	msg := ""
	switch v := abort.(type) {
	case string:
		msg = v
	case error:
		msg = v.Error()
	default:
		msg = "?"
	}
	if wantSub != "" && !strings.Contains(msg, wantSub) {
		t.Errorf("%s: aborted with %q, want it to contain %q", what, msg, wantSub)
	}
}

func h(choice, salt string) string { return moveHash(choice, salt) }

func h0(s string) string {
	x := sha256Sum(s)
	return x
}

json.gno

package game32

import (
	"strconv"
	"strings"

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

// jsonStr returns s as a quoted, escaped JSON string (game28 concatenated raw
// user strings into JSON, so a guild name with a quote broke every reader).
func jsonStr(s string) string {
	var b strings.Builder
	b.WriteByte('"')
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch c {
		case '"':
			b.WriteString(`\"`)
		case '\\':
			b.WriteString(`\\`)
		case '\n':
			b.WriteString(`\n`)
		case '\r':
			b.WriteString(`\r`)
		case '\t':
			b.WriteString(`\t`)
		default:
			if c < 0x20 {
				b.WriteString(`\u00`)
				b.WriteByte("0123456789abcdef"[c>>4])
				b.WriteByte("0123456789abcdef"[c&0xf])
			} else {
				b.WriteByte(c)
			}
		}
	}
	b.WriteByte('"')
	return b.String()
}

// sanitizeName trims and strips control characters from a display name.
func sanitizeName(s string) string {
	var b strings.Builder
	for _, r := range strings.TrimSpace(s) {
		if r < 0x20 || r == 0x7f {
			continue
		}
		b.WriteRune(r)
	}
	return b.String()
}

// isSafeId reports whether s is a short [a-z0-9_.-] identifier.
func isSafeId(s string, maxLen int) bool {
	if s == "" || len(s) > maxLen {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.') {
			return false
		}
	}
	return true
}

func isHex64(s string) bool {
	if len(s) != 64 {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
			return false
		}
	}
	return true
}

// parseStringRows parses a JSON array of arrays of strings, e.g.
// [["g1..","grin","10"],["g1..","joy","4"]]. Numbers are accepted unquoted.
// Panics on malformed input.
func parseStringRows(s string) [][]string {
	p := &jparser{s: s}
	p.ws()
	p.expect('[')
	var rows [][]string
	p.ws()
	if p.peek() == ']' {
		p.i++
		return rows
	}
	for {
		p.ws()
		p.expect('[')
		var row []string
		p.ws()
		if p.peek() == ']' {
			p.i++
		} else {
			for {
				p.ws()
				row = append(row, p.value())
				p.ws()
				if p.peek() == ',' {
					p.i++
					continue
				}
				p.expect(']')
				break
			}
		}
		rows = append(rows, row)
		p.ws()
		if p.peek() == ',' {
			p.i++
			continue
		}
		p.expect(']')
		break
	}
	p.ws()
	if p.i != len(p.s) {
		panic("invalid JSON: trailing data")
	}
	return rows
}

// parseStringList parses ["a","b",...].
func parseStringList(s string) []string {
	rows := parseStringRows("[" + s + "]")
	if len(rows) != 1 {
		panic("invalid JSON list")
	}
	return rows[0]
}

type jparser struct {
	s string
	i int
}

func (p *jparser) peek() byte {
	if p.i >= len(p.s) {
		panic("invalid JSON: unexpected end")
	}
	return p.s[p.i]
}

func (p *jparser) ws() {
	for p.i < len(p.s) && (p.s[p.i] == ' ' || p.s[p.i] == '\n' || p.s[p.i] == '\t' || p.s[p.i] == '\r') {
		p.i++
	}
}

func (p *jparser) expect(c byte) {
	if p.peek() != c {
		panic("invalid JSON: expected " + string(c) + " at " + strconv.Itoa(p.i))
	}
	p.i++
}

func (p *jparser) value() string {
	if p.peek() != '"' {
		st := p.i
		for p.i < len(p.s) && (p.s[p.i] >= '0' && p.s[p.i] <= '9' || p.s[p.i] == '-') {
			p.i++
		}
		if st == p.i {
			panic("invalid JSON: expected string or number at " + strconv.Itoa(st))
		}
		return p.s[st:p.i]
	}
	p.i++
	var b strings.Builder
	for {
		c := p.peek()
		p.i++
		if c == '"' {
			return b.String()
		}
		if c == '\\' {
			e := p.peek()
			p.i++
			switch e {
			case '"', '\\', '/':
				b.WriteByte(e)
			case 'n':
				b.WriteByte('\n')
			case 't':
				b.WriteByte('\t')
			case 'r':
				b.WriteByte('\r')
			default:
				panic("invalid JSON escape")
			}
			continue
		}
		b.WriteByte(c)
	}
}

// ── avl uint helpers ─────────────────────────────────────────────────────────

func getU(t *avl.Tree, key string) uint64 {
	if !t.Has(key) {
		return 0
	}
	v, _ := strconv.ParseUint(t.Get(key).(string), 10, 64)
	return v
}

func setU(t *avl.Tree, key string, v uint64) {
	t.Set(key, strconv.FormatUint(v, 10))
}

// addU adds d to a stored counter; panics instead of wrapping on overflow.
func addU(t *avl.Tree, key string, d uint64) uint64 {
	old := getU(t, key)
	v := old + d
	if v < old {
		panic("math overflow")
	}
	setU(t, key, v)
	return v
}

func balOf(addr, coin string) uint64 { return getU(&balances, addr+":"+coin) }

func creditBal(addr, coin string, amt uint64) {
	if amt > 0 {
		addU(&balances, addr+":"+coin, amt)
	}
}

func debitBal(addr, coin string, amt uint64) {
	have := balOf(addr, coin)
	if have < amt {
		panic("insufficient " + coin + ": need " + strconv.FormatUint(amt, 10) + " have " + strconv.FormatUint(have, 10))
	}
	setU(&balances, addr+":"+coin, have-amt)
}

sherlock_regress_test.gno

package game32

import (
	"strings"
	"testing"
	"time"
)

// Sherlock's 4 main-tree exploit probes (SHERLOCK_REPORT §4), inverted:
// each must now be refused by the single game29 realm.

func TestSherlockH1aBankAndFreePass_Closed(cur realm, t *testing.T) {
	setup()
	bot := ta("sherlock-bot")
	testing.SetRealm(testing.NewUserRealm(bot))
	exp := time.Now().Unix() + 300
	mustAbort(t, "unsigned bank claim", revive(func() { ClaimAndMint(cross(cur), `[["grin","1000"]]`, 1, exp, "") }), "")
	mustAbort(t, "forged bank claim", revive(func() { ClaimAndMint(cross(cur), `[["grin","1000"]]`, 1, exp, strings.Repeat("ab", 64)) }), "")
	mustAbort(t, "free pass", revive(func() { ActivateGnomePass(cross(cur), 3650) }), "")
	if strings.Contains(AllBalances(bot.String()), "grin") || HasActivePass(bot.String()) {
		t.Errorf("H1a open: %s", AllBalances(bot.String()))
	}
}

func TestSherlockN1ForgedMedal_Closed(cur realm, t *testing.T) {
	setup()
	bot := ta("sherlock-n1")
	testing.SetRealm(testing.NewUserRealm(bot))
	mustAbort(t, "forged medal", revive(func() { ClaimAchievement(cross(cur), "made-up-medal", 1, time.Now().Unix()+300, "") }), "")
	if strings.Contains(GetMedals(bot.String()), "made-up-medal") {
		t.Errorf("N1 open")
	}
}

func TestSherlockH2bCommitOverwrite_Closed(cur realm, t *testing.T) {
	setup()
	bot := ta("sherlock-h2b")
	testing.SetRealm(testing.NewUserRealm(bot))
	mustAbort(t, "commit on missing lobby", revive(func() { CommitPvpMove(cross(cur), "no-such-lobby", "aaaa") }), "")
}

func TestSherlockH1fSybil_Closed(cur realm, t *testing.T) {
	setup()
	main := ta("sherlock-main")
	for _, n := range []string{"s1", "s2", "s3"} {
		a := ta("sherlock-" + n)
		testing.SetRealm(testing.NewUserRealm(a))
		mustAbort(t, "sybil claim", revive(func() { ClaimAndMint(cross(cur), `[["grin","1000"]]`, 1, time.Now().Unix()+300, "") }), "")
		mustAbort(t, "sybil transfer", revive(func() { Transfer(cross(cur), "grin", main.String(), "1000") }), "")
	}
	if strings.Contains(AllBalances(main.String()), "grin") {
		t.Errorf("H1f open: %s", AllBalances(main.String()))
	}
}

vectors_test.gno

// Code generated by scripts/game29-test-vectors.mjs. DO NOT EDIT.

package game32

var voucherVectors = map[string]string{
	"gnomoji-voucher-v2|dev|ach|g1d4jkgctv94nxzundv4e97h6lta047h6lz94un4|1|1234568490|made-up-medal,mythic-legend": "95ea1ef535b5ab0464933e15cf2c621da2f058bf0c85076c17fc381ad0b5fe6ae34f4054bd5e225d757541022abed72d861d68cd958fda2dc7872bb68180550b",
	"gnomoji-voucher-v2|dev|ach|g1v93ksttsta047h6lta047h6lta047h6ls2nnsr|1|1234568490|blocks_1": "f5d7b1342657fea173a5d40e8863337e4668a73db305a4c4bfdfa384d7b339f3e8f68bb4a87d3c432aa75a975bcbd76570ccf3dc75e2772eceff9b4e08b67f02",
	"gnomoji-voucher-v2|dev|ach|g1v93ksttsta047h6lta047h6lta047h6ls2nnsr|2|1234568490|blocks_1": "dea0ab0698a740bee04f06ff7ecf29d7615a6c1240281c4de5564683269b19c29fbd5c5831727158ae922394d44bb598647e8033c276a7148cd3f80586709205",
	"gnomoji-voucher-v2|dev|ach|g1v93ksttsta047h6lta047h6lta047h6ls2nnsr|3|1234568490|g.grin.10": "86db78c6780dbf0b06821f9c1a3bb9e007bfffa6b6e3fe1fd3f27a47f5f93b94289371e25d8b7958510224ef801e6ba44b9e35f87b8496d4e6c20d62cf94f70a",
	"gnomoji-voucher-v2|dev|ach|g1v93ksttsta047h6lta047h6lta047h6ls2nnsr|5|1234568490|g.grin.10,g.grin.100,nope": "414b79be155877a063770fac010f556cb986d43a8742920ff5641c5e340481762f08a5a9433d9400f8b9482861dbfdbb65187b6da88dc514e627f65b98c49d0e",
	"gnomoji-voucher-v2|dev|ach|g1wckhqh6lta047h6lta047h6lta047h6l5lsxnf|1|1234568490|[[\"grin\",\"10\"]]": "ea556448be5e5b6fb427037b8c43a04d003ad13aaa25e506c59624cd51898922bc86ace87217b2df2d04444e6283bd6ec1a586ecb550d2bcb1ade875d29e6505",
	"gnomoji-voucher-v2|dev|claim|g10pcz6urvv9uk2ujlta047h6lta047h6lgn9puu|1|1234568490|grin:10": "aee8bc52aeda982a2c86c83df30e867c5a2abfc437b6cfd5c92a755b0118d18f6257b33d1d703dc901c77652a0e2c411d553c38e9c8427afdecf77c3239abb02",
	"gnomoji-voucher-v2|dev|claim|g1d45kwunpw3jj6urvv9uk2ujlta047h6lm4sy7j|1|1234568490|grin:1": "f9b2625c24eb9ec1c66a5d2c36f6578dbd4e3702e42c1ac399d5865bf4e98038148cd376cae17a829ed51dded22404c0f61c242b55cf166c16ff5bb3f9e5a20c",
	"gnomoji-voucher-v2|dev|claim|g1dejhwttsd3shjetj94382cmtv4697h6ltnjpz0|1|1234568490|grin:1": "03c35ba8c2fbaafca43d16d67e0d5808c59b31bb7fa9d89ec09fbc5a1d0b95e8083488e77b49aafd38847b86c4301224e28c55b3f99e3c1af82ed79f1012c90f",
	"gnomoji-voucher-v2|dev|claim|g1dqckgttzda697h6lta047h6lta047h6l3a59xv|1|1234568490|dragon:1": "252485f5fce785305214ec03d71242ae749706aa6db767722859909ca50328786d5b9f84926144bc154ffaba073876fb8cc5a8fd8c1e060a5fce9f688884e008",
	"gnomoji-voucher-v2|dev|claim|g1dqckvttdv95kuh6lta047h6lta047h6l3ketj7|1|1234568490|grin:100": "64156721648589ed3034a2e83328d47967d79f1f7ce0e9bcfe044f391bb0f60fe89020b370d5c82dbb3e64b06e9dfc4ca590ab7eedabc3ba338301288409ce09",
	"gnomoji-voucher-v2|dev|claim|g1dqckxttzda697h6lta047h6lta047h6l50zyz9|1|1234568490|fake-coin:50000": "c88e2b3563cea12460af9c0c8179156e3925a502e9cffa446ed862168a62f2e50cf21119b8f2a250801a07177018d3031ebc84d98d40aba36dc9a95f5bee460d",
	"gnomoji-voucher-v2|dev|claim|g1dqckyttzda697h6lta047h6lta047h6lxftedx|1|1234568490|grin:100": "c44079ace2b04d5f8fb3261f8343ba5b0e7d2c648eb5d40df3b0bb3646d136cd14786b1b245749bb79507f76541ea96ee324496ddcc110a8a997d599d6e99f0c",
	"gnomoji-voucher-v2|dev|claim|g1v93ksttsta047h6lta047h6lta047h6ls2nnsr|4|1234568490|grin:20": "2506adcf609020dc97264efd928c92f5156da36eaeb7e8f23faeeb60a795f7103fec1edb6bc88e0b4db7b3f15612b7959aa68b84c96f1ae7f9be7bcf0a1a4d04",
	"gnomoji-voucher-v2|dev|claim|g1wckhqh6lta047h6lta047h6lta047h6l5lsxnf|1|1234567889|grin:10": "e94b62d9ba72df423e24e2cbe973ef5c6805ec34bfcaf497cd90806209e3f1305c1941f514eee56c86cb129223d8af8f1f22632d879a869e3c6d8d3160779b0c",
	"gnomoji-voucher-v2|dev|claim|g1wckhqh6lta047h6lta047h6lta047h6l5lsxnf|1|1234568490|grin:10": "a98671e28f2a70fea9d6ecb0fd2a7e652d565ed316cf7ff5ce5f5a7e4d4c645c7ad37421dece1441b91e23318c922c528aeb2141df10620655c567851da8ce01",
	"gnomoji-voucher-v2|dev|claim|g1wckhqh6lta047h6lta047h6lta047h6l5lsxnf|1|1234571490|grin:10": "335ab798639232d79245b101c829dc86a9ac9d5c15c54837fe4908bcce78ebc24453d3f566259d86eca38e38adfb29e89fb61d331734bc0abc98d79ccb546908",
	"gnomoji-voucher-v2|dev|claim|g1wckhqmrp09jhyh6lta047h6lta047h6lcq6a6q|1|1234568490|grin:50": "8ef539352973672121176ecdcfe70e387d24a00c4884b925cb6a7363e3b756d1deba0073562806457b7bad140aef8568f848a9933c36a018b8237f0ea1b3f300",
	"gnomoji-voucher-v2|dev|claim|g1wejkjm3dwp047h6lta047h6lta047h6ljh4a8n|1|1234568490|joy:100": "0e56f9d4f953a23e013aafcc6e8cd5d7bcb1d53b1683e2c0f93511f5902f9b78ff92d047fb152a82cc7f280bcf61adaaea362f12a2113f68447e8100e101c20b",
	"gnomoji-voucher-v2|dev|claim|g1wfshgefdwp047h6lta047h6lta047h6lwt2ctw|1|1234568490|grin:200": "aa3a00ad5f48bebed1c1bb0951532c95490193f3da209d88d6de62ec3c511ce7638e8550ad5411dee5be178a61b688aa41548cca2a9e264dbcee9efa87f0a807",
	"gnomoji-voucher-v2|dev|claim|g1wfshgefdwp047h6lta047h6lta047h6lwt2ctw|2|1234568490|grin:1": "702c638a3059efbe71658b9f3a222b5f9774b44a3a1ab80b74feeb6536937fb3beaf8cbeae6cf139c4100d0aa122585e142c59ba2c44cf86fd0d9e8cb27c6a0f",
	"gnomoji-voucher-v2||claim|g10pcz6urvv9uk2ujlta047h6lta047h6lgn9puu|2|1234568555|music:5": "eddf3e9d7f049e6c7d051f200790a1de299a8c6b413c1c2644a53aac516f203016b1bd8acccbc2b7331df1e5d8d949faf6f7481082b646181e5773a873ee4e03",
	"gnomoji-voucher-v2||claim|g1dqck2ttxwfjhx6zlta047h6lta047h6lf23l7v|1|1234568815|grin:1440": "d95e1762cfedc32500f949539f4a4f1a348a68e586e49e51c33cbd7bd213a19a8537c3818e5d49d4b85acba770edaaceee592ec9a45c4a1c8e20fb8793683e0e",
	"gnomoji-voucher-v2||claim|g1wfshgefdwp047h6lta047h6lta047h6lwt2ctw|3|1234568555|grin:60": "db24a8d270c633e516beb45d064af62f611f2fe85d2d5d4240aa05dae112de73d1b8fa146f4d4f01adec5b7617170f04897540925e189e4c879deab1b2107700",
	"gnomoji-voucher-v2||claim|g1wfshgefdwp047h6lta047h6lta047h6lwt2ctw|4|1234568620|grin:90": "396f4a774924fb4b525dd1cb98d51c91e719d88db7131171649d8a30fbbb639fa9bd72e83cbed18deea67a9976f8cc35eccd33030f4a7f0518c4412f5112ca05",
}