foukoapi 0.1.2-alpha.1

Cross-platform bot framework in Rust: one codebase, many platforms. Shared accounts, embeds, keyboards, economy, i18n and pluggable storage; Telegram and Discord adapters included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! Batteries-included economy: XP, levels, coins, cooldowns and a
//! leaderboard, all layered on top of [`Accounts`] so linked accounts
//! share one wallet.
//!
//! The design goal is "drop it in and it just works". Give [`Economy`]
//! the same [`Accounts`] your bot already uses and you get:
//!
//! - [`Economy::add_xp`] / [`Economy::wallet`] - XP that auto-mints coins,
//!   with a level curve.
//! - [`Economy::add_coins`] / [`Economy::transfer`] - a spendable balance.
//! - [`Economy::cooldown_remaining`] / [`Economy::touch_cooldown`] - rate
//!   limits for `/daily`, `/gamble`, and friends.
//! - [`Economy::leaderboard`] / [`Economy::rank_of`] - rankings backed by
//!   a player index the store maintains for you.
//! - [`Economy::title`] / [`Economy::color`] - small cosmetic slots bots
//!   can sell in a shop.
//!
//! Everything resolves through a player's *primary* identity, so a user
//! who linked Telegram and Discord sees the same XP and coins on both.

use crate::{accounts::Accounts, platform::PlatformKind, storage::Storage, Result};
use std::sync::Arc;

/// Namespaced keys so the economy never trips over account-linking data.
const XP_PREFIX: &str = "foukoapi:econ:xp:";
const COINS_PREFIX: &str = "foukoapi:econ:coins:";
const TITLE_PREFIX: &str = "foukoapi:econ:title:";
const NAME_PREFIX: &str = "foukoapi:econ:name:";
const COLOR_PREFIX: &str = "foukoapi:econ:color:";
const COOLDOWN_PREFIX: &str = "foukoapi:econ:cd:";
const ACH_PREFIX: &str = "foukoapi:econ:ach:";

/// XP-per-coin conversion used by [`Economy::add_xp`].
pub const XP_PER_COIN: u64 = 10;

/// An economy handle sharing storage with [`Accounts`].
///
/// Clone it freely - it's just a few `Arc`s under the hood.
#[derive(Clone)]
pub struct Economy {
    storage: Arc<dyn Storage>,
    accounts: Accounts,
    /// Serialises every read-modify-write against the store so parallel
    /// grants and transfers can't lose updates or double-spend. Shared by
    /// all clones of this handle.
    lock: Arc<tokio::sync::Mutex<()>>,
}

/// What one [`Economy::add_xp`] call produced.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct XpGain {
    /// New XP total after the grant.
    pub xp: u64,
    /// Coins minted by the boundaries this grant crossed.
    pub coins_minted: u64,
}

/// A player's resolved balances.
#[derive(Debug, Clone)]
pub struct Wallet {
    /// Lifetime experience points.
    pub xp: u64,
    /// Spendable coins.
    pub coins: u64,
    /// Level derived from `xp` via [`Economy::level_for`].
    pub level: u32,
}

/// What [`Economy::leaderboard`] ranks on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Metric {
    /// Rank by lifetime XP.
    Xp,
    /// Rank by current coin balance.
    Coins,
}

/// One row of a leaderboard.
#[derive(Debug, Clone)]
pub struct RankedPlayer {
    /// The player's primary identity, `"platform:id"`.
    pub primary: String,
    /// The metric value this player was ranked on.
    pub value: u64,
    /// Zero-based position in the ranking.
    pub position: usize,
}

impl Economy {
    /// Build an economy that shares [`Accounts`]' storage. This is the
    /// one you want: balances follow the account link automatically.
    pub fn new(accounts: Accounts) -> Self {
        Self {
            storage: accounts.storage_ref().clone(),
            accounts,
            lock: Arc::new(tokio::sync::Mutex::new(())),
        }
    }

    /// Resolve a user to the primary identity their balances live under.
    ///
    /// If this identity was linked to another account after it had already
    /// earned something, its old balances sit under the pre-link key. We
    /// fold those into the primary on sight, so linking never leaves a
    /// ghost entry on the leaderboard.
    async fn primary(&self, platform: PlatformKind, user_id: &str) -> String {
        let me = format!("{platform}:{user_id}");
        let primary = self
            .accounts
            .primary_for(platform, user_id)
            .await
            .unwrap_or_else(|_| me.clone());
        if primary != me {
            if let Err(e) = self.merge_identity(&me, &primary).await {
                tracing::error!(from = %me, into = %primary, error = %e, "economy: identity merge failed");
            }
        }
        primary
    }

    /// Fold everything stored under `from` into `into`: XP and coins are
    /// summed, achievements unioned, cosmetics and the display name kept
    /// from `into` when both exist. The `from` keys are deleted, so this
    /// runs at most once per orphaned identity. Each write into `into`
    /// happens before the matching `from` delete, so a failure mid-way
    /// never drops a balance - at worst the merge just runs again later.
    async fn merge_identity(&self, from: &str, into: &str) -> Result<()> {
        let _guard = self.lock.lock().await;
        let from_xp = self.read(&format!("{XP_PREFIX}{from}")).await;
        let from_coins = self.read(&format!("{COINS_PREFIX}{from}")).await;
        if from_xp == 0 && from_coins == 0 {
            return Ok(()); // nothing to fold; skip the write churn
        }
        tracing::info!(from = %from, into = %into, "economy: merging linked identity");

        if from_xp > 0 {
            let into_key = format!("{XP_PREFIX}{into}");
            let total = self.read(&into_key).await.saturating_add(from_xp);
            self.storage.set(&into_key, &total.to_string()).await?;
            self.storage.del(&format!("{XP_PREFIX}{from}")).await?;
        }
        if from_coins > 0 {
            let into_key = format!("{COINS_PREFIX}{into}");
            let total = self.read(&into_key).await.saturating_add(from_coins);
            self.storage.set(&into_key, &total.to_string()).await?;
            self.storage.del(&format!("{COINS_PREFIX}{from}")).await?;
        }
        // Cosmetics and name: only fill gaps, the primary's own win.
        for prefix in [TITLE_PREFIX, COLOR_PREFIX, NAME_PREFIX] {
            let from_key = format!("{prefix}{from}");
            if let Ok(Some(v)) = self.storage.get(&from_key).await {
                let into_key = format!("{prefix}{into}");
                if matches!(self.storage.get(&into_key).await, Ok(None)) {
                    self.storage.set(&into_key, &v).await?;
                }
                self.storage.del(&from_key).await?;
            }
        }
        // Achievements: union of both sides.
        let from_key = format!("{ACH_PREFIX}{from}");
        if let Ok(Some(theirs)) = self.storage.get(&from_key).await {
            let into_key = format!("{ACH_PREFIX}{into}");
            let mut merged: Vec<String> = self
                .storage
                .get(&into_key)
                .await
                .ok()
                .flatten()
                .map(|blob| blob.lines().map(str::to_owned).collect())
                .unwrap_or_default();
            for a in theirs.lines() {
                if !a.is_empty() && !merged.iter().any(|m| m == a) {
                    merged.push(a.to_owned());
                }
            }
            self.storage.set(&into_key, &merged.join("\n")).await?;
            self.storage.del(&from_key).await?;
        }
        Ok(())
    }

    // -- reads ---------------------------------------------------------------

    /// Fetch a player's full wallet.
    pub async fn wallet(&self, platform: PlatformKind, user_id: &str) -> Wallet {
        let primary = self.primary(platform, user_id).await;
        self.wallet_of(&primary).await
    }

    /// Fetch a wallet straight from a primary identity (as returned by the
    /// leaderboard).
    pub async fn wallet_of(&self, primary: &str) -> Wallet {
        let xp = self.read(&format!("{XP_PREFIX}{primary}")).await;
        let coins = self.read(&format!("{COINS_PREFIX}{primary}")).await;
        Wallet {
            xp,
            coins,
            level: Self::level_for(xp),
        }
    }

    /// Current coin balance.
    pub async fn coins(&self, platform: PlatformKind, user_id: &str) -> u64 {
        let primary = self.primary(platform, user_id).await;
        self.read(&format!("{COINS_PREFIX}{primary}")).await
    }

    // -- writes --------------------------------------------------------------

    /// Grant XP and mint a coin for every [`XP_PER_COIN`] points earned.
    /// A single large grant pays out every coin boundary it crosses, not
    /// just one. Coins are credited before the XP write so a failed XP
    /// write can't strand a crossed boundary.
    pub async fn add_xp(
        &self,
        platform: PlatformKind,
        user_id: &str,
        amount: u64,
    ) -> Result<XpGain> {
        let primary = self.primary(platform, user_id).await;
        let _guard = self.lock.lock().await;
        let key = format!("{XP_PREFIX}{primary}");
        let before = self.read(&key).await;
        if amount == 0 {
            return Ok(XpGain {
                xp: before,
                coins_minted: 0,
            });
        }
        let after = before.saturating_add(amount);
        let minted = (after / XP_PER_COIN).saturating_sub(before / XP_PER_COIN);
        if minted > 0 {
            self.add_coins_locked(&primary, minted as i64).await?;
        }
        self.storage.set(&key, &after.to_string()).await?;
        Ok(XpGain {
            xp: after,
            coins_minted: minted,
        })
    }

    /// Add coins (negative to subtract, clamped at zero). Returns the new
    /// balance.
    pub async fn add_coins(
        &self,
        platform: PlatformKind,
        user_id: &str,
        delta: i64,
    ) -> Result<u64> {
        let primary = self.primary(platform, user_id).await;
        let _guard = self.lock.lock().await;
        self.add_coins_locked(&primary, delta).await
    }

    /// Move `amount` coins from one user to another, both resolved through
    /// their primaries. Fails if the sender is short. Returns the sender's
    /// remaining balance on success.
    pub async fn transfer(
        &self,
        from: (PlatformKind, &str),
        to: (PlatformKind, &str),
        amount: u64,
    ) -> Result<u64> {
        let sender = self.primary(from.0, from.1).await;
        let recipient = self.primary(to.0, to.1).await;
        if sender == recipient {
            return Err(crate::Error::Other("can't send coins to yourself".into()));
        }
        // Check, debit and credit under one guard so two concurrent
        // transfers can't both pass the balance check.
        let _guard = self.lock.lock().await;
        let balance = self.read(&format!("{COINS_PREFIX}{sender}")).await;
        if balance < amount {
            return Err(crate::Error::Other("not enough coins".into()));
        }
        let remaining = self.add_coins_locked(&sender, -(amount as i64)).await?;
        if let Err(e) = self.add_coins_locked(&recipient, amount as i64).await {
            // Credit failed: put the debited coins back, best effort.
            if let Err(refund_err) = self.add_coins_locked(&sender, amount as i64).await {
                tracing::error!(
                    sender = %sender,
                    amount,
                    error = %refund_err,
                    "transfer refund failed - coins lost"
                );
            }
            return Err(e);
        }
        Ok(remaining)
    }

    /// Read-modify-write on a coin balance. Caller must hold `self.lock`.
    async fn add_coins_locked(&self, primary: &str, delta: i64) -> Result<u64> {
        let key = format!("{COINS_PREFIX}{primary}");
        let current = self.read(&key).await as i64;
        let next = (current + delta).max(0) as u64;
        self.storage.set(&key, &next.to_string()).await?;
        Ok(next)
    }

    // -- levels --------------------------------------------------------------

    /// Level for an XP total. Reaching level `L` costs `L*(L+1)*10` XP,
    /// giving thresholds 20, 60, 120, 200, ...
    pub fn level_for(xp: u64) -> u32 {
        let mut level: u32 = 0;
        loop {
            let next = (level as u64 + 1) * (level as u64 + 2) * 10;
            if xp < next || level > 1000 {
                return level;
            }
            level += 1;
        }
    }

    /// The XP band `[lower, upper)` bracketing `level`, handy for progress
    /// bars. A player at `level` has `xp` somewhere in this half-open range.
    pub fn level_bounds(level: u32) -> (u64, u64) {
        let l = level as u64;
        let lower = l * (l + 1) * 10;
        let upper = (l + 1) * (l + 2) * 10;
        (lower, upper)
    }

    // -- cooldowns -----------------------------------------------------------

    /// Seconds until `action` is usable again for this user; `0` when
    /// it's ready now.
    pub async fn cooldown_remaining(
        &self,
        platform: PlatformKind,
        user_id: &str,
        action: &str,
        window_secs: i64,
    ) -> i64 {
        let primary = self.primary(platform, user_id).await;
        let last = self
            .read(&format!("{COOLDOWN_PREFIX}{action}:{primary}"))
            .await as i64;
        (window_secs - (now() - last)).max(0)
    }

    /// Start `action`'s cooldown window from now.
    pub async fn touch_cooldown(
        &self,
        platform: PlatformKind,
        user_id: &str,
        action: &str,
    ) -> Result<()> {
        let primary = self.primary(platform, user_id).await;
        self.storage
            .set(
                &format!("{COOLDOWN_PREFIX}{action}:{primary}"),
                &now().to_string(),
            )
            .await
    }

    // -- cosmetics -----------------------------------------------------------

    /// The equipped title, if the player has one.
    pub async fn title(&self, platform: PlatformKind, user_id: &str) -> Option<String> {
        let primary = self.primary(platform, user_id).await;
        self.storage
            .get(&format!("{TITLE_PREFIX}{primary}"))
            .await
            .ok()
            .flatten()
            .filter(|s| !s.is_empty())
    }

    /// Equip a title (empty string clears it).
    pub async fn set_title(
        &self,
        platform: PlatformKind,
        user_id: &str,
        title: &str,
    ) -> Result<()> {
        let primary = self.primary(platform, user_id).await;
        self.storage
            .set(&format!("{TITLE_PREFIX}{primary}"), title)
            .await
    }

    /// Remember a user's latest display name, keyed by primary identity, so
    /// leaderboards can show names instead of raw ids. Called opportunisti-
    /// cally (e.g. from a message hook).
    pub async fn set_display_name(
        &self,
        platform: PlatformKind,
        user_id: &str,
        name: &str,
    ) -> Result<()> {
        let primary = self.primary(platform, user_id).await;
        self.storage
            .set(&format!("{NAME_PREFIX}{primary}"), name)
            .await
    }

    /// The stored display name for a primary identity, if we've seen one.
    pub async fn display_name_of(&self, primary: &str) -> Option<String> {
        self.storage
            .get(&format!("{NAME_PREFIX}{primary}"))
            .await
            .ok()
            .flatten()
            .filter(|s| !s.is_empty())
    }

    /// The custom profile colour, if bought.
    pub async fn color(&self, platform: PlatformKind, user_id: &str) -> Option<u32> {
        let primary = self.primary(platform, user_id).await;
        self.storage
            .get(&format!("{COLOR_PREFIX}{primary}"))
            .await
            .ok()
            .flatten()
            .and_then(|s| u32::from_str_radix(s.trim_start_matches('#'), 16).ok())
    }

    /// Store a custom profile colour.
    pub async fn set_color(&self, platform: PlatformKind, user_id: &str, rgb: u32) -> Result<()> {
        let primary = self.primary(platform, user_id).await;
        self.storage
            .set(&format!("{COLOR_PREFIX}{primary}"), &format!("{rgb:06X}"))
            .await
    }

    // -- achievements --------------------------------------------------------

    /// Grant an achievement by id. Returns `true` if it was newly awarded,
    /// `false` if the user already had it (so a caller can announce it only
    /// the first time). Ids are opaque strings the bot defines; names and
    /// descriptions live on the bot side so they stay fully customisable.
    pub async fn grant_achievement(
        &self,
        platform: PlatformKind,
        user_id: &str,
        id: &str,
    ) -> Result<bool> {
        let primary = self.primary(platform, user_id).await;
        let _guard = self.lock.lock().await;
        let key = format!("{ACH_PREFIX}{primary}");
        let mut owned = self.read_list(&key).await;
        if owned.iter().any(|a| a == id) {
            return Ok(false);
        }
        owned.push(id.to_owned());
        self.storage.set(&key, &owned.join("\n")).await?;
        Ok(true)
    }

    /// Whether the user already holds `id`.
    pub async fn has_achievement(&self, platform: PlatformKind, user_id: &str, id: &str) -> bool {
        let primary = self.primary(platform, user_id).await;
        self.read_list(&format!("{ACH_PREFIX}{primary}"))
            .await
            .iter()
            .any(|a| a == id)
    }

    /// Every achievement id the user has earned, in the order granted.
    pub async fn achievements(&self, platform: PlatformKind, user_id: &str) -> Vec<String> {
        let primary = self.primary(platform, user_id).await;
        self.read_list(&format!("{ACH_PREFIX}{primary}")).await
    }

    async fn read_list(&self, key: &str) -> Vec<String> {
        self.storage
            .get(key)
            .await
            .ok()
            .flatten()
            .map(|blob| {
                blob.lines()
                    .filter(|s| !s.is_empty())
                    .map(str::to_owned)
                    .collect()
            })
            .unwrap_or_default()
    }

    // -- leaderboard ---------------------------------------------------------

    /// Top `limit` players by `metric`, highest first.
    pub async fn leaderboard(&self, metric: Metric, limit: usize) -> Vec<RankedPlayer> {
        let mut ranked = self.ranked_all(metric).await;
        ranked.truncate(limit);
        ranked
    }

    /// A single user's rank (and value) for `metric`, or `None` if they've
    /// never earned anything.
    pub async fn rank_of(
        &self,
        platform: PlatformKind,
        user_id: &str,
        metric: Metric,
    ) -> Option<RankedPlayer> {
        let primary = self.primary(platform, user_id).await;
        self.ranked_all(metric)
            .await
            .into_iter()
            .find(|r| r.primary == primary)
    }

    /// How many players the economy has seen (anyone with XP or coins).
    pub async fn player_count(&self) -> usize {
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        for (key, _) in self
            .storage
            .list_prefix(XP_PREFIX)
            .await
            .unwrap_or_default()
        {
            if let Some(p) = key.strip_prefix(XP_PREFIX) {
                seen.insert(p.to_owned());
            }
        }
        for (key, _) in self
            .storage
            .list_prefix(COINS_PREFIX)
            .await
            .unwrap_or_default()
        {
            if let Some(p) = key.strip_prefix(COINS_PREFIX) {
                seen.insert(p.to_owned());
            }
        }
        seen.len()
    }

    async fn ranked_all(&self, metric: Metric) -> Vec<RankedPlayer> {
        let prefix = match metric {
            Metric::Xp => XP_PREFIX,
            Metric::Coins => COINS_PREFIX,
        };
        // Scan the store for every "<prefix><primary>" key at once instead
        // of keeping a hand-maintained index.
        let mut rows: Vec<(String, u64)> = self
            .storage
            .list_prefix(prefix)
            .await
            .unwrap_or_default()
            .into_iter()
            .filter_map(|(key, value)| {
                let primary = key.strip_prefix(prefix)?.to_owned();
                let value = value.parse().unwrap_or(0);
                Some((primary, value))
            })
            .collect();
        rows.sort_by_key(|row| std::cmp::Reverse(row.1));
        rows.into_iter()
            .enumerate()
            .map(|(position, (primary, value))| RankedPlayer {
                primary,
                value,
                position,
            })
            .collect()
    }

    async fn read(&self, key: &str) -> u64 {
        self.storage
            .get(key)
            .await
            .ok()
            .flatten()
            .and_then(|s| s.parse().ok())
            .unwrap_or(0)
    }
}

fn now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{storage::MemoryStorage, PlatformKind};

    fn econ() -> Economy {
        Economy::new(Accounts::new(MemoryStorage::new()))
    }

    #[test]
    fn level_curve() {
        assert_eq!(Economy::level_for(0), 0);
        assert_eq!(Economy::level_for(19), 0);
        assert_eq!(Economy::level_for(20), 1);
        assert_eq!(Economy::level_for(60), 2);
        assert_eq!(Economy::level_for(119), 2);
        assert_eq!(Economy::level_for(120), 3);
    }

    #[test]
    fn level_bounds_bracket_the_xp() {
        for xp in [0u64, 5, 25, 61, 200, 999] {
            let level = Economy::level_for(xp);
            let (lower, upper) = Economy::level_bounds(level);
            assert!(lower <= xp, "lower {lower} should be <= xp {xp}");
            assert!(xp < upper, "xp {xp} should be < upper {upper}");
        }
    }

    #[tokio::test]
    async fn xp_mints_coins_across_boundaries() {
        let e = econ();
        let d = PlatformKind::Discord;
        // 25 XP crosses two 10-XP boundaries, so two coins.
        let gain = e.add_xp(d, "u1", 25).await.unwrap();
        assert_eq!(gain.xp, 25);
        assert_eq!(gain.coins_minted, 2);
        let w = e.wallet(d, "u1").await;
        assert_eq!(w.xp, 25);
        assert_eq!(w.coins, 2);
    }

    #[tokio::test]
    async fn concurrent_grants_do_not_lose_updates() {
        let e = econ();
        let d = PlatformKind::Discord;
        let mut handles = Vec::new();
        for _ in 0..20 {
            let e = e.clone();
            handles.push(tokio::spawn(async move {
                e.add_xp(d, "u", 5).await.unwrap();
            }));
        }
        for h in handles {
            h.await.unwrap();
        }
        let w = e.wallet(d, "u").await;
        assert_eq!(w.xp, 100);
        assert_eq!(w.coins, 10);
    }

    #[tokio::test]
    async fn concurrent_transfers_cannot_overdraw() {
        let e = econ();
        let d = PlatformKind::Discord;
        e.add_coins(d, "rich", 100).await.unwrap();
        let a = {
            let e = e.clone();
            tokio::spawn(async move { e.transfer((d, "rich"), (d, "p1"), 100).await })
        };
        let b = {
            let e = e.clone();
            tokio::spawn(async move { e.transfer((d, "rich"), (d, "p2"), 100).await })
        };
        let (ra, rb) = (a.await.unwrap(), b.await.unwrap());
        // Exactly one transfer may succeed with a 100-coin balance.
        assert!(ra.is_ok() != rb.is_ok());
        let total = e.coins(d, "rich").await + e.coins(d, "p1").await + e.coins(d, "p2").await;
        assert_eq!(total, 100);
    }

    #[tokio::test]
    async fn transfer_moves_coins_and_refuses_overdraft() {
        let e = econ();
        let d = PlatformKind::Discord;
        e.add_coins(d, "rich", 100).await.unwrap();
        let left = e.transfer((d, "rich"), (d, "poor"), 30).await.unwrap();
        assert_eq!(left, 70);
        assert_eq!(e.coins(d, "poor").await, 30);
        assert!(e.transfer((d, "poor"), (d, "rich"), 999).await.is_err());
    }

    #[tokio::test]
    async fn leaderboard_orders_by_value() {
        let e = econ();
        let d = PlatformKind::Discord;
        e.add_xp(d, "a", 100).await.unwrap();
        e.add_xp(d, "b", 300).await.unwrap();
        e.add_xp(d, "c", 200).await.unwrap();
        let top = e.leaderboard(Metric::Xp, 10).await;
        assert_eq!(top[0].primary, "discord:b");
        assert_eq!(top[1].primary, "discord:c");
        assert_eq!(top[2].primary, "discord:a");
        assert_eq!(top[0].position, 0);
    }

    #[tokio::test]
    async fn rank_of_reports_position() {
        let e = econ();
        let d = PlatformKind::Discord;
        e.add_xp(d, "a", 100).await.unwrap();
        e.add_xp(d, "b", 300).await.unwrap();
        let rank = e.rank_of(d, "a", Metric::Xp).await.unwrap();
        assert_eq!(rank.position, 1); // behind "b"
        assert!(e.rank_of(d, "ghost", Metric::Xp).await.is_none());
    }

    #[tokio::test]
    async fn linking_merges_previously_earned_balances() {
        // A user earns XP on Discord, then links it to their Telegram
        // account with Telegram as primary. The old Discord-keyed XP must
        // fold into the primary instead of haunting the leaderboard.
        let accounts = Accounts::new(crate::storage::MemoryStorage::new());
        let e = Economy::new(accounts.clone());
        let d = PlatformKind::Discord;
        let t = PlatformKind::Telegram;

        e.add_xp(d, "42", 50).await.unwrap();
        assert_eq!(e.wallet_of("discord:42").await.xp, 50);

        // Link: telegram starts it, discord redeems, then telegram is
        // chosen as primary for both sides.
        let code = accounts.start_link(t, "777").await.unwrap();
        accounts.redeem_link(&code, d, "42").await.unwrap();
        accounts.set_primary(d, "42", "telegram:777").await.unwrap();

        // Any economy touch through the Discord identity now folds the
        // old balance into the primary.
        e.add_xp(d, "42", 1).await.unwrap();
        let w = e.wallet(t, "777").await;
        assert_eq!(w.xp, 51);
        assert_eq!(e.wallet_of("discord:42").await.xp, 0);

        // And the leaderboard has a single row for this person.
        let top = e.leaderboard(Metric::Xp, 10).await;
        assert_eq!(top.len(), 1);
        assert_eq!(top[0].primary, "telegram:777");
    }

    #[tokio::test]
    async fn cooldown_tracks_a_window() {
        let e = econ();
        let d = PlatformKind::Discord;
        // Nothing stamped yet: ready immediately.
        assert_eq!(e.cooldown_remaining(d, "u", "daily", 60).await, 0);
        e.touch_cooldown(d, "u", "daily").await.unwrap();
        // Right after touching, a 60s window should still be ticking.
        assert!(e.cooldown_remaining(d, "u", "daily", 60).await > 0);
        // A zero-length window is always ready.
        assert_eq!(e.cooldown_remaining(d, "u", "daily", 0).await, 0);
    }

    #[tokio::test]
    async fn cosmetics_persist() {
        let e = econ();
        let d = PlatformKind::Discord;
        assert!(e.title(d, "u").await.is_none());
        e.set_title(d, "u", "Legend").await.unwrap();
        assert_eq!(e.title(d, "u").await.as_deref(), Some("Legend"));
        e.set_color(d, "u", 0x00C2A8).await.unwrap();
        assert_eq!(e.color(d, "u").await, Some(0x00C2A8));
    }

    #[tokio::test]
    async fn achievements_grant_once() {
        let e = econ();
        let d = PlatformKind::Discord;
        assert!(!e.has_achievement(d, "u", "first_daily").await);
        assert!(e.grant_achievement(d, "u", "first_daily").await.unwrap()); // newly granted
        assert!(!e.grant_achievement(d, "u", "first_daily").await.unwrap()); // already had it
        assert!(e.has_achievement(d, "u", "first_daily").await);
        e.grant_achievement(d, "u", "high_roller").await.unwrap();
        assert_eq!(
            e.achievements(d, "u").await,
            vec!["first_daily".to_owned(), "high_roller".to_owned()]
        );
    }
}