garden.gno
137.79 Kb · 3001 lines
1// Package garden is Gnotchi's pet realm, v6: the free, allowlisted, drand-rolled, hold-many
2// realm MINT.md designs end to end. It inherits garden/v4's machinery -- the SaveDay shape,
3// meters, garden plots, levels, and the List/Buy/Cancel trading surface -- but NOT v4's
4// invariants (MINT.md section 6). garden/v4 is live, immutable and untouched by this file; its
5// two gnomes stay exactly where they are forever (MINT.md section 6, BATCH-ONE.md section 0).
6//
7// ============================================================================================
8// WHAT v6 IS: v5 PLUS EXACTLY TWO FIXES, AND NOTHING ELSE. READ THIS FIRST.
9// ============================================================================================
10//
11// garden/v5 is DEPLOYED AND LIVE on the onyx testnet. v6 exists because a review on 2026-10-16
12// found a hole that the original design, the test suite and the adversarial security review
13// (ATTACK-REVIEW.md, eight attack goals) all missed -- not a vulnerability, a MISSING FEATURE
14// that contradicts something the owner asked for in his own words. This file is a DELIBERATELY
15// NARROW, SURGICAL COPY of v5. Every line of v5 that is not one of the two fixes below is
16// carried forward byte-for-byte, including every comment recording why something is shaped as
17// it is and the three real defects mutation testing found and fixed. v5 survived a security
18// audit; every unrelated change made here would be a change that has not been audited, so none
19// was made. If you are about to "also improve" something while reading this file: don't. Write
20// a v7.
21//
22// FIX 1 -- A v5 GNOME CANNOT HAVE A NAME, AND THE GAME NEEDS ONE.
23//
24// v5's gnome struct has no name field, no setter, and `character` -- the only identity string
25// it carries -- is "" for every gnome outside the three capped one-of-ones. Confirmed on the
26// LIVE CHAIN, not inferred: `GnomeByToken("0000002")` on the deployed v5 returns
27// character "". So 21 of Batch One's 24 gnomes would have been permanently anonymous, with no
28// way ever to fix it, because the realm is immutable.
29//
30// That directly contradicts the owner's own instruction that in-game characters "should
31// refer to you as your gnome name" -- the adventure's whole NPC dialogue surface is built on
32// a name existing. v5's own package doc argued the opposite ("NO PLAYER-CHOSEN NAME... the
33// app is free to let an owner caption their own gnome off chain"), and that argument was
34// WRONG in one specific, load-bearing way worth recording rather than quietly deleting: an
35// off-chain caption is not an identity. It cannot travel with the token through a sale, it
36// cannot be read by another realm, it cannot be reserved against impersonation, and the
37// adventure realm cannot greet you by it. The reasoning that was right -- that nothing
38// should be CHOSEN at mint time -- is preserved exactly: see SetName below.
39//
40// THE SHAPE, AND WHY. Naming is a SEPARATE ACT, AFTER the roll, never part of it. `Claim`
41// still takes no arguments and `Settle` still takes no name: the entire point of the mint is
42// that you do not choose what you get (MINT.md section 1a/section 2), and nothing here
43// weakens that. Naming what you already got is a different act entirely, performed by a
44// different function, at a different time, by the token's current owner only.
45//
46// FIX 2 -- v5 NEVER STORED THE DRAND ROUND THAT PRODUCED EACH GNOME.
47//
48// v5 emits the settling round in its `Settle` event and then forgets it. "Which round made
49// this gnome" was therefore a transaction-log archaeology problem rather than a state read:
50// `Provenance` returns adoptedAt/acquiredAt/saleCount and there was no getter for the round
51// at all. Since "provably unrigged" is this project's headline claim (ECONOMY.md section 1),
52// a holder being unable to verify their own gnome with one query was a gap between what the
53// project says and what the chain can answer. v6 stores the round on the gnome itself
54// (gnome.settledRound) and exposes it (SettledRound). See settleCore.
55//
56// ============================================================================================
57//
58// WHAT CHANGES FROM v4, IN ONE TABLE, EACH CITED TO THE DOCUMENT THAT DECIDED IT:
59//
60// - Adopt(name, hat, coat, eyes, nose) is GONE. Nothing is chosen by a caller any more.
61// DECISIONS.md 2026-10-15 deprecates the DIY picker as a product direction; MINT.md
62// section 1a/section 2 replace it with a roll.
63// - An ALLOWLIST gates who may ever claim (MINT.md section 11: "gate issuance, never the
64// secondary market"). Admin-managed, additive and removable, never touching the mint
65// itself once a claim has spent its roll.
66// - ONE ROLL PER WALLET, FOREVER, enforced independently of whether the resulting gnome is
67// still held (MINT.md section 1a/section 2.3). hasRolled is permanent; nothing in this file
68// clears it, and selling the gnome does not refund the roll.
69// - FREE. Claim refuses coins exactly as v4's Adopt refuses them (MINT.md section 1a/2.5,
70// GAMES.md rule 6: "random when earned, exact when bought... free: random is allowed").
71// - THE ROLL IS TWO-PHASE, SETTLED BY DRAND (MINT.md section 10, the load-bearing finding of
72// this whole file). A single-transaction roll is peekable two ways, verified against
73// gno.land's own source and binary rather than assumed from Ethereum's model: vm/qeval can
74// call a crossing function for free with no signature, and `gnokey maketx call -simulate
75// only` previews a real signed call against the last committed block with no gas and no
76// broadcast. Neither tool is the cause; the cause is that gno.land exposes NO on-chain
77// entropy at all -- chain/runtime has ChainHeight and nothing else, math/rand is PCG seeded
78// (0,0) on every node forever, and there is no shipped VRF -- so any single-transaction
79// formula, however it is dressed up, is something a caller can evaluate offline for every
80// block it might land in before ever deciding to broadcast. The fix MINT.md section 10.5
81// settles on, and this file builds, is a commit/reveal split across this project's own
82// deployed drand verifier: Claim spends the one-time roll and pins a ROUND THAT DOES NOT
83// EXIST YET; Settle, permissionless, computes the result once that round is actually
84// published. One player signature, not two -- the player signs Claim only.
85// - PARTS FROM A WEIGHTED TABLE (ECONOMY.md section 3), not a player's choice, with three
86// named one-of-ones (Hob, Thistle, Wick -- BATCH-ONE.md section 7) capped at one each.
87// - COUNTED RARITY. Every part's population is tracked on chain and readable by anyone --
88// MINT.md section 13's "nine gnomes in the world have this nose" has to be a chain fact,
89// and EyesCount/NoseCount/HatCount/CoatCount below are that fact, not an app claim layered
90// on top.
91// - MINT ONE, HOLD MANY, PLAY ONE (MINT.md section 2a). Buy's one-gnome-per-address refusal is
92// GONE -- deliberately, and only from Buy, never from Claim (see Claim's hasRolled gate,
93// which is the cap that still matters). An address may hold any number of gnomes; exactly
94// one is ever AWAKE, tracked by activeToken, and only the awake one can ever gain a cared
95// day, a streak, a level or XP. SaveDay and ChooseType resolve through activeToken, never
96// through "the" gnome for an address, because there no longer is one.
97// - SWITCHING (Wake) is free, at most once per UTC day (MINT.md section 2a), the same
98// day-boundary discipline SaveDay's own dailyCareDay already uses.
99// - THE SECONDARY MARKET IS OPEN: Buy/List/Cancel carry over v4's shape and fee (MINT.md
100// section 11), with no allowlist on buying and no hold cap.
101// - THE LOCK: the three named one-of-ones cannot be listed until they have lockCaredDays
102// cared days; every ordinary gnome trades from day one (MINT.md section 12/13, "Option A" --
103// lock only the named one-of-ones, recommended there and NOT YET CONFIRMED BY THE OWNER,
104// which is why lockCaredDays is one named constant and nothing else in this file assumes
105// its value). A gnome's own caredDayCount never decreases and is not reset by Buy, so once
106// a named gnome unlocks it stays unlocked through every future sale.
107// - A GENESIS GNOME, minted to this realm's own address at deploy, non-transferable, never
108// listable, separate from the 24-gnome batch (DECISIONS.md 2026-10-15: "the genesis gnome
109// belongs to nobody, permanently, on purpose"). Its name is not yet settled anywhere in this
110// project's documents; genesisGnomeName below is a placeholder, named as one.
111//
112// WHAT IS DELIBERATELY OUT OF SCOPE FOR THIS FILE, EACH A SCOPING DECISION MADE BY THIS PASS,
113// NOT A GAP IN THE BRIEF THAT ASKED FOR IT. Recorded here in the open the same way MINT.md
114// records its own open questions, so a future reader finds the reasoning in one hop:
115//
116// - NO SetRule/FreezeRules TUNABLE ADMIN SURFACE. v4's ruleBand/SetRule/FreezeRules machinery
117// is real and proven, but every care-mechanic number below is a fixed constant at v4's own
118// deploy defaults instead. The brief this file was written against lists eleven concrete
119// requirements and none of them is "tunable rules"; adding v4's whole admin-ratchet surface
120// on top of everything already new here would have roughly doubled this file's size and
121// its audit surface for a feature nobody asked for in this pass. A FUTURE VERSION can add
122// it back following v4's own pattern exactly if the owner wants it. (v5 said "a v6" here;
123// v6 exists now and deliberately did not, for the same reason it added nothing else.)
124// - NO NAME AT MINT TIME. This entry REPLACES v5's own "NO PLAYER-CHOSEN NAME" entry, which
125// is the thing v6 exists to correct -- see the "WHAT v6 IS" section at the top of this file
126// for the full account of what that argument got right and what it got wrong. What survives
127// from it, unchanged and non-negotiable: NOTHING IS CHOSEN BY A CALLER AT MINT TIME,
128// INCLUDING A NAME. `Claim` takes no arguments; `Settle` takes no name. v4's
129// validNameRune/validNameCharset/hasVisibleNameContent machinery (three audit rounds' worth,
130// per v4's own comment) is carried back into this file WHOLE, not re-derived, because the
131// naming act moved rather than disappeared -- it is now SetName, callable only by the
132// token's current owner, only after the roll has already irrevocably decided what they got.
133// - NO OpenBatch ADMIN SURFACE. MINT.md section 6 floats an owner-callable OpenBatch for
134// adding future batches' rosters; the task this file was built against names a single
135// 24-gnome batch (BATCH-ONE.md) and does not ask for a mechanism to open a second one. The
136// batch here is sized once, at deploy, by the batchCap/numNamedEditions constants below. A
137// FUTURE VERSION is the natural place for OpenBatch if a second batch is ever wanted, the
138// same way every other irreversible-shape decision in this project has gotten its own
139// version rather than a retrofit. (v5 said "a garden/v6 is the natural place"; v6 exists
140// now and deliberately did NOT take that opportunity -- it is two fixes and nothing else.)
141//
142// A REAL FLAW FOUND AND FIXED WHILE DESIGNING Settle, RECORDED HERE RATHER THAN QUIETLY FIXED
143// AND FORGOTTEN -- the same discipline MINT.md section 10 models for its own single-transaction
144// finding. An earlier version of this design picked the three named one-of-ones by drawing
145// "without replacement" from a shrinking pool: remainingTotal = batchCap - settledCount,
146// remainingNamed = 3 - namedAssignedCount, and a claimant's pick = seed % remainingTotal. THAT
147// IS PEEKABLE AND GAMEABLE, even though the seed itself is honestly drand-derived and
148// unforgeable: because remainingTotal only ever shrinks as OTHER claimants settle, and Settle is
149// permissionless and callable at any later time, a claimant whose seed is already fixed (the
150// moment their pinned round publishes) can simply precompute, for every possible remainingTotal
151// from 1 to batchCap, whether that value would win them a named edition -- and then wait,
152// costing nothing, until the rest of the batch happens to settle into a state that does. The fix
153// below removes every dependency on shrinking, observable, time-varying state from the decision:
154// a claimant's own named-edition pick is `seed % batchCap`, against a modulus that is a
155// COMPILE-TIME CONSTANT, not a moving count, so there is nothing left to wait for -- the only
156// residual order-dependence is which of possibly several colliding claimants (bad luck, not
157// strategy: nobody can change their own pick by choosing when to settle) gets a named edition
158// that more than one of them rolled, and that is resolved by whichever Settle call lands on
159// chain first.
160//
161// A SECOND AUDIT PASS NAMED THIS PRECISELY: "settling promptly", said above and in an earlier
162// version of Settle's own comment, OVERSTATES what the residual actually rewards. It is not
163// "whoever claimed first" or "whoever cared most" -- pendingClaim.claimedAt is never consulted
164// by the tie-break, and Settle is permissionless, so a bystander (a searcher, a bribed relayer,
165// a claimant's own bot) can win a collision for whichever side pays for transaction-ordering
166// priority, regardless of who rolled or claimed first. Considered and rejected: tie-breaking on
167// claimedAt instead. It sounds like the honest fix, but it is not reachable without a worse
168// trade-off -- Settle finalizes irrevocably (it mints a real token to a real owner, who may
169// already have acted on it), so honoring an earlier claimedAt would mean either refusing to
170// finalize ANY collision candidate until every possible earlier claimant's round has published
171// and settled (reintroducing exactly the wait-and-see window section 10 and this fix exist to
172// close, now around a deadline instead of a pool size) or reaching back to UNDO an already-
173// settled mint (which nothing in this realm, or any grc721-based realm in this project, has ever
174// claimed to be able to do, and which would be a strictly worse property than the one being
175// fixed). What actually holds, stated precisely rather than aspirationally: nobody can improve
176// THEIR OWN odds by choosing when to settle (the property section 10 is about, and the property
177// this fix actually guarantees); the residual is an ordinary transaction-ordering race over a
178// LOW-PROBABILITY, LOW-STAKES event (three slots in a batch of 24, decided among whichever
179// handful of claimants happen to collide), the same shape of race every permissionless action on
180// every chain is already subject to, not a new hole this design opened. See Settle's own comment
181// for the arithmetic.
182//
183// SETTLE CAN NOW PAY FOR ITS OWN BEACON RELAY, OWNER-APPROVED 2026-10-15, THE DAY AFTER THIS FILE
184// WAS FIRST WRITTEN. The two-phase roll above depends on beacon/v2 actually having the pinned
185// round's drand signature by the time Settle runs, and until this change that was somebody
186// else's problem: a relay has to happen, by a human or a bot, running outside this realm and
187// outside this project's control, or a claimant who has already spent their one-and-only roll is
188// stuck mid-mint through no fault of their own -- found live, not hypothetically, while building
189// this file: the project's own beacon was observed ~2 days stale. The fix the owner asked for
190// ("can we have the mint transaction pay the beacon though") is `SettleWithSignature` below: the
191// player's own app fetches the pinned round's signature from drand's public API (the same
192// `https://api.drand.sh/<chain>/public/<round>` this file's own test fixtures are fetched from)
193// and passes it straight through; Settle relays it itself, in the same transaction, before
194// computing the result. One transaction, and the player pays its gas -- TO THE NETWORK, same as
195// any other transaction's gas, NOT to this project, so it never touches the free-mint promise
196// (MINT.md section 14: "gas is still a payment, just not to us... the operator takes no stake").
197// Three things this buys, in the owner's own order of importance:
198//
199// - IT COSTS THE PROJECT NOTHING. The alternative to a player-paid relay is an operator-run one
200// -- a cron job or a bot calling beacon.Publish on a schedule, which is real recurring GNOT
201// spend with no revenue to offset it (MINT.md section 14 forecloses an unlock fee, batch one
202// is free end to end). This change deletes that cost rather than budgeting for it.
203// - A PLAYER CAN NEVER BE BLOCKED BY THIS PROJECT'S OWN HOUSEKEEPING. The stuck-mid-mint state
204// above is now unreachable for anyone willing to fetch their own round's signature: their own
205// Settle call makes the round available, with no dependency on this project, a third-party
206// relay, or anyone else's goodwill.
207// - THE BEACON GETS FRESHER AS A SIDE EFFECT, FOR EVERYONE ELSE USING IT. beacon/v2 is a shared,
208// permissionless, on-demand record (see its own package doc) -- a round this realm's own
209// claimants cause to be published is published for every other consumer of that beacon too,
210// not just for this realm.
211//
212// THREE THINGS WORKED OUT BY QUERYING THE LIVE CHAIN, NOT ASSUMED, because this is new
213// cross-realm write surface and this project's own history (the SPLASH beacon migration,
214// MEMORY.md) is built from exactly the kind of interrealm detail that gets guessed wrong:
215//
216// 1. WHAT beacon.Publish DOES ON AN ALREADY-PUBLISHED ROUND. Fetched byte-for-byte from the live
217// deployed realm itself (gno.land/r/g1r4aw43kagaaquhegxw6xr346h9f2qu2ezf0jar/beacon/v2) via
218// the public onyx-1 RPC's `vm/qfile` query, 2026-10-15, and diffed identical against this
219// project's own vendored copy at realms/_vendor/beacon/v2/beacon.gno -- it PANICS, it does not
220// no-op: `func Publish(cur realm, round int64, sigHex string) { if Published(round) { panic
221// ("beacon: round already published") } ... }`. SettleWithSignature therefore checks
222// `beacon.Published` itself BEFORE ever calling Publish, exactly once, and never calls Publish
223// at all if the round is already there -- calling it unconditionally would make this function
224// fail every time a relay (another claimant's own SettleWithSignature, or anyone else) beat it
225// to the punch, which given Settle's own permissionless, callable-by-anyone design is an
226// ordinary and expected race, not an edge case.
227// 2. THAT Publish IS REACHABLE CROSS-REALM AS `beacon.Publish(cross(cur), round, sigHex)`, and
228// that it carries no caller-identity check at all for this function to trip over. Confirmed
229// two ways: the live source pulled in point 1 shows Publish's body never reads `cur` or calls
230// `cur.Previous()` -- it is permissionless by whoever relays, not merely by whichever address
231// -- and this exact call shape is already proven working, not merely plausible, by this
232// file's OWN test harness: garden_test.gno's `publishAs` helper has called
233// `beacon.Publish(cross(cur), round, sigHex)` from this package since the day this file was
234// written, and every test that calls it passes. SettleWithSignature's own call is the
235// identical shape with `cur` being Settle's own realm parameter instead of a test helper's.
236// (`cur.Previous()` inside beacon.Publish would resolve to THIS realm, garden/v5, when called
237// this way rather than to the human wallet that called Settle -- a real interrealm fact worth
238// recording even though Publish does not currently branch on it: if beacon/v2 ever grows a
239// caller-identity check, re-read this paragraph before assuming Settle's relay still works.)
240// 3. GAS. Measured on this toolchain with r/splash/beacon/zz_gas_test.gno's own method
241// (`gno test -run TestZZGas -print-runtime-metrics=true -v`, net of this package's own fixed
242// per-test-call overhead): a bare Settle today costs ~6.2M gas; beacon.Publish alone costs
243// ~18.5M gas on THIS realm's measurement (the same order of magnitude as beacon/v2's own
244// documented 16,970,375, re-measured rather than quoted because toolchain and realm storage
245// both shift it). SettleWithSignature's worst case -- the round not yet published at all --
246// is therefore on the order of ~25M gas total, call it 1% of the 3e9 block gas limit and a
247// few hundredths of a GNOT at this chain's gas price. Reasonable: it is roughly four times a
248// bare Settle, not an order of magnitude more, it still leaves room for well over a hundred
249// such settlements in a single block, and it replaces a cost this project would otherwise have
250// paid itself, recurringly, forever, to keep the beacon fresh by some other means.
251//
252// THE SHAPE: TWO ENTRY POINTS, ONE SHARED CORE, NOT ONE FUNCTION WITH AN OPTIONAL SIGNATURE.
253// `Settle(cur realm, claimant address)` is UNCHANGED in behaviour and UNCHANGED in signature --
254// every existing test and every existing caller that already knows (or does not care) whether the
255// round is published keeps working exactly as before, at exactly its old gas cost, with no
256// signature to fetch or supply. `SettleWithSignature(cur realm, claimant address, sigHex string)`
257// is new, and is for a caller that HAS a signature and wants its transaction to publish the round
258// if nobody else already has. A Gno realm's exported functions take a fixed argument list -- there
259// is no overloading, and an optional/variadic last argument would still force every caller,
260// including every test and the app's own simpler "it's already published" path, to pass an empty
261// string they have no use for, for a case (publishing) that is the EXCEPTION, not the rule, since
262// most settlements land after some earlier claimant or relay has already published the shared
263// round. Two named entry points make the exception visible in the function name instead of buried
264// in an argument, and cost nothing extra: both share one unexported `settleCore`, so there is
265// exactly one copy of the draw-and-mint logic, not two drifting in parallel. And it is SAFE for
266// either one to be called in either actual on-chain state: Settle still refuses cleanly, with its
267// original message, if the round genuinely is not published yet; SettleWithSignature still
268// succeeds, with its supplied signature simply going unused, if the round turns out to already be
269// published by the time it runs (point 1's race) -- neither caller has to know in advance which
270// state they are in, they only have to know whether they personally HAVE a signature to offer.
271package garden
272
273import (
274 "strconv"
275 "strings"
276 "time"
277 "unicode" // v6 fix 1: v4's name charset allowlist, carried back whole. See validNameRune.
278 "unicode/utf8" // v6 fix 1: rune counting, never len(). See validNameLength.
279
280 "gno.land/p/nt/avl/v0"
281 "gno.land/p/nt/grc721/v0"
282 "gno.land/p/nt/seqid/v0"
283
284 "chain"
285 "chain/banker"
286 "chain/runtime/unsafe"
287
288 beacon "gno.land/r/g1r4aw43kagaaquhegxw6xr346h9f2qu2ezf0jar/beacon/v2"
289)
290
291// ============================================================================
292// THE THREE SALE CONSTANTS. CARRIED OVER, UNCHANGED, FROM garden/v4's 2026-10-11 DECISION, AS
293// PLACEHOLDERS FOR THIS NEW REALM. Nobody has asked the owner to re-confirm these specifically
294// for v5 -- re-decide or re-confirm them before ever deploying this file; see gnomod.toml's own
295// checklist item 0. init() below still gates them exactly as v4's assertFeeConfig does, so an
296// edit to a value that cannot work fails at deploy rather than succeeding silently forever.
297// ============================================================================
298const (
299 saleFeeRecipient = "g1ylpe9juk8cafgf9rt09wzuz85ug2lyfk5metyv" // gnotchi-opponent, v4's choice
300 saleFeeRateBps = int64(500) // 5% of the declared price
301 saleFeeFloorUgnot = int64(1_000_000) // 1 GNOT flat minimum per sale
302)
303
304// ============================================================================
305// Constants that are NOT tunable, and never will be: see the package doc's "out of scope"
306// section for why v5 has no SetRule surface at all.
307// ============================================================================
308
309const (
310 collectionName = "Gnotchi gnomes"
311 collectionSymbol = "GNOME"
312
313 // adminAddress is the only address AdminAllow/AdminDisallow will accept. Compiled in, with
314 // no transfer function, for the same reason v4 has none: an admin-transfer path is a second
315 // authority path, and a lost admin key merely freezes the allowlist, which is recoverable by
316 // redeploying a v6 -- not a disaster.
317 //
318 // THIS IS THE ONYX TESTNET DEPLOY KEY `gnotchi-deploy`, which is also the namespace this
319 // realm deploys under (see gnomod.toml) and the only key on this host with enough GNOT to
320 // pay for the admin calls -- AdminAllow and Settle both cost fees, and v4's old key
321 // (g1r4aw43..., the retired splash-deploy) is down to dust, so compiling that address in
322 // here would have produced an admin that could not afford to act. Correct for onyx, wrong
323 // for anywhere real. Change it before deploying anywhere that matters; see gnomod.toml.
324 adminAddress = "g1nq99m3h9ed7vqve6ajpr3qwy2ls252m8jnundm"
325
326 // numEyes / numNoses / the hat and coat catalogues: THE SAME FOUR-DIMENSIONAL FACE SPACE
327 // garden/v4 uses (SPRITES.md's Phase 1: 10 eyes x 8 noses x 4 hats x 4 coats = 1,280 looks).
328 // Nothing here is a new catalogue; eyesWeights/noseWeights below are a weighted DRAW over
329 // the same ids v4 already validates, per ECONOMY.md section 3 and MINT.md section 13's
330 // counted-rarity decision ("no tiers... rarity becomes population frequency counted on
331 // chain"). hat and coat are drawn UNIFORMLY (25% each): ECONOMY.md section 3 only specifies
332 // weights for the "permanent pair" (eyes, nose), and BATCH-ONE.md section 4a says so
333 // explicitly -- "assigning the section 3 percentages to hat and coat as well... is real work
334 // this document does not do... flagged here as the next thing to specify". A uniform draw is
335 // the honest placeholder until that work happens, not a guess dressed up as one.
336 numEyes = int64(10)
337 numNoses = int64(8)
338
339 // hourSeconds/daySeconds: unchanged from v4.
340 hourSeconds = int64(3600)
341 daySeconds = int64(86400)
342
343 // ---- care-mechanic constants, fixed at v4's own deploy DEFAULTS (v4's ruleBands table).
344 // See the package doc: v5 deliberately carries no tunable-rules admin surface.
345 numPlots = 3 // acorns.plots
346 plantCost = int64(1) // acorns.plantCost
347 feedCost = int64(1) // acorns.feedCost
348 acornsStart = int64(10)
349 meterMax = int64(10)
350 patCheer = int64(3)
351 hungryAtOrBelow = int64(2)
352
353 growHours = int64(24)
354 patCooldownHours = int64(12)
355 tinkerCost = int64(5)
356 levelBase = int64(50)
357 levelStep = int64(25)
358 sulkyPenaltyPct = int64(10)
359 harvestPerPlot = int64(3)
360 feedBelly = int64(4)
361 bellyDropEveryHours = int64(3)
362 cheerDropEveryHours = int64(6)
363 dailyCareCap = int64(60)
364
365 // acornReserve: v4's fix for the acorn softlock (AUDIT-DEPLOYED.md G9), carried over
366 // unchanged. See v4's own constant for the full argument; the short version is that a
367 // SaveDay batch that spends acorns may never end with fewer than this and nothing planted.
368 acornReserve = plantCost + feedCost
369
370 happyBonusPct = int64(10)
371 happyWindowHours = int64(2)
372 sulkyAfterHours = int64(72)
373 maxLevel = int64(20)
374 typeAtLevel = int64(5)
375
376 xpPat = int64(5)
377 xpFeed = int64(5)
378 xpHarvestPerPlot = int64(10)
379 xpTinkerTask = int64(15)
380
381 maxActionsPerCall = 32
382 maxBackfillHours = int64(48)
383 caredWindowDays = uint(64)
384
385 maxGnomesPageSize = 100
386 maxListingsPageSize = 100
387
388 // ---- the sale. Shape constants, unchanged from v4.
389 ugnotDenom = "ugnot"
390 maxPriceUgnot = int64(1_000_000_000_000_000)
391 maxFeeRateBps = int64(10_000)
392 maxListingDays = int64(30)
393
394 moodHungry = "hungry"
395 moodSulky = "sulky"
396 moodHappy = "happy"
397 moodContent = "content"
398
399 actionPat = "pat"
400 actionFeed = "feed"
401 actionPlant = "plant"
402 actionHarvest = "harvest"
403 actionTinker = "tinker"
404
405 typeGardener = "gardener"
406 typeExplorer = "explorer"
407 typeTinkerer = "tinkerer"
408
409 // ============================================================================
410 // THE MINT: allowlist, one roll per wallet, the batch, the lock, the drand pin. Every
411 // number below is a single named constant, each trivially changeable, per the brief's own
412 // instruction for the lock specifically and applied here to the pin offset too.
413 // ============================================================================
414
415 // batchCap: BATCH-ONE.md's own roster -- 24 gnomes, total, forever, this batch. 21 ordinary
416 // plus three named one-of-ones (numNamedEditions below). Closed the instant mintedCount
417 // reaches this; nothing in this file can ever raise it (no OpenBatch -- see the package
418 // doc's "out of scope" section).
419 batchCap = int64(24)
420
421 // numNamedEditions: Hob, Thistle and Wick (namedEditionOrder below), cap ONE EACH. "Cap 1" is
422 // not a different mechanism from any other cap, MINT.md section 3's own point -- it is the
423 // same characterOwner.Has check any other population cap would use, just at the number one.
424 numNamedEditions = 3
425
426 // lockCaredDays: MINT.md section 12/13's RECOMMENDATION, explicitly not yet confirmed by the
427 // owner ("Option A... this is a recommendation, not a decision"). The three named one-of-ones
428 // cannot be listed until they have this many cared days; every ordinary gnome trades from
429 // day one. One named constant, nothing else in this file assumes 30 specifically.
430 lockCaredDays = int64(30)
431
432 // ============================================================================
433 // v6 FIX 1: THE NAME. maxNameLen is v4's own constant at v4's own value, kept in step with
434 // app/js/config.js's NAME_MAX_LEN (24) by hand, because Gno has no way to read that file at
435 // build time -- the same hand-maintained pairing v4 documented and v6 inherits. The app's
436 // NAME_RULE.MAX_LEN must equal this number; TestMaxNameLenMatchesTheAppsRule pins the value
437 // so a change here fails a test rather than silently diverging from the one rule the app
438 // shows a player before they pay gas.
439 // ============================================================================
440 maxNameLen = 24
441
442 // pinOffsetSeconds / pinOffsetRounds: how far into drand's future Claim pins a round, sized
443 // AS SECONDS, from drand evmnet's own period (beacon.PeriodSeconds, re-exported from this
444 // project's own bls254 package, not restated here), per MINT.md section 10.5's explicit
445 // instruction -- never as a round count checked only against a block count, which is the
446 // exact dimensional trap this project's own history (the SPLASH raffle shipping with a 100x
447 // wrong round/block ratio, MEMORY.md) says cost real time once already. 60 seconds is twenty
448 // drand rounds at the 3-second period CurrentRound() at Claim time is comfortably able to
449 // pin as "not yet signed by anyone, including drand itself" -- see Claim's own comment for
450 // why the margin matters even though CurrentRound() is pure arithmetic over block time, not
451 // a relay-dependent estimate.
452 pinOffsetSeconds = int64(60)
453)
454
455// pinOffsetRounds is a const expression over an imported const (beacon.PeriodSeconds), which Gno
456// permits across package boundaries exactly as it would within one; TestPinOffsetIsTwentyRounds
457// pins the arithmetic rather than trusting the comment above.
458const pinOffsetRounds = pinOffsetSeconds / beacon.PeriodSeconds
459
460// kindEnd-style ratchet machinery: deliberately absent. See the package doc.
461
462// hatOptions / coatOptions: v4's validHats/validCoats catalogue, as an ORDERED array rather than
463// a set, because Settle needs to draw a POSITION, not merely validate one. Order is frozen the
464// moment this realm deploys, exactly as v4's own numEyes/numNoses ordering is frozen -- a part
465// may be redrawn; it may never be reordered, removed or renumbered (v4's own comment on this).
466var hatOptions = [4]string{"red", "purple", "green", "navy"}
467var coatOptions = [4]string{"blue", "teal", "orange", "brown"}
468
469// eyesWeights: ECONOMY.md section 3, verbatim -- "eyes across 4 colours at 15%, 3 at 9%, 2 at
470// 5%, 1 at 3%" -- 4+3+2+1 = 10 entries = numEyes, and 4*15+3*9+2*5+1*3 = 100.
471// TestWeightTablesSumToOneHundred pins the sum rather than trusting the arithmetic in this
472// comment; drawWeighted's own fallback additionally makes a drift here fail safe, not silently.
473var eyesWeights = [10]int64{15, 15, 15, 15, 9, 9, 9, 5, 5, 3}
474
475// noseWeights: ECONOMY.md section 3 says only "nose similar across 8 shapes" and gives no exact
476// percentages -- BATCH-ONE.md section 4a names this directly as real work nobody has done yet.
477// This is a SHAPE-FAITHFUL INTERPRETATION, not a transcription: four tiers of two shapes each,
478// 20/20/15/15/10/10/5/5, the same big-gap-then-smaller-gaps shape eyesWeights has, scaled to 8
479// entries and summing to 100. Flagged here, not quietly presented as sourced, so the owner or a
480// future author can replace it with real numbers the moment ECONOMY.md section 3 gets them.
481var noseWeights = [8]int64{20, 20, 15, 15, 10, 10, 5, 5}
482
483// namedEditionOrder: BATCH-ONE.md section 7's three names, in the fixed order Settle's
484// namedPick indexes into. The order carries no meaning -- it is not a ranking -- it only has to
485// be fixed, which it is, forever, the moment this realm deploys.
486var namedEditionOrder = [numNamedEditions]string{"hob", "thistle", "wick"}
487
488// namedEditionDisplayNames: BATCH-ONE.md section 7's three names AS THEY ARE WRITTEN -- "Hob,
489// Thistle, Wick", the form this file's own documentation uses throughout -- paired by index with
490// namedEditionOrder above.
491//
492// WHY A SECOND ARRAY RATHER THAN JUST CAPITALISING namedEditionOrder, which is the change a
493// reviewer will reach for first: namedEditionOrder's values are not labels, they are KEYS.
494// settleCore writes characterOwner.Set(character, ...) and tests characterOwner.Has(candidate)
495// with those exact strings, and the public CharacterOwner(name) reader does a raw tree Get with
496// no case folding at all -- so CharacterOwner("hob") resolving is a chain fact that an
497// off-chain caller already depends on, and init() registers the genesis gnome under the matching
498// lowercase key "genesis". Capitalising namedEditionOrder would move those keys to "Hob" while
499// leaving "genesis" lowercase, break CharacterOwner("hob") for every existing caller, and it is
500// unfixable after deploy. The keys stay canonical.
501//
502// This array exists ONLY to supply the gnome's `name`, which is a DISPLAY STRING and has always
503// been a different thing from its canonical key -- see canonicalNameKey's own comment on why the
504// stored form and the uniqueness key are deliberately two strings. nameOwner is still keyed by
505// canonicalNameKey(name), which folds "Hob" to "hob", so reservedNameKeys and the uniqueness
506// index are untouched by this: no new mechanism, just the display side of a separation that was
507// already here. TestNamedEditionDisplayNamesPairWithTheirCanonicalKeys pins the pairing in both
508// directions, so an edit to either array that breaks it fails a test rather than shipping a
509// one-of-one whose display name canonicalises to somebody else's key.
510var namedEditionDisplayNames = [numNamedEditions]string{"Hob", "Thistle", "Wick"}
511
512// namedEditionDisplayName maps a named edition's canonical character key to its display name.
513// Used by settleCore's mint and mirrored by the test fabricator, so there is exactly one copy of
514// the mapping. Returns the input unchanged for anything that is not one of the three editions --
515// which is unreachable from settleCore (it only ever passes a namedEditionOrder entry) and is a
516// pass-through rather than a panic because this is a label lookup, not a security boundary.
517func namedEditionDisplayName(character string) string {
518 for i, canonical := range namedEditionOrder {
519 if canonical == character {
520 return namedEditionDisplayNames[i]
521 }
522 }
523 return character
524}
525
526// genesisGnomeName: DECISIONS.md 2026-10-15 settles the MECHANISM (minted to this realm's own
527// address, non-transferable, never listable, separate from the batch) but never settles a NAME
528// anywhere in this project's documents. Placeholder, named as one; change it freely before
529// deploying.
530//
531// CHANGED FROM v5 IN ONE RESPECT, deliberately: v5's comment ended "it is read by nothing else
532// in this file", which was true there and is NOT true here. v6 fix 1 writes this string into the
533// genesis gnome's own `name` field at init() and registers its canonical key in nameOwner, so
534// changing it also changes which name is taken. It must still canonicalise to one of
535// reservedNameKeys below, or an ordinary gnome could be named "Genesis" and pose as it --
536// TestGenesisNameIsReserved pins exactly that, so an edit here that breaks the pairing fails a
537// test rather than shipping.
538const genesisGnomeName = "Genesis"
539
540// reservedNameKeys: the canonical name keys NO ORDINARY GNOME MAY EVER TAKE -- the three named
541// one-of-ones (BATCH-ONE.md section 7's roster, re-read rather than assumed: Hob, Thistle, Wick)
542// plus the genesis gnome. Checked by SetName; see assertNameAssignable.
543//
544// WHY THIS EXISTS SEPARATELY FROM THE nameOwner UNIQUENESS INDEX, which is the subtle part and
545// the reason a reviewer should not "simplify" one of the two away: the uniqueness index only
546// protects a name that is ALREADY TAKEN BY A LIVING TOKEN. Hob's cap-one edition may not have
547// been minted yet -- its namedPick is a pure function of a drand round nobody has rolled -- and
548// for the whole window before it mints, nameOwner has no "hob" key at all. Without this list,
549// the FIRST ordinary claimant could name their gnome "Hob", take the key, and the real Hob would
550// then mint into a collection where its own name already belongs to an impostor. Reservation
551// covers the pre-mint window; uniqueness covers the post-mint one. Both are needed, and together
552// they are the "two locks on a door" discipline this file already uses for the genesis gnome.
553//
554// Every entry is already in canonical form (lowercase, single-spaced, trimmed), and
555// TestReservedNameKeysAreCanonical pins that -- a non-canonical entry here would be a key
556// canonicalNameKey could never produce, i.e. a reservation that silently protects nothing.
557var reservedNameKeys = [numNamedEditions + 1]string{"hob", "thistle", "wick", "genesis"}
558
559// ============================================================================
560// Storage
561// ============================================================================
562
563// plot: unchanged from v4. plantedAt == 0 is the empty state; readyAt is stored, not computed,
564// so a future change to growHours (there is none possible in this file, but the shape is kept
565// for the day a v6 adds tuning back) could never reach backwards into an already-planted plot.
566type plot struct {
567 plantedAt int64
568 readyAt int64
569}
570
571// gnome is the whole persisted pet. EVERY FIELD HERE HAS AN EXPORTED READER -- v4's own rule,
572// carried over verbatim: a realm cannot grow a second chance at this after deploy.
573//
574// NOT HERE, DELIBERATELY: a hat/coat the OWNER chose (nothing is chosen at mint any more;
575// hat/coat are ROLLED exactly as eyes/nose are, and are exactly as permanent as eyes/nose always
576// were in v4 -- there has never been a function anywhere in this family of realms that changes a
577// gnome's hat or coat after mint). v5's own comment also listed "a name" here; v6 fix 1 is
578// precisely the correction of that, and `name` is below.
579//
580// character is "" for every ordinary gnome and one of namedEditionOrder's three strings for a
581// named one-of-one. eyes/nose/hat/coat are the sentinel -1/-1/""/"" for a named edition: its
582// look is NOT a point in the ordinary 1,280-look space, it is BATCH-ONE.md section 6's own new
583// art (Hob's crown and gold coat, Thistle's helmet and axe, Wick's lantern), which this contract
584// does not need to know the pixels of -- only that Character(tokenID) names it, so the app can
585// render the right thing. A named edition's parts are therefore never counted in
586// eyesCounts/noseCounts/hatCounts/coatCounts: it is already as rare as a thing can be, at cap
587// one, counted instead through characterOwner.
588type gnome struct {
589 hat string
590 coat string
591 eyes int64
592 nose int64
593 character string
594
595 // name: v6 FIX 1. The gnome's own name, as its owner typed it, byte-for-byte -- this realm
596 // NEVER rewrites it (see canonicalNameKey's own comment on why the stored form and the
597 // uniqueness key are deliberately two different strings).
598 //
599 // "" means UNNAMED, which is the state EVERY ordinary gnome is minted in and stays in until
600 // its owner calls SetName. That is not an oversight to be fixed by defaulting it to
601 // something: a gnome with no name yet is honestly nameless, and inventing "Gnome #7" on
602 // chain would make a fabricated string indistinguishable from a chosen one forever.
603 //
604 // For the THREE NAMED ONE-OF-ONES and for the GENESIS GNOME this is set ONCE, at mint, to
605 // their own character name, and SetName refuses them permanently (their identity is the
606 // whole point of them -- see SetName's own guard). So `name != ""` does not imply "an owner
607 // chose this"; `character == ""` is the test for that.
608 name string
609
610 // settledRound: v6 FIX 2. The drand round whose published signature produced this gnome's
611 // parts -- the single number that makes "provably unrigged" (ECONOMY.md section 1) checkable
612 // by a holder in one state read instead of a transaction-log search. Written once, in
613 // settleCore, from the pendingClaim's own pinned round; never written again by anything.
614 //
615 // 0 means "not produced by a roll at all", which is true of exactly one token for the whole
616 // life of this realm: the genesis gnome, minted directly in init() and never rolled for. A
617 // caller can tell the two apart without ambiguity because round 0 is not a real drand round
618 // and never will be.
619 settledRound int64
620
621 level int64
622 gnomeType string
623 adoptedAt int64 // unix seconds; the moment Settle minted this gnome, or init() for genesis
624
625 belly int64
626 bellyAt int64
627 cheer int64
628 cheerAt int64
629
630 lastPatAt int64
631 lastHappyEventAt int64
632
633 totalXp int64
634
635 xpGarden int64
636 xpTinker int64
637 harvestCount int64
638
639 dailyCareXp int64
640 dailyCareDay int64
641
642 plots [numPlots]plot
643
644 lastTinkerAt int64
645
646 // Cared days. v4's own shape, unchanged: the chain stores FACTS (which UTC days were
647 // cared for), never the STREAK RULE, which stays in app/js/rules.js's streakFrom. See
648 // v4's gnome struct comment for the full argument; it applies here without edit.
649 caredDayCount int64
650 lastCaredDay int64
651 caredMask uint64
652
653 lastActionAt int64
654
655 // lastWokenAt: unix seconds, the moment THIS token last became somebody's active gnome --
656 // set at mint (settleCore), at purchase (Buy), and at every explicit Wake, always to "now" at
657 // that moment, never anything earlier. SaveDay's backfill floor is max(lastActionAt,
658 // lastWokenAt, now-48h): a token cannot be credited for any period before it was actually the
659 // active one, closing the gap ATTACK-REVIEW.md goal 7 found -- v4 never needed this field
660 // because v4 enforced one gnome per address, so there was no second token to backfill against
661 // while this one slept. See SaveDay's own comment for the full argument.
662 lastWokenAt int64
663
664 acquiredAt int64
665 saleCount int64
666}
667
668// listing: unchanged in shape from v4, now simply one of possibly SEVERAL a single owner may
669// have standing at once (mint one, hold many) -- listings is still keyed by tokenID, which was
670// always the right key for this and needed no change.
671type listing struct {
672 seller address
673 priceUgnot int64
674 buyer address
675 listedAt int64
676 expiresAt int64
677}
678
679// feeConfig: unchanged from v4.
680type feeConfig struct {
681 recipient address
682 rateBps int64
683 floorUgnot int64
684}
685
686// pendingClaim is the record Claim writes and Settle consumes: the permanent, irrevocable fact
687// that this address spent its one roll, and the future drand round it is waiting on.
688type pendingClaim struct {
689 round int64
690 claimedAt int64
691}
692
693var (
694 token *grc721.Token
695 ledger *grc721.PrivateLedger
696
697 nextID seqid.ID
698
699 gnomes = avl.NewTree() // tokenID -> *gnome
700
701 // ownerTokens: owner address -> *[]string, every tokenID that address currently holds.
702 // MINT.md section 2a's "hold many": v4 never needed this because v4 never let an address
703 // hold more than one. See addOwnerToken/removeOwnerToken.
704 ownerTokens = avl.NewTree()
705
706 // activeToken: owner address -> tokenID string, the ONE gnome that is awake for that
707 // address right now. Absent means "nothing awake" -- reachable only for an address that has
708 // never settled a claim or bought a gnome, or that has sold its only awake gnome and not yet
709 // woken another (Buy deliberately does not auto-promote a replacement; see Buy's comment).
710 activeToken = avl.NewTree()
711
712 // lastWakeDay: owner address -> int64 UTC day number, the once-per-day gate on Wake.
713 lastWakeDay = avl.NewTree()
714
715 // lastCaredDayForOwner: owner address -> int64 UTC day number, the most recent calendar day
716 // on which ANY ONE of this owner's tokens has already banked a cared day. The package doc is
717 // explicit and unconditional: "exactly one is ever AWAKE... and only the awake one can ever
718 // gain... a cared day" (see this file's own doc comment). lastWokenAt (see the gnome struct)
719 // closes the BACKFILL half of ATTACK-REVIEW.md goal 7 -- a token cannot backfill a day it
720 // spent asleep. This tree closes the LIVE half: without it, an owner could Wake(B) partway
721 // through a UTC day already spent genuinely caring for A, then genuinely care for B too,
722 // using only real-time, non-backfilled timestamps, and bank the SAME calendar day on BOTH --
723 // no backfill panic ever fires, because neither action is backfilled, each is simply real
724 // care given to whichever gnome was actually awake at the time. That still doubles the one
725 // property this bookkeeping exists to measure (lockCaredDays' 30-day resale lock, and the
726 // public cared-days streak), for one wallet, once per day, for as many tokens as the owner is
727 // willing to switch through -- the exact harm goal 7 names, reached by a second, undiscovered
728 // mechanism. recordCaredDay only ever runs, and this tree only ever advances, when the day
729 // being recorded is NEWLY banked for this OWNER, not merely newly banked for this TOKEN.
730 lastCaredDayForOwner = avl.NewTree()
731
732 balances = avl.NewTree() // owner address -> int64 acorns, per PLAYER, exactly as v4
733
734 listings = avl.NewTree() // tokenID -> *listing
735
736 // allowlist: owner address -> true. Admin-managed (AdminAllow/AdminDisallow), gates Claim
737 // only -- MINT.md section 11: "gate issuance, never the secondary market". Buying and
738 // selling need no entry here at all.
739 allowlist = avl.NewTree()
740
741 // hasRolled: owner address -> true, PERMANENT, never removed by anything in this file. "One
742 // roll per wallet, forever" (MINT.md section 1a/2.3), independent of whether the resulting
743 // gnome is still held, independent of whether the address is later removed from the
744 // allowlist. Disallowing an address after it has rolled does not and cannot un-roll it.
745 hasRolled = avl.NewTree()
746
747 // pendingClaims: owner address -> *pendingClaim. Written by Claim, removed by Settle. At
748 // most one per address, because hasRolled already refuses a second Claim from the same one.
749 pendingClaims = avl.NewTree()
750
751 // eyesCounts / noseCounts / hatCounts / coatCounts: counted rarity (MINT.md section 13).
752 // Keyed by the part's own id/name, value is a lifetime population count, incremented only by
753 // an ORDINARY Settle (never by a named one-of-one, which is counted separately below, and
754 // never decremented: there is no burn, and a sale moves a part without minting one).
755 eyesCounts = avl.NewTree()
756 noseCounts = avl.NewTree()
757 hatCounts = avl.NewTree()
758 coatCounts = avl.NewTree()
759
760 // nameOwner: v6 FIX 1, the uniqueness index. canonicalNameKey(name) -> tokenID. A key is
761 // present if and only if exactly one living token currently carries a name that canonicalises
762 // to it, which is what makes "names are unique across the collection" a chain fact rather
763 // than an app convention.
764 //
765 // IT IS KEYED ON THE CANONICAL FORM, NOT THE TYPED FORM, and that is the whole point: with a
766 // raw-string key, "Hob", "hob", "HOB" and "Hob " are four different keys, so uniqueness would
767 // be worth nothing and the one-of-one reservation below could be walked straight around by
768 // changing one letter's case. See canonicalNameKey.
769 //
770 // RENAMING FREES THE OLD KEY, and that is REQUIRED, not a convenience. If SetName only ever
771 // added keys, a single token could lock up an unbounded number of names by renaming over and
772 // over -- one gnome, one transaction each, every good name in the collection permanently
773 // unavailable to everybody else. Freeing on rename bounds what any wallet can hold hostage to
774 // exactly one name per token it owns, and since no address can ever hold more than batchCap
775 // tokens, the worst case for the entire realm is 24 names held at once by the 24 tokens that
776 // exist. See SetName's commit block, which removes before it sets.
777 nameOwner = avl.NewTree()
778
779 // characterOwner: one of namedEditionOrder's three names -> tokenID, present only once that
780 // edition has actually been minted. Has(name) is both "has this cap-one edition been taken"
781 // (Settle's own fallback check) and "does it exist yet" (CharacterOwner's reader) -- the same
782 // single tree answers both questions, which is why there is no separate counter for it.
783 characterOwner = avl.NewTree()
784
785 mintedCount int64 // reservations made by Claim, gates batchCap; never decremented
786 settledCount int64 // completions made by Settle; informational only, see BatchStatus
787
788 genesisTokenID string // set exactly once, in init()
789
790 rulesFrozen = true // always true: there are no rules to freeze or unfreeze in v5. See AdminState.
791
792 fee feeConfig
793
794 transferGate string
795)
796
797func init(cur realm) {
798 if !address(adminAddress).IsValid() {
799 panic("garden: adminAddress is not a valid address; fix the constant before deploying")
800 }
801
802 cfg := feeConfig{
803 recipient: address(saleFeeRecipient),
804 rateBps: saleFeeRateBps,
805 floorUgnot: saleFeeFloorUgnot,
806 }
807 assertFeeConfig(cfg, cur.Address())
808 fee = cfg
809
810 token, ledger = grc721.NewToken(collectionName, collectionSymbol, 0, cur)
811 ledger.RegisterExtension(&saleGateExtension{})
812
813 // THE GENESIS GNOME. Minted here, directly, to this realm's own address -- never through
814 // Claim, never counted against batchCap, never allowlist-gated, because it is not a roll and
815 // not part of the batch (DECISIONS.md 2026-10-15). No wallet holds this realm's private key,
816 // so no transaction can ever be signed as its owner: List, Buy and Wake all additionally
817 // refuse genesisTokenID by name as a second, redundant lock, and saleGateExtension's
818 // OnTransfer refuses it unconditionally as a third -- the same "two locks on a door that
819 // already has one" discipline v4's own sale gate uses, because the claim "belongs to
820 // nobody" is only as strong as the weakest reachable path around it.
821 id := nextID.Next()
822 genesisTokenID = id.String()
823 me := cur.Address()
824 if err := ledger.Mint(me, grc721.TokenID(genesisTokenID)); err != nil {
825 panic(err)
826 }
827 now := time.Now().Unix()
828 gnomes.Set(genesisTokenID, &gnome{
829 character: "genesis",
830 // v6 FIX 1: the genesis gnome carries its own name from the instant this realm exists.
831 // It is the one token whose name was never chosen by an owner and never can be -- no
832 // wallet holds this realm's key, and SetName refuses any token with a character anyway.
833 name: genesisGnomeName,
834 eyes: -1,
835 nose: -1,
836 level: 1,
837 adoptedAt: now,
838 belly: meterMax,
839 bellyAt: now,
840 cheer: meterMax,
841 cheerAt: now,
842 lastActionAt: now,
843 acquiredAt: now,
844 // settledRound stays 0: the genesis gnome was never rolled for. See the field's comment.
845 })
846 addOwnerToken(me, genesisTokenID)
847
848 // v6 FIX 1: register the genesis name in the uniqueness index, so NameOwner resolves it and
849 // no ordinary gnome can take it. reservedNameKeys already refuses it independently of this
850 // write (same two-locks discipline as the genesis transfer refusals above) -- this one makes
851 // the index COMPLETE, so "every name a living token carries is in nameOwner" holds without an
852 // exception a future reader would have to know about.
853 nameOwner.Set(canonicalNameKey(genesisGnomeName), genesisTokenID)
854
855 // Registered under its own name, "genesis", in the SAME tree the three named one-of-ones
856 // use -- not because it competes with their cap (BatchStatus's namedMinted count iterates
857 // namedEditionOrder only, which "genesis" is never a member of, so this cannot affect the
858 // batch), but so CharacterOwner("genesis") resolves instead of silently reporting not-found
859 // for the one named character that is neither ordinary nor one of the three. Second-audit-
860 // pass finding (G7): fixed here, not left as a reader inconsistency.
861 characterOwner.Set("genesis", genesisTokenID)
862
863 chain.Emit("Genesis", "tokenId", genesisTokenID, "name", genesisGnomeName)
864}
865
866// assertFeeConfig: unchanged from v4's own gate.
867func assertFeeConfig(cfg feeConfig, realmAddr address) {
868 if !cfg.recipient.IsValid() {
869 panic("garden: DEPLOY GATE: saleFeeRecipient is not a valid address; fix the constant at the top of garden.gno before deploying")
870 }
871 if cfg.recipient == realmAddr {
872 panic("garden: DEPLOY GATE: saleFeeRecipient is this realm's own address, and coins sent there are burned because there is no withdrawal path")
873 }
874 if cfg.recipient == address(adminAddress) {
875 panic("garden: DEPLOY GATE: saleFeeRecipient is the admin/deploy key; the fee recipient must be an address chosen for that purpose, not the key that happens to deploy")
876 }
877 if cfg.rateBps < 1 || cfg.rateBps > maxFeeRateBps {
878 panic("garden: DEPLOY GATE: saleFeeRateBps must be between 1 and " + strconv.FormatInt(maxFeeRateBps, 10) + " basis points; fix the constant at the top of garden.gno before deploying")
879 }
880 if cfg.floorUgnot < 1 || cfg.floorUgnot > maxPriceUgnot {
881 panic("garden: DEPLOY GATE: saleFeeFloorUgnot must be between 1 and " + strconv.FormatInt(maxPriceUgnot, 10) + " ugnot; fix the constant at the top of garden.gno before deploying")
882 }
883}
884
885// saleGateExtension: v4's shape, plus the genesis refusal. Panics on every transfer except the
886// one Buy is performing right now, and ALWAYS panics for genesisTokenID regardless of
887// transferGate -- there is no path, including a future bug in Buy, by which the genesis gnome
888// should ever be transferable, so this checks it first and unconditionally.
889type saleGateExtension struct{}
890
891func (saleGateExtension) ExtensionKind() string { return "sale-gate" }
892
893func (saleGateExtension) OnMint(to address, tid grc721.TokenID) {}
894
895func (saleGateExtension) OnTransfer(from, to address, tid grc721.TokenID) {
896 if tid.String() == genesisTokenID {
897 panic("garden: the genesis gnome belongs to nobody and can never change hands")
898 }
899 if transferGate == "" || transferGate != tid.String() {
900 panic("garden: a gnome can only change hands through Buy; every other transfer is permanently disabled")
901 }
902}
903
904func (saleGateExtension) OnBurn(tid grc721.TokenID) {
905 panic("garden: gnomes cannot be burned")
906}
907
908// ============================================================================
909// Admin: the allowlist. The only admin-reachable state in this whole realm -- there is no
910// SetRule, no FreezeRules, no fee steward, no treasury reach, nothing else at all.
911// ============================================================================
912
913// AdminAllow adds addr to the allowlist, so it may call Claim. Adding an address a second time
914// is a harmless no-op. Adding an address that has already rolled changes nothing -- hasRolled is
915// checked independently and is permanent regardless of allowlist state.
916func AdminAllow(cur realm, addr address) {
917 if !unsafe.OriginSend().IsZero() {
918 panic("garden: admin calls accept no coins")
919 }
920 caller := cur.Previous().Address()
921 if caller != address(adminAddress) {
922 panic("garden: only the admin may manage the allowlist")
923 }
924 if !addr.IsValid() {
925 panic("garden: not a valid address")
926 }
927 allowlist.Set(addr.String(), true)
928 chain.Emit("AdminAllow", "admin", caller.String(), "address", addr.String())
929}
930
931// AdminDisallow removes addr from the allowlist. It does NOT, and cannot, undo a roll already
932// spent: hasRolled is a separate, permanent record, and this function never touches it. Removing
933// an address that was never allowed, or that has already claimed, is a harmless no-op.
934func AdminDisallow(cur realm, addr address) {
935 if !unsafe.OriginSend().IsZero() {
936 panic("garden: admin calls accept no coins")
937 }
938 caller := cur.Previous().Address()
939 if caller != address(adminAddress) {
940 panic("garden: only the admin may manage the allowlist")
941 }
942 allowlist.Remove(addr.String())
943 chain.Emit("AdminDisallow", "admin", caller.String(), "address", addr.String())
944}
945
946// ============================================================================
947// Claim: the one roll. Phase one of two. MINT.md section 10.5 step 1.
948// ============================================================================
949
950// Claim spends the caller's one-and-only roll on this realm and pins a drand round that does
951// not exist yet. It mints NOTHING -- Settle does that, once the pinned round is actually
952// published -- because the whole point of this split is that the result must not be computable,
953// by anyone, including this transaction's own caller, at the moment the roll becomes irrevocable
954// (MINT.md section 10.2: gno.land has no on-chain entropy at all, so anything decidable inside
955// one transaction is decidable by the caller before broadcasting it).
956//
957// WALLET-ONLY, the same reasoning as v4's Adopt: a gnome minted to a realm's address could never
958// be recovered, so a batching, sponsor or multicall realm must never be able to spend a roll on
959// anyone's behalf. The `gnokey maketx run` shape is refused by the identical gate, for the
960// identical reason (IsUserCall is false for both).
961func Claim(cur realm) {
962 if !cur.Previous().IsUserCall() {
963 panic("garden: claim must be called directly by a wallet, not through another realm; the one roll this spends could never be returned to an address that could not hold the resulting gnome")
964 }
965 if !unsafe.OriginSend().IsZero() {
966 panic("garden: claim accepts no coins; the mint is free, exactly as garden/v4's adopt already refuses coins, and nothing here can return them")
967 }
968
969 caller := cur.Previous().Address()
970 if !caller.IsValid() {
971 panic("garden: claim requires a valid caller address")
972 }
973
974 if !allowlist.Has(caller.String()) {
975 panic("garden: this address is not on the allowlist; ask the owner to add it before claiming")
976 }
977
978 if hasRolled.Has(caller.String()) {
979 panic("garden: this address has already rolled on this realm; one roll per wallet, forever, whether or not the resulting gnome is still held")
980 }
981
982 if mintedCount >= batchCap {
983 panic("garden: batch one is closed; all " + strconv.FormatInt(batchCap, 10) + " editions have already been claimed")
984 }
985
986 // CurrentRound() is pure arithmetic over THIS call's own block time (RoundAt(time.Now())),
987 // not an extrapolation from however recently somebody last relayed -- see MINT.md section
988 // 10.4's own live measurement of EstimatedLatestRound() erroring under a stale relay while
989 // CurrentRound() kept working regardless. Pinning pinOffsetRounds past it is therefore safe
990 // against relay staleness; the margin exists only for ordinary block-time/wall-clock skew.
991 round := beacon.CurrentRound() + pinOffsetRounds
992
993 // ---- commit. Nothing below this line can fail. ----
994 hasRolled.Set(caller.String(), true)
995 mintedCount++
996 pendingClaims.Set(caller.String(), &pendingClaim{round: round, claimedAt: time.Now().Unix()})
997
998 chain.Emit("Claim", "claimant", caller.String(), "round", strconv.FormatInt(round, 10))
999}
1000
1001// ============================================================================
1002// Settle: permissionless. Phase two of two. MINT.md section 10.5 step 2. Two entry points, one
1003// shared core -- see the package doc's "SETTLE CAN NOW PAY FOR ITS OWN BEACON RELAY" section for
1004// the full account of why, what it costs, and the two live-chain facts (beacon.Publish panics
1005// rather than no-ops on an already-published round; beacon.Publish is reachable cross-realm as
1006// beacon.Publish(cross(cur), round, sigHex), already proven by this package's own test harness)
1007// that shape of both functions below depends on.
1008// ============================================================================
1009
1010// pendingClaimFor looks up claimant's pending roll, shared by both Settle and
1011// SettleWithSignature so the "no pending claim" message and lookup logic exist exactly once.
1012func pendingClaimFor(claimant address) *pendingClaim {
1013 pcv := pendingClaims.Get(claimant.String())
1014 pc, ok := pcv.(*pendingClaim)
1015 if !ok || pc == nil {
1016 panic("garden: no pending claim for this address; it must Claim first, or this claim has already been settled")
1017 }
1018 return pc
1019}
1020
1021// Settle computes and permanently mints the result of claimant's pending roll, once the round
1022// Claim pinned has actually been published to the beacon by SOMEBODY -- another claimant's own
1023// SettleWithSignature, a relay, anyone. It does not publish anything itself; call
1024// SettleWithSignature instead if the round is not published yet and the caller has its
1025// signature to offer. ANYONE may call this -- the claimant themself, the project's own relayer, a
1026// stranger -- because by the time it can succeed at all, nothing is left to decide: the drand
1027// signature for the pinned round either exists publicly or it does not, and the parts this mints
1028// are a pure function of (that signature, the claimant's own address), fixed the instant the
1029// round is published, not the instant Settle happens to be called. Simulating this call before
1030// calling it for real previews a fact, not a choice -- exactly the property MINT.md section 10.5
1031// names as the whole fix: "reading the result afterward is a free query, same as any other realm
1032// read."
1033//
1034// Refuses coins for the same reason every other non-paying function here does: there is no
1035// banker to return them, and this is a free, permissionless computation, never a payment.
1036func Settle(cur realm, claimant address) {
1037 if !unsafe.OriginSend().IsZero() {
1038 panic("garden: settle accepts no coins; it is a free, permissionless computation, not a payment")
1039 }
1040 if !claimant.IsValid() {
1041 panic("garden: settle requires a valid claimant address")
1042 }
1043
1044 pc := pendingClaimFor(claimant)
1045
1046 if !beacon.Published(pc.round) {
1047 panic("garden: drand round " + strconv.FormatInt(pc.round, 10) + " has not been relayed to the beacon yet; call Settle again once it has, or call SettleWithSignature with the round's drand signature (fetched from drand's own public API) to relay it yourself in this same transaction -- relaying is permissionless, and so is settling")
1048 }
1049
1050 settleCore(claimant, pc)
1051}
1052
1053// SettleWithSignature is Settle, plus: if claimant's pinned round has not been published yet,
1054// this function publishes it ITSELF first, in this same transaction, using sigHex -- the round's
1055// drand signature, which the caller's own app fetches read-only from drand's public API
1056// (https://api.drand.sh/<chain>/public/<round> or any mirror) and passes straight through
1057// unmodified. This is the function a player's app should call once it has fetched a signature;
1058// Settle (above) remains for a caller with no signature to offer, or that already knows (or does
1059// not care) that somebody else has published the round.
1060//
1061// SAFE EITHER WAY THE ROUND TURNS OUT TO BE, which is the one property this function exists to
1062// guarantee and the live chain fact its shape is built around (see the package doc): beacon/v2's
1063// own Publish PANICS, not no-ops, when the round is already published, so this function checks
1064// beacon.Published first and only calls Publish if that check says no. If the round was published
1065// by someone else (another claimant's own SettleWithSignature, a relay, anyone) between the
1066// moment the caller fetched sigHex and the moment this transaction lands, sigHex is simply never
1067// used -- this function still succeeds, exactly as Settle would have. A bad sigHex, by contrast,
1068// is a real failure: beacon.Publish rejects it with its own "beacon: invalid signature" panic,
1069// which aborts this whole call (and the claim stays pending, to be retried with a correct
1070// signature or left for Settle once someone else relays it).
1071//
1072// Refuses coins for the same reason Settle does and every non-paying function here does: there
1073// is no banker to return them, and this is a free, permissionless computation -- the only payment
1074// anywhere in this call is the ordinary GNOT gas the caller's own transaction spends, to the
1075// network, never to this project (MINT.md section 14).
1076func SettleWithSignature(cur realm, claimant address, sigHex string) {
1077 if !unsafe.OriginSend().IsZero() {
1078 panic("garden: settle accepts no coins; it is a free, permissionless computation, not a payment")
1079 }
1080 if !claimant.IsValid() {
1081 panic("garden: settle requires a valid claimant address")
1082 }
1083
1084 pc := pendingClaimFor(claimant)
1085
1086 if !beacon.Published(pc.round) {
1087 // Permissionless and carries no caller-identity check (verified against the live
1088 // deployed beacon/v2 source -- see the package doc): this realm relaying on a player's
1089 // behalf is exactly as valid as the player relaying directly, or anyone else doing so.
1090 beacon.Publish(cross(cur), pc.round, sigHex)
1091 }
1092
1093 settleCore(claimant, pc)
1094}
1095
1096// settleCore is Settle's and SettleWithSignature's shared tail: the draw, the mint, and every
1097// write that follows, once the caller above has already confirmed the pinned round is published.
1098// Takes no `cur realm` because it makes no cross-realm call of its own -- beacon.Randomness and
1099// beacon.Published below are plain reads, not crossing functions, exactly as they always were
1100// before this change.
1101func settleCore(claimant address, pc *pendingClaim) {
1102 randomnessHex := beacon.Randomness(pc.round)
1103
1104 if mintedCount < settledCount+1 {
1105 // Unreachable: Claim never lets mintedCount fall behind settledCount+1 for a claim that
1106 // is about to settle, because mintedCount is incremented before any pendingClaim this
1107 // function could ever read exists. Named so this function is correct on its own terms,
1108 // the same discipline v4's Buy uses for its own unreachable checks.
1109 panic("garden: batch accounting is inconsistent; refusing to mint")
1110 }
1111
1112 // THE NAMED-EDITION PICK. seed % batchCap, against the COMPILE-TIME CONSTANT batchCap, never
1113 // against a shrinking count of what remains -- see the package doc's "flaw found and fixed"
1114 // section for why that distinction is the whole safety property here. namedPick is fixed the
1115 // instant randomnessHex exists (i.e. the instant the pinned round is signed by drand, which
1116 // nobody controls), and WHEN Settle happens to be called after that changes nothing about it.
1117 namedPick := seedFor(randomnessHex, claimant, "slot") % uint64(batchCap)
1118
1119 // The ordinary draw is always computed, unconditionally, whether or not namedPick lands in
1120 // the named range -- so a claimant whose pick collides with an edition someone else already
1121 // settled first has a ready, equally valid fallback rather than needing a second derivation.
1122 eyesSeed := seedFor(randomnessHex, claimant, "eyes")
1123 noseSeed := seedFor(randomnessHex, claimant, "nose")
1124 hatCoatSeed := seedFor(randomnessHex, claimant, "hatcoat")
1125 drawnEyes := int64(drawWeighted(eyesWeights[:], 100, eyesSeed))
1126 drawnNose := int64(drawWeighted(noseWeights[:], 100, noseSeed))
1127 drawnHat := hatOptions[hatCoatSeed%uint64(len(hatOptions))]
1128 drawnCoat := coatOptions[(hatCoatSeed/uint64(len(hatOptions)))%uint64(len(coatOptions))]
1129
1130 character := ""
1131 eyes, nose := drawnEyes, drawnNose
1132 hat, coat := drawnHat, drawnCoat
1133 if namedPick < uint64(numNamedEditions) {
1134 candidate := namedEditionOrder[namedPick]
1135 if !characterOwner.Has(candidate) {
1136 // Whichever Settle call lands on chain first among possibly several colliding
1137 // claimants gets this edition; a later one finds characterOwner already holds it and
1138 // falls through to its own ordinary draw instead. This is a transaction-ordering
1139 // race, not a strategy any claimant can win by choosing WHEN to settle their OWN
1140 // claim -- their own pick is already fixed and cannot change -- see the package doc's
1141 // "a real flaw found and fixed" section for why claimedAt-based tie-breaking was
1142 // considered and rejected, and for the precise property this guarantees instead.
1143 character = candidate
1144 eyes, nose = -1, -1
1145 hat, coat = "", ""
1146 }
1147 }
1148
1149 settledCount++
1150
1151 id := nextID.Next()
1152 tid := grc721.TokenID(id.String())
1153 if err := ledger.Mint(claimant, tid); err != nil {
1154 panic(err)
1155 }
1156
1157 // v6 FIX 1: a named one-of-one is born with its own name; an ordinary gnome is born NAMELESS
1158 // and stays that way until its owner calls SetName. Nothing is chosen at mint time, including
1159 // a name -- `character` here is a pure function of the drand round, not of anything the
1160 // claimant asked for, so assigning the name that goes with it is not a choice either.
1161 //
1162 // The name written here is the DISPLAY form -- "Hob", not the canonical key "hob" that
1163 // `character` is and that characterOwner is keyed by. See namedEditionDisplayNames for why
1164 // those are two strings and why collapsing them into one would break CharacterOwner.
1165 name := ""
1166 if character != "" {
1167 name = namedEditionDisplayName(character)
1168 }
1169
1170 now := time.Now().Unix()
1171 gnomes.Set(tid.String(), &gnome{
1172 hat: hat,
1173 coat: coat,
1174 eyes: eyes,
1175 nose: nose,
1176 character: character,
1177 name: name,
1178 // v6 FIX 2: the drand round that produced this gnome, stored rather than only emitted.
1179 // pc.round is the round Claim pinned and the one beacon.Randomness was just read at, so
1180 // this is the exact number a holder needs to re-derive their own parts from drand's own
1181 // public API and check this realm did not rig them.
1182 settledRound: pc.round,
1183 level: 1,
1184 adoptedAt: now,
1185 belly: meterMax,
1186 bellyAt: now,
1187 cheer: meterMax,
1188 cheerAt: now,
1189 lastActionAt: now,
1190 lastWokenAt: now,
1191 acquiredAt: now,
1192 })
1193
1194 addOwnerToken(claimant, tid.String())
1195 if character != "" {
1196 characterOwner.Set(character, tid.String())
1197 // v6 FIX 1: a named edition's name is taken the instant it mints. reservedNameKeys
1198 // already refused it to everyone else before this moment (that is the pre-mint half of
1199 // the protection -- see its own comment); this write is the post-mint half, so the
1200 // nameOwner index is complete for every living token without exception.
1201 nameOwner.Set(canonicalNameKey(name), tid.String())
1202 } else {
1203 eyesCounts.Set(strconv.FormatInt(eyes, 10), eyesCount(eyes)+1)
1204 noseCounts.Set(strconv.FormatInt(nose, 10), noseCount(nose)+1)
1205 hatCounts.Set(hat, hatCount(hat)+1)
1206 coatCounts.Set(coat, coatCount(coat)+1)
1207 }
1208
1209 grantStartingPurseIfNew(claimant)
1210
1211 // Auto-wake only if this claimant currently has nothing awake at all (never settled or
1212 // bought a gnome before, or sold their only one). Never otherwise: a claimant who already
1213 // has an awake gnome gets this one asleep in their stash, exactly as a purchase would (Buy's
1214 // own comment explains why switching must always be a deliberate Wake, never a side effect).
1215 if !activeToken.Has(claimant.String()) {
1216 activeToken.Set(claimant.String(), tid.String())
1217 }
1218
1219 pendingClaims.Remove(claimant.String())
1220
1221 chain.Emit(
1222 "Settle",
1223 "claimant", claimant.String(),
1224 "tokenId", tid.String(),
1225 "round", strconv.FormatInt(pc.round, 10),
1226 "character", character,
1227 "eyes", strconv.FormatInt(eyes, 10),
1228 "nose", strconv.FormatInt(nose, 10),
1229 "hat", hat,
1230 "coat", coat,
1231 )
1232}
1233
1234// fnv64a is a plain, non-cryptographic 64-bit FNV-1a hash. IT IS NOT THE SOURCE OF
1235// UNPREDICTABILITY HERE -- drand's signature for a not-yet-existent round is, exactly as MINT.md
1236// section 10.5 designs. This exists only to DECORRELATE independent draws (two different
1237// claimants sharing a pinned round, or one claimant's own eyes-draw from their own nose-draw)
1238// from a single public drand value, the same category of use math/rand's PCG(0,0) would be fine
1239// for once combined with a secure external seed -- see MINT.md section 10.5's own list of unsafe
1240// constructions for why math/rand ALONE is not used, and note this is never alone: every call
1241// site below mixes in beacon.Randomness(pc.round), which is the only thing doing real work.
1242func fnv64a(s string) uint64 {
1243 const offset64 = uint64(14695981039346656037)
1244 const prime64 = uint64(1099511628211)
1245 h := offset64
1246 for i := 0; i < len(s); i++ {
1247 h ^= uint64(s[i])
1248 h *= prime64
1249 }
1250 return h
1251}
1252
1253// seedFor derives one independent-looking 64-bit value from the published drand randomness, the
1254// claimant's own address, and a purpose string -- so a single drand round can safely drive
1255// several unrelated draws (which named edition, which eyes, which nose, which hat/coat) for
1256// several different simultaneous claimants without any of them correlating with each other.
1257func seedFor(randomnessHex string, claimant address, purpose string) uint64 {
1258 return fnv64a(randomnessHex + "|" + claimant.String() + "|" + purpose)
1259}
1260
1261// drawWeighted picks an index into weights (which TestWeightTablesSumToOneHundred pins as
1262// summing to totalWeight) using seed as the source of randomness -- a plain cumulative-sum
1263// bucket walk, MINT.md section 10.5's own recommendation for what Settle should do ("a simple,
1264// bounded index... easy to audit"), applied to a weight table instead of a published array,
1265// which is the same shape of arithmetic.
1266func drawWeighted(weights []int64, totalWeight int64, seed uint64) int {
1267 if totalWeight <= 0 {
1268 panic("garden: drawWeighted: totalWeight must be positive")
1269 }
1270 x := int64(seed % uint64(totalWeight))
1271 var cum int64
1272 for i, w := range weights {
1273 cum += w
1274 if x < cum {
1275 return i
1276 }
1277 }
1278 // Unreachable if weights sums to exactly totalWeight, which the test above pins. Returning
1279 // the last index rather than panicking keeps Settle from ever aborting a claimant's one and
1280 // only roll over an arithmetic slip elsewhere in this file.
1281 return len(weights) - 1
1282}
1283
1284// ============================================================================
1285// Wake: switching which gnome is awake. MINT.md section 2a.
1286// ============================================================================
1287
1288// Wake makes tokenID the caller's awake gnome. Free, and limited to once per UTC day -- the same
1289// day-boundary discipline SaveDay's own dailyCareDay already uses, chosen over a GNOT fee for the
1290// reason MINT.md section 2a gives: "a cost that cannot be bought, only lived".
1291func Wake(cur realm, tokenID string) {
1292 if !unsafe.OriginSend().IsZero() {
1293 panic("garden: wake accepts no coins; switching which gnome is awake is free, once per UTC day")
1294 }
1295
1296 if tokenID == genesisTokenID {
1297 panic("garden: the genesis gnome belongs to nobody and can never be woken")
1298 }
1299
1300 caller := cur.Previous().Address()
1301 if !caller.IsValid() {
1302 panic("garden: wake requires a valid caller address")
1303 }
1304
1305 owner, ok := ownerOfToken(tokenID)
1306 if !ok || owner != caller {
1307 panic("garden: you do not own that gnome")
1308 }
1309
1310 if active, hasActive := activeToken.Get(caller.String()).(string); hasActive && active == tokenID {
1311 panic("garden: that gnome is already awake")
1312 }
1313
1314 now := time.Now().Unix()
1315 today := dayNumber(now)
1316 if last, isInt := lastWakeDay.Get(caller.String()).(int64); isInt && last == today {
1317 panic("garden: switching which gnome is awake is limited to once per UTC day; try again tomorrow")
1318 }
1319
1320 // g must exist: ownerOfToken above already confirmed tokenID is a real, owned token.
1321 // Recording lastWokenAt HERE, on the token actually being woken, is the other half of the
1322 // fix for ATTACK-REVIEW.md goal 7 -- see the gnome struct's own comment on the field. The
1323 // token being put to sleep (whichever was active(caller) a moment ago, if any) needs no
1324 // symmetrical write: its own lastActionAt/caredDayCount are already frozen facts the instant
1325 // it stops being the active one (SaveDay can only ever act on activeGnomeForAddr's result),
1326 // and the next time anything reactivates IT, that reactivation (another Wake, a later Buy by
1327 // a new owner, etc.) will set its lastWokenAt correctly at that time, exactly as this call is
1328 // doing now.
1329 g, ok := gnomeByTokenID(tokenID)
1330 if !ok {
1331 panic("garden: that gnome does not exist")
1332 }
1333 g.lastWokenAt = now
1334 gnomes.Set(tokenID, g)
1335
1336 activeToken.Set(caller.String(), tokenID)
1337 lastWakeDay.Set(caller.String(), today)
1338
1339 chain.Emit("Wake", "owner", caller.String(), "tokenId", tokenID)
1340}
1341
1342// ============================================================================
1343// SaveDay: v4's shape, exactly, resolved through the caller's ACTIVE gnome rather than "the"
1344// gnome for that address -- because after mint one/hold many/play one, there no longer is one.
1345// A sleeping gnome is simply never found here: activeGnomeForAddr only ever returns the awake
1346// token, so care applied to "my gnome" always means the one gnome actually allowed to earn
1347// anything (MINT.md section 2a: "a sleeping gnome earns zero -- no cared days, no streak, no
1348// level, no XP").
1349// ============================================================================
1350
1351type saveAction struct {
1352 kind string
1353 at int64
1354 plot int
1355}
1356
1357func SaveDay(cur realm, actionsRaw string) {
1358 if !unsafe.OriginSend().IsZero() {
1359 panic("garden: save day accepts no coins; only Buy takes payment, and nothing else here can return them")
1360 }
1361
1362 caller := cur.Previous().Address()
1363 if !caller.IsValid() {
1364 panic("garden: save day requires a valid caller address")
1365 }
1366
1367 tid, g, ok := activeGnomeForAddr(caller)
1368 if !ok {
1369 panic("garden: no gnome is awake for this address; claim or buy one, or Wake one of your own")
1370 }
1371
1372 now := time.Now().Unix()
1373 actions := parseActions(actionsRaw)
1374
1375 if len(actions) == 0 {
1376 chain.Emit("SaveDay", "owner", caller.String(), "tokenId", tid, "actions", "0", "xpApplied", "0")
1377 return
1378 }
1379
1380 earliestAllowed := now - maxBackfillHours*hourSeconds
1381
1382 // awakeSince: the moment THIS token last became the active one (set by settleCore, Buy, and
1383 // Wake -- see the gnome struct's own comment). ATTACK-REVIEW.md goal 7: without this, a
1384 // token's own earliestAllowed was bounded only by its own lastActionAt and the 48-hour
1385 // horizon, with nothing checking that the backfilled window actually fell inside a period
1386 // this specific token was awake. A token that just became active (whether by a brand-new
1387 // Claim/Settle, a Buy, or an explicit Wake switching away from a sibling in the same stable)
1388 // cannot backfill anything from before that moment -- it was asleep then, and MINT.md /
1389 // DECISIONS.md are both explicit that a sleeping gnome earns zero, full stop, not "zero
1390 // unless a sibling token happens to cover the gap."
1391 awakeSince := g.lastWokenAt
1392 if awakeSince > earliestAllowed {
1393 earliestAllowed = awakeSince
1394 }
1395
1396 firstDay := dayNumber(actions[0].at)
1397 prevAt := g.lastActionAt
1398 if prevAt < earliestAllowed {
1399 prevAt = earliestAllowed
1400 }
1401 for _, a := range actions {
1402 if a.at <= earliestAllowed {
1403 if a.at <= awakeSince {
1404 panic("garden: this action predates the last time this gnome was woken; a sleeping gnome earns nothing for the time it was asleep")
1405 }
1406 panic("garden: this action is more than " + strconv.FormatInt(maxBackfillHours, 10) + " hours old; care can only be backfilled for the last " + strconv.FormatInt(maxBackfillHours, 10) + " hours, not longer absences")
1407 }
1408 if a.at <= prevAt {
1409 panic("garden: action timestamp must be strictly after the last saved action")
1410 }
1411 if a.at > now {
1412 panic("garden: action timestamp cannot be in the future")
1413 }
1414 if dayNumber(a.at) != firstDay {
1415 panic("garden: every action in one SaveDay call must fall on the same UTC day")
1416 }
1417 prevAt = a.at
1418 }
1419
1420 work := *g
1421 acorns := balanceOf(caller)
1422 spentThisCall := false
1423
1424 gateWaived := acorns < acornReserve && !anyPlotPlanted(g)
1425 rawCareXp := int64(0)
1426 tinkeredThisCall := false
1427
1428 for _, a := range actions {
1429 switch a.kind {
1430 case actionPat:
1431 if !canPat(work.lastPatAt, a.at, patCooldownHours) {
1432 panic("garden: pat must be at least " + strconv.FormatInt(patCooldownHours, 10) + " hours after the last one")
1433 }
1434 work.lastPatAt = a.at
1435 work.lastHappyEventAt = a.at
1436 work.cheer = clampMeter(meterNow(work.cheer, work.cheerAt, a.at, cheerDropEveryHours) + patCheer)
1437 work.cheerAt = a.at
1438 rawCareXp += xpPat
1439
1440 case actionFeed:
1441 if acorns < feedCost {
1442 panic("garden: not enough acorns to feed")
1443 }
1444 acorns -= feedCost
1445 spentThisCall = true
1446 work.belly = clampMeter(meterNow(work.belly, work.bellyAt, a.at, bellyDropEveryHours) + feedBelly)
1447 work.bellyAt = a.at
1448 work.lastHappyEventAt = a.at
1449 rawCareXp += xpFeed
1450
1451 case actionPlant:
1452 waived := gateWaived && acorns < acornReserve
1453 if !waived && meterNow(work.belly, work.bellyAt, a.at, bellyDropEveryHours) <= hungryAtOrBelow {
1454 panic("garden: too hungry to garden; feed first")
1455 }
1456 p := &work.plots[a.plot]
1457 if p.plantedAt != 0 {
1458 panic("garden: that plot is already planted")
1459 }
1460 if acorns < plantCost {
1461 panic("garden: not enough acorns to plant")
1462 }
1463 acorns -= plantCost
1464 spentThisCall = true
1465 p.plantedAt = a.at
1466 p.readyAt = a.at + growHours*hourSeconds
1467
1468 case actionHarvest:
1469 p := &work.plots[a.plot]
1470 if p.plantedAt == 0 {
1471 panic("garden: that plot has nothing to harvest")
1472 }
1473 if a.at < p.readyAt {
1474 panic("garden: that plot is not ready to harvest yet")
1475 }
1476 p.plantedAt = 0
1477 p.readyAt = 0
1478 acorns += harvestPerPlot
1479 work.xpGarden += xpHarvestPerPlot
1480 work.harvestCount++
1481 rawCareXp += xpHarvestPerPlot
1482
1483 case actionTinker:
1484 if tinkeredThisCall {
1485 panic("garden: only one tinker task per day")
1486 }
1487 if work.lastTinkerAt != 0 && dayNumber(work.lastTinkerAt) == dayNumber(a.at) {
1488 panic("garden: already did a tinker task today")
1489 }
1490 if acorns < tinkerCost {
1491 panic("garden: not enough acorns to tinker")
1492 }
1493 acorns -= tinkerCost
1494 spentThisCall = true
1495 work.xpTinker += xpTinkerTask
1496 work.lastTinkerAt = a.at
1497 tinkeredThisCall = true
1498 rawCareXp += xpTinkerTask
1499
1500 default:
1501 panic("garden: unknown action kind")
1502 }
1503 }
1504
1505 if spentThisCall && acorns < acornReserve && !anyPlotPlanted(&work) {
1506 panic("garden: that would leave fewer than " + strconv.FormatInt(acornReserve, 10) + " acorns with nothing planted, and a gnome with no acorns and no garden can never earn another; plant first, or keep " + strconv.FormatInt(acornReserve, 10) + " back")
1507 }
1508
1509 latestActionAt := actions[len(actions)-1].at
1510 bellyAtEnd := meterNow(work.belly, work.bellyAt, latestActionAt, bellyDropEveryHours)
1511 mood := moodNow(bellyAtEnd, work.lastPatAt, work.lastHappyEventAt, work.adoptedAt, latestActionAt, hungryAtOrBelow)
1512
1513 adjustedXp := rawCareXp
1514 switch mood {
1515 case moodHappy:
1516 adjustedXp = adjustedXp * (100 + happyBonusPct) / 100
1517 case moodSulky:
1518 adjustedXp = adjustedXp * (100 - sulkyPenaltyPct) / 100
1519 }
1520
1521 if work.dailyCareDay != firstDay {
1522 work.dailyCareDay = firstDay
1523 work.dailyCareXp = 0
1524 }
1525 remainingToday := dailyCareCap - work.dailyCareXp
1526 if remainingToday < 0 {
1527 remainingToday = 0
1528 }
1529 if adjustedXp > remainingToday {
1530 adjustedXp = remainingToday
1531 }
1532 work.dailyCareXp += adjustedXp
1533
1534 work.totalXp += adjustedXp
1535 work.level = levelFromXp(work.totalXp)
1536
1537 // At most ONE of this owner's tokens may ever bank a given UTC day as cared-for -- see
1538 // lastCaredDayForOwner's own comment. Without this, Wake (once per day, but still once)
1539 // lets an owner genuinely care for A earlier today, switch to B, and genuinely care for B
1540 // too, banking the SAME calendar day on both from nothing but real, non-backfilled
1541 // timestamps -- the live-switch half of ATTACK-REVIEW.md goal 7 that lastWokenAt's backfill
1542 // floor does not by itself prevent. XP, acorns, feeding, planting and harvesting are
1543 // deliberately NOT gated here: those are this token's own resource mechanics (already
1544 // bounded per-gnome by dailyCareCap) and giving B real care today is still real care: only
1545 // the CARED-DAY LEDGER -- the thing lockCaredDays and the public streak actually count -- is
1546 // restricted to one credit per owner per day.
1547 if lastOwnerDay, ok := lastCaredDayForOwner.Get(caller.String()).(int64); !ok || lastOwnerDay != firstDay {
1548 if recordCaredDay(&work, firstDay) {
1549 lastCaredDayForOwner.Set(caller.String(), firstDay)
1550 }
1551 }
1552 work.lastActionAt = latestActionAt
1553
1554 setBalance(caller, acorns)
1555 *g = work
1556 gnomes.Set(tid, g)
1557
1558 chain.Emit(
1559 "SaveDay",
1560 "owner", caller.String(),
1561 "tokenId", tid,
1562 "actions", strconv.Itoa(len(actions)),
1563 "xpApplied", strconv.FormatInt(adjustedXp, 10),
1564 "mood", mood,
1565 )
1566}
1567
1568// ============================================================================
1569// ChooseType: v4's shape, resolved through the active gnome.
1570// ============================================================================
1571
1572func ChooseType(cur realm, kind string) {
1573 if !unsafe.OriginSend().IsZero() {
1574 panic("garden: choose type accepts no coins; only Buy takes payment, and nothing else here can return them")
1575 }
1576
1577 caller := cur.Previous().Address()
1578 if !caller.IsValid() {
1579 panic("garden: choose type requires a valid caller address")
1580 }
1581
1582 tid, g, ok := activeGnomeForAddr(caller)
1583 if !ok {
1584 panic("garden: no gnome is awake for this address")
1585 }
1586
1587 if g.gnomeType != "" {
1588 panic("garden: this gnome's calling is already chosen and cannot be changed")
1589 }
1590
1591 level := levelFromXp(g.totalXp)
1592 if level < typeAtLevel {
1593 panic("garden: a calling can only be chosen at level " + strconv.FormatInt(typeAtLevel, 10) + " or above")
1594 }
1595
1596 if kind != typeGardener && kind != typeExplorer && kind != typeTinkerer {
1597 panic("garden: a calling is one of \"" + typeGardener + "\", \"" + typeExplorer + "\" or \"" + typeTinkerer + "\"")
1598 }
1599
1600 work := *g
1601 work.gnomeType = kind
1602 work.level = level
1603 *g = work
1604 gnomes.Set(tid, g)
1605
1606 chain.Emit("ChooseType", "owner", caller.String(), "tokenId", tid, "type", kind)
1607}
1608
1609// ============================================================================
1610// v6 FIX 1: SetName. THE ONLY NEW WRITE SURFACE IN THIS WHOLE FILE RELATIVE TO v5.
1611//
1612// WHY IT IS A SEPARATE FUNCTION AND NOT A PARAMETER ON Claim OR Settle, which is the first
1613// thing a reader will wonder and the one design question here that is already settled: the mint
1614// is a ROLL, and the whole safety property of the two-phase roll (MINT.md section 10.5, and this
1615// file's own package doc at length) is that the claimant does not and cannot choose what comes
1616// out of it. A name parameter on Claim would not technically break that -- a name does not
1617// influence the draw -- but it would blur the one sentence the product has to be able to say
1618// without an asterisk ("you do not choose what you get"), and it would mean a claimant has to
1619// have decided on a name at the exact moment they are least able to: before they have any idea
1620// what they are naming. Naming what you GOT is a different act from getting it, so it is a
1621// different function, called later, by the owner, as many times as they like.
1622//
1623// ONLY THE CURRENT OWNER. Not the original claimant -- the CURRENT owner. A gnome that has been
1624// sold belongs to its buyer, and so does its name; the seller loses the ability to rename it at
1625// the same instant they lose the token, through the same ownerOfToken check every other
1626// owner-gated function in this file uses (Wake, List). There is no admin override: this realm's
1627// admin can gate issuance and nothing else (see AdminAllow's own comment), and a name is not
1628// issuance.
1629// ============================================================================
1630
1631// SetName names tokenID, which the caller must currently own, or RENAMES it. Free, unlimited,
1632// and refused for the three named one-of-ones and the genesis gnome.
1633//
1634// RENAMING IS ALLOWED, NOT ONE-SHOT, and this is a deliberate decision with a named trade-off
1635// rather than an oversight. On an immutable realm a one-shot name means a typo is forever, and
1636// "my gnome is called Fenncik" is a worse permanent outcome than "somebody changed their mind".
1637// Aavegotchi, the closest prior art this project has looked at, allows renaming. What it costs:
1638// a name is not a stable identifier over time, so nothing anywhere -- in this realm, in the
1639// adventure realm, or in the app -- may ever key anything on a name. tokenID is the identifier;
1640// the name is a label. (The nameOwner index is keyed BY name only to answer "is this taken",
1641// never to identify a gnome; every function here looks tokens up by tokenID.)
1642//
1643// Refuses coins for the same reason every other non-paying function here does: there is no
1644// banker to return them, and naming your own gnome is free (MINT.md section 14 -- batch one is
1645// free end to end, and this is not a new place to charge).
1646func SetName(cur realm, tokenID string, name string) {
1647 if !unsafe.OriginSend().IsZero() {
1648 panic("garden: set name accepts no coins; naming your own gnome is free, and nothing here can return them")
1649 }
1650
1651 // Checked FIRST and by name, before the ownership lookup that would also refuse it: the
1652 // genesis gnome belongs to nobody, so there is no caller for whom the owner check could ever
1653 // pass, but saying so explicitly is this file's established discipline for it (List, Buy and
1654 // Wake all do the same) and it gives a reader of the panic the real reason rather than a
1655 // misleading "you do not own that gnome".
1656 if tokenID == genesisTokenID {
1657 panic("garden: the genesis gnome belongs to nobody and can never be renamed")
1658 }
1659
1660 caller := cur.Previous().Address()
1661 if !caller.IsValid() {
1662 panic("garden: set name requires a valid caller address")
1663 }
1664
1665 owner, ok := ownerOfToken(tokenID)
1666 if !ok || owner != caller {
1667 panic("garden: you do not own that gnome")
1668 }
1669
1670 g, isGnome := gnomeByTokenID(tokenID)
1671 if !isGnome {
1672 panic("garden: that tokenID does not exist")
1673 }
1674
1675 // THE THREE NAMED ONE-OF-ONES KEEP THEIR CHARACTER NAME, PERMANENTLY. Hob is Hob; that is
1676 // the entire point of a cap-one edition, and an owner who could rename Hob to "xXx" would be
1677 // destroying the thing they were lucky enough to roll, irreversibly, for everyone who comes
1678 // after them. This also closes the obvious way around the reservation: if a named edition
1679 // could be renamed, its own canonical key would be freed by the rename (SetName's commit
1680 // block frees the old key by design -- see nameOwner's comment) and "hob" would become
1681 // takeable by an ordinary gnome even though reservedNameKeys still lists it, because
1682 // reservation is checked against the NEW name, never the freed one. Refusing the rename
1683 // outright is what keeps those two mechanisms from interacting.
1684 if g.character != "" {
1685 panic("garden: " + g.character + " is a named one-of-one and keeps its own name permanently; only ordinary gnomes can be named")
1686 }
1687
1688 // A LISTED GNOME CANNOT BE RENAMED, because the seller still owns it right up until the
1689 // instant Buy lands and every guard above would therefore pass. THE ATTACK: Alice names
1690 // token A "Pebble" and lists it. Bob reads the name, broadcasts Buy(A) with the full price.
1691 // Before Bob's transaction lands, Alice calls SetName(A, "Junk") -- she is still the owner,
1692 // so nothing refuses her -- and then SetName(B, "Pebble") on a second token she keeps, which
1693 // the rename just freed the canonical key for (see the commit block below: the old key is
1694 // released by design). Bob's Buy still succeeds, at the agreed price, for a gnome now called
1695 // "Junk", and "Pebble" is permanently out of his reach because names are unique and
1696 // first-come. Buy cannot defend itself here: it never reads g.name and takes no expected-name
1697 // argument, so there is nothing for it to compare. Refusing the rename while a listing stands
1698 // is what makes the name a buyer reads part of what they are actually buying.
1699 //
1700 // The test is listingFor, the SAME predicate Cancel uses for "is this gnome for sale" -- not
1701 // a second notion of "listed" that could drift out of step with the marketplace's own. It is
1702 // deliberately presence-based rather than presence-plus-unexpired: an expired listing is
1703 // unbuyable (Buy refuses it) so renaming under one is harmless, but copying Buy's inline
1704 // expiry comparison here would be a second copy of a liveness rule that could later drift,
1705 // and refusing slightly too much costs the owner one Cancel call while refusing slightly too
1706 // little reopens the hole on an immutable realm.
1707 if _, isListed := listingFor(tokenID); isListed {
1708 panic("garden: that gnome is listed for sale and cannot be renamed while a buyer may already have a purchase in flight; cancel the listing first, then rename it")
1709 }
1710
1711 // All validation and every refusal happens in here, before any write below.
1712 assertNameAssignable(name, tokenID)
1713
1714 // ---- commit. Nothing below this line can fail. ----
1715
1716 // FREE THE OLD KEY BEFORE TAKING THE NEW ONE. Required, not tidiness -- see nameOwner's own
1717 // comment: without this, one token could hoard every name in the collection by renaming
1718 // repeatedly. Order matters for one specific case: renaming a gnome to a different
1719 // capitalisation of the name it already has ("fennick" -> "Fennick") canonicalises to the
1720 // SAME key, so removing first and setting second is the only order that does not either
1721 // delete the key it just wrote or refuse a legal, harmless re-capitalisation.
1722 if g.name != "" {
1723 nameOwner.Remove(canonicalNameKey(g.name))
1724 }
1725 nameOwner.Set(canonicalNameKey(name), tokenID)
1726
1727 previous := g.name
1728 g.name = name
1729 gnomes.Set(tokenID, g)
1730
1731 chain.Emit(
1732 "SetName",
1733 "owner", caller.String(),
1734 "tokenId", tokenID,
1735 "name", name,
1736 "previousName", previous,
1737 )
1738}
1739
1740// assertNameAssignable is SetName's refusal gate: it panics with nameAssignabilityProblem's
1741// message, or returns normally if name may be assigned to tokenID. The rules themselves are in
1742// nameAssignabilityProblem, not here, so the free NameAvailability query and this enforcing path
1743// can never disagree about what is allowed -- there is exactly one copy.
1744func assertNameAssignable(name string, tokenID string) {
1745 if problem := nameAssignabilityProblem(name, tokenID); problem != "" {
1746 panic(problem)
1747 }
1748}
1749
1750// nameAssignabilityProblem is THE one copy of the naming rules. It returns "" if name may be
1751// assigned to tokenID, or the exact player-meaningful message explaining which rule refused it.
1752//
1753// IT RETURNS ITS REFUSAL RATHER THAN PANICKING IT so that NameAvailability can offer the same
1754// answer as a free read without any recover() -- see NameAvailability's own note on why recover
1755// is avoided on this toolchain.
1756//
1757// ORDER IS DELIBERATE AND MATCHES app/js/config.js's nameError, which mirrors v4's realm order:
1758// length, then charset, then visible content, then (new in v6) reservation, then uniqueness. A
1759// name that fails several rules reports the first, so the app's own message and the realm's
1760// refusal always name the SAME rule for the same input rather than disagreeing about which
1761// problem is the problem.
1762func nameAssignabilityProblem(name string, tokenID string) string {
1763 if !validNameLength(name) {
1764 return "garden: name must be 1-" + strconv.Itoa(maxNameLen) + " characters"
1765 }
1766
1767 // Checked before the general charset refusal purely so the message is useful: iOS "smart
1768 // punctuation" is ON BY DEFAULT and silently rewrites a straight apostrophe to U+2018/U+2019
1769 // and a hyphen to U+2013/U+2014 (app/js/config.js's third audit round, finding Y8). A player
1770 // who typed "O'Hare" on an iPhone did not type anything strange, and telling them their name
1771 // "contains a character that is not an allowed letter" would be true but useless.
1772 //
1773 // THIS IS A REFUSAL, NOT A TRANSFORM, AND THAT IS THE POINT. config.js's normalizeName folds
1774 // those four code points back to ASCII in the BROWSER, before submitting -- a narrowing
1775 // transform whose own comment notes "the realm remains the sole authority". This realm
1776 // deliberately does NOT fold them itself: a name is now a reserved, unique, first-come
1777 // resource, so silently rewriting what somebody signed for would mean the key they got is not
1778 // the key they asked for, and two players could race for a name neither of them typed.
1779 // Refusing and naming the reason keeps the realm's accepted set exactly as narrow as v4's
1780 // while still telling an iPhone player what happened.
1781 if hasSmartPunctuation(name) {
1782 return "garden: name contains curly quotes or dashes, which a phone keyboard may have substituted for a plain apostrophe or hyphen; retype it with a straight ' or -"
1783 }
1784
1785 if !validNameCharset(name) {
1786 return "garden: name contains a character that is not an allowed letter, digit, space, hyphen or apostrophe"
1787 }
1788
1789 if !hasVisibleNameContent(name) {
1790 return "garden: name must contain at least one visible character"
1791 }
1792
1793 key := canonicalNameKey(name)
1794
1795 // RESERVATION. An ordinary gnome may not be named after a cap-one edition or the genesis
1796 // gnome, whether or not that edition has minted yet -- see reservedNameKeys' own comment for
1797 // why this is not already covered by the uniqueness check below.
1798 for _, reserved := range reservedNameKeys {
1799 if key == reserved {
1800 return "garden: \"" + name + "\" is reserved for a named one-of-one and cannot be taken by an ordinary gnome"
1801 }
1802 }
1803
1804 // UNIQUENESS. Checked against the CANONICAL key, so case and spacing variants of a taken name
1805 // are refused too -- the cheapest impersonation attempt there is.
1806 //
1807 // The `holder != tokenID` test is what makes a HARMLESS self-rename legal: re-capitalising
1808 // your own gnome's own name ("fennick" -> "Fennick") canonicalises to a key you already hold,
1809 // and refusing that as "already taken" would be refusing you your own name. Callers who want
1810 // the general "is this free for anybody" question pass tokenID "" (NameAvailability's own
1811 // documented shape), which can never equal a real tokenID, so nothing is accidentally
1812 // exempted by it.
1813 if holder, taken := nameOwnerOf(key); taken && holder != tokenID {
1814 return "garden: the name \"" + name + "\" is already taken by gnome " + holder + "; names are unique across the collection"
1815 }
1816
1817 return ""
1818}
1819
1820// ============================================================================
1821// SALE: List/Cancel/Buy. v4's shape, DESIGN.md section 9's reasoning unchanged, minus the
1822// one-gnome-per-address refusal in Buy (MINT.md section 2a: removed from Buy, never from Claim)
1823// and plus a tokenID parameter on List/Cancel, because an owner may now have more than one
1824// gnome to choose among, and plus the lockCaredDays check on the three named one-of-ones.
1825// ============================================================================
1826
1827// List offers tokenID, which the caller must own, for sale. The lock: a named one-of-one
1828// (character != "") cannot be listed until it has lockCaredDays cared days; an ordinary gnome
1829// has no such restriction, trading from the moment it is minted (MINT.md section 12/13).
1830func List(cur realm, tokenID string, priceUgnot int64, buyer address, days int64) {
1831 if !unsafe.OriginSend().IsZero() {
1832 panic("garden: list accepts no coins; only Buy takes payment")
1833 }
1834
1835 if tokenID == genesisTokenID {
1836 panic("garden: the genesis gnome belongs to nobody and can never be listed")
1837 }
1838
1839 caller := cur.Previous().Address()
1840 if !caller.IsValid() {
1841 panic("garden: list requires a valid caller address")
1842 }
1843
1844 owner, ok := ownerOfToken(tokenID)
1845 if !ok || owner != caller {
1846 panic("garden: you do not own that gnome")
1847 }
1848
1849 gv := gnomes.Get(tokenID)
1850 g, isGnome := gv.(*gnome)
1851 if !isGnome || g == nil {
1852 panic("garden: that tokenID does not exist")
1853 }
1854
1855 if g.character != "" && g.caredDayCount < lockCaredDays {
1856 panic("garden: " + g.character + " is one of the three named one-of-ones and cannot be listed until it has " +
1857 strconv.FormatInt(lockCaredDays, 10) + " cared days; it has " + strconv.FormatInt(g.caredDayCount, 10))
1858 }
1859
1860 if priceUgnot < 0 {
1861 panic("garden: a price cannot be negative")
1862 }
1863 if priceUgnot > maxPriceUgnot {
1864 panic("garden: price exceeds the maximum of " + strconv.FormatInt(maxPriceUgnot, 10) + " ugnot")
1865 }
1866 if days < 1 || days > maxListingDays {
1867 panic("garden: a listing lasts between 1 and " + strconv.FormatInt(maxListingDays, 10) + " days")
1868 }
1869
1870 buyer = address(lowerASCII(string(buyer)))
1871 if buyer != address("") {
1872 if !buyer.IsValid() {
1873 panic("garden: reserved buyer is not a valid address; pass an empty address to let anyone buy")
1874 }
1875 if buyer == caller {
1876 panic("garden: you cannot reserve your own gnome for yourself")
1877 }
1878 }
1879
1880 now := time.Now().Unix()
1881 listings.Set(tokenID, &listing{
1882 seller: caller,
1883 priceUgnot: priceUgnot,
1884 buyer: buyer,
1885 listedAt: now,
1886 expiresAt: now + days*daySeconds,
1887 })
1888
1889 feeUgnot := feeFor(priceUgnot)
1890 chain.Emit(
1891 "List",
1892 "seller", caller.String(),
1893 "tokenId", tokenID,
1894 "priceUgnot", strconv.FormatInt(priceUgnot, 10),
1895 "feeUgnot", strconv.FormatInt(feeUgnot, 10),
1896 "totalUgnot", strconv.FormatInt(priceUgnot+feeUgnot, 10),
1897 "buyer", buyer.String(),
1898 "expiresAt", strconv.FormatInt(now+days*daySeconds, 10),
1899 )
1900}
1901
1902// Cancel withdraws the caller's own listing on tokenID. Only the seller who created it may.
1903func Cancel(cur realm, tokenID string) {
1904 if !unsafe.OriginSend().IsZero() {
1905 panic("garden: cancel accepts no coins; only Buy takes payment")
1906 }
1907
1908 caller := cur.Previous().Address()
1909 if !caller.IsValid() {
1910 panic("garden: cancel requires a valid caller address")
1911 }
1912
1913 l, ok := listingFor(tokenID)
1914 if !ok {
1915 panic("garden: that gnome is not for sale")
1916 }
1917 if l.seller != caller {
1918 panic("garden: only the seller can cancel their own listing")
1919 }
1920
1921 listings.Remove(tokenID)
1922 chain.Emit("Cancel", "seller", caller.String(), "tokenId", tokenID)
1923}
1924
1925// Buy purchases the listed gnome tokenID. v4's validate-then-commit shape, unchanged, MINUS the
1926// one-gnome-per-address refusal: MINT.md section 2a removes the hold cap from Buy specifically,
1927// and only from Buy -- Claim's hasRolled gate is the cap that still matters, and this function
1928// never touches it.
1929func Buy(cur realm, tokenID string) {
1930 if !cur.Previous().IsUserCall() {
1931 panic("garden: buy must be called directly by a wallet, not through another realm; the coins attached to a transaction belong to the realm the wallet called")
1932 }
1933 buyer := cur.Previous().Address()
1934 if !buyer.IsValid() {
1935 panic("garden: buy requires a valid caller address")
1936 }
1937
1938 if tokenID == genesisTokenID {
1939 panic("garden: the genesis gnome belongs to nobody and can never be bought")
1940 }
1941
1942 l, ok := listingFor(tokenID)
1943 if !ok {
1944 panic("garden: that gnome is not for sale")
1945 }
1946
1947 now := time.Now().Unix()
1948 if now > l.expiresAt {
1949 panic("garden: that listing has expired; the seller must list again")
1950 }
1951 if l.seller == buyer {
1952 panic("garden: you cannot buy your own gnome")
1953 }
1954 if l.buyer != address("") && l.buyer != buyer {
1955 panic("garden: that gnome is reserved for a different buyer")
1956 }
1957
1958 tid := grc721.TokenID(tokenID)
1959 owner, err := token.OwnerOf(tid)
1960 if err != nil || owner != l.seller {
1961 panic("garden: that listing is stale; the seller no longer owns that gnome")
1962 }
1963 gv := gnomes.Get(tokenID)
1964 g, isGnome := gv.(*gnome)
1965 if !isGnome || g == nil {
1966 panic("garden: that listing names a gnome this realm does not hold")
1967 }
1968
1969 feeUgnot := feeFor(l.priceUgnot)
1970 total := l.priceUgnot + feeUgnot
1971 send := unsafe.OriginSend()
1972 if !exactUgnot(send, total) {
1973 panic("garden: buy requires exactly " + strconv.FormatInt(total, 10) + ugnotDenom +
1974 " attached (" + strconv.FormatInt(l.priceUgnot, 10) + " price + " +
1975 strconv.FormatInt(feeUgnot, 10) + " fee); got " + coinsString(send))
1976 }
1977
1978 // ---- commit. Nothing below this line can fail on chain. ----
1979
1980 transferGate = tokenID
1981 if err := ledger.TransferFrom(l.seller, l.seller, buyer, tid); err != nil {
1982 panic(err)
1983 }
1984 transferGate = ""
1985
1986 removeOwnerToken(l.seller, tokenID)
1987 addOwnerToken(buyer, tokenID)
1988 listings.Remove(tokenID)
1989
1990 // Active-token bookkeeping (mint one, hold many, play one). If this was the seller's awake
1991 // gnome, they fall asleep entirely rather than another of their gnomes quietly becoming
1992 // active -- switching is always a deliberate Wake, never a side effect of a sale. If the
1993 // buyer currently has nothing awake at all, this purchase becomes their active gnome
1994 // automatically, so a first-time buyer is never left with nothing playable.
1995 if av, isActive := activeToken.Get(l.seller.String()).(string); isActive && av == tokenID {
1996 activeToken.Remove(l.seller.String())
1997 }
1998 if !activeToken.Has(buyer.String()) {
1999 activeToken.Set(buyer.String(), tokenID)
2000 }
2001
2002 settled := int64(0)
2003 for i := 0; i < numPlots; i++ {
2004 p := &g.plots[i]
2005 if p.plantedAt == 0 {
2006 continue
2007 }
2008 if now >= p.readyAt {
2009 settled += harvestPerPlot
2010 } else {
2011 settled += plantCost
2012 }
2013 p.plantedAt = 0
2014 p.readyAt = 0
2015 }
2016 if settled > 0 {
2017 setBalance(l.seller, balanceOf(l.seller)+settled)
2018 }
2019
2020 g.acquiredAt = now
2021 g.saleCount++
2022 g.lastActionAt = now
2023 // lastWokenAt resets here too, same as lastActionAt, whether or not this purchase becomes
2024 // the buyer's active gnome below -- if it does not (buyer already has something awake), this
2025 // value is simply overwritten by the eventual explicit Wake that does activate it. Either
2026 // way, nothing the SELLER (or anyone else) did with this token before the sale can be
2027 // backfilled by the BUYER afterward: SaveDay's floor cannot reach earlier than this moment.
2028 g.lastWokenAt = now
2029 gnomes.Set(tokenID, g)
2030
2031 grantStartingPurseIfNew(buyer)
2032
2033 bank := banker.NewBanker(banker.BankerTypeOriginSend, cur)
2034 me := cur.Address()
2035 if l.priceUgnot > 0 {
2036 bank.SendCoins(me, l.seller, chain.Coins{{Denom: ugnotDenom, Amount: l.priceUgnot}})
2037 }
2038 bank.SendCoins(me, fee.recipient, chain.Coins{{Denom: ugnotDenom, Amount: feeUgnot}})
2039
2040 chain.Emit(
2041 "Sale",
2042 "tokenId", tokenID,
2043 "seller", l.seller.String(),
2044 "buyer", buyer.String(),
2045 "priceUgnot", strconv.FormatInt(l.priceUgnot, 10),
2046 "feeUgnot", strconv.FormatInt(feeUgnot, 10),
2047 "feeRecipient", fee.recipient.String(),
2048 "settledAcorns", strconv.FormatInt(settled, 10),
2049 )
2050}
2051
2052// ============================================================================
2053// Readers
2054// ============================================================================
2055
2056func Listing(tokenID string) (seller address, priceUgnot int64, buyer address, listedAtUnix, expiresAtUnix, feeUgnot, totalUgnot int64, found bool) {
2057 l, ok := listingFor(tokenID)
2058 if !ok {
2059 return address(""), 0, address(""), 0, 0, 0, 0, false
2060 }
2061 fee := feeFor(l.priceUgnot)
2062 return l.seller, l.priceUgnot, l.buyer, l.listedAt, l.expiresAt, fee, l.priceUgnot + fee, true
2063}
2064
2065func TotalListings() int64 {
2066 return int64(listings.Size())
2067}
2068
2069func ListingsPage(offset, limit int) []string {
2070 if offset < 0 {
2071 panic("garden: offset must not be negative")
2072 }
2073 if limit <= 0 {
2074 panic("garden: limit must be positive")
2075 }
2076 if limit > maxListingsPageSize {
2077 limit = maxListingsPageSize
2078 }
2079 tokenIDs := make([]string, 0, limit)
2080 listings.IterateByOffset(offset, limit, func(key string, value any) bool {
2081 tokenIDs = append(tokenIDs, key)
2082 return false
2083 })
2084 return tokenIDs
2085}
2086
2087func QuoteFee(priceUgnot int64) (feeUgnot, totalUgnot int64) {
2088 f := feeFor(priceUgnot)
2089 return f, priceUgnot + f
2090}
2091
2092func FeeRules() string {
2093 return "saleFeeRateBps=" + strconv.FormatInt(fee.rateBps, 10) +
2094 ";saleFeeFloorUgnot=" + strconv.FormatInt(fee.floorUgnot, 10) +
2095 ";saleFeeRecipient=" + fee.recipient.String()
2096}
2097
2098func Provenance(tokenID string) (adoptedAtUnix, acquiredAtUnix, saleCount int64, found bool) {
2099 g, ok := gnomeByTokenID(tokenID)
2100 if !ok {
2101 return 0, 0, 0, false
2102 }
2103 return g.adoptedAt, g.acquiredAt, g.saleCount, true
2104}
2105
2106// ---- v6's new readers. FIVE additions, every one of them read-only. The existing readers'
2107// SIGNATURES ARE ALL UNCHANGED FROM v5 ON PURPOSE, including Provenance's and GnomeByToken's,
2108// even though the round and the name would both have fitted naturally into them: the app already
2109// reads v5's shapes, and widening a tuple return breaks every existing caller for no gain that a
2110// dedicated reader does not already give. Reads are free and unmetered, so "one more query" costs
2111// a caller nothing; a changed signature costs them a rewrite.
2112
2113// Name returns tokenID's name, or found=false if there is no such token.
2114//
2115// A name of "" is a REAL, EXPECTED ANSWER, not an error: it means this gnome has not been named
2116// yet, which is the state every ordinary gnome mints in. found reports whether the TOKEN exists,
2117// never whether it has a name -- check the string for that.
2118func Name(tokenID string) (name string, found bool) {
2119 g, ok := gnomeByTokenID(tokenID)
2120 if !ok {
2121 return "", false
2122 }
2123 return g.name, true
2124}
2125
2126// NameOwner resolves a name to the tokenID currently carrying it, matching the same way SetName
2127// refuses duplicates: on the canonical form, so any capitalisation or spacing of a taken name
2128// finds it. This is the uniqueness index read back, and the honest answer to "who is Fennick".
2129func NameOwner(name string) (tokenID string, found bool) {
2130 return nameOwnerOf(canonicalNameKey(name))
2131}
2132
2133// NameAvailability answers "would SetName accept this name, and if not why" WITHOUT a transaction
2134// -- a free query against the same assertNameAssignable the write path uses, so the realm itself
2135// is the authority the app checks against instead of a second copy of the rules that can drift
2136// from it. reason is "" when ok is true, and the realm's own refusal message otherwise.
2137//
2138// The tokenID argument matters for exactly one case: a name is available TO THE TOKEN THAT
2139// ALREADY HOLDS IT (re-capitalising your own gnome's name). Pass "" to ask the general question
2140// "is this name free for somebody new", which is what an app naming a fresh gnome wants.
2141//
2142// THIS IS A CONVENIENCE, NOT THE AUTHORITY, and the distinction is load-bearing: a true answer
2143// here can be made false by somebody else's transaction landing first. SetName re-checks
2144// everything itself, always -- this function cannot be used to skip a check, only to avoid
2145// wasting a player's gas on a refusal that was already knowable.
2146//
2147// NOTE ON SHAPE, because the obvious implementation is a trap on this toolchain: this does NOT
2148// call SetName's validator and recover() from its panic. `recover()` does not reliably catch a
2149// panic across a realm boundary in Gno (MEMORY.md records this costing this project real time),
2150// and a reader should not have to reason about whether a same-realm call is the exception. So the
2151// rules live in nameAssignabilityProblem, which RETURNS its refusal instead of panicking it, and
2152// both this reader and assertNameAssignable call that one copy. No recover anywhere.
2153func NameAvailability(name string, tokenID string) (ok bool, reason string) {
2154 reason = nameAssignabilityProblem(name, tokenID)
2155 return reason == "", reason
2156}
2157
2158// SettledRound returns the drand round whose published signature produced tokenID's parts --
2159// v6 FIX 2, and the one query that makes this project's "provably unrigged" claim (ECONOMY.md
2160// section 1) checkable by a holder rather than merely asserted at them. Fetch
2161// https://api.drand.sh/<chain>/public/<round>, hash its signature, and re-derive the parts with
2162// this file's own seedFor/drawWeighted against your own address: a round signed by drand before
2163// anybody knew who would pin it cannot have been chosen to produce a particular gnome.
2164//
2165// round == 0 means this token was never produced by a roll, which is true of exactly one token
2166// ever: the genesis gnome. found reports whether the token exists.
2167func SettledRound(tokenID string) (round int64, found bool) {
2168 g, ok := gnomeByTokenID(tokenID)
2169 if !ok {
2170 return 0, false
2171 }
2172 return g.settledRound, true
2173}
2174
2175// MaxNameLen is maxNameLen read back, so the app can show the limit it will be held to instead of
2176// hardcoding a second copy of the number (app/js/config.js's NAME_MAX_LEN is the other copy, and
2177// the two are kept equal by hand and by TestMaxNameLenMatchesTheAppsRule).
2178func MaxNameLen() int64 { return int64(maxNameLen) }
2179
2180// GnomeByToken: the basic facts for one token -- hat, coat, eyes, nose, character (empty for an
2181// ordinary gnome), level, calling and the moment it was minted. SIGNATURE UNCHANGED FROM v5 --
2182// the name is Name(tokenID) and the round is SettledRound(tokenID); see the note above.
2183func GnomeByToken(tokenID string) (hat, coat string, eyes, nose int64, character string, level int64, gnomeType string, adoptedAtUnix int64, found bool) {
2184 g, ok := gnomeByTokenID(tokenID)
2185 if !ok {
2186 return "", "", 0, 0, "", 0, "", 0, false
2187 }
2188 return g.hat, g.coat, g.eyes, g.nose, g.character, g.level, g.gnomeType, g.adoptedAt, true
2189}
2190
2191// ActiveGnome returns the tokenID that is awake for addr right now, or found=false if nothing
2192// is (never claimed or bought a gnome, or sold the only one and has not Woken another since).
2193func ActiveGnome(addr address) (tokenID string, found bool) {
2194 tid, isStr := activeToken.Get(addr.String()).(string)
2195 if !isStr || tid == "" {
2196 return "", false
2197 }
2198 return tid, true
2199}
2200
2201// OwnerTokens returns every tokenID addr currently holds, in no particular order. Unbounded and
2202// unpaginated deliberately: batchCap is 24 and the genesis gnome is permanently unreachable to
2203// any wallet, so no address can ever hold more than batchCap tokens, which is a small, fixed
2204// upper bound this call is always safely within.
2205func OwnerTokens(addr address) []string {
2206 v := ownerTokens.Get(addr.String())
2207 list, ok := v.(*[]string)
2208 if !ok || list == nil {
2209 return []string{}
2210 }
2211 out := make([]string, len(*list))
2212 copy(out, *list)
2213 return out
2214}
2215
2216// TokensPage: the global token enumerator, hollowmere/v1's own pattern (TotalClaimants/
2217// ClaimantsPage) applied here, because v4's own missing-enumerator lesson (DECISIONS.md:780-791,
2218// arena/v1 shipping with no challenge inbox and no way to ever add one) is unavailable to fix
2219// after deploy and twenty lines now is cheaper than "unavailable forever" later.
2220func TokensPage(offset, limit int) []string {
2221 if offset < 0 {
2222 panic("garden: offset must not be negative")
2223 }
2224 if limit <= 0 {
2225 panic("garden: limit must be positive")
2226 }
2227 if limit > maxGnomesPageSize {
2228 limit = maxGnomesPageSize
2229 }
2230 ids := make([]string, 0, limit)
2231 gnomes.IterateByOffset(offset, limit, func(key string, value any) bool {
2232 ids = append(ids, key)
2233 return false
2234 })
2235 return ids
2236}
2237
2238func GardenState(tokenID string) (plantedAtCsv, readyAtCsv string, readyCount int64, found bool) {
2239 g, ok := gnomeByTokenID(tokenID)
2240 if !ok {
2241 return "", "", 0, false
2242 }
2243 now := time.Now().Unix()
2244 planted := make([]string, 0, numPlots)
2245 ready := make([]string, 0, numPlots)
2246 for i := 0; i < numPlots; i++ {
2247 p := g.plots[i]
2248 planted = append(planted, strconv.FormatInt(p.plantedAt, 10))
2249 ready = append(ready, strconv.FormatInt(p.readyAt, 10))
2250 if p.plantedAt != 0 && now >= p.readyAt {
2251 readyCount++
2252 }
2253 }
2254 return strings.Join(planted, ","), strings.Join(ready, ","), readyCount, true
2255}
2256
2257func CareState(tokenID string) (belly, cheer, acorns, totalXp, lastPatAtUnix, lastHappyEventAtUnix, lastActionAtUnix int64, found bool) {
2258 g, ok := gnomeByTokenID(tokenID)
2259 if !ok {
2260 return 0, 0, 0, 0, 0, 0, 0, false
2261 }
2262 owner, hasOwner := ownerOfToken(tokenID)
2263 acornBalance := int64(0)
2264 if hasOwner {
2265 acornBalance = balanceOf(owner)
2266 }
2267 now := time.Now().Unix()
2268 return meterNow(g.belly, g.bellyAt, now, bellyDropEveryHours),
2269 meterNow(g.cheer, g.cheerAt, now, cheerDropEveryHours),
2270 acornBalance, g.totalXp, g.lastPatAt, g.lastHappyEventAt, g.lastActionAt, true
2271}
2272
2273func MeterState(tokenID string) (belly, bellyAtUnix, cheer, cheerAtUnix int64, found bool) {
2274 g, ok := gnomeByTokenID(tokenID)
2275 if !ok {
2276 return 0, 0, 0, 0, false
2277 }
2278 return g.belly, g.bellyAt, g.cheer, g.cheerAt, true
2279}
2280
2281func Progress(tokenID string) (xpGarden, xpTinker, harvestCount, lastTinkerAtUnix, caredDayCount, dailyCareXpSpent, dailyCareDay int64, found bool) {
2282 g, ok := gnomeByTokenID(tokenID)
2283 if !ok {
2284 return 0, 0, 0, 0, 0, 0, 0, false
2285 }
2286 return g.xpGarden, g.xpTinker, g.harvestCount, g.lastTinkerAt,
2287 g.caredDayCount, g.dailyCareXp, g.dailyCareDay, true
2288}
2289
2290func CaredDays(tokenID string) (daysCsv string, found bool) {
2291 g, ok := gnomeByTokenID(tokenID)
2292 if !ok {
2293 return "", false
2294 }
2295 return caredDaysCsv(g), true
2296}
2297
2298func Mood(tokenID string) (mood string, found bool) {
2299 g, ok := gnomeByTokenID(tokenID)
2300 if !ok {
2301 return "", false
2302 }
2303 now := time.Now().Unix()
2304 belly := meterNow(g.belly, g.bellyAt, now, bellyDropEveryHours)
2305 return moodNow(belly, g.lastPatAt, g.lastHappyEventAt, g.adoptedAt, now, hungryAtOrBelow), true
2306}
2307
2308// IsLocked reports whether tokenID is currently refused by List's lockCaredDays check -- true
2309// only for a named one-of-one with fewer than lockCaredDays cared days; false for every ordinary
2310// gnome, always, and false for a named one-of-one once it has enough cared days.
2311func IsLocked(tokenID string) (locked bool, found bool) {
2312 g, ok := gnomeByTokenID(tokenID)
2313 if !ok {
2314 return false, false
2315 }
2316 return g.character != "" && g.caredDayCount < lockCaredDays, true
2317}
2318
2319func CollectionInfo() (name, symbol string) {
2320 return collectionName, collectionSymbol
2321}
2322
2323func TotalSupply() int64 {
2324 return token.TotalSupply()
2325}
2326
2327func BalanceOf(addr address) int64 {
2328 n, err := token.BalanceOf(addr)
2329 if err != nil {
2330 return 0
2331 }
2332 return n
2333}
2334
2335func OwnerOfToken(tokenID string) (owner address, found bool) {
2336 return ownerOfToken(tokenID)
2337}
2338
2339func TotalGnomes() int64 {
2340 return token.TotalSupply()
2341}
2342
2343func Acorns(addr address) (acorns int64, found bool) {
2344 if !balances.Has(addr.String()) {
2345 return 0, false
2346 }
2347 return balanceOf(addr), true
2348}
2349
2350// ---- counted rarity readers (MINT.md section 13): "nine gnomes in the world have this nose"
2351// has to be a chain fact. These four, plus CharacterOwner below, are that fact.
2352
2353func EyesCount(id int64) int64 { return eyesCount(id) }
2354func NoseCount(id int64) int64 { return noseCount(id) }
2355func HatCount(hat string) int64 { return hatCount(hat) }
2356func CoatCount(coat string) int64 { return coatCount(coat) }
2357
2358// CharacterOwner resolves one of the three named one-of-ones, or the genesis gnome under its
2359// own name "genesis", to its tokenID, once minted. (Second-audit-pass nitpick: an earlier
2360// version of this comment said only "one of the three named one-of-ones", which stopped being
2361// true the moment init() registered "genesis" here too -- see init()'s own comment for why that
2362// registration is safe and never touches the three editions' cap.)
2363func CharacterOwner(name string) (tokenID string, found bool) {
2364 v := characterOwner.Get(name)
2365 s, ok := v.(string)
2366 if !ok {
2367 return "", false
2368 }
2369 return s, true
2370}
2371
2372// ---- the mint's own state, read back.
2373
2374func IsAllowlisted(addr address) bool {
2375 return allowlist.Has(addr.String())
2376}
2377
2378func HasRolled(addr address) bool {
2379 return hasRolled.Has(addr.String())
2380}
2381
2382func PendingClaim(addr address) (round, claimedAtUnix int64, found bool) {
2383 v := pendingClaims.Get(addr.String())
2384 pc, ok := v.(*pendingClaim)
2385 if !ok || pc == nil {
2386 return 0, 0, false
2387 }
2388 return pc.round, pc.claimedAt, true
2389}
2390
2391// BatchStatus: mintedCount is reservations made by Claim (gates batchCap); settledCount is
2392// completions made by Settle (always <= mintedCount, the gap being pending, unsettled claims);
2393// namedMinted is how many of the three named one-of-ones have actually been minted so far --
2394// read live off characterOwner rather than a separate counter, so there is only ever one source
2395// of truth for "has this edition been taken".
2396func BatchStatus() (mintedSoFar, settledSoFar, batchCapOut, namedMinted, namedCapOut int64) {
2397 // NAMED RETURNS DELIBERATELY DO NOT SHARE A NAME WITH THE PACKAGE-LEVEL mintedCount/
2398 // settledCount VARS. An earlier version of this function used mintedCount/settledCount as
2399 // its own named returns, which SHADOWED the package vars for the whole function body, so
2400 // `return mintedCount, settledCount, ...` returned the zero-valued local named returns
2401 // instead of the real package state -- this function always reported a fresh batch,
2402 // silently, with no error, which TestBatchClosesAtCapAndRefusesFurtherClaims caught by
2403 // actually driving claims until the realm said the batch was full and finding it never did.
2404 // Found and fixed before audit; recorded here rather than silently corrected, the same
2405 // discipline this file's own package doc uses for the Settle timing flaw.
2406 nm := int64(0)
2407 for _, name := range namedEditionOrder {
2408 if characterOwner.Has(name) {
2409 nm++
2410 }
2411 }
2412 return mintedCount, settledCount, batchCap, nm, numNamedEditions
2413}
2414
2415func GenesisTokenID() string {
2416 return genesisTokenID
2417}
2418
2419func AdminState() (admin address, frozen bool) {
2420 return address(adminAddress), rulesFrozen
2421}
2422
2423func LastWakeDay(addr address) (day int64, found bool) {
2424 v, ok := lastWakeDay.Get(addr.String()).(int64)
2425 return v, ok
2426}
2427
2428// ============================================================================
2429// Render
2430// ============================================================================
2431
2432// Render DELIBERATELY ECHOES NO PLAYER-SUPPLIED STRING, and v6 keeps it that way even though it
2433// now has gnome names it could print. THIS IS THE DEFENCE AGAINST ABUSIVE NAMES ON A PUBLIC PAGE,
2434// and it is structural rather than a filter: gnoweb renders this output as markdown, so a page
2435// that listed names would be a markdown sink fed by arbitrary player input, and the project would
2436// then own a moderation problem on an immutable realm with no moderation surface. v5's own
2437// adversarial review (ATTACK-REVIEW.md, "Render sanitisation") recorded "no injection surface" as
2438// a property of this function; adding a name here would have been the one change in this file
2439// that falsified an audited claim.
2440//
2441// Belt and braces, because "nothing echoes names today" is only one edit away from being false:
2442// the name charset allowlist (letters, digits, space, hyphen, apostrophe -- see validNameRune)
2443// excludes every markdown metacharacter there is. No '[', ']', '(', ')', '<', '>', '*', '_',
2444// backtick, pipe or newline can appear in a name, so even a future Render that DID print one
2445// could not be made to inject link syntax, a raw HTML tag or a table break. An abusive name is
2446// therefore limited to being rude in words, visible only to someone who queries that specific
2447// token, never on a page this project publishes.
2448func Render(path string) string {
2449 if path != "" {
2450 return "garden/v6: unknown path"
2451 }
2452 minted, settled, cap_, namedMinted, namedCap := BatchStatus()
2453 out := "# Gnotchi gnomes -- garden/v6\n\n"
2454 out += "Batch One: " + strconv.FormatInt(minted, 10) + " claimed, " +
2455 strconv.FormatInt(settled, 10) + " settled, of " + strconv.FormatInt(cap_, 10) + " ever.\n\n"
2456 out += "Named one-of-ones minted: " + strconv.FormatInt(namedMinted, 10) + " of " + strconv.FormatInt(namedCap, 10) + ".\n\n"
2457 out += "Total supply (including the genesis gnome): " + strconv.FormatInt(TotalSupply(), 10) + "\n\n"
2458 out += "Free to claim, if your address is on the allowlist. One roll per wallet, ever. " +
2459 "Claim pins a future drand round; Settle, callable by anyone once that round is " +
2460 "published, mints the result.\n"
2461 return out
2462}
2463
2464// ============================================================================
2465// Internal helpers
2466// ============================================================================
2467
2468func gnomeByTokenID(tokenID string) (*gnome, bool) {
2469 v := gnomes.Get(tokenID)
2470 g, ok := v.(*gnome)
2471 if !ok || g == nil {
2472 return nil, false
2473 }
2474 return g, true
2475}
2476
2477// activeGnomeForAddr resolves addr's AWAKE gnome, if any. This is the one and only lookup
2478// SaveDay and ChooseType use -- there is deliberately no "the gnome for this address" any more.
2479func activeGnomeForAddr(addr address) (tid string, g *gnome, found bool) {
2480 tidStr, ok := activeToken.Get(addr.String()).(string)
2481 if !ok || tidStr == "" {
2482 return "", nil, false
2483 }
2484 gg, ok := gnomeByTokenID(tidStr)
2485 if !ok {
2486 return "", nil, false
2487 }
2488 return tidStr, gg, true
2489}
2490
2491func ownerOfToken(tokenID string) (owner address, found bool) {
2492 if !gnomes.Has(tokenID) {
2493 return address(""), false
2494 }
2495 o, err := token.OwnerOf(grc721.TokenID(tokenID))
2496 if err != nil {
2497 return address(""), false
2498 }
2499 return o, true
2500}
2501
2502// addOwnerToken / removeOwnerToken: the hold-many index. ownerTokens stores a *[]string per
2503// owner so repeated appends mutate one allocation rather than replacing the tree entry every
2504// time; removal does a linear scan, which is fine at this realm's permanent, tiny upper bound
2505// (batchCap = 24 tokens that will ever exist, minus the one permanently unreachable genesis
2506// gnome, so no owner's slice is ever longer than 24 entries for the whole life of this realm).
2507func addOwnerToken(addr address, tokenID string) {
2508 v := ownerTokens.Get(addr.String())
2509 list, ok := v.(*[]string)
2510 if !ok || list == nil {
2511 fresh := []string{tokenID}
2512 ownerTokens.Set(addr.String(), &fresh)
2513 return
2514 }
2515 *list = append(*list, tokenID)
2516}
2517
2518func removeOwnerToken(addr address, tokenID string) {
2519 v := ownerTokens.Get(addr.String())
2520 list, ok := v.(*[]string)
2521 if !ok || list == nil {
2522 return
2523 }
2524 out := make([]string, 0, len(*list))
2525 for _, id := range *list {
2526 if id != tokenID {
2527 out = append(out, id)
2528 }
2529 }
2530 *list = out
2531}
2532
2533func balanceOf(addr address) int64 {
2534 v := balances.Get(addr.String())
2535 n, ok := v.(int64)
2536 if !ok {
2537 return 0
2538 }
2539 return n
2540}
2541
2542func setBalance(addr address, v int64) {
2543 if v < 0 {
2544 panic("garden: acorn balance cannot go negative")
2545 }
2546 balances.Set(addr.String(), v)
2547}
2548
2549func grantStartingPurseIfNew(addr address) {
2550 if !balances.Has(addr.String()) {
2551 balances.Set(addr.String(), acornsStart)
2552 }
2553}
2554
2555func feeFor(priceUgnot int64) int64 {
2556 return fee.floorUgnot + priceUgnot*fee.rateBps/10000
2557}
2558
2559func exactUgnot(send chain.Coins, want int64) bool {
2560 if len(send) != 1 {
2561 return false
2562 }
2563 return send[0].Denom == ugnotDenom && send[0].Amount == want
2564}
2565
2566func coinsString(c chain.Coins) string {
2567 if len(c) == 0 {
2568 return "nothing"
2569 }
2570 out := ""
2571 for i, coin := range c {
2572 if i > 0 {
2573 out += ","
2574 }
2575 out += strconv.FormatInt(coin.Amount, 10) + coin.Denom
2576 }
2577 return out
2578}
2579
2580func listingFor(tokenID string) (*listing, bool) {
2581 v := listings.Get(tokenID)
2582 l, ok := v.(*listing)
2583 if !ok || l == nil {
2584 return nil, false
2585 }
2586 if l.priceUgnot < 0 {
2587 return nil, false
2588 }
2589 return l, true
2590}
2591
2592// ============================================================================
2593// v6 FIX 1: name validation and canonicalisation. validNameLength/validNameCharset/
2594// hasVisibleNameContent/validNameRune/invisibleLetterRunes are v4's OWN IMPLEMENTATIONS, carried
2595// back byte-for-byte -- three audit rounds' worth of work (v4's own comment), including v2's
2596// audit fix F3 (\uXXXX escapes rather than literal invisible glyphs, so the denylist is readable
2597// in an editor and cannot be silently emptied by a formatter that strips default-ignorable
2598// characters). They are NOT re-derived here and must not be "tidied": every line of that
2599// allowlist was argued for once already.
2600//
2601// THE DENYLIST IS THE PART THAT MATTERS AND THE PART THAT LOOKS REDUNDANT. All four entries are
2602// genuinely LETTERS by Unicode's own classification, so unicode.IsLetter accepts every one of
2603// them -- and all four render as NOTHING AT ALL. They exist in fonts purely as filler. Without
2604// this list, "Hob" and "Hob<U+3164>" are different names that look identical in every UI either
2605// will ever be shown in, which is impersonation with no defence available to the person being
2606// impersonated. app/js/config.js's NAME_INVISIBLE_LETTERS is the same four code points, exposed
2607// there for the app's own tests; TestEveryInvisibleLetterIsRefused table-drives this map directly
2608// so neither side's coverage can silently fall behind the other (config.js's finding Y3: before
2609// that change every test on both sides of the stack only ever exercised U+3164).
2610//
2611// CARRIED FORWARD UNCHANGED, AND STILL AN OPEN PRODUCT QUESTION, NOT A SETTLED ONE: this
2612// allowlist excludes every COMBINING MARK (chiefly Unicode category Mn), which makes zalgo names
2613// structurally impossible -- and also makes NFD Latin, Devanagari, Thai, vocalised Hebrew and
2614// Arabic unspellable. realms/garden/NOTES.md records that trade-off in full as the owner's to
2615// revisit (v4's third audit round, finding Y7). v6 carries it forward rather than silently
2616// re-deciding it, exactly as v4 carried it forward from v1/v2. Precomposed letters (é as a single
2617// code point) are accepted fine; the exclusion is specifically and only about combining marks.
2618// ============================================================================
2619
2620func validNameLength(name string) bool {
2621 // RuneCountInString, never len(): len() counts BYTES, so a 24-character name in any
2622 // non-ASCII script would be refused for being "too long" while an ASCII one of the same
2623 // visible length passed.
2624 n := utf8.RuneCountInString(name)
2625 return n > 0 && n <= maxNameLen
2626}
2627
2628func validNameCharset(name string) bool {
2629 for _, r := range name {
2630 if !validNameRune(r) {
2631 return false
2632 }
2633 }
2634 return true
2635}
2636
2637func hasVisibleNameContent(name string) bool {
2638 for _, r := range name {
2639 if r != ' ' {
2640 return true
2641 }
2642 }
2643 return false
2644}
2645
2646// invisibleLetterRunes: the four code points that are Unicode LETTERS and render as nothing. See
2647// the section comment above for why a letter allowlist alone cannot catch these. Written as
2648// \uXXXX escapes (v2's audit fix F3) so they survive an editor or formatter that strips
2649// default-ignorable characters -- a denylist that can be silently emptied protects nothing.
2650//
2651// v3 through v5 carried this comment while the entries themselves were literal invisible glyphs,
2652// so the comment was false about its own code for three versions and the protection it describes
2653// was not actually in place. Restored here, with the escapes BACK IN THE SOURCE this time.
2654//
2655// The escapes alone are only half of F3. TestEveryInvisibleLetterIsRefused table-drives this map,
2656// which means it tests whatever the map happens to contain -- swap one entry for an ordinary
2657// letter and that test still passes while the realm ships banning the letter and accepting the
2658// invisible one. TestInvisibleLetterRunesIsExactlyFourPinnedCodepoints is the other half: it
2659// pins all four code points BY ESCAPE, independently of this map's contents, so that
2660// substitution fails loudly.
2661var invisibleLetterRunes = map[rune]bool{
2662 '\u115f': true, // HANGUL CHOSEONG FILLER
2663 '\u1160': true, // HANGUL JUNGSEONG FILLER
2664 '\u3164': true, // HANGUL FILLER
2665 '\uffa0': true, // HALFWIDTH HANGUL FILLER
2666}
2667
2668func validNameRune(r rune) bool {
2669 switch r {
2670 case ' ', '-', '\'':
2671 return true
2672 }
2673 if invisibleLetterRunes[r] {
2674 return false
2675 }
2676 return unicode.IsLetter(r) || unicode.IsDigit(r)
2677}
2678
2679// smartPunctuationRunes: the four code points iOS substitutes by default for a straight
2680// apostrophe or hyphen. NONE of them is accepted by validNameRune -- this map exists only so the
2681// refusal can SAY SO instead of reporting a generic charset failure to a player who typed an
2682// ordinary apostrophe on an ordinary phone. See nameAssignabilityProblem's own comment on why
2683// this realm refuses rather than folds them.
2684var smartPunctuationRunes = map[rune]bool{
2685 '‘': true, // LEFT SINGLE QUOTATION MARK
2686 '’': true, // RIGHT SINGLE QUOTATION MARK
2687 '–': true, // EN DASH
2688 '—': true, // EM DASH
2689}
2690
2691func hasSmartPunctuation(name string) bool {
2692 for _, r := range name {
2693 if smartPunctuationRunes[r] {
2694 return true
2695 }
2696 }
2697 return false
2698}
2699
2700// canonicalNameKey folds a name to the key nameOwner and reservedNameKeys compare on: lowercase
2701// ASCII, runs of spaces collapsed to one, leading and trailing spaces removed.
2702//
2703// THE STORED NAME AND THE KEY ARE DELIBERATELY TWO DIFFERENT STRINGS. The gnome keeps the name
2704// its owner typed, exactly as typed, because that is what a person chose and the app should show
2705// it back to them unaltered. The KEY exists only to answer "is this the same name as that one"
2706// for uniqueness and reservation, and for THAT question "Hob", "hob", "HOB" and "Hob" with two
2707// spaces in it are all plainly the same name. Keying on the raw string instead would make
2708// uniqueness worthless and would let anyone walk around the one-of-one reservation by changing
2709// one letter's case.
2710//
2711// WHAT IT DELIBERATELY DOES NOT DO, stated plainly rather than left for a reader to discover:
2712// it does not close cross-script HOMOGLYPHS. Cyrillic "А", Greek "Ο" and fullwidth "A" are all
2713// Unicode letters, all accepted, and all visually confusable with their Latin counterparts, so
2714// "Нob" with a Cyrillic Н is a different key from "Hob" and will be allowed. This is the SAME
2715// accepted residual app/js/config.js's NAME_CHARSET_RE documents in its own comment, carried
2716// forward knowingly: closing it properly needs a confusables table (thousands of mappings,
2717// versioned by Unicode, compiled into an immutable realm) and the honest cost/benefit at a
2718// 24-gnome collection does not justify it. The defence that IS in place for the case that
2719// actually matters -- the three cap-one editions -- is that their names are reserved and
2720// unrenameable, so a homoglyph impostor can exist but can never hold the real key, and
2721// CharacterOwner (not a name lookup) is what resolves the genuine Hob.
2722//
2723// ASCII-only lowercasing, following lowerASCII's own v4 reasoning: strings.ToLower would apply
2724// locale-independent Unicode case folding whose behaviour is a toolchain-version detail on an
2725// immutable realm, and the keys that MUST match exactly (reservedNameKeys) are all ASCII.
2726func canonicalNameKey(name string) string {
2727 lowered := lowerASCII(name)
2728
2729 out := make([]byte, 0, len(lowered))
2730 prevSpace := true // true at the start, so leading spaces are dropped by the same test
2731 for i := 0; i < len(lowered); i++ {
2732 c := lowered[i]
2733 if c == ' ' {
2734 if prevSpace {
2735 continue
2736 }
2737 prevSpace = true
2738 out = append(out, c)
2739 continue
2740 }
2741 prevSpace = false
2742 out = append(out, c)
2743 }
2744 // One trailing space may survive the loop above (a name ending in a space emits it before the
2745 // loop ends); drop it.
2746 if len(out) > 0 && out[len(out)-1] == ' ' {
2747 out = out[:len(out)-1]
2748 }
2749 return string(out)
2750}
2751
2752func nameOwnerOf(key string) (tokenID string, found bool) {
2753 v := nameOwner.Get(key)
2754 s, ok := v.(string)
2755 if !ok || s == "" {
2756 return "", false
2757 }
2758 return s, true
2759}
2760
2761// lowerASCII: v4's own helper, unchanged -- ASCII-only on purpose (see v4's own comment on why
2762// not strings.ToLower).
2763func lowerASCII(s string) string {
2764 b := []byte(s)
2765 for i, c := range b {
2766 if c >= 'A' && c <= 'Z' {
2767 b[i] = c + ('a' - 'A')
2768 }
2769 }
2770 return string(b)
2771}
2772
2773func anyPlotPlanted(g *gnome) bool {
2774 for i := 0; i < numPlots; i++ {
2775 if g.plots[i].plantedAt != 0 {
2776 return true
2777 }
2778 }
2779 return false
2780}
2781
2782func eyesCount(id int64) int64 {
2783 v := eyesCounts.Get(strconv.FormatInt(id, 10))
2784 n, ok := v.(int64)
2785 if !ok {
2786 return 0
2787 }
2788 return n
2789}
2790
2791func noseCount(id int64) int64 {
2792 v := noseCounts.Get(strconv.FormatInt(id, 10))
2793 n, ok := v.(int64)
2794 if !ok {
2795 return 0
2796 }
2797 return n
2798}
2799
2800func hatCount(hat string) int64 {
2801 v := hatCounts.Get(hat)
2802 n, ok := v.(int64)
2803 if !ok {
2804 return 0
2805 }
2806 return n
2807}
2808
2809func coatCount(coat string) int64 {
2810 v := coatCounts.Get(coat)
2811 n, ok := v.(int64)
2812 if !ok {
2813 return 0
2814 }
2815 return n
2816}
2817
2818// ---- parsing, meters, mood, level: v4's own proven implementations, byte-for-byte, with
2819// rule() lookups replaced by this file's fixed constants (see the package doc: no SetRule here).
2820
2821func parseActions(raw string) []saveAction {
2822 if raw == "" {
2823 return nil
2824 }
2825
2826 count := 1
2827 for i := 0; i < len(raw); i++ {
2828 if raw[i] == ';' {
2829 count++
2830 }
2831 }
2832 if count > maxActionsPerCall {
2833 panic("garden: too many actions in one call; the limit is " + strconv.Itoa(maxActionsPerCall))
2834 }
2835
2836 parts := strings.Split(raw, ";")
2837 actions := make([]saveAction, 0, len(parts))
2838 for _, part := range parts {
2839 if part == "" {
2840 panic("garden: empty action entry")
2841 }
2842 fields := strings.Split(part, ":")
2843 switch fields[0] {
2844 case actionPat, actionFeed, actionTinker:
2845 if len(fields) != 2 {
2846 panic("garden: malformed action: " + quoteAction(part))
2847 }
2848 actions = append(actions, saveAction{kind: fields[0], at: parseUnixField(fields[1], part)})
2849 case actionPlant, actionHarvest:
2850 if len(fields) != 3 {
2851 panic("garden: malformed action: " + quoteAction(part))
2852 }
2853 actions = append(actions, saveAction{
2854 kind: fields[0],
2855 plot: parsePlotField(fields[1], part),
2856 at: parseUnixField(fields[2], part),
2857 })
2858 default:
2859 panic("garden: unknown action kind: " + quoteAction(part))
2860 }
2861 }
2862 return actions
2863}
2864
2865func quoteAction(part string) string {
2866 return "\"" + part + "\""
2867}
2868
2869func parseUnixField(s, part string) int64 {
2870 n, err := strconv.ParseInt(s, 10, 64)
2871 if err != nil || n < 0 {
2872 panic("garden: malformed timestamp in action: " + quoteAction(part))
2873 }
2874 return n
2875}
2876
2877func parsePlotField(s, part string) int {
2878 n, err := strconv.Atoi(s)
2879 if err != nil || n < 0 || n >= numPlots {
2880 panic("garden: malformed plot index in action: " + quoteAction(part))
2881 }
2882 return n
2883}
2884
2885func dayNumber(unixSeconds int64) int64 { return unixSeconds / daySeconds }
2886
2887// recordCaredDay reports, via banked, whether it actually incremented g.caredDayCount -- false
2888// on the no-op branch (day == g.lastCaredDay already, e.g. a second SaveDay call the same UTC
2889// day, or a token bought mid-day that the SELLER had already banked that exact day for before
2890// the sale). SaveDay's own caller-scoped gate (lastCaredDayForOwner) depends on this: it must
2891// only spend the owner's one-bank-per-day allowance on a call that actually banked something,
2892// never on a no-op -- a gno-auditor re-audit found that an unconditional advance let a buyer's
2893// SaveDay on a token the seller had already banked that day silently consume the buyer's own
2894// allowance for the rest of that day, denying an otherwise fully legitimate cared day on a
2895// DIFFERENT, genuinely active token later the same day. See the call site in SaveDay.
2896func recordCaredDay(g *gnome, day int64) (banked bool) {
2897 if g.lastCaredDay == 0 {
2898 g.lastCaredDay = day
2899 g.caredMask = 1
2900 g.caredDayCount = 1
2901 return true
2902 }
2903 if day == g.lastCaredDay {
2904 return false
2905 }
2906 shift := uint(day - g.lastCaredDay)
2907 if shift >= caredWindowDays {
2908 g.caredMask = 1
2909 } else {
2910 g.caredMask = (g.caredMask << shift) | 1
2911 }
2912 g.lastCaredDay = day
2913 g.caredDayCount++
2914 return true
2915}
2916
2917func caredDaysCsv(g *gnome) string {
2918 if g.lastCaredDay == 0 {
2919 return ""
2920 }
2921 days := make([]string, 0, caredWindowDays)
2922 for i := uint(0); i < caredWindowDays; i++ {
2923 if g.caredMask&(1<<i) != 0 {
2924 days = append(days, strconv.FormatInt(g.lastCaredDay-int64(i), 10))
2925 }
2926 }
2927 return strings.Join(days, ",")
2928}
2929
2930func meterNow(value, setAt, now, dropEveryHours int64) int64 {
2931 if dropEveryHours <= 0 {
2932 return value
2933 }
2934 elapsedHours := (now - setAt) / hourSeconds
2935 if elapsedHours <= 0 {
2936 return clampMeter(value)
2937 }
2938 drops := elapsedHours / dropEveryHours
2939 return clampMeter(value - drops)
2940}
2941
2942func clampMeter(v int64) int64 {
2943 if v < 0 {
2944 return 0
2945 }
2946 if v > meterMax {
2947 return meterMax
2948 }
2949 return v
2950}
2951
2952func canPat(lastPatAt, now, cooldownHours int64) bool {
2953 if lastPatAt == 0 {
2954 return true
2955 }
2956 return now-lastPatAt >= cooldownHours*hourSeconds
2957}
2958
2959func moodNow(belly, lastPatAt, lastHappyEventAt, adoptedAt, now, hungryThreshold int64) string {
2960 if belly <= hungryThreshold {
2961 return moodHungry
2962 }
2963 if lastHappyEventAt == 0 {
2964 if now-adoptedAt <= happyWindowHours*hourSeconds {
2965 return moodContent
2966 }
2967 return moodSulky
2968 }
2969 if now-lastHappyEventAt <= happyWindowHours*hourSeconds {
2970 return moodHappy
2971 }
2972 if now-lastHappyEventAt >= sulkyAfterHours*hourSeconds {
2973 return moodSulky
2974 }
2975 return moodContent
2976}
2977
2978func xpToNext(level int64) int64 { return levelBase + levelStep*level }
2979
2980func totalXpForLevel(level int64) int64 {
2981 if level <= 1 {
2982 return 0
2983 }
2984 total := int64(0)
2985 for l := int64(1); l < level; l++ {
2986 total += xpToNext(l)
2987 }
2988 return total
2989}
2990
2991func levelFromXp(totalXp int64) int64 {
2992 level := int64(1)
2993 for level < maxLevel {
2994 need := totalXpForLevel(level + 1)
2995 if totalXp < need {
2996 break
2997 }
2998 level++
2999 }
3000 return level
3001}