# Wallet Balance Synchronization

## Overview
This document describes how the platform ensures that the user's balance remains synchronized across the UI after any balance-impacting transaction (e.g., funding an investment, rewards, etc.).

We use a **Query Invalidation** pattern via TanStack Query (React Query) to "react" to backend changes.

---

## Synchronization Architecture

### 1. Dedicated Multi-Wallet Endpoint
To avoid expensive re-authentication calls just to fetch a balance, the backend provides dedicated endpoints:
- `GET /api/users/me/`: Returns the full user profile.
- `GET /api/users/me/wallets/`: Returns an array of current wallet balances.

### 2. Supported Wallets
The system tracks multiple point types as defined in the `User` model:
| Type | Label | Description |
| :--- | :--- | :--- |
| `credit_balance` | Primary | Main funds used for investments. |
| `bonus` | Bonus | Promotional rewards and bonuses. |

---

## The "Reaction" Pattern

React does not have a built-in "reaction" system for external state. We achieve the "reaction" by standardizing on TanStack Query keys and invalidating them on successful mutations.

### 1. Centralized Query Keys
We use high-level keys for user data:
- `['user']`: Tracks general profile data and main balance.
- `['wallets']`: Tracks the list of all wallet balances.

### 2. Mutation Invalidation (Triggering the Sync)
Whenever a component performs a mutation that changes a wallet state (like `useCreateInvestment`), it must invalidate these keys in its `onSuccess` callback.

```typescript
// Example Implementation in useCreateInvestment.ts
const queryClient = useQueryClient();

return useMutation({
  mutationFn: (amount) => api.createInvestment(amount),
  onSuccess: () => {
    // This triggers the "reaction" by forcing a fresh fetch
    queryClient.invalidateQueries({ queryKey: ['user'] });
    queryClient.invalidateQueries({ queryKey: ['wallets'] });
  }
});
```

---

## Backend Requirements
To support this synchronization, the backend ensures:
- All balance updates use `django-wallet-utils` for atomic operations.
- The `User` model accurately reflects all wallet types as individual `DecimalField` columns.
- The `/me/wallets/` endpoint returns the latest snapshot from the DB.

For details on the underlying wallet package, see `django-wallet-utils/docs/usage.md`.
