Playground
exchange_book.gno
package game33
// ── 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 game33
// ── 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"
"chain/banker"
"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)) + `"}`
}
// ── GNOT bridge ───────────────────────────────────────────────────────────────
//
// DepositGnot and WithdrawGnot are the ONLY two places where ugnot crosses
// between the Gno banker and the exchange's internal balance system.
//
// Security:
// - DepositGnot requires a direct EOA call (exchangeCaller panics for
// cross-realm calls) so no intermediate realm can deposit on a player's behalf.
// - WithdrawGnot is intentionally NOT gated by requireMarketOpen: like
// RemoveLiquidity and CancelOrder, withdrawals must always work even while
// the exchange is paused or the caller is banned — it's the player's own money.
// - The realm can only SendCoins ugnot it actually holds; the debit comes
// first so if accounting ever drifts, the debit panics before any send.
// - WithdrawFunds (admin pass revenue) remains completely isolated:
// WithdrawGnot debits from the player's internal "gnot" balance, which is
// a separate accounting entry from passRevenueUgnot. The two pools of ugnot
// cannot mix via any code path.
// DepositGnot wraps the ugnot attached to this MsgCall into the exchange's
// internal "gnot" balance, enabling the player to trade or provide GNOT
// liquidity. Attach the desired ugnot amount to the MsgCall as a send value.
func DepositGnot(cur realm) uint64 {
caller := exchangeCaller(cur)
sent := banker.NewBanker(banker.BankerTypeOriginSend, cur).GetCoins(cur.Address())
amt := uint64(0)
for _, c := range sent {
if c.Denom == "ugnot" {
amt = uint64(c.Amount)
}
}
if amt == 0 {
panic("attach ugnot to deposit (MsgCall send field)")
}
gnotDeposited = addChk(gnotDeposited, amt)
creditBal(caller, gnotCoinId, amt)
chain.Emit("GnotDeposited", "who", caller, "amount", u(amt))
return amt
}
// WithdrawGnot converts internal "gnot" balance back to real ugnot and sends
// it to the caller. Works while the exchange is paused — it is an exit, not a
// trade. Any player can call this for their own balance at any time.
func WithdrawGnot(cur realm, amtStr string) {
caller := exchangeCaller(cur)
amt, err := strconv.ParseUint(amtStr, 10, 64)
if err != nil || amt == 0 || amt > maxAmount {
panic("invalid amount")
}
requireBalance(caller, gnotCoinId, amt)
// Debit first — if the send ever panics, the player keeps their internal
// balance intact (they can retry). The realm holds the actual ugnot so
// the send cannot fail due to insufficient realm funds as long as
// gnotDeposited accounting is correct.
debitBal(caller, gnotCoinId, amt)
b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
b.SendCoins(cur.Address(), address(caller), chain.Coins{chain.NewCoin("ugnot", int64(amt))})
chain.Emit("GnotWithdrawn", "who", caller, "amount", u(amt))
}
exchange_gnot.gno
package game33
// ── P2P exchange: COIN/GNOT constant-product pools ───────────────────────────
//
// Mirrors exchange_pool.gno exactly, but the hub side is "gnot" (internal
// pseudo-coin representing deposited ugnot) instead of "grin".
//
// Pool keys use the coin ID directly (e.g. "fire", "cool") — they live in a
// separate AVL tree (gnotPools) so they cannot collide with the COIN/GRIN
// pools in the `pools` tree.
//
// Players must call DepositGnot (exchange_core.gno) first to wrap ugnot into
// internal "gnot" balance before they can trade or provide liquidity here.
// WithdrawGnot unwraps "gnot" back to real ugnot at any time.
//
// Security properties identical to exchange_pool.gno:
// - All amounts uint64, all arithmetic checked (no wraps).
// - Rounding always favors the pool.
// - Reserves are internal counters — no banker calls here.
// - RemoveGnotLiquidity works while paused or banned (it's an exit).
// - minLiquidity (1000) shares burned on first deposit (sandwich resistance).
import (
"strconv"
"time"
"chain"
"gno.land/p/nt/avl/v0"
)
var (
gnotPools avl.Tree // coin → *pool (reuses the pool struct from exchange_pool.gno)
gnotLpPositions avl.Tree // coin+":"+addr → *lpPos
)
// gnotPool returns the COIN/GNOT pool for coin, panicking if it doesn't exist.
func gnotPool(coin string) *pool {
if !gnotPools.Has(coin) {
panic("no GNOT pool for " + coin)
}
return gnotPools.Get(coin).(*pool)
}
// ── Write functions ───────────────────────────────────────────────────────────
// OpenGnotPool creates a new COIN/GNOT pool and seeds the first liquidity,
// atomically setting the opening price. Any player who holds the coin and
// enough deposited GNOT can call this — no admin required.
//
// coinAmt/gnotAmt set the price ratio; whoever opens the pool first controls
// the opening price. 1,000 shares are permanently burned as a seed.
func OpenGnotPool(cur realm, coin string, coinAmt uint64, gnotAmt uint64, minShares uint64, deadline int64) uint64 {
caller := exchangeCaller(cur)
requireMarketOpen(caller)
requireDeadline(deadline)
requireAmount("coinAmt", coinAmt)
requireAmount("gnotAmt", gnotAmt)
if coin == hubCoin {
panic("grin has its own COIN/GRIN pool: use OpenPool")
}
if coin == gnotCoinId {
panic("cannot open a GNOT/GNOT pool")
}
requireCoin(coin)
if gnotPools.Has(coin) {
panic("GNOT pool already exists: use AddGnotLiquidity to stake")
}
s := isqrt128(coinAmt, gnotAmt)
if s <= minLiquidity {
panic("first deposit too small: sqrt(coinAmt x gnotAmt) must exceed 1000")
}
minted := s - minLiquidity
if minted < minShares {
panic("slippage: shares below minimum")
}
requireBalance(caller, coin, coinAmt)
requireBalance(caller, gnotCoinId, gnotAmt)
// ── all checks passed; writes start here ──
p := &pool{coin: coin}
gnotPools.Set(coin, p)
p.shares = addChk(minted, minLiquidity)
debitBal(caller, coin, coinAmt)
debitBal(caller, gnotCoinId, gnotAmt)
p.rCoin = coinAmt
p.rHub = gnotAmt
now := time.Now().Unix()
rk := rootKPerShare(p)
gnotLpPositions.Set(coin+":"+caller, &lpPos{shares: minted, entryRKPS: rk, depositTs: now})
chain.Emit("GnotPoolCreated", "coin", coin)
chain.Emit("GnotLiquidityAdded", "coin", coin, "who", caller,
"coinIn", u(coinAmt), "gnotIn", u(gnotAmt), "shares", u(minted))
return minted
}
// AddGnotLiquidity deposits up to coinMax of `coin` and gnotMax internal GNOT.
// Follows the current pool ratio. Reverts unless at least minShares are minted.
func AddGnotLiquidity(cur realm, coin string, coinMax uint64, gnotMax uint64, minShares uint64, deadline int64) uint64 {
caller := exchangeCaller(cur)
requireMarketOpen(caller)
requireDeadline(deadline)
requireAmount("coinMax", coinMax)
requireAmount("gnotMax", gnotMax)
p := gnotPool(coin)
if p.paused {
panic("GNOT pool paused")
}
var aCoin, aHub, minted uint64
if p.shares == 0 {
aCoin, aHub = coinMax, gnotMax
s := isqrt128(aCoin, aHub)
if s <= minLiquidity {
panic("first deposit too small: sqrt(coin×gnot) must exceed 1000")
}
minted = s - minLiquidity
} else {
aHub = gnotMax
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, gnotCoinId, aHub)
// ── all checks passed; writes start here ──
if p.shares == 0 {
p.shares = addChk(minted, minLiquidity)
} else {
p.shares = addChk(p.shares, minted)
}
debitBal(caller, coin, aCoin)
debitBal(caller, gnotCoinId, aHub)
p.rCoin = addChk(p.rCoin, aCoin)
p.rHub = addChk(p.rHub, aHub)
key := coin + ":" + caller
now := time.Now().Unix()
rk := rootKPerShare(p)
if gnotLpPositions.Has(key) {
pos := gnotLpPositions.Get(key).(*lpPos)
tot := addChk(pos.shares, minted)
pos.entryRKPS = addChk(mulDiv(pos.entryRKPS, pos.shares, tot), mulDivUp(rk, minted, tot))
pos.depositTs = int64(addChk(mulDiv(uint64(pos.depositTs), pos.shares, tot), mulDivUp(uint64(now), minted, tot)))
pos.shares = tot
} else {
gnotLpPositions.Set(key, &lpPos{shares: minted, entryRKPS: rk, depositTs: now})
}
chain.Emit("GnotLiquidityAdded", "coin", coin, "who", caller,
"coinIn", u(aCoin), "gnotIn", u(aHub), "shares", u(minted))
return minted
}
// RemoveGnotLiquidity is always available — works while the exchange or pool
// is paused. Returns (coinOut, gnotOut).
func RemoveGnotLiquidity(cur realm, coin string, shares uint64, minCoin uint64, minGnot uint64, deadline int64) (uint64, uint64) {
caller := exchangeCaller(cur)
requireDeadline(deadline)
p := gnotPool(coin)
key := coin + ":" + caller
if !gnotLpPositions.Has(key) {
panic("no GNOT liquidity position in " + coin)
}
pos := gnotLpPositions.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 < minGnot {
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 {
gnotLpPositions.Remove(key)
}
creditBal(caller, coin, outCoin)
creditBal(caller, gnotCoinId, outHub)
chain.Emit("GnotLiquidityRemoved", "coin", coin, "who", caller,
"coinOut", u(outCoin), "gnotOut", u(outHub), "shares", u(shares))
return outCoin, outHub
}
// poolSwapGnot executes one hop (coin↔gnot) for internal routing.
// The caller's input must already have been debited.
func poolSwapGnot(p *pool, inIsHub bool, amountIn uint64) uint64 {
if !poolOpenForSwaps(p) {
panic("GNOT pool " + p.coin + " is not open for swaps (paused or under 2000 gnot 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(gnotCoinId, 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 GNOT pool")
}
if isqrt128(p.rCoin, p.rHub) < kBefore {
panic("invariant: k decreased in GNOT pool")
}
return out
}
// ── View functions ────────────────────────────────────────────────────────────
// GnotBalance returns the caller's internal GNOT balance (deposited ugnot).
func GnotBalance(addr string) string {
return u(balOf(addr, gnotCoinId))
}
// GnotPoolInfo returns the state of the COIN/GNOT pool for `coin`.
func GnotPoolInfo(coin string) string {
if !gnotPools.Has(coin) {
return `{"coin":` + jsonStr(coin) + `,"exists":false}`
}
p := gnotPool(coin)
return `{"coin":` + jsonStr(coin) + `,"rCoin":"` + u(p.rCoin) + `","rGnot":"` + u(p.rHub) +
`","shares":"` + u(p.shares) + `","paused":` + strconv.FormatBool(p.paused) +
`,"open":` + strconv.FormatBool(poolOpenForSwaps(p)) + `}`
}
// GnotPools lists COIN/GNOT pools (paginated, ≤ 50 per call).
func GnotPools(limit int, offset int) string {
if limit <= 0 || limit > maxViewLimit {
limit = maxViewLimit
}
if offset < 0 {
offset = 0
}
out := "["
n := 0
gnotPools.IterateByOffset(offset, limit, func(_ string, v any) bool {
if n > 0 {
out += ","
}
p := v.(*pool)
out += `{"coin":` + jsonStr(p.coin) + `,"rCoin":"` + u(p.rCoin) + `","rGnot":"` + u(p.rHub) +
`","shares":"` + u(p.shares) + `","paused":` + strconv.FormatBool(p.paused) +
`,"open":` + strconv.FormatBool(poolOpenForSwaps(p)) + `}`
n++
return false
})
return out + "]"
}
// QuoteGnotSwap quotes a single GNOT-pool swap; "0" if unavailable.
func QuoteGnotSwap(coinIn string, coinOut string, amountIn uint64) string {
if amountIn == 0 || amountIn > maxAmount {
return "0"
}
c, inIsHub := coinIn, false
if coinIn == gnotCoinId {
c, inIsHub = coinOut, true
} else if coinOut != gnotCoinId {
return "0" // neither side is gnot — not a GNOT pool swap
}
if !gnotPools.Has(c) {
return "0"
}
p := gnotPool(c)
if !poolOpenForSwaps(p) {
return "0"
}
out, _ := poolQuote(p, inIsHub, amountIn)
return u(out)
}
// GnotLpPosition shows one GNOT LP position and current withdrawal value.
func GnotLpPosition(coin string, addr string) string {
key := coin + ":" + addr
if !gnotLpPositions.Has(key) || !gnotPools.Has(coin) {
return `{"coin":` + jsonStr(coin) + `,"shares":"0"}`
}
pos := gnotLpPositions.Get(key).(*lpPos)
p := gnotPool(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) + `","gnotOut":"` + u(oh) + `","warmupLeft":` + strconv.FormatInt(warm, 10) + `}`
}
// GnotLpPositions lists all GNOT LP positions for an address (paginated).
func GnotLpPositions(addr string, limit int, offset int) string {
if limit <= 0 || limit > maxViewLimit {
limit = maxViewLimit
}
if offset < 0 {
offset = 0
}
out := "["
n := 0
gnotPools.IterateByOffset(offset, limit, func(coin string, _ any) bool {
if gnotLpPositions.Has(coin + ":" + addr) {
if n > 0 {
out += ","
}
out += GnotLpPosition(coin, addr)
n++
}
return false
})
return out + "]"
}
exchange_pool.gno
package game33
// ── 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 game33
// ── 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)
}
// gnotPathOut quotes amountIn of coinIn → coinOut through GNOT pools.
// Handles: gnot↔coin (one GNOT pool hop), coin↔coin via gnot hub (two hops).
// Read-only; ok=false if no suitable GNOT pool exists or is open.
func gnotPathOut(coinIn, coinOut string, amountIn uint64) (uint64, bool) {
if amountIn == 0 || coinIn == coinOut {
return 0, false
}
if coinIn == gnotCoinId || coinOut == gnotCoinId {
c, inIsHub := coinIn, false
if coinIn == gnotCoinId {
c, inIsHub = coinOut, true
}
if !gnotPools.Has(c) {
return 0, false
}
p := gnotPool(c)
if !poolOpenForSwaps(p) {
return 0, false
}
out, _ := poolQuote(p, inIsHub, amountIn)
return out, out > 0
}
// coin→coin via gnot: coinIn→gnot→coinOut
mid, ok := gnotPathOut(coinIn, gnotCoinId, amountIn)
if !ok {
return 0, false
}
return gnotPathOut(gnotCoinId, coinOut, mid)
}
// bestPathOut returns the best available output from either GRIN or GNOT pools.
// Read-only; used by routePlanAny for GNOT-aware routing.
func bestPathOut(coinIn, coinOut string, amountIn uint64) (uint64, bool) {
gOut, gOk := poolPathOut(coinIn, coinOut, amountIn)
nOut, nOk := gnotPathOut(coinIn, coinOut, amountIn)
if gOk && nOk {
if nOut > gOut {
return nOut, true
}
return gOut, true
}
if gOk {
return gOut, true
}
if nOk {
return nOut, true
}
return 0, false
}
// 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) + `"}`
}
// ── GNOT-aware routing ────────────────────────────────────────────────────────
//
// SwapRouteGnot and QuoteRouteGnot mirror SwapRoute/QuoteRoute but accept
// gnotCoinId ("gnot") as either coinIn or coinOut (or both sides being game
// coins routed through GNOT pools). They bypass requireCoin for "gnot" since
// that pseudo-coin is not in coinRarity.
// requireCoinOrGnot validates a coin for GNOT-aware routes.
func requireCoinOrGnot(coin string) {
if coin == gnotCoinId {
return
}
requireCoin(coin)
}
// gnotRoutePlan is routePlan extended to also check GNOT pools. It uses
// bestPathOut (max of GRIN and GNOT pool outputs) for the pool comparison.
func gnotRoutePlan(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 := bestPathOut(coinIn, coinOut, remaining); ok {
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 := bestPathOut(coinIn, coinOut, remaining); ok {
poolOut = out
} else {
remaining = 0
}
}
return take, expired, remaining, bookOut, poolOut
}
// executeGnotPoolSwap executes the pool leg of a GNOT-aware swap, choosing
// the better route (GRIN or GNOT pools) for the given pair.
func executeGnotPoolSwap(coinIn, coinOut string, poolIn uint64) uint64 {
if poolIn == 0 {
return 0
}
// Try GNOT pool path first if it gives better output than GRIN path.
gnotOut, gnotOk := gnotPathOut(coinIn, coinOut, poolIn)
grinOut, grinOk := poolPathOut(coinIn, coinOut, poolIn)
useGnot := gnotOk && (!grinOk || gnotOut >= grinOut)
if useGnot {
// Execute via GNOT pools
if coinIn == gnotCoinId {
return poolSwapGnot(gnotPool(coinOut), true, poolIn)
} else if coinOut == gnotCoinId {
return poolSwapGnot(gnotPool(coinIn), false, poolIn)
} else {
// coin→coin via gnot: coinIn→gnot→coinOut
mid := poolSwapGnot(gnotPool(coinIn), false, poolIn)
return poolSwapGnot(gnotPool(coinOut), true, mid)
}
} else if grinOk {
// Execute via GRIN pools (existing logic)
if coinIn == hubCoin {
return poolSwap(getPool(coinOut), true, poolIn)
} else if coinOut == hubCoin {
return poolSwap(getPool(coinIn), false, poolIn)
} else {
mid := poolSwap(getPool(coinIn), false, poolIn)
return poolSwap(getPool(coinOut), true, mid)
}
}
panic("no pool path available for " + coinIn + "→" + coinOut)
}
// SwapRouteGnot swaps coinIn for coinOut where either side may be "gnot".
// Uses the order book first (same as SwapRoute) then the best available pool
// (GRIN or GNOT, whichever gives better output).
func SwapRouteGnot(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)
requireCoinOrGnot(coinIn)
requireCoinOrGnot(coinOut)
if coinIn == coinOut {
panic("coinIn and coinOut must differ")
}
take, expired, poolIn, bookOut, poolOut := gnotRoutePlan(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)
out = addChk(out, executeGnotPoolSwap(coinIn, coinOut, poolIn))
}
if out != planned {
panic("invariant: GNOT route plan mismatch")
}
creditBal(caller, coinOut, out)
chain.Emit("SwapRoutedGnot", "who", caller, "in", coinIn, "out", coinOut, "amountIn", u(amountIn),
"bookFills", strconv.Itoa(len(take)), "poolIn", u(poolIn), "amountOut", u(out))
return out
}
// QuoteRouteGnot previews SwapRouteGnot (either side may be "gnot").
func QuoteRouteGnot(caller string, coinIn string, coinOut string, amountIn uint64, maxFills int) string {
if amountIn == 0 || amountIn > maxAmount || coinIn == coinOut {
return `{"out":"0"}`
}
if coinIn != gnotCoinId {
if _, ok := coinRarity[coinIn]; !ok {
return `{"out":"0"}`
}
}
if coinOut != gnotCoinId {
if _, ok := coinRarity[coinOut]; !ok {
return `{"out":"0"}`
}
}
take, _, poolIn, bookOut, poolOut := gnotRoutePlan(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)))
}
// Determine which pool type serves the route (for informational output)
gnotOut, gnotOk := gnotPathOut(coinIn, coinOut, poolIn)
_, grinOk := poolPathOut(coinIn, coinOut, poolIn)
poolType := "grin"
if gnotOk && (!grinOk || gnotOut >= poolOut) {
poolType = "gnot"
}
return `{"bookIn":"` + u(bookIn) + `","bookOut":"` + u(bookOut) + `","bookFills":` + strconv.Itoa(len(take)) +
`,"poolIn":"` + u(poolIn) + `","poolOut":"` + u(poolOut) + `","poolType":"` + poolType + `"` +
`,"out":"` + u(addChk(bookOut, poolOut)) + `","unused":"` + u(amountIn-bookIn-poolIn) + `"}`
}
game_admin.gno
package game33
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/g1algwpj0dch4stpy7pd87n7a3cwx3pjymlpexn7/game33")
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 game33
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 game33
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 game33
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_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 game33
import (
"gno.land/p/nt/avl/v0"
)
const realmPkgPath = "gno.land/r/g1algwpj0dch4stpy7pd87n7a3cwx3pjymlpexn7/game33"
// ── 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)
// GNOT exchange bridge: pseudo-coin ID used inside the exchange balance
// system to represent deposited ugnot. Players call DepositGnot to wrap
// ugnot → internal "gnot", and WithdrawGnot to unwrap back to ugnot.
gnotCoinId = "gnot"
gnotDeposited uint64 // lifetime ugnot deposited (accounting / audit)
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 game33
// ── 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 game33
// ── 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 game33
// ── 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 game33
// ── 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 game33
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 — game33\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_mining.gno
package game33
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 game33
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 game33
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 game33
// ── 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 game33
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/g1algwpj0dch4stpy7pd87n7a3cwx3pjymlpexn7/game33" gno = "0.9" [addpkg] creator = "g1algwpj0dch4stpy7pd87n7a3cwx3pjymlpexn7" height = 555370 max_deposit = "100000000ugnot"
json.gno
package game33
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)
}