feat: marketplace, économie à crédits, perks temps réel & pubs réelles

Transforme XIP en réseau social satirique complet : monnaie fictive,
marketplace, cosmétiques visibles de tous, messages riches sandboxés,
pubs pilotées par les données, et tous les compteurs mock rendus réels.

Backend (Bun + Hono + Prisma + Redis)
- Économie par IP : modèles Wallet/Purchase/Entitlement, lib/wallet.ts
  avec spend() atomique (point unique du paywall) + recharge gratuite.
- isLocalhost() → mode gratuit (README « si localhost: pas de paywall »).
- Marketplace : lib/catalog.ts (achat transactionnel, stock limité,
  limites par IP) + routes/shop.ts ; 10 produits seedés (idempotent).
- Perks : lib/perks.ts (cache Redis busté à l'achat) ; authorPerks
  injecté dans les payloads messages + endpoint batch /api/perks ;
  frame WS « perks » global pour MAJ live des messages déjà affichés.
- Messages riches : Message.richMode/richContent, gating par entitlement.
- Pubs réelles : modèle Ad seedé avec les 4 pubs (ex-hardcodées),
  rotation par API, comptage d'impressions réel + réconciliation.
- WebSocket : IP capturée par connexion → broadcastToIp / broadcast ;
  frames wallet/perks/ads/alert.
- Pièces jointes : lib/storage.ts (UUID, jamais exécuté) + routes/uploads.ts
  (limite 1 Mo sauf déblocage/localhost, Content-Disposition: attachment).
- Alerte audio : routes/alert.ts (cooldown serveur Redis NX, clamp durée).
- Compteur « argent extorqué » réel : impressions×CPM + crédits dépensés.

Frontend (Vue 3 + Vite)
- /shop : ShopPage + ProductCard fidèles aux maquettes ; composables
  useWallet/useShop/usePerks/useAds/useAttachments/useAlert.
- UI de réponse (bannière + sous-threads), solde + lien Shop dans le header.
- Perks rendus : Style Doré (or), Pets autour de l'IP, NoAds masque les pubs.
- RichContent.vue : iframe sandbox verrouillée (htmlcss sans script ;
  js allow-scripts seul, jamais allow-same-origin) + CSP.
- AdBand/InlineCasinoAd pilotés par l'API ; barre de saisie avec 📎,
  compteur de caractères, composer riche et bouton alerte.

Infra
- Migration economy_ads_attachments_rich ; seed idempotent (produits+pubs).
- vite.config : usePolling (HMR fiable sur /mnt/c via WSL).
- backend/.gitignore : uploads/.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-30 22:47:23 +02:00
parent 97f6fdaeae
commit cf239ab95f
46 changed files with 4080 additions and 198 deletions

View File

@@ -13,3 +13,21 @@ export function getIpColor(ip: string): string {
export function getIpGlow(color: string): string {
return color === '#666688' ? 'none' : `0 0 8px ${color}80`;
}
/** Gold skin (Style Doré) — overrides the djb2 palette for owners. */
const GOLD = '#ffdd44';
interface PerkLike {
skin?: 'gold';
}
/** Perk-aware color: gold for Style Doré owners, else the deterministic palette. */
export function getIpColorWithPerks(ip: string, perks?: PerkLike | null): string {
if (perks?.skin === 'gold') return GOLD;
return getIpColor(ip);
}
export function getIpGlowWithPerks(ip: string, perks?: PerkLike | null): string {
if (perks?.skin === 'gold') return `0 0 10px ${GOLD}cc`;
return getIpGlow(getIpColor(ip));
}

View File

@@ -0,0 +1,67 @@
import { ref, watch } from 'vue';
/** Ad inventory client: fetch ads by slot, report impressions (debounced). */
// Shared signal: bumped when the server broadcasts an `ads` frame (e.g. a user
// bought a Cadre de Pub). All useAds instances refetch when this changes.
const adsRevision = ref(0);
export function bumpAdsRevision(): void {
adsRevision.value++;
}
export interface Ad {
id: string;
brand: string;
subtitle?: string | null;
url?: string | null;
cta?: string | null;
icon?: string | null;
tone: string; // blue | green | purple | casino | user
kind: string; // band | casino
ownerIp?: string | null;
imageUrl?: string | null;
}
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';
export function useAds(kind: 'band' | 'casino') {
const ads = ref<Ad[]>([]);
async function fetchAds(): Promise<void> {
try {
const res = await fetch(`${API_URL}/api/ads?kind=${kind}`);
if (res.ok) ads.value = (await res.json()) as Ad[];
} catch {
/* ignore */
}
}
// Refetch whenever the server signals an inventory change.
watch(adsRevision, () => void fetchAds());
// Debounced impression reporting (each ad id at most once per flush).
const pending = new Set<string>();
let timer: ReturnType<typeof setTimeout> | null = null;
function reportImpression(id: string): void {
pending.add(id);
if (timer) return;
timer = setTimeout(flush, 800);
}
async function flush(): Promise<void> {
timer = null;
const ids = [...pending];
pending.clear();
if (!ids.length) return;
try {
await fetch(`${API_URL}/api/ads/impressions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids }),
});
} catch {
/* ignore */
}
}
return { ads, fetchAds, reportImpression };
}

View File

@@ -0,0 +1,86 @@
import { ref } from 'vue';
/**
* Global audio alert (paid, consumable). On an `alert` WS frame, every tab plays
* the sound at full volume for at most maxDurationMs. If a custom mp3 URL is
* provided it's played; otherwise a synthesized siren is used (WebAudio).
*
* Browser autoplay policies block sound before a user gesture — we unlock the
* AudioContext on the first click anywhere.
*/
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';
let audioCtx: AudioContext | null = null;
const lastFiredAt = ref(0);
function unlock(): void {
if (!audioCtx) {
const AC = (window as any).AudioContext || (window as any).webkitAudioContext;
if (AC) audioCtx = new AC();
}
if (audioCtx && audioCtx.state === 'suspended') void audioCtx.resume();
}
// Unlock on the first interaction.
if (typeof window !== 'undefined') {
window.addEventListener('pointerdown', unlock, { once: false });
}
function playSiren(maxDurationMs: number): void {
if (!audioCtx) return;
const dur = Math.min(maxDurationMs, 5000) / 1000;
const now = audioCtx.currentTime;
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = 'sawtooth';
// Warble between two pitches like an air-raid siren.
osc.frequency.setValueAtTime(440, now);
for (let t = 0; t < dur; t += 0.5) {
osc.frequency.linearRampToValueAtTime(880, now + t + 0.25);
osc.frequency.linearRampToValueAtTime(440, now + t + 0.5);
}
gain.gain.setValueAtTime(1, now); // volume à fond
gain.gain.setValueAtTime(1, now + dur - 0.05);
gain.gain.linearRampToValueAtTime(0, now + dur);
osc.connect(gain).connect(audioCtx.destination);
osc.start(now);
osc.stop(now + dur);
}
function playMp3(url: string, maxDurationMs: number): void {
const audio = new Audio(url);
audio.volume = 1;
void audio.play().catch(() => { /* autoplay blocked */ });
setTimeout(() => { audio.pause(); audio.currentTime = 0; }, Math.min(maxDurationMs, 5000));
}
/** Handle an incoming `alert` frame. */
export function handleAlertFrame(data: { soundUrl?: string; maxDurationMs?: number }): void {
lastFiredAt.value = Date.now();
const max = data.maxDurationMs ?? 5000;
unlock();
if (data.soundUrl) playMp3(data.soundUrl, max);
else playSiren(max);
}
export function useAlert() {
async function fireAlert(soundUrl?: string): Promise<{ ok: boolean; error?: string }> {
unlock();
try {
const res = await fetch(`${API_URL}/api/alert`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ soundUrl }),
});
if (!res.ok) {
const d = await res.json().catch(() => ({}));
return { ok: false, error: d.error || 'Alerte impossible' };
}
return { ok: true };
} catch {
return { ok: false, error: 'Réseau indisponible' };
}
}
return { fireAlert };
}

View File

@@ -0,0 +1,43 @@
/** Upload helper: posts a file to /api/uploads, returns its metadata. */
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';
export interface UploadedAttachment {
id: string;
filename: string;
mimeType: string;
size: number;
}
export type UploadResult =
| { ok: true; attachment: UploadedAttachment }
| { ok: false; error: string };
export function useAttachments() {
async function uploadFile(file: File): Promise<UploadResult> {
const form = new FormData();
form.append('file', file);
try {
const res = await fetch(`${API_URL}/api/uploads`, { method: 'POST', body: form });
const data = await res.json().catch(() => ({}));
if (!res.ok) return { ok: false, error: data.error || 'Upload refusé' };
return { ok: true, attachment: data as UploadedAttachment };
} catch {
return { ok: false, error: 'Réseau indisponible' };
}
}
/** Human file size. */
function kb(bytes: number): string {
if (bytes >= 1_000_000) return (bytes / 1_000_000).toFixed(1) + ' Mo';
if (bytes >= 1000) return Math.round(bytes / 1000) + ' Ko';
return bytes + ' o';
}
/** URL to fetch/download an attachment. */
function urlFor(id: string): string {
return `${API_URL}/api/uploads/${id}`;
}
return { uploadFile, kb, urlFor };
}

View File

@@ -1,10 +1,27 @@
import { ref, onMounted } from 'vue';
import { useRealtime } from './useRealtime';
import { useWallet, applyWalletFrame } from './useWallet';
import { setPerks, applyPerksFrame, type Perks } from './usePerks';
import { bumpAdsRevision } from './useAds';
import { handleAlertFrame } from './useAlert';
export interface Reply {
id: string;
content: string;
authorIp: string;
createdAt: string;
parentId?: string | null;
authorPerks?: Perks;
richMode?: 'none' | 'htmlcss' | 'js';
richContent?: string | null;
attachments?: Attachment[];
}
export interface Attachment {
id: string;
filename: string;
mimeType: string;
size: number;
}
export interface Message extends Reply {
@@ -19,37 +36,164 @@ export function useMessages() {
const loading = ref(false);
const sending = ref(false);
/** Seed the perks store from a message + its replies. */
function harvestPerks(m: Message): void {
setPerks(m.authorIp, m.authorPerks);
for (const r of m.replies ?? []) setPerks(r.authorIp, r.authorPerks);
}
async function fetchMessages(): Promise<void> {
loading.value = true;
try {
const res = await fetch(`${API_URL}/api/messages`);
if (res.ok) {
// L'API renvoie du plus récent au plus ancien ; on inverse pour affichage chronologique
messages.value = ((await res.json()) as Message[]).reverse();
// API returns newest→oldest; reverse for chronological display.
const list = ((await res.json()) as Message[]).reverse();
list.forEach(harvestPerks);
messages.value = list;
}
} finally {
loading.value = false;
}
}
async function postMessage(content: string): Promise<boolean> {
if (!content.trim()) return false;
/** Add a message pushed over the WebSocket (new thread or reply), with dedup. */
function addIncoming(raw: Message & { parentId: string | null }): void {
if (!raw || !raw.id) return;
// Always record the author's perks, even for replies.
setPerks(raw.authorIp, raw.authorPerks);
if (raw.parentId == null) {
// New top-level thread.
if (messages.value.some((m) => m.id === raw.id)) return;
messages.value.push({ ...raw, replies: raw.replies ?? [] });
return;
}
// Reply: attach to its parent thread if we have it.
const parent = messages.value.find((m) => m.id === raw.parentId);
if (!parent) return; // thread not loaded; reconnect-resync will reconcile
if (parent.replies.some((r) => r.id === raw.id)) return;
parent.replies.push({
id: raw.id,
content: raw.content,
authorIp: raw.authorIp,
createdAt: raw.createdAt,
parentId: raw.parentId,
authorPerks: raw.authorPerks,
richMode: raw.richMode,
richContent: raw.richContent,
attachments: raw.attachments,
});
}
const { fetchWallet, ip: myIp } = useWallet();
// The viewer's own perks (drives NoAds gating, rich-composer unlocks, etc.).
const myPerks = ref<Perks>({});
async function fetchMyPerks(): Promise<void> {
try {
const res = await fetch(`${API_URL}/api/shop/me`);
if (!res.ok) return;
const { entitlements } = (await res.json()) as {
entitlements: { kind: string; metaJson?: string | null }[];
};
const p: Perks = {};
const pets: { char: string; position: 'left' | 'right' | 'both' }[] = [];
for (const e of entitlements) {
let meta: any = {};
try { meta = e.metaJson ? JSON.parse(e.metaJson) : {}; } catch { /* */ }
if (e.kind === 'noads') { p.noads = true; if (meta.plan === 'annual') p.badge = true; }
if (e.kind === 'style-dore') p.skin = 'gold';
if (e.kind === 'pet' && meta.char) pets.push({ char: meta.char, position: meta.position ?? 'left' });
if (e.kind === 'element-skin') p.elementSkin = true;
if (e.kind === 'rich-htmlcss') p.richHtmlcss = true;
if (e.kind === 'rich-js') p.richJs = true;
if (e.kind === 'no-file-limit') p.noFileLimit = true;
if (e.kind === 'audio-alert') p.audioAlert = true;
}
if (pets.length) p.pets = pets.slice(0, 3);
myPerks.value = p;
if (myIp.value) setPerks(myIp.value, p);
} catch {
/* ignore */
}
}
const { stats, connected, sendTyping } = useRealtime({
onMessage: addIncoming,
onReconnect: () => {
fetchMessages();
fetchWallet();
fetchMyPerks();
},
onWallet: applyWalletFrame,
onPerks: (data: { ip: string; perks: Perks }) => {
applyPerksFrame(data);
// If it's about us, update myPerks too (viewer-scoped perks like NoAds).
if (myIp.value && data.ip === myIp.value) myPerks.value = data.perks ?? {};
},
onAds: () => bumpAdsRevision(), // a user ad entered rotation → refetch
onAlert: (data) => handleAlertFrame(data), // paid global audio alert
});
interface PostExtras {
parentId?: string;
richMode?: 'htmlcss' | 'js';
richContent?: string;
attachmentIds?: string[];
}
async function postMessage(content: string, extras: PostExtras = {}): Promise<boolean> {
const hasRich = !!extras.richContent && !!extras.richMode;
const hasFiles = !!extras.attachmentIds?.length;
// Allow empty text only when there's rich content or an attachment.
if (!content.trim() && !hasRich && !hasFiles) return false;
sending.value = true;
try {
const res = await fetch(`${API_URL}/api/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: content.trim() }),
body: JSON.stringify({
content: content.trim() || ' ',
parentId: extras.parentId,
richMode: extras.richMode,
richContent: extras.richContent,
attachmentIds: extras.attachmentIds,
}),
});
if (!res.ok) return false;
await fetchMessages();
// The created message comes back via the WebSocket broadcast, so no
// re-fetch here. Fallback: if the socket is down, add it locally.
if (!connected.value) {
const created = (await res.json()) as Message;
addIncoming(
created.parentId == null ? { ...created, replies: [] } : created
);
}
return true;
} finally {
sending.value = false;
}
}
onMounted(fetchMessages);
onMounted(() => {
fetchMessages();
fetchWallet();
fetchMyPerks();
});
return { messages, loading, sending, postMessage };
return {
messages,
loading,
sending,
postMessage,
stats,
connected,
sendTyping,
myPerks,
fetchMyPerks,
};
}

View File

@@ -0,0 +1,41 @@
import { reactive } from 'vue';
/**
* Perks store (module-level singleton): maps an author IP → its visible perks.
* Seeded from message payloads (authorPerks), updated live by WS `perks` frames,
* and read by MessageItem to colour names / render pets for every author.
*/
export type PetPosition = 'left' | 'right' | 'both';
export interface Perks {
skin?: 'gold';
pets?: { char: string; position: PetPosition }[];
noads?: boolean;
badge?: boolean;
elementSkin?: boolean;
richHtmlcss?: boolean;
richJs?: boolean;
noFileLimit?: boolean;
audioAlert?: boolean;
}
const map = reactive<Record<string, Perks>>({});
/** Merge perks for one IP (from a message payload or a perks frame). */
export function setPerks(ip: string, perks: Perks | undefined | null): void {
if (!ip || !perks) return;
map[ip] = perks;
}
/** Apply a WS `perks` frame: { ip, perks }. */
export function applyPerksFrame(data: { ip: string; perks: Perks }): void {
if (data?.ip) map[data.ip] = data.perks ?? {};
}
export function usePerks() {
function perksFor(ip: string): Perks {
return map[ip] ?? {};
}
return { perksFor, setPerks };
}

View File

@@ -0,0 +1,125 @@
import { ref, onMounted, onUnmounted } from 'vue';
/** Mirror of the backend StatsSnapshot. */
export interface Stats {
// live
connectedTabs: number;
typingNow: number;
lettersPerSec: number;
msgsPerMin: number;
// totals
messages: number;
replies: number;
charsSent: number;
lettersTyped: number;
uniqueIps: number;
longestMsg: number;
// derived
abandonRate: number;
avgLength: number;
moneyExtorted: number;
}
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';
const WS_URL = API_URL.replace(/^http/, 'ws') + '/ws';
const TYPING_FLUSH_MS = 400; // batch keystroke deltas before sending
const RECONNECT_DELAY_MS = 1500;
interface RealtimeHooks {
onMessage?: (raw: any) => void;
/** Called when the socket reconnects after a drop — use to resync state. */
onReconnect?: () => void;
/** Wallet update for THIS tab's IP (balance changed). */
onWallet?: (data: any) => void;
/** A visible perk changed for some IP (skin/pet) — update that author everywhere. */
onPerks?: (data: any) => void;
/** Ad inventory changed (e.g. a user bought a Cadre de Pub). */
onAds?: (data: any) => void;
/** A paid global audio alert was fired. */
onAlert?: (data: any) => void;
}
export function useRealtime(hooks: RealtimeHooks = {}) {
const stats = ref<Stats | null>(null);
const connected = ref(false);
let ws: WebSocket | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
let typingTimer: ReturnType<typeof setTimeout> | null = null;
let typingBuffer = 0;
let everConnected = false;
let closedByUs = false;
function connect(): void {
try {
ws = new WebSocket(WS_URL);
} catch {
scheduleReconnect();
return;
}
ws.onopen = () => {
connected.value = true;
if (everConnected) hooks.onReconnect?.();
everConnected = true;
};
ws.onmessage = (ev) => {
let msg: { type?: string; data?: any };
try {
msg = JSON.parse(ev.data);
} catch {
return;
}
if (msg.type === 'stats') stats.value = msg.data as Stats;
else if (msg.type === 'message') hooks.onMessage?.(msg.data);
else if (msg.type === 'wallet') hooks.onWallet?.(msg.data);
else if (msg.type === 'perks') hooks.onPerks?.(msg.data);
else if (msg.type === 'ads') hooks.onAds?.(msg.data);
else if (msg.type === 'alert') hooks.onAlert?.(msg.data);
};
ws.onclose = () => {
connected.value = false;
if (!closedByUs) scheduleReconnect();
};
ws.onerror = () => {
ws?.close();
};
}
function scheduleReconnect(): void {
if (reconnectTimer || closedByUs) return;
reconnectTimer = setTimeout(() => {
reconnectTimer = null;
connect();
}, RECONNECT_DELAY_MS);
}
/** Report keystrokes (delta ≥ 0). Marks this tab as "typing" and feeds the global counter. */
function sendTyping(delta: number): void {
typingBuffer += Math.max(0, delta);
if (typingTimer) return;
typingTimer = setTimeout(flushTyping, TYPING_FLUSH_MS);
}
function flushTyping(): void {
typingTimer = null;
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'typing', delta: typingBuffer }));
}
typingBuffer = 0;
}
onMounted(connect);
onUnmounted(() => {
closedByUs = true;
if (reconnectTimer) clearTimeout(reconnectTimer);
if (typingTimer) clearTimeout(typingTimer);
ws?.close();
});
return { stats, connected, sendTyping };
}

View File

@@ -0,0 +1,123 @@
import { ref } from 'vue';
import { useWallet } from './useWallet';
/** Marketplace client: catalogue, my entitlements, purchase flow. */
export interface Product {
id: string;
category: string;
name: string;
subtitle?: string | null;
kind: string;
basePrice: number; // centi-credits
promoPrice?: number | null;
badge?: string | null;
stockLimit?: number | null;
stockSold: number;
sortOrder: number;
metaJson?: string | null;
}
export interface Entitlement {
id: string;
ip: string;
kind: string;
active: boolean;
expiresAt?: string | null;
metaJson?: string | null;
createdAt: string;
}
export interface PurchaseOptions {
plan?: 'monthly' | 'annual';
durationDays?: number;
format?: 'static' | 'gif';
url?: string;
petDesign?: string;
petChar?: string;
petPosition?: 'left' | 'right' | 'both';
}
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';
export function useShop() {
const products = ref<Product[]>([]);
const entitlements = ref<Entitlement[]>([]);
const loading = ref(false);
const buying = ref<string | null>(null); // productId currently being purchased
const lastError = ref<string | null>(null);
const lastSuccess = ref<string | null>(null);
const { fetchWallet } = useWallet();
async function fetchProducts(): Promise<void> {
loading.value = true;
try {
const res = await fetch(`${API_URL}/api/shop/products`);
if (res.ok) products.value = (await res.json()) as Product[];
} finally {
loading.value = false;
}
}
async function fetchMe(): Promise<void> {
try {
const res = await fetch(`${API_URL}/api/shop/me`);
if (res.ok) {
const data = await res.json();
entitlements.value = data.entitlements ?? [];
}
} catch {
/* ignore */
}
}
function owns(kind: string): boolean {
return entitlements.value.some((e) => e.kind === kind && e.active);
}
function petCount(): number {
return entitlements.value.filter((e) => e.kind === 'pet' && e.active).length;
}
async function purchase(productId: string, options: PurchaseOptions = {}): Promise<boolean> {
buying.value = productId;
lastError.value = null;
lastSuccess.value = null;
try {
const res = await fetch(`${API_URL}/api/shop/purchase`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId, options }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
lastError.value = data.error || 'Achat impossible';
return false;
}
lastSuccess.value = `Acheté : ${productId}`;
// Refresh wallet + my entitlements (WS also pushes wallet, this is belt-and-braces).
await Promise.all([fetchWallet(), fetchMe(), fetchProducts()]);
return true;
} catch {
lastError.value = 'Réseau indisponible';
return false;
} finally {
buying.value = null;
}
}
return {
products,
entitlements,
loading,
buying,
lastError,
lastSuccess,
fetchProducts,
fetchMe,
owns,
petCount,
purchase,
};
}

View File

@@ -0,0 +1,72 @@
import { ref } from 'vue';
/**
* Wallet store (module-level singleton so the header, shop, and composer all
* share one balance). Credits are CENTI-CREDITS server-side; `displayBalance`
* converts to a human "crédits" number. Live updates arrive via the WS `wallet`
* frame, routed here through useMessages' realtime hook (applyWalletFrame).
*/
export interface WalletView {
ip: string;
balance: number; // centi-credits, or a huge sentinel in free mode
freeMode: boolean;
}
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';
const ip = ref<string>('');
const balanceRaw = ref<number>(0); // centi-credits
const freeMode = ref<boolean>(false);
const loaded = ref<boolean>(false);
function apply(view: WalletView): void {
ip.value = view.ip;
balanceRaw.value = view.balance;
freeMode.value = view.freeMode;
loaded.value = true;
}
/** Called by the realtime `wallet` frame handler. */
export function applyWalletFrame(data: WalletView): void {
apply(data);
}
async function fetchWallet(): Promise<void> {
try {
const res = await fetch(`${API_URL}/api/wallet`);
if (res.ok) apply((await res.json()) as WalletView);
} catch {
/* offline — keep last known */
}
}
async function topUp(): Promise<void> {
try {
const res = await fetch(`${API_URL}/api/wallet/topup`, { method: 'POST' });
if (res.ok) apply((await res.json()) as WalletView);
} catch {
/* ignore */
}
}
/** Human-readable balance ("∞" in free mode, else credits with 2 decimals). */
function displayBalance(): string {
if (freeMode.value) return '∞';
return (balanceRaw.value / 100).toLocaleString('fr-FR', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
}
export function useWallet() {
return {
ip,
balanceRaw,
freeMode,
loaded,
fetchWallet,
topUp,
displayBalance,
};
}