Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

book.gno

package fish

import (
	"chain"
	"strconv"
)

func List(cur realm, id int, priceUgnot int64) {
	caller := requireUser(cur)
	if priceUgnot <= 0 || priceUgnot > maxPrice {
		panic("fish: price")
	}
	takeExact(0)
	body := must(id)
	if body.owner != caller {
		panic("fish: owner")
	}
	guardMovable(body)
	if body.mustHeal {
		panic("fish: heal")
	}
	moveToken(caller, caller, self, id)
	body.listed = true
	body.seller = caller
	body.price = priceUgnot
	body.owner = self
	chain.Emit("List", "id", strconv.Itoa(id), "seller", caller.String(), "price", strconv.FormatInt(priceUgnot, 10))
}

func UpdatePrice(cur realm, id int, priceUgnot int64) {
	caller := requireUser(cur)
	if priceUgnot <= 0 || priceUgnot > maxPrice {
		panic("fish: price")
	}
	takeExact(0)
	body := must(id)
	if !body.listed {
		panic("fish: listed")
	}
	if body.seller != caller {
		panic("fish: owner")
	}
	body.price = priceUgnot
	chain.Emit("List", "id", strconv.Itoa(id), "seller", caller.String(), "price", strconv.FormatInt(priceUgnot, 10))
}

func Cancel(cur realm, id int) {
	caller := requireUser(cur)
	takeExact(0)
	body := must(id)
	if !body.listed {
		panic("fish: listed")
	}
	if body.seller != caller {
		panic("fish: owner")
	}
	moveToken(self, self, body.seller, id)
	body.owner = body.seller
	body.seller = address("")
	body.price = 0
	body.listed = false
	chain.Emit("Cancel", "id", strconv.Itoa(id))
}

func Buy(cur realm, id int) {
	caller := requireUser(cur)
	body := must(id)
	if !body.listed {
		panic("fish: listed")
	}
	if caller == body.seller {
		panic("fish: self")
	}
	takeExact(body.price)
	proto := body.price * protocolBps / 10000
	royal := body.price * royaltyBps / 10000
	if proto+royal > body.price {
		panic("fish: fee")
	}
	sellerAmt := body.price - proto - royal
	send(body.seller, sellerAmt, cur)
	send(creator, royal, cur)
	send(protocolSink, proto, cur)
	moveToken(self, self, caller, id)
	body.owner = caller
	body.seller = address("")
	body.price = 0
	body.listed = false
	chain.Emit("Buy", "id", strconv.Itoa(id), "buyer", caller.String())
}

func ItemLine(id int) string {
	body := must(id)
	return strconv.Itoa(body.id) + "|" + body.name + "|" + addrStr(body.owner) + "|" + addrStr(body.seller) + "|" +
		strconv.FormatInt(body.price, 10) + "|" + strconv.FormatBool(body.listed) + "|" + body.image + "|fish|" +
		body.rarity + "|Size:" + body.size + ";Trait:" + body.trait + ";Species:" + body.species + ";HP:" + strconv.Itoa(body.hp) +
		"|true|-1"
}

func ListOpen() string {
	requireInit()
	out := ""
	n := 0
	for _, body := range bodies {
		if body == nil || !body.listed || body.burned {
			continue
		}
		if n >= listCap {
			break
		}
		if out != "" {
			out += "\n"
		}
		out += ItemLine(body.id)
		n++
	}
	return out
}

func addrStr(a address) string {
	if !a.IsValid() {
		return ""
	}
	return a.String()
}

combat.gno

package fish

import (
	"chain"
	"strconv"
	"time"

	"gno.land/r/g1n4pl5uc4yt5r96m9w6fmdznx3x0jyg8l6arhmt/party"
)

type damageRow struct {
	owner address
	dmg   int
}

// blows[victimID] sums HP actually removed, keyed by the attacker's owner.
var blows [][]damageRow

// Bite is one user call and takes no payment. The hit test is sector-center
// reach plus a 42 degree mouth cone. A miss does not start cooldown. Members
// of the same party cannot bite each other. A killing blow pays the smaller
// Pool X and leaves the NFT at 30% HP. The killer share is split by HP removed.
// Empty cheer and viewer shares pay the season sink.
func Bite(cur realm, id, target int) {
	caller := requireUser(cur)
	takeExact(0)
	if id == target {
		panic("fish: bite")
	}
	atk := must(id)
	vic := must(target)
	if atk.owner != caller {
		panic("fish: owner")
	}
	if atk.mustHeal || vic.mustHeal {
		panic("fish: heal")
	}
	now := time.Now().Unix()
	if !liveFish(atk, now) || !liveFish(vic, now) {
		panic("fish: match")
	}
	if atk.owner == vic.owner {
		panic("fish: bite")
	}
	if party.SameParty(cross(cur), atk.owner, vic.owner) {
		panic("fish: party")
	}
	nowMs := time.Now().UnixMilli()
	// A cave or reef does not dodge. The cone still has to face the fish inside.
	if !mouthHit(atk, vic) && !shelterMouth(atk, vic, nowMs) {
		panic("fish: range")
	}
	if nowMs < atk.nextBiteMilli {
		panic("fish: cool")
	}
	if atk.bittenBy == vic.id && nowMs < atk.bittenUntil {
		panic("fish: cool")
	}
	cool := nowMs + cooldownMs(atk.rarity)
	atk.nextBiteMilli = cool
	atk.lastCombatMilli = nowMs
	if redirectShelter(atk, vic, nowMs) {
		chain.Emit("Bite", "id", strconv.Itoa(id), "target", strconv.Itoa(target), "damage", "shelter")
		return
	}
	vic.lastCombatMilli = nowMs
	vic.bittenBy = atk.id
	vic.bittenUntil = cool
	dmg := strikeFought(biteNow(atk), vic.hp, atk.size, vic.size, atk.rarity, vic.rarity)
	landed := dmg
	if landed > vic.hpNow {
		landed = vic.hpNow
	}
	addDamage(vic.id, atk.owner, landed)
	if vic.hpNow > dmg {
		vic.hpNow -= dmg
		chain.Emit("Bite", "id", strconv.Itoa(id), "target", strconv.Itoa(target), "damage", strconv.Itoa(dmg))
		return
	}
	payKill(atk, vic, cur)
}

func payKill(atk, vic *fishBody, rlm realm) {
	if !rlm.IsCurrent() {
		panic("fish: realm")
	}
	covered := coveredStake(atk.pool, vic.pool)
	excess := vic.pool - covered
	killer, lp, season, burn, cheer, viewer := splitParts(covered)
	nowMs := time.Now().UnixMilli()
	creditBout(atk)
	creditBout(vic)
	growFromKill(atk, vic)
	returnCheers(vic, rlm)
	vic.pool = 0
	vic.inMatch = false
	vic.boutPaid = false
	vic.mustHeal = true
	vic.hpNow = downHP(vic.hp)
	cheerHeld := bookCheerClaims(atk, vic, cheer, nowMs)
	season += cheer - cheerHeld
	viewHeld := bookWatchClaims(atk, vic, viewer, nowMs)
	season += viewer - viewHeld
	send(vic.owner, excess, rlm)
	payKiller(atk.owner, vic.id, killer, rlm)
	send(lpSink, lp, rlm)
	send(seasonSink, season, rlm)
	send(burnSink, burn, rlm)
	clearDamage(vic.id)
	chain.Emit(
		"Kill",
		"id", strconv.Itoa(atk.id),
		"target", strconv.Itoa(vic.id),
		"covered", strconv.FormatInt(covered, 10),
		"killer", strconv.FormatInt(killer, 10),
	)
}

// payKiller splits the killer share by HP removed among current members.
// The party realm holds no coins. A solo owner, or a party with no recorded
// damage, receives the whole share. Dust goes to the highest damage, and a
// tie prefers the owner who landed the blow.
func payKiller(owner address, victim int, amount int64, rlm realm) {
	if amount <= 0 {
		return
	}
	pid := party.PartyOf(cross(rlm), owner)
	if pid == 0 {
		send(owner, amount, rlm)
		return
	}
	n := party.MemberCount(cross(rlm), pid)
	if n <= 0 {
		send(owner, amount, rlm)
		return
	}
	owners := make([]address, n)
	weights := make([]int, n)
	total := 0
	for i := 0; i < n; i++ {
		who := party.MemberAt(cross(rlm), pid, i)
		owners[i] = who
		w := damageOf(victim, who)
		if w < 0 {
			w = 0
		}
		weights[i] = w
		total += w
	}
	if total <= 0 {
		send(owner, amount, rlm)
		return
	}
	shares := splitWeights(amount, weights, owner, owners)
	for i := range owners {
		send(owners[i], shares[i], rlm)
	}
}

func splitWeights(amount int64, weights []int, prefer address, owners []address) []int64 {
	total := 0
	for _, w := range weights {
		if w > 0 {
			total += w
		}
	}
	out := make([]int64, len(weights))
	if amount <= 0 || total <= 0 {
		return out
	}
	var used int64
	best := -1
	bestW := 0
	for i, w := range weights {
		if w <= 0 {
			continue
		}
		share := amount * int64(w) / int64(total)
		out[i] = share
		used += share
		if best < 0 || w > bestW || (w == bestW && i < len(owners) && owners[i] == prefer) {
			best = i
			bestW = w
		}
	}
	if used < amount && best >= 0 {
		out[best] += amount - used
	}
	return out
}

func addDamage(id int, owner address, n int) {
	if n <= 0 || id < 1 || !owner.IsValid() {
		return
	}
	for len(blows) <= id {
		blows = append(blows, nil)
	}
	rows := blows[id]
	for i := 0; i < len(rows); i++ {
		if rows[i].owner == owner {
			rows[i].dmg += n
			blows[id] = rows
			return
		}
	}
	blows[id] = append(rows, damageRow{owner: owner, dmg: n})
}

func damageOf(id int, owner address) int {
	if id < 0 || id >= len(blows) {
		return 0
	}
	for i := 0; i < len(blows[id]); i++ {
		if blows[id][i].owner == owner && blows[id][i].dmg > 0 {
			return blows[id][i].dmg
		}
	}
	return 0
}

// clearDamage drops incoming blows so the next entry starts clean.
func clearDamage(id int) {
	if id < 0 || id >= len(blows) {
		return
	}
	blows[id] = nil
}

// creditBout counts one finished entry. Leave does not call it.
// SettleMatch does not count the entry again.
func creditBout(body *fishBody) {
	if body.boutPaid {
		return
	}
	body.boutPaid = true
	body.bouts++
}

func liveFish(body *fishBody, now int64) bool {
	if now < 0 {
		return false
	}
	return body.inMatch && body.pool > 0
}

func downHP(max int) int {
	hp := max * 30 / 100
	if hp < 1 {
		return 1
	}
	return hp
}

func coveredStake(killerPool, victimPool int64) int64 {
	if killerPool < 0 {
		killerPool = 0
	}
	if victimPool < 0 {
		victimPool = 0
	}
	if killerPool < victimPool {
		return killerPool
	}
	return victimPool
}

// splitParts is 80/10/3/2/4/1. Dust joins burn. Season here is only the 3%.
func splitParts(amount int64) (killer, lp, season, burn, cheer, viewer int64) {
	if amount < 0 {
		amount = 0
	}
	killer = amount * 8000 / 10000
	lp = amount * 1000 / 10000
	season = amount * 300 / 10000
	burnPart := amount * 200 / 10000
	cheer = amount * 400 / 10000
	viewer = amount * 100 / 10000
	dust := amount - killer - lp - season - burnPart - cheer - viewer
	burn = burnPart + dust
	return
}

// splitKill folds empty cheer and viewer into season. Callers that book those
// shares use splitParts instead.
func splitKill(amount int64) (killer, lp, season, burn int64) {
	var cheer, viewer int64
	killer, lp, season, burn, cheer, viewer = splitParts(amount)
	season += cheer + viewer
	return
}

func strikeDamage(bite, hpMax int, atkSize, defSize string) int {
	dmg := bite * 100 / (hpMax + 100)
	if dmg < 1 {
		dmg = 1
	}
	if sizeIndex(atkSize)-sizeIndex(defSize) >= 2 {
		dmg = dmg * 5000 / 10000
		if dmg < 1 {
			dmg = 1
		}
	}
	return dmg
}

func sizeIndex(size string) int {
	switch size {
	case "small":
		return 0
	case "medium":
		return 1
	case "large":
		return 2
	default:
		panic("fish: size")
	}
}

func biteOf(rarity, size, trait string) int {
	var base int64
	switch rarity {
	case "common":
		base = 22
	case "uncommon":
		base = 26
	case "rare":
		base = 31
	case "epic":
		base = 37
	case "legendary":
		base = 44
	case "mythic":
		base = 52
	default:
		panic("fish: rarity")
	}
	traitBps := int64(10000)
	if trait == "fang" {
		traitBps = 11200
	}
	sizeBps := int64(10000)
	if size == "small" {
		sizeBps = 8600
	} else if size == "large" {
		sizeBps = 11800
	}
	v := (base*traitBps*sizeBps + 50_000_000) / 100_000_000
	if v < 1 {
		v = 1
	}
	return int(v)
}

func cooldownMs(rarity string) int64 {
	switch rarity {
	case "common":
		return 2400
	case "uncommon":
		return 2550
	case "rare":
		return 2700
	case "epic":
		return 2850
	case "legendary":
		return 3000
	case "mythic":
		return 3200
	default:
		panic("fish: rarity")
	}
}

// reachUnits is the dodged bite reach in 1/10000 of a world unit.
// A sector is 8 world units, so the next center is 80000 units away.
func reachUnits(rarity, size string, dodgeTenths int) int64 {
	var spec int64
	switch rarity {
	case "common":
		spec = 10000
	case "uncommon":
		spec = 10600
	case "rare":
		spec = 11200
	case "epic":
		spec = 11800
	case "legendary":
		spec = 12400
	case "mythic":
		spec = 13200
	default:
		panic("fish: rarity")
	}
	sizeMod := int64(10000)
	if size == "small" {
		sizeMod = 8600
	} else if size == "large" {
		sizeMod = 12200
	}
	reach := spec * sizeMod * 8 / 10000
	reach -= int64(dodgeTenths) * 1000
	if reach < 10_000 {
		return 10_000
	}
	return reach
}

func inReach(atk, def *fishBody) bool {
	return inReachDodge(atk, def, def.dodge)
}

func inReachDodge(atk, def *fishBody, dodge int) bool {
	dx := int64(atk.sx - def.sx)
	dz := int64(atk.sz - def.sz)
	span := dx*dx + dz*dz
	reach := reachUnits(atk.rarity, atk.size, dodge)
	dist2 := span * 80_000 * 80_000
	return dist2 <= reach*reach
}

fish.gno

// Package fish is the Shoal collection. Each fish is a GRC721 on this realm.
// List, cancel, buy, and Bite live here too. Gno cannot pull a foreign token into
// Bazaar, so the book is not a second package.
//
// Not deployed. Init does not call bazaarv2 Reserve or Register.
package fish

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

	"gno.land/p/nt/grc721/metadata/v0"
	"gno.land/p/nt/grc721/v0"
	"gno.land/p/nt/seqid/v0"
)

const (
	denom        = "ugnot"
	ugnot        = 1_000_000
	mintFee      = 5 * ugnot
	layFee       = 2 * ugnot
	upgradeFee   = 15 * ugnot
	protocolBps  = 200
	maxRoyalty   = 1000
	maxPrice     = 1_000_000 * ugnot
	combatLockMs = 5000
	layBlocks    = 2
	listCap      = 50
)

type fishBody struct {
	id              int
	name            string
	rarity          string
	species         string
	size            string
	trait           string
	hp              int
	hpNow           int
	dodge           int
	bouts           int
	layBoutsUsed    int
	layOpen         bool
	layHeight       int64
	pool            int64
	inMatch         bool
	boutPaid        bool
	mustHeal        bool
	startUnix       int64
	endUnix         int64
	sx              int
	sz              int
	faceDx          int
	faceDz          int
	growth          int
	evolved         bool
	aspect          string
	aspectBps       int
	healDay         int64
	healsUsed       int
	healReadyAt     int64
	springBorn      int64
	nextMoveMilli   int64
	burstUntil      int64
	nextBurstAt     int64
	nextBiteMilli   int64
	lastCombatMilli int64
	bittenBy        int
	bittenUntil     int64
	owner           address
	seller          address
	price           int64
	listed          bool
	burned          bool
	image           string
}

var (
	bodies       []*fishBody
	nextID       int
	minted       int
	inited       bool
	token        *grc721.Token
	ledger       *grc721.PrivateLedger
	metaView     *metadata.Metadata
	metaLed      *metadata.Ledger
	tokenSeq     seqid.ID
	creator      address
	self         address
	upgradeSink  address
	lpSink       address
	burnSink     address
	protocolSink address
	seasonSink   address
	royaltyBps   int64
	imageBase    string
	colName      string
	colSymbol    string
)

func Init(cur realm, name, symbol, images string, royalty int64, upgrade, lp, burn, protocol, season address) {
	if !cur.IsCurrent() {
		panic("fish: realm")
	}
	if !cur.Previous().IsUserCall() {
		panic("fish: eoa")
	}
	if inited {
		panic("fish: init")
	}
	takeExact(0)
	if !validCollectionName(name) || !validSymbol(symbol) {
		panic("fish: name")
	}
	if !strings.HasPrefix(images, "https://") || strings.Contains(images, "|") || len(images) > 160 {
		panic("fish: image")
	}
	if royalty < 0 || royalty > maxRoyalty {
		panic("fish: royalty")
	}
	if !upgrade.IsValid() || !lp.IsValid() || !burn.IsValid() || !protocol.IsValid() || !season.IsValid() {
		panic("fish: sink")
	}
	tok, led := grc721.NewToken(name, symbol, tokenSeq.Next(), cur)
	token = tok
	ledger = led
	metaView, metaLed = metadata.NewMetadata(led)
	creator = cur.Previous().Address()
	self = cur.Address()
	upgradeSink = upgrade
	lpSink = lp
	burnSink = burn
	protocolSink = protocol
	seasonSink = season
	royaltyBps = royalty
	imageBase = images
	colName = name
	colSymbol = symbol
	bodies = []*fishBody{nil}
	nextID = 0
	minted = 0
	inited = true
	chain.Emit("Init", "creator", creator.String(), "symbol", symbol)
}

func Mint(cur realm, name, size, trait string) int {
	caller := requireUser(cur)
	if unplayed(caller) {
		panic("fish: unplayed")
	}
	if !validFishName(name) {
		panic("fish: name")
	}
	if !validSize(size) {
		panic("fish: size")
	}
	if !validTrait(trait) {
		panic("fish: trait")
	}
	takeExact(mintFee)
	payMint(mintFee, cur)
	return issue(caller, name, "common", size, trait)
}

func Transfer(cur realm, to address, id int) {
	caller := requireUser(cur)
	takeExact(0)
	if !to.IsValid() || to == caller || to == self {
		panic("fish: addr")
	}
	body := must(id)
	if body.owner != caller {
		panic("fish: owner")
	}
	guardMovable(body)
	moveToken(caller, caller, to, id)
	body.owner = to
}

func TransferFrom(cur realm, from, to, tid string) {
	caller := requireUser(cur)
	takeExact(0)
	id := parseID(tid)
	src := address(from)
	dst := address(to)
	if !src.IsValid() || !dst.IsValid() || dst == self {
		panic("fish: addr")
	}
	body := must(id)
	if body.owner != src {
		panic("fish: owner")
	}
	guardMovable(body)
	moveToken(caller, src, dst, id)
	body.owner = dst
}

func Approve(cur realm, to, tid string) {
	caller := requireUser(cur)
	takeExact(0)
	id := parseID(tid)
	body := must(id)
	guardMovable(body)
	who := address(to)
	if to != "" && !who.IsValid() {
		panic("fish: addr")
	}
	if err := ledger.Approve(caller, who, tokenID(id)); err != nil {
		panic("fish: approve")
	}
}

func SetApprovalForAll(cur realm, operator string, approved bool) {
	caller := requireUser(cur)
	takeExact(0)
	op := address(operator)
	if !op.IsValid() {
		panic("fish: addr")
	}
	if err := ledger.SetApprovalForAll(caller, op, approved); err != nil {
		panic("fish: approve")
	}
}

func OwnerOf(tid string) (address, error) {
	requireInit()
	id, err := strconv.Atoi(tid)
	if err != nil || id < 1 || id >= len(bodies) || bodies[id] == nil || bodies[id].burned {
		return address(""), errors.New("fish: unknown")
	}
	return bodies[id].owner, nil
}

func Name() string {
	requireInit()
	return token.GetName()
}

func Symbol() string {
	requireInit()
	return token.GetSymbol()
}

func GrcName() string   { return Name() }
func GrcSymbol() string { return Symbol() }

func BalanceOf(addr string) int64 {
	requireInit()
	who := address(addr)
	if !who.IsValid() {
		return 0
	}
	n, err := token.BalanceOf(who)
	if err != nil {
		return 0
	}
	return n
}

func GrcBalanceOf(addr string) int64 { return BalanceOf(addr) }

func TokenURI(tid string) string {
	id := parseID(tid)
	must(id)
	uri, err := metaView.TokenURI(tokenID(id))
	if err != nil || uri == "" {
		panic("fish: uri")
	}
	return uri
}

func TokensOf(owner string) string {
	requireInit()
	who := address(owner)
	if !who.IsValid() {
		return ""
	}
	out := ""
	for _, body := range bodies {
		if body == nil || body.burned || body.owner != who {
			continue
		}
		if out != "" {
			out += ","
		}
		out += strconv.Itoa(body.id)
	}
	return out
}

func TokenOfOwnerByIndex(owner string, index int64) string {
	requireInit()
	who := address(owner)
	if !who.IsValid() {
		panic("fish: addr")
	}
	if index < 0 {
		panic("fish: index")
	}
	var seen int64
	for _, body := range bodies {
		if body == nil || body.burned || body.owner != who {
			continue
		}
		if seen == index {
			return strconv.Itoa(body.id)
		}
		seen++
	}
	panic("fish: index")
}

func TotalSupply() int64 {
	requireInit()
	return token.TotalSupply()
}

func GetApproved(id int) string {
	requireInit()
	who, err := token.GetApproved(tokenID(id))
	if err != nil || !who.IsValid() {
		return ""
	}
	return who.String()
}

func IsApprovedForAll(owner, operator string) bool {
	requireInit()
	a := address(owner)
	b := address(operator)
	if !a.IsValid() || !b.IsValid() {
		return false
	}
	return token.IsApprovedForAll(a, b)
}

func MintPrice() int64   { return mintFee }
func MaxSupply() int     { return 0 }
func Minted() int        { return minted }
func RoyaltyBps() int64  { return royaltyBps }
func Creator() address   { return creator }
func ProtocolBps() int64 { return protocolBps }

func BoutsOf(id int) int      { return must(id).bouts }
func PoolOf(id int) int64     { return must(id).pool }
func Listed(id int) bool      { return must(id).listed }
func InMatch(id int) bool     { return must(id).inMatch }
func LayOpen(id int) bool     { return must(id).layOpen }
func RarityOf(id int) string  { return must(id).rarity }
func SizeOf(id int) string    { return must(id).size }
func TraitOf(id int) string   { return must(id).trait }
func SpeciesOf(id int) string { return must(id).species }

func issue(to address, name, rarity, size, trait string) int {
	nextID++
	id := nextID
	maxHP := hpOf(rarity, size, trait)
	body := &fishBody{
		id:      id,
		name:    name,
		rarity:  rarity,
		species: speciesOf(rarity),
		size:    size,
		trait:   trait,
		hp:      maxHP,
		hpNow:   maxHP,
		dodge:           dodgeOf(size),
		faceDx:          0,
		faceDz:          -1,
		aspectBps:       10000,
		springBorn:      -1,
		lastCombatMilli: -1,
		owner:           to,
		image:   imageBase + "/" + rarity + ".png",
	}
	for len(bodies) <= id {
		bodies = append(bodies, nil)
	}
	bodies[id] = body
	minted++
	mintGRC(to, body)
	return id
}

func mintGRC(to address, body *fishBody) {
	tid := tokenID(body.id)
	if err := ledger.Mint(to, tid); err != nil {
		panic("fish: mint")
	}
	if err := metaLed.SetTokenURI(tid, tokenJSON(body)); err != nil {
		panic("fish: uri")
	}
}

func burnGRC(id int) {
	if err := ledger.Burn(tokenID(id)); err != nil {
		panic("fish: burn")
	}
}

func moveToken(spender, from, to address, id int) {
	if err := ledger.TransferFrom(spender, from, to, tokenID(id)); err != nil {
		panic("fish: transfer")
	}
}

func tokenJSON(body *fishBody) string {
	return "data:application/json;charset=utf-8," +
		`{"name":"` + body.name + `","description":"Shoal fish","image":"` + body.image +
		`","attributes":[{"trait_type":"Species","value":"` + body.species +
		`"},{"trait_type":"Size","value":"` + body.size +
		`"},{"trait_type":"Trait","value":"` + body.trait +
		`"},{"trait_type":"Rarity","value":"` + body.rarity +
		`"},{"trait_type":"HP","value":"` + strconv.Itoa(body.hp) + `"}]}`
}

func requireUser(cur realm) address {
	if !cur.IsCurrent() {
		panic("fish: realm")
	}
	if !cur.Previous().IsUserCall() {
		panic("fish: eoa")
	}
	return cur.Previous().Address()
}

func requireInit() {
	if !inited || token == nil {
		panic("fish: init")
	}
}

func takeExact(n int64) {
	sent := unsafe.OriginSend()
	if n == 0 {
		if len(sent) != 0 {
			panic("fish: payment")
		}
		return
	}
	if len(sent) != 1 || sent[0].Denom != denom || sent[0].Amount != n {
		panic("fish: payment")
	}
}

func payMint(fee int64, rlm realm) {
	up := fee * 7000 / 10000
	lp := fee * 2000 / 10000
	burn := fee - up - lp
	send(upgradeSink, up, rlm)
	send(lpSink, lp, rlm)
	send(burnSink, burn, rlm)
}

func send(to address, amt int64, rlm realm) {
	if amt == 0 {
		return
	}
	if !to.IsValid() {
		panic("fish: sink")
	}
	bk := banker.NewBanker(banker.BankerTypeRealmSend, rlm)
	bk.SendCoins(rlm.Address(), to, chain.Coins{{Denom: denom, Amount: amt}})
}

func must(id int) *fishBody {
	requireInit()
	if id < 1 || id >= len(bodies) || bodies[id] == nil || bodies[id].burned {
		panic("fish: unknown")
	}
	return bodies[id]
}

func guardMovable(body *fishBody) {
	if body.listed {
		panic("fish: listed")
	}
	if body.inMatch {
		panic("fish: match")
	}
	if body.pool != 0 {
		panic("fish: pool")
	}
	if body.layOpen {
		panic("fish: lay")
	}
}

func unplayed(owner address) bool {
	for _, body := range bodies {
		if body == nil || body.burned || body.bouts >= 1 {
			continue
		}
		if body.owner == owner || (body.listed && body.seller == owner) {
			return true
		}
	}
	return false
}

func tokenID(id int) grc721.TokenID {
	return grc721.TokenID(strconv.Itoa(id))
}

func parseID(tid string) int {
	id, err := strconv.Atoi(tid)
	if err != nil || id < 1 {
		panic("fish: unknown")
	}
	return id
}

func validFishName(name string) bool {
	if len(name) < 1 || len(name) > 20 {
		return false
	}
	for _, c := range name {
		if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != ' ' {
			return false
		}
	}
	return true
}

func validCollectionName(name string) bool {
	return name != "" && len(name) <= 64 && !strings.Contains(name, "|")
}

func validSymbol(symbol string) bool {
	if symbol == "" || len(symbol) > grc721.MaxSymbolLen {
		return false
	}
	for _, c := range symbol {
		if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') {
			return false
		}
	}
	return true
}

func validSize(size string) bool {
	return size == "small" || size == "medium" || size == "large"
}

func validTrait(trait string) bool {
	return trait == "swift" || trait == "fang" || trait == "hide"
}

func speciesOf(rarity string) string {
	switch rarity {
	case "common":
		return "Minnow"
	case "uncommon":
		return "Mackerel"
	case "rare":
		return "Snapper"
	case "epic":
		return "Angler"
	case "legendary":
		return "Koi Dragon"
	case "mythic":
		return "Abyss Leviathan"
	default:
		panic("fish: rarity")
	}
}

func hpBase(rarity string) int {
	switch rarity {
	case "common":
		return 100
	case "uncommon":
		return 112
	case "rare":
		return 126
	case "epic":
		return 142
	case "legendary":
		return 160
	case "mythic":
		return 180
	default:
		panic("fish: rarity")
	}
}

func hpOf(rarity, size, trait string) int {
	hp := hpBase(rarity)
	if size == "small" {
		hp = hp * 88 / 100
	}
	if size == "large" {
		hp = hp * 120 / 100
	}
	if trait == "hide" {
		hp = hp * 112 / 100
	}
	if hp < 1 {
		hp = 1
	}
	return hp
}

func dodgeOf(size string) int {
	if size == "small" {
		return 24
	}
	return 0
}

func arenaStake(stake int64) bool {
	if stake >= 5*ugnot && stake < 20*ugnot {
		return true
	}
	if stake >= 20*ugnot && stake < 80*ugnot {
		return true
	}
	if stake >= 80*ugnot && stake < 300*ugnot {
		return true
	}
	return stake >= 300*ugnot && stake <= 1000*ugnot
}

gnomod.toml

module = "gno.land/r/g1n4pl5uc4yt5r96m9w6fmdznx3x0jyg8l6arhmt/fish"
gno = "0.9"

[addpkg]
  creator = "g1n4pl5uc4yt5r96m9w6fmdznx3x0jyg8l6arhmt"
  height = 156516
  max_deposit = "50000000ugnot"

life.gno

package fish

import (
	"chain/runtime"
	"crypto/sha256"
	"strconv"
	"time"
)

func Register(cur realm, id int, stake int64) {
	caller := requireUser(cur)
	body := must(id)
	if body.owner != caller {
		panic("fish: owner")
	}
	if body.inMatch {
		panic("fish: match")
	}
	if body.mustHeal {
		panic("fish: heal")
	}
	guardMovable(body)
	if tooHurt(body) {
		panic("fish: hp")
	}
	if walletInSea(caller) {
		panic("fish: one")
	}
	if !arenaStake(stake) {
		panic("fish: stake")
	}
	takeExact(stake)
	now := time.Now().Unix()
	body.pool = stake
	body.inMatch = true
	body.boutPaid = false
	body.startUnix = now
	body.endUnix = 0
	body.lastCombatMilli = -1
	body.nextMoveMilli = 0
	body.burstUntil = 0
	body.nextBurstAt = 0
	body.springBorn = -1
	placeSwimmer(body)
	clearDamage(id)
}

func Leave(cur realm, id int) {
	caller := requireUser(cur)
	takeExact(0)
	body := must(id)
	if body.owner != caller {
		panic("fish: owner")
	}
	if !body.inMatch {
		panic("fish: match")
	}
	nowMs := time.Now().UnixMilli()
	if body.lastCombatMilli >= 0 && nowMs < body.lastCombatMilli+combatLockMs {
		panic("fish: stay")
	}
	returnCheers(body, cur)
	stake := body.pool
	body.pool = 0
	body.inMatch = false
	body.boutPaid = false
	clearDamage(id)
	send(caller, stake, cur)
}

func SettleMatch(cur realm, id int) {
	requireUser(cur)
	takeExact(0)
	body := must(id)
	if !body.inMatch {
		panic("fish: match")
	}
	_ = body
	panic("fish: sea")
}

func CommitLay(cur realm, id int) {
	caller := requireUser(cur)
	body := must(id)
	if body.owner != caller {
		panic("fish: owner")
	}
	guardMovable(body)
	left := body.bouts - body.layBoutsUsed
	if left < 3 {
		panic("fish: bouts")
	}
	takeExact(layFee)
	payMint(layFee, cur)
	body.layBoutsUsed = body.bouts
	body.layOpen = true
	body.layHeight = runtime.ChainHeight()
}

func SettleLay(cur realm, id int) int {
	requireUser(cur)
	takeExact(0)
	body := must(id)
	if !body.layOpen {
		panic("fish: lay")
	}
	height := runtime.ChainHeight()
	if height < body.layHeight+layBlocks {
		panic("fish: early")
	}
	trait := traitFrom(body.id, body.layHeight, height, time.Now().Unix())
	body.layOpen = false
	return issue(body.owner, body.name+" fry", body.rarity, body.size, trait)
}

func Upgrade(cur realm, keep, food int) int {
	caller := requireUser(cur)
	if keep == food {
		panic("fish: upgrade")
	}
	a := must(keep)
	b := must(food)
	if a.owner != caller || b.owner != caller {
		panic("fish: owner")
	}
	guardMovable(a)
	guardMovable(b)
	if a.rarity != b.rarity || a.size != b.size || a.trait != b.trait {
		panic("fish: pair")
	}
	if a.rarity != "common" {
		panic("fish: roll")
	}
	if a.bouts < 1 || b.bouts < 1 {
		panic("fish: bouts")
	}
	takeExact(upgradeFee)
	send(upgradeSink, upgradeFee, cur)
	name := a.name
	size := a.size
	trait := a.trait
	burnBody(a)
	burnBody(b)
	return issue(caller, name, "uncommon", size, trait)
}

func burnBody(body *fishBody) {
	burnGRC(body.id)
	body.burned = true
	body.owner = address("")
	body.seller = address("")
	body.price = 0
	body.listed = false
	body.pool = 0
	body.inMatch = false
	body.layOpen = false
}

func traitFrom(id int, commitHeight, settleHeight, unix int64) string {
	raw := strconv.Itoa(id) + ":" + strconv.FormatInt(commitHeight, 10) + ":" + strconv.FormatInt(settleHeight, 10) + ":" + strconv.FormatInt(unix, 10)
	sum := sha256.Sum256([]byte(raw))
	var n int64
	for i := 0; i < len(sum); i++ {
		n = (n*256 + int64(sum[i])) % 3
	}
	switch n {
	case 0:
		return "swift"
	case 1:
		return "fang"
	default:
		return "hide"
	}
}

sea.gno

package fish

import (
	"chain/runtime/unsafe"
	"math"
	"time"
)

// One shared sea. Cells are 8 world units. A sector center is the chain position.
// Springs and shelter discs use the same layout as the practice sea. No RNG.

const (
	seaRadius         = 360
	sector            = 8
	unitMilli         = 1000
	sectorMilli       = 8000
	mouthAlignNum     = 552264
	mouthContact      = 1000
	healsPerDay       = 2
	healPercent       = 40
	healCooldownMs    = 8 * 3600 * 1000
	ictOffsetMs       = 7 * 3600 * 1000
	dayMs             = 24 * 3600 * 1000
	springPeriodMs    = 20000
	springLifeMs      = 15000
	springRadiusMilli = 3000
	springHealPercent = 20
	shelterHPMax      = 64
	shelterRebuildMs  = 20000
	burstWindowMs     = 1000
	burstCoolMs       = 2000
	viewerShards      = 10
	viewerWatchMs     = 15000
	viewerWindowMs    = 30000
	minCheer          = ugnot
	growMediumAt      = 2
	growLargeAt       = 4
	growEvolveAt      = 6
)

type cheerRow struct {
	fish   int
	who    address
	amount int64
	live   bool
}

type claimRow struct {
	who     address
	amount  int64
	kind    string
	killAt  int64
	expires int64
	claimed bool
	killer  address
	victim  address
	killID  int
}

type watchRow struct {
	who   address
	since int64
}

type disc struct {
	x     int
	z     int
	r     int
	inner int
	kind  string
}

var (
	cheers      []cheerRow
	claims      []claimRow
	watches     []watchRow
	killSeq     int
	shelterHP   []int
	shelterDown []int64
	shelterTable = []disc{
		{x: 96_000, z: 8_000, inner: 5_200, kind: "reef"},
		{x: -120_000, z: 72_000, inner: 5_600, kind: "reef"},
		{x: 28_000, z: -110_000, inner: 4_400, kind: "cave"},
		{x: -140_000, z: 150_000, inner: 4_400, kind: "cave"},
	}
	rockTable = []disc{
		{x: 18_000, z: -24_000, r: 3_600},
		{x: -8_000, z: 48_000, r: 3_600},
		{x: 120_000, z: -48_000, r: 4_200},
	}
)

func Turn(cur realm, id, dx, dz int) {
	caller := requireUser(cur)
	takeExact(0)
	body := must(id)
	if body.owner != caller {
		panic("fish: owner")
	}
	if !body.inMatch || body.pool <= 0 {
		panic("fish: match")
	}
	if dx < -1 || dx > 1 || dz < -1 || dz > 1 || (dx == 0 && dz == 0) {
		panic("fish: face")
	}
	body.faceDx = dx
	body.faceDz = dz
}

func Move(cur realm, id int) {
	caller := requireUser(cur)
	takeExact(0)
	body := swimming(id)
	if body.owner != caller {
		panic("fish: owner")
	}
	now := time.Now().UnixMilli()
	if now < body.nextMoveMilli {
		panic("fish: move")
	}
	stepFish(body, now)
}

func Burst(cur realm, id int) {
	caller := requireUser(cur)
	takeExact(0)
	body := swimming(id)
	if body.owner != caller {
		panic("fish: owner")
	}
	now := time.Now().UnixMilli()
	if now < body.nextBurstAt {
		return
	}
	body.burstUntil = now + burstWindowMs
	body.nextBurstAt = body.burstUntil + burstCoolMs
}

func Heal(cur realm, id int) {
	caller := requireUser(cur)
	takeExact(0)
	body := must(id)
	if body.owner != caller {
		panic("fish: owner")
	}
	if body.inMatch {
		panic("fish: match")
	}
	now := time.Now().UnixMilli()
	day, used, ready := rolledHeal(body, now)
	if body.hpNow >= body.hp && !body.mustHeal {
		panic("fish: hp")
	}
	if used >= healsPerDay || now < ready {
		panic("fish: heal")
	}
	used++
	if used >= healsPerDay {
		ready = now + healCooldownMs
	}
	writeHeal(body, day, used, ready)
	gain := body.hp * healPercent / 100
	body.hpNow += gain
	if body.hpNow > body.hp {
		body.hpNow = body.hp
	}
	if body.hpNow < 1 {
		body.hpNow = 1
	}
	body.mustHeal = false
}

func RushHeal(cur realm, id int) {
	caller := requireUser(cur)
	body := must(id)
	if body.owner != caller {
		panic("fish: owner")
	}
	now := time.Now().UnixMilli()
	day, used, ready := rolledHeal(body, now)
	if used < healsPerDay || now >= ready {
		panic("fish: heal")
	}
	remaining := ready - now
	cost := int64(tierOf(body.rarity)) * remaining * ugnot / (16 * 3_600_000)
	takeExact(cost)
	writeHeal(body, day, healsPerDay-1, 0)
	send(burnSink, cost, cur)
}

// Cheer locks ugnot on a fish already in the sea. The deposit comes back when
// that fish leaves or is downed. It does not change bite.
func Cheer(cur realm, id int) {
	caller := requireUser(cur)
	body := must(id)
	sent := unsafe.OriginSend()
	if len(sent) != 1 || sent[0].Denom != denom || sent[0].Amount < minCheer {
		panic("fish: payment")
	}
	amount := sent[0].Amount
	if caller == body.owner {
		panic("fish: cheer")
	}
	if !liveFish(body, time.Now().Unix()) {
		panic("fish: match")
	}
	if cheerLocked(id)+amount > body.pool/2 {
		panic("fish: cap")
	}
	cheers = append(cheers, cheerRow{fish: id, who: caller, amount: amount, live: true})
}

func Watch(cur realm, on bool) {
	caller := requireUser(cur)
	takeExact(0)
	if !on {
		dropWatch(caller)
		return
	}
	for i := range watches {
		if watches[i].who == caller {
			return
		}
	}
	watches = append(watches, watchRow{who: caller, since: time.Now().UnixMilli()})
}

func Claim(cur realm, id int) {
	caller := requireUser(cur)
	takeExact(0)
	if id < 1 || id > len(claims) {
		panic("fish: claim")
	}
	row := &claims[id-1]
	if row.claimed {
		panic("fish: claim")
	}
	now := time.Now().UnixMilli()
	if row.expires > 0 && now >= row.expires {
		amt := row.amount
		row.claimed = true
		row.amount = 0
		send(seasonSink, amt, cur)
		return
	}
	if row.kind == "watch" {
		if caller == row.killer || caller == row.victim {
			panic("fish: claim")
		}
		if !watchEligible(caller, row.killAt) {
			panic("fish: watch")
		}
		if watchClaimed(caller, row.killID) {
			panic("fish: claim")
		}
		row.who = caller
	} else if row.who != caller {
		panic("fish: owner")
	}
	amt := row.amount
	row.claimed = true
	row.amount = 0
	send(caller, amt, cur)
}

func swimming(id int) *fishBody {
	body := must(id)
	if !liveFish(body, time.Now().Unix()) {
		panic("fish: match")
	}
	if body.mustHeal {
		panic("fish: heal")
	}
	return body
}

func walletInSea(owner address) bool {
	for _, body := range bodies {
		if body == nil || body.burned || !body.inMatch {
			continue
		}
		if body.owner == owner {
			return true
		}
	}
	return false
}

func tooHurt(body *fishBody) bool {
	if body.hp <= 0 {
		return true
	}
	return body.hpNow*100 < body.hp*30
}

func placeSwimmer(body *fishBody) {
	ensureSea()
	for sx := 0; sx < 90; sx++ {
		if tryPlace(body, sx, 0) {
			return
		}
	}
	for sz := 1; sz < 40; sz++ {
		for sx := -40; sx < 40; sx++ {
			if tryPlace(body, sx, sz) {
				return
			}
		}
	}
	panic("fish: sea")
}

func tryPlace(body *fishBody, sx, sz int) bool {
	if spawnBlocked(sx, sz) || cellTaken(sx, sz, body.id) {
		return false
	}
	body.sx = sx
	body.sz = sz
	body.faceDx = 0
	body.faceDz = -1
	return true
}

func stepFish(body *fishBody, now int64) {
	if body.faceDx == 0 && body.faceDz == 0 {
		panic("fish: face")
	}
	nx := body.sx + body.faceDx
	nz := body.sz + body.faceDz
	if !sectorInSea(nx, nz) {
		panic("fish: sea")
	}
	if cellBlocked(nx, nz, body.size, now) {
		panic("fish: cover")
	}
	body.sx = nx
	body.sz = nz
	body.nextMoveMilli = now + moveDelay(body, now)
	touchSpring(body, now)
}

func sectorInSea(sx, sz int) bool {
	x, z := cellMilli(sx, sz)
	dx := int64(x)
	dz := int64(z)
	limit := int64(seaRadius * unitMilli)
	return dx*dx+dz*dz <= limit*limit
}

func cellTaken(sx, sz, self int) bool {
	for _, body := range bodies {
		if body == nil || body.burned || body.id == self || !body.inMatch {
			continue
		}
		if body.sx == sx && body.sz == sz {
			return true
		}
	}
	return false
}

func spawnBlocked(sx, sz int) bool {
	if !sectorInSea(sx, sz) {
		return true
	}
	ensureSea()
	for i := range rockTable {
		if discHolds(sx, sz, rockTable[i].x, rockTable[i].z, rockTable[i].r) {
			return true
		}
	}
	now := time.Now().UnixMilli()
	for i := range shelterTable {
		refreshShelter(i, now)
		if shelterHP[i] <= 0 {
			continue
		}
		if discHolds(sx, sz, shelterTable[i].x, shelterTable[i].z, shelterTable[i].inner) {
			return true
		}
	}
	return false
}

func cellBlocked(sx, sz int, size string, now int64) bool {
	if !sectorInSea(sx, sz) {
		return true
	}
	ensureSea()
	for i := range rockTable {
		if discHolds(sx, sz, rockTable[i].x, rockTable[i].z, rockTable[i].r) {
			return true
		}
	}
	for i := range shelterTable {
		refreshShelter(i, now)
		if shelterHP[i] <= 0 || shelterAdmits(shelterTable[i].kind, size) {
			continue
		}
		if discHolds(sx, sz, shelterTable[i].x, shelterTable[i].z, shelterTable[i].inner) {
			return true
		}
	}
	return false
}

func cellMilli(sx, sz int) (int, int) {
	return sx*sectorMilli + sectorMilli/2, sz*sectorMilli + sectorMilli/2
}

func insideDisc(x, z, cx, cz, r int) bool {
	dx := int64(x - cx)
	dz := int64(z - cz)
	rr := int64(r)
	return dx*dx+dz*dz <= rr*rr
}

func ensureSea() {
	if len(shelterHP) == len(shelterTable) && len(shelterDown) == len(shelterTable) {
		return
	}
	shelterHP = make([]int, len(shelterTable))
	shelterDown = make([]int64, len(shelterTable))
	for i := range shelterHP {
		shelterHP[i] = shelterHPMax
	}
}

func refreshShelter(i int, now int64) {
	ensureSea()
	if shelterHP[i] > 0 {
		return
	}
	if shelterDown[i] > 0 && now >= shelterDown[i] {
		shelterHP[i] = shelterHPMax
		shelterDown[i] = 0
	}
}

func shelterAdmits(kind, size string) bool {
	if size == "large" {
		return false
	}
	if kind == "cave" {
		return size == "small"
	}
	return size == "small" || size == "medium"
}

func coverIndex(body *fishBody, now int64) int {
	ensureSea()
	for i := range shelterTable {
		refreshShelter(i, now)
		if shelterHP[i] <= 0 || !shelterAdmits(shelterTable[i].kind, body.size) {
			continue
		}
		if discHolds(body.sx, body.sz, shelterTable[i].x, shelterTable[i].z, shelterTable[i].inner) {
			return i
		}
	}
	return -1
}

func redirectShelter(atk, vic *fishBody, now int64) bool {
	idx := coverIndex(vic, now)
	if idx < 0 || shelterAdmits(shelterTable[idx].kind, atk.size) {
		return false
	}
	if discHolds(atk.sx, atk.sz, shelterTable[idx].x, shelterTable[idx].z, shelterTable[idx].inner) {
		return false
	}
	dmg := strikeDamage(biteNow(atk), shelterHPMax, atk.size, "medium")
	if dmg > shelterHP[idx] {
		dmg = shelterHP[idx]
	}
	shelterHP[idx] -= dmg
	if shelterHP[idx] <= 0 {
		shelterHP[idx] = 0
		shelterDown[idx] = now + shelterRebuildMs
	}
	return true
}

func mouthHit(atk, def *fishBody) bool {
	return mouthAimed(atk, def, def.dodge)
}

// shelterMouth is a bite against the pocket, not against the fish's dodge.
// The attacker must stand outside, must not fit inside, and must face the fish.
func shelterMouth(atk, vic *fishBody, now int64) bool {
	idx := coverIndex(vic, now)
	if idx < 0 || shelterAdmits(shelterTable[idx].kind, atk.size) {
		return false
	}
	if discHolds(atk.sx, atk.sz, shelterTable[idx].x, shelterTable[idx].z, shelterTable[idx].inner) {
		return false
	}
	return mouthAimed(atk, vic, 0)
}

// Sector centers sit off the practice discs, same as a spring on z = 0.
// The cell that holds the point counts as inside.
func discHolds(sx, sz, cx, cz, r int) bool {
	x, z := cellMilli(sx, sz)
	if insideDisc(x, z, cx, cz, r) {
		return true
	}
	px := int(math.Floor(float64(cx) / float64(sectorMilli)))
	pz := int(math.Floor(float64(cz) / float64(sectorMilli)))
	return sx == px && sz == pz
}

func mouthAimed(atk, def *fishBody, dodge int) bool {
	if !inReachDodge(atk, def, dodge) {
		return false
	}
	ax, az := cellMilli(atk.sx, atk.sz)
	bx, bz := cellMilli(def.sx, def.sz)
	dx := bx - ax
	dz := bz - az
	dist2 := int64(dx)*int64(dx) + int64(dz)*int64(dz)
	if dist2 <= int64(mouthContact)*int64(mouthContact) {
		return true
	}
	fx, fz := faceMilli(atk.faceDx, atk.faceDz)
	lead := mouthLead(atk.size)
	mx := dx - fx*lead/1000
	mz := dz - fz*lead/1000
	mouth2 := int64(mx)*int64(mx) + int64(mz)*int64(mz)
	if mouth2 == 0 {
		return true
	}
	dot := int64(mx)*int64(fx) + int64(mz)*int64(fz)
	if dot <= 0 {
		return false
	}
	return dot*dot >= int64(mouthAlignNum)*mouth2
}

func faceMilli(dx, dz int) (int, int) {
	if dx == 0 && dz == 0 {
		return 0, -1000
	}
	span := dx*dx + dz*dz
	if span == 1 {
		return dx * 1000, dz * 1000
	}
	if span == 2 {
		sx := 707
		sz := 707
		if dx < 0 {
			sx = -707
		}
		if dz < 0 {
			sz = -707
		}
		return sx, sz
	}
	return 0, -1000
}

func mouthLead(size string) int {
	switch size {
	case "small":
		return 700
	case "large":
		return 1450
	default:
		return 1000
	}
}

func biteNow(body *fishBody) int {
	b := biteOf(body.rarity, body.size, body.trait)
	if body.evolved && body.aspectBps > 0 {
		b = (b*body.aspectBps + 5000) / 10000
	}
	if b < 1 {
		return 1
	}
	return b
}

func strikeFought(bite, hpMax int, atkSize, defSize, atkR, defR string) int {
	dmg := bite * 100 / (hpMax + 100)
	if dmg < 1 {
		dmg = 1
	}
	if defR == preyOf(atkR) {
		dmg = dmg * 3 / 2
		if dmg < 1 {
			dmg = 1
		}
		return dmg
	}
	if sizeIndex(atkSize)-sizeIndex(defSize) >= 2 {
		dmg = dmg * 5000 / 10000
		if dmg < 1 {
			dmg = 1
		}
	}
	if atkR == preyOf(defR) {
		dmg = dmg * 2 / 3
		if dmg < 1 {
			dmg = 1
		}
	}
	return dmg
}

func preyOf(rarity string) string {
	switch rarity {
	case "common":
		return "mythic"
	case "uncommon":
		return "common"
	case "rare":
		return "uncommon"
	case "epic":
		return "rare"
	case "legendary":
		return "epic"
	case "mythic":
		return "legendary"
	default:
		panic("fish: rarity")
	}
}

func nextRarity(rarity string) string {
	switch rarity {
	case "common":
		return "uncommon"
	case "uncommon":
		return "rare"
	case "rare":
		return "epic"
	case "epic":
		return "legendary"
	case "legendary":
		return "mythic"
	default:
		return ""
	}
}

func growFromKill(atk, vic *fishBody) {
	if sizeIndex(vic.size) >= sizeIndex(atk.size)+1 {
		atk.growth += 2
	} else {
		atk.growth++
	}
	next := atk.size
	if next == "small" && atk.growth >= growMediumAt {
		next = "medium"
	}
	if next == "medium" && atk.growth >= growLargeAt {
		next = "large"
	}
	if next != atk.size {
		old := atk.hp
		if old < 1 {
			old = 1
		}
		atk.size = next
		atk.hp = hpOf(atk.rarity, next, atk.trait)
		atk.dodge = dodgeOf(next)
		atk.hpNow = atk.hpNow * atk.hp / old
		if atk.hpNow < 1 {
			atk.hpNow = 1
		}
		if atk.hpNow > atk.hp {
			atk.hpNow = atk.hp
		}
	}
	if atk.evolved || atk.size != "large" || atk.growth < growEvolveAt {
		return
	}
	aspect := nextRarity(atk.rarity)
	if aspect == "" {
		return
	}
	atk.evolved = true
	atk.aspect = aspect
	atk.aspectBps = 10800
	atk.hp = (atk.hp*108 + 50) / 100
	if atk.hp < 1 {
		atk.hp = 1
	}
	atk.hpNow = (atk.hpNow*108 + 50) / 100
	if atk.hpNow < 1 {
		atk.hpNow = 1
	}
	if atk.hpNow > atk.hp {
		atk.hpNow = atk.hp
	}
}

func worldSpeed(body *fishBody) int {
	base := 100
	switch body.rarity {
	case "common":
		base = 100
	case "uncommon":
		base = 97
	case "rare":
		base = 94
	case "epic":
		base = 91
	case "legendary":
		base = 88
	case "mythic":
		base = 85
	default:
		panic("fish: rarity")
	}
	units := base * 220 / 1000
	if body.size == "small" {
		units = units * 116 / 100
	}
	if body.size == "large" {
		units = units * 88 / 100
	}
	if body.trait == "swift" {
		units = units * 112 / 100
	}
	if units < 1 {
		return 1
	}
	return units
}

func moveDelay(body *fishBody, now int64) int64 {
	units := worldSpeed(body)
	if now < body.burstUntil {
		units = units * 7 / 4
	}
	if units < 1 {
		units = 1
	}
	delay := int64(sector*1000) / int64(units)
	if delay < 1 {
		return 1
	}
	return delay
}

func tierOf(rarity string) int {
	switch rarity {
	case "common":
		return 1
	case "uncommon":
		return 2
	case "rare":
		return 3
	case "epic":
		return 4
	case "legendary":
		return 5
	case "mythic":
		return 6
	default:
		panic("fish: rarity")
	}
}

func rolledHeal(body *fishBody, now int64) (day int64, used int, ready int64) {
	day = (now + ictOffsetMs) / dayMs
	used = body.healsUsed
	ready = body.healReadyAt
	if body.healDay != day {
		used = 0
		ready = 0
	}
	if used >= healsPerDay && ready > 0 && now >= ready {
		used = healsPerDay - 1
		ready = 0
	}
	return
}

func writeHeal(body *fishBody, day int64, used int, ready int64) {
	body.healDay = day
	body.healsUsed = used
	body.healReadyAt = ready
}

func cheerLocked(id int) int64 {
	var n int64
	for i := range cheers {
		if cheers[i].live && cheers[i].fish == id {
			n += cheers[i].amount
		}
	}
	return n
}

func returnCheers(body *fishBody, rlm realm) {
	for i := range cheers {
		if !cheers[i].live || cheers[i].fish != body.id {
			continue
		}
		amt := cheers[i].amount
		who := cheers[i].who
		cheers[i].live = false
		cheers[i].amount = 0
		send(who, amt, rlm)
	}
}

func bookCheerClaims(atk, vic *fishBody, cheer, now int64) int64 {
	if cheer <= 0 {
		return 0
	}
	var weights []int
	var owners []address
	for i := range cheers {
		if !cheers[i].live || cheers[i].fish != atk.id || cheers[i].amount <= 0 {
			continue
		}
		weights = append(weights, int(cheers[i].amount))
		owners = append(owners, cheers[i].who)
	}
	if len(weights) == 0 {
		return 0
	}
	shares := splitWeights(cheer, weights, owners[0], owners)
	killSeq++
	var placed int64
	for i, share := range shares {
		if share <= 0 {
			continue
		}
		claims = append(claims, claimRow{
			who:     owners[i],
			amount:  share,
			kind:    "cheer",
			killAt:  now,
			killer:  atk.owner,
			victim:  vic.owner,
			killID:  killSeq,
		})
		placed += share
	}
	return placed
}

func bookWatchClaims(atk, vic *fishBody, viewer, now int64) int64 {
	if viewer <= 0 || !anyEligible(atk.owner, vic.owner, now) {
		return 0
	}
	shard := viewer / int64(viewerShards)
	if shard <= 0 {
		return 0
	}
	killSeq++
	var placed int64
	for i := 0; i < viewerShards; i++ {
		claims = append(claims, claimRow{
			amount:  shard,
			kind:    "watch",
			killAt:  now,
			expires: now + viewerWindowMs,
			killer:  atk.owner,
			victim:  vic.owner,
			killID:  killSeq,
		})
		placed += shard
	}
	return placed
}

func anyEligible(killer, victim address, killAt int64) bool {
	for i := range watches {
		if watchEligible(watches[i].who, killAt) && watches[i].who != killer && watches[i].who != victim {
			return true
		}
	}
	return false
}

func watchEligible(who address, killAt int64) bool {
	for i := range watches {
		if watches[i].who == who && watches[i].since <= killAt-viewerWatchMs {
			return true
		}
	}
	return false
}

func watchClaimed(who address, killID int) bool {
	for i := range claims {
		if claims[i].claimed && claims[i].kind == "watch" && claims[i].killID == killID && claims[i].who == who {
			return true
		}
	}
	return false
}

func dropWatch(who address) {
	next := make([]watchRow, 0, len(watches))
	for i := range watches {
		if watches[i].who != who {
			next = append(next, watches[i])
		}
	}
	watches = next
}

func springMilli(now int64) (x, z int, born int64, ok bool) {
	if now < 0 {
		return 0, 0, 0, false
	}
	slot := now / springPeriodMs
	born = slot * springPeriodMs
	if now >= born+springLifeMs {
		return 0, 0, born, false
	}
	angle := math.Mod(float64(slot)*2.399963, 2*math.Pi)
	radius := 48 + (slot*17)%9*22
	x = int(math.Floor(math.Cos(angle)*float64(radius)*1000 + 0.5))
	z = int(math.Floor(math.Sin(angle)*float64(radius)*1000 + 0.5))
	return x, z, born, true
}

func springTouches(sx, sz, springX, springZ int) bool {
	fx, fz := cellMilli(sx, sz)
	dx := int64(fx - springX)
	dz := int64(fz - springZ)
	limit := int64(springRadiusMilli)
	if dx*dx+dz*dz <= limit*limit {
		return true
	}
	ssx := int(math.Floor(float64(springX) / float64(sectorMilli)))
	ssz := int(math.Floor(float64(springZ) / float64(sectorMilli)))
	return sx == ssx && sz == ssz
}

func touchSpring(body *fishBody, now int64) {
	if body == nil || body.burned || body.mustHeal || !body.inMatch || body.pool <= 0 {
		return
	}
	x, z, born, ok := springMilli(now)
	if !ok || body.springBorn == born {
		return
	}
	if !springTouches(body.sx, body.sz, x, z) {
		return
	}
	body.springBorn = born
	gain := body.hp * springHealPercent / 100
	if gain < 1 {
		gain = 1
	}
	body.hpNow += gain
	if body.hpNow > body.hp {
		body.hpNow = body.hp
	}
}