After changing the icon

This commit is contained in:
Your Name 2026-10-12 19:18:13 +02:00
parent c79844571f
commit 24a24a7897
109 changed files with 2299 additions and 494 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

After

Width:  |  Height:  |  Size: 411 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 174 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 1023 B

After

Width:  |  Height:  |  Size: 549 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

After

Width:  |  Height:  |  Size: 411 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

After

Width:  |  Height:  |  Size: 411 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 548 KiB

View File

@ -0,0 +1,248 @@
"""Generate TLoto brand PNGs and distribute to web/mobile icon slots."""
from __future__ import annotations
import math
import shutil
from pathlib import Path
from PIL import Image, ImageDraw, ImageFilter
ROOT = Path(__file__).resolve().parents[1]
BRAND = ROOT / "brand"
AI_SRC = Path(
r"C:\Users\ADMIN\.cursor\projects\d-Projects-Workplace-Own-Projects-games-app\assets\tloto-mark-final.jpg"
)
if not AI_SRC.exists():
AI_SRC = Path(
r"C:\Users\ADMIN\.cursor\projects\d-Projects-Workplace-Own-Projects-games-app\assets\tloto-mark-v1.jpg"
)
NAVY = (11, 15, 26, 255)
GOLD = (212, 175, 55, 255)
EMERALD_TOP = (52, 211, 153, 255)
EMERALD = (16, 185, 129, 255)
EMERALD_DEEP = (4, 120, 87, 255)
def _lerp(a, b, t: float):
return tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(4))
def _rounded_rect_mask(size: int, radius: int) -> Image.Image:
m = Image.new("L", (size, size), 0)
d = ImageDraw.Draw(m)
d.rounded_rectangle((0, 0, size - 1, size - 1), radius=radius, fill=255)
return m
def draw_mark(size: int = 1024) -> Image.Image:
"""Vector-like raster of the fused T+L mark."""
s = size
img = Image.new("RGBA", (s, s), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
# Background squircle
bg = Image.new("RGBA", (s, s), (0, 0, 0, 0))
bg_draw = ImageDraw.Draw(bg)
rr = int(s * 0.22)
bg_draw.rounded_rectangle((0, 0, s - 1, s - 1), radius=rr, fill=NAVY)
# Gold border
inset = int(s * 0.05)
border_w = max(2, int(s * 0.022))
bg_draw.rounded_rectangle(
(inset, inset, s - 1 - inset, s - 1 - inset),
radius=max(1, rr - inset // 2),
outline=GOLD,
width=border_w,
)
img = Image.alpha_composite(img, bg)
draw = ImageDraw.Draw(img)
# Glyph geometry in 128-space scaled
def xy(x: float, y: float) -> tuple[float, float]:
return x / 128 * s, y / 128 * s
# Continuous TL path points (outer contour)
pts = [
xy(34, 24),
xy(84, 24),
xy(102, 40),
xy(84, 56),
xy(54, 56),
xy(54, 74),
xy(76, 74),
xy(94, 90),
xy(76, 106),
xy(34, 106),
xy(17, 90),
xy(17, 40),
]
# Build filled glyph on its own layer for gradient
glyph = Image.new("RGBA", (s, s), (0, 0, 0, 0))
gdraw = ImageDraw.Draw(glyph)
# Approximate smooth TL with thick rounded polygon + rounded bars
# Top canopy (T)
top = [
xy(28, 28),
xy(88, 28),
xy(100, 40),
xy(88, 52),
xy(50, 52),
xy(50, 40),
xy(28, 40),
]
# Stem
stem = [
xy(28, 40),
xy(50, 40),
xy(50, 88),
xy(28, 88),
]
# Foot (L)
foot = [
xy(28, 78),
xy(82, 78),
xy(94, 90),
xy(82, 102),
xy(28, 102),
]
def fill_soft(poly, color):
gdraw.polygon(poly, fill=color)
# Gradient by layered fills
fill_soft(top, EMERALD_TOP)
fill_soft(stem, EMERALD)
fill_soft(foot, EMERALD_DEEP)
# Soften joints with overlapping rounded rects
x0, y0 = xy(28, 28)
x1, y1 = xy(50, 102)
gdraw.rounded_rectangle((x0, y0, x1, y1), radius=int(s * 0.06), fill=EMERALD)
# Top arm
tx0, ty0 = xy(28, 28)
tx1, ty1 = xy(100, 52)
gdraw.rounded_rectangle((tx0, ty0, tx1, ty1), radius=int(s * 0.07), fill=EMERALD_TOP)
# Blend mid
mx0, my0 = xy(28, 40)
mx1, my1 = xy(92, 52)
gdraw.rounded_rectangle((mx0, my0, mx1, my1), radius=int(s * 0.05), fill=EMERALD)
# L foot
fx0, fy0 = xy(28, 78)
fx1, fy1 = xy(94, 102)
gdraw.rounded_rectangle((fx0, fy0, fx1, fy1), radius=int(s * 0.07), fill=EMERALD)
# Slight blur then re-composite for premium softness at edges
glyph = glyph.filter(ImageFilter.GaussianBlur(radius=max(0.4, s / 900)))
# Re-sharpen core by overlaying unblurred core at lower opacity handled via mask
core = Image.new("RGBA", (s, s), (0, 0, 0, 0))
cdraw = ImageDraw.Draw(core)
cdraw.rounded_rectangle((x0, y0, x1, y1), radius=int(s * 0.06), fill=EMERALD)
cdraw.rounded_rectangle((tx0, ty0, tx1, ty1), radius=int(s * 0.07), fill=EMERALD_TOP)
cdraw.rounded_rectangle((fx0, fy0, fx1, fy1), radius=int(s * 0.07), fill=EMERALD)
glyph = Image.alpha_composite(glyph, core)
img = Image.alpha_composite(img, glyph)
draw = ImageDraw.Draw(img)
# Gold spark at joint
cx, cy = xy(54, 52)
r = s * 0.028
spark = [
(cx, cy - r * 1.7),
(cx + r * 0.35, cy - r * 0.35),
(cx + r * 1.7, cy),
(cx + r * 0.35, cy + r * 0.35),
(cx, cy + r * 1.7),
(cx - r * 0.35, cy + r * 0.35),
(cx - r * 1.7, cy),
(cx - r * 0.35, cy - r * 0.35),
]
draw.polygon(spark, fill=GOLD)
return img
def prepare_from_ai(size: int = 1024) -> Image.Image | None:
if not AI_SRC.exists():
return None
src = Image.open(AI_SRC).convert("RGBA")
# Center-crop to square
w, h = src.size
side = min(w, h)
left = (w - side) // 2
top = (h - side) // 2
src = src.crop((left, top, left + side, top + side))
src = src.resize((size, size), Image.Resampling.LANCZOS)
# Apply squircle mask so PNG edges are clean for adaptive icons
mask = _rounded_rect_mask(size, int(size * 0.22))
out = Image.new("RGBA", (size, size), (0, 0, 0, 0))
out.paste(src, (0, 0))
out.putalpha(mask)
return out
def save_png(img: Image.Image, path: Path, size: int | None = None) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
out = img if size is None else img.resize((size, size), Image.Resampling.LANCZOS)
if out.mode != "RGBA":
out = out.convert("RGBA")
out.save(path, format="PNG", optimize=True)
def make_lockup(mark: Image.Image, width: int = 1600, height: int = 512) -> Image.Image:
canvas = Image.new("RGBA", (width, height), (0, 0, 0, 0))
mark_size = height
m = mark.resize((mark_size, mark_size), Image.Resampling.LANCZOS)
canvas.paste(m, (0, 0), m)
# Wordmark drawn by SVG/text elsewhere; keep mark-only lockup base transparent
# Consumers use SVG lockup for text; PNG lockup = mark + transparent padding
return canvas
def distribute(master: Image.Image) -> None:
# Brand master
save_png(master, BRAND / "prediqo-mark.png", 1024)
save_png(master, BRAND / "prediqo-app-icon.png", 1024)
save_png(master, BRAND / "prediqo-mark-source.png", 1024)
lockup = make_lockup(master)
save_png(lockup, BRAND / "prediqo-lockup.png")
save_png(lockup, BRAND / "prediqo-lockup-source.png")
# Web public
web_brand = ROOT / "prediqo_web" / "public" / "brand"
save_png(master, web_brand / "prediqo-mark.png", 512)
save_png(master, web_brand / "prediqo-app-icon.png", 512)
save_png(lockup, web_brand / "prediqo-lockup.png")
shutil.copy2(BRAND / "prediqo-mark.svg", web_brand / "prediqo-mark.svg")
shutil.copy2(BRAND / "prediqo-lockup.svg", web_brand / "prediqo-lockup.svg")
# Favicon SVG (same mark)
shutil.copy2(BRAND / "prediqo-mark.svg", ROOT / "prediqo_web" / "public" / "favicon.svg")
# Mobile assets
mobile_brand = ROOT / "prediqo_mobile" / "assets" / "brand"
save_png(master, mobile_brand / "prediqo-mark.png", 512)
save_png(master, mobile_brand / "prediqo-app-icon.png", 1024)
save_png(lockup, mobile_brand / "prediqo-lockup.png")
shutil.copy2(BRAND / "prediqo-mark.svg", mobile_brand / "prediqo-mark.svg")
# Mobile web favicon
save_png(master, ROOT / "prediqo_mobile" / "web" / "favicon.png", 192)
print("Distributed brand assets.")
def main() -> None:
ai = prepare_from_ai(1024)
# Prefer AI master; fall back to vector draw only if AI source is missing.
master = ai if ai is not None else draw_mark(1024)
print(f"Using AI master from {AI_SRC}" if ai is not None else "Using vector-drawn master")
distribute(master)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,57 @@
"""Make SVG mark identical to the master PNG by embedding it."""
from __future__ import annotations
import base64
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BRAND = ROOT / "brand"
PNG = BRAND / "prediqo-mark.png"
def main() -> None:
b64 = base64.b64encode(PNG.read_bytes()).decode("ascii")
mark = (
'<svg xmlns="http://www.w3.org/2000/svg" '
'xmlns:xlink="http://www.w3.org/1999/xlink" '
'viewBox="0 0 128 128" role="img" aria-label="Tloto mark">\n'
" <!-- Identical to prediqo-mark.png (embedded master artwork) -->\n"
f' <image href="data:image/png;base64,{b64}" '
'x="0" y="0" width="128" height="128" '
'preserveAspectRatio="xMidYMid meet"/>\n'
"</svg>\n"
)
lockup = (
'<svg xmlns="http://www.w3.org/2000/svg" '
'xmlns:xlink="http://www.w3.org/1999/xlink" '
'viewBox="0 0 400 128" role="img" aria-label="Tloto">\n'
f' <image href="data:image/png;base64,{b64}" '
'x="0" y="0" width="128" height="128" '
'preserveAspectRatio="xMidYMid meet"/>\n'
' <text x="152" y="82" '
'font-family="Inter, Segoe UI, system-ui, sans-serif" '
'font-size="64" font-weight="800" fill="#F8FAFC" '
'letter-spacing="-1.5">TLOTO</text>\n'
"</svg>\n"
)
targets_mark = [
BRAND / "prediqo-mark.svg",
ROOT / "prediqo_web" / "public" / "brand" / "prediqo-mark.svg",
ROOT / "prediqo_web" / "public" / "favicon.svg",
ROOT / "prediqo_mobile" / "assets" / "brand" / "prediqo-mark.svg",
]
targets_lockup = [
BRAND / "prediqo-lockup.svg",
ROOT / "prediqo_web" / "public" / "brand" / "prediqo-lockup.svg",
]
for path in targets_mark:
path.write_text(mark, encoding="utf-8")
print(f"wrote {path}")
for path in targets_lockup:
path.write_text(lockup, encoding="utf-8")
print(f"wrote {path}")
if __name__ == "__main__":
main()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 389 KiB

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 389 KiB

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 KiB

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 389 KiB

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

After

Width:  |  Height:  |  Size: 411 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

After

Width:  |  Height:  |  Size: 156 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 548 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 389 KiB

After

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 592 B

After

Width:  |  Height:  |  Size: 773 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1013 B

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.3 KiB

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

After

Width:  |  Height:  |  Size: 108 KiB

View File

@ -38,7 +38,7 @@
</scene>
</scenes>
<resources>
<image name="LaunchImage" width="1024" height="1024"/>
<image name="LaunchImage" width="512" height="512"/>
<image name="LaunchBackground" width="1" height="1"/>
</resources>
</document>

View File

@ -62,6 +62,9 @@ Future<void> configureDependencies({AppConfig? config}) async {
if (!sl.isRegistered<WalletRepositoryImpl>()) {
sl.registerLazySingleton<WalletRepositoryImpl>(() => WalletRepositoryImpl(sl()));
}
if (!sl.isRegistered<WalletRepository>()) {
sl.registerLazySingleton<WalletRepository>(() => sl<WalletRepositoryImpl>());
}
if (!sl.isRegistered<AdminRepositoryImpl>()) {
sl.registerLazySingleton<AdminRepositoryImpl>(() => AdminRepositoryImpl(sl()));
}
@ -99,7 +102,14 @@ Future<void> configureDependencies({AppConfig? config}) async {
sl.registerFactory<AuthBloc>(() => AuthBloc(sl())..add(const AuthCheckRequested()));
}
if (!sl.isRegistered<WalletBloc>()) {
sl.registerFactory<WalletBloc>(() => WalletBloc(sl<WalletRepositoryImpl>()));
sl.registerFactory<WalletBloc>(
() => WalletBloc(
sl<WalletRepository>(),
sl<HealthRepository>(),
sl<ReferralRepository>(),
shareCards: sl<ShareCardRepository>(),
),
);
}
if (!sl.isRegistered<PredictionBloc>()) {
sl.registerFactory<PredictionBloc>(() => PredictionBloc(sl(), sl(), sl()));

View File

@ -4,12 +4,90 @@ import '../../core/network/api_client.dart';
import '../../data/models/advertisement_models.dart';
import '../../domain/repositories/advertisement_repository.dart';
/// Short TTL + in-flight coalesce for `/api/v1/advertisements`.
/// Shared by Home and Welcome, keyed by placement.
class AdvertisementStore {
static const ttl = Duration(seconds: 45);
List<AdvertisementModel>? _cached;
DateTime? _cachedAt;
Future<List<AdvertisementModel>>? _inFlight;
int fetchStarts = 0;
List<AdvertisementModel>? peekLast() => _cached;
List<AdvertisementModel>? peekFresh() {
if (_cached == null || _cachedAt == null) return null;
if (DateTime.now().difference(_cachedAt!) >= ttl) return null;
return _cached;
}
void invalidate() {
_cached = null;
_cachedAt = null;
}
Future<List<AdvertisementModel>> get(
Future<List<AdvertisementModel>> Function() fetch, {
bool force = false,
}) async {
if (!force) {
final hit = peekFresh();
if (hit != null) return hit;
if (_inFlight != null) return _inFlight!;
}
fetchStarts++;
final future = fetch().then((value) {
_cached = value;
_cachedAt = DateTime.now();
return value;
});
_inFlight = future;
try {
return await future;
} finally {
if (identical(_inFlight, future)) _inFlight = null;
}
}
}
class AdvertisementRepositoryImpl implements AdvertisementRepository {
AdvertisementRepositoryImpl(this._api);
final ApiClient _api;
final Map<String, AdvertisementStore> _stores = {};
AdvertisementStore storeFor({String? placement}) =>
_stores.putIfAbsent(placement ?? '', AdvertisementStore.new);
@override
Future<List<AdvertisementModel>> list({String? placement}) async {
List<AdvertisementModel>? peekCached({String? placement}) =>
storeFor(placement: placement).peekFresh();
@override
List<AdvertisementModel>? peekLast({String? placement}) =>
storeFor(placement: placement).peekLast();
@override
void invalidate({String? placement}) {
if (placement != null) {
storeFor(placement: placement).invalidate();
return;
}
for (final store in _stores.values) {
store.invalidate();
}
}
@override
Future<List<AdvertisementModel>> list({String? placement, bool force = false}) {
return storeFor(placement: placement).get(
() => _fetch(placement: placement),
force: force,
);
}
Future<List<AdvertisementModel>> _fetch({String? placement}) async {
try {
final res = await _api.dio.get(
'/api/v1/advertisements',

View File

@ -4,17 +4,92 @@ import '../../core/network/api_client.dart';
import '../../data/models/game_catalog_models.dart';
import '../../domain/repositories/game_catalog_repository.dart';
/// Short TTL + in-flight coalesce for `/api/v1/games`.
/// Shared by Home, Welcome, and the Predict catalog.
class GameCatalogStore {
static const ttl = Duration(seconds: 45);
List<GameCatalogItem>? _cached;
DateTime? _cachedAt;
Future<List<GameCatalogItem>>? _inFlight;
int fetchStarts = 0;
List<GameCatalogItem>? peekLast() => _cached;
List<GameCatalogItem>? peekFresh() {
if (_cached == null || _cachedAt == null) return null;
if (DateTime.now().difference(_cachedAt!) >= ttl) return null;
return _cached;
}
void invalidate() {
_cached = null;
_cachedAt = null;
}
Future<List<GameCatalogItem>> get(
Future<List<GameCatalogItem>> Function() fetch, {
bool force = false,
}) async {
if (!force) {
final hit = peekFresh();
if (hit != null) return hit;
if (_inFlight != null) return _inFlight!;
}
fetchStarts++;
final future = fetch().then((value) {
_cached = value;
_cachedAt = DateTime.now();
return value;
});
_inFlight = future;
try {
return await future;
} finally {
if (identical(_inFlight, future)) _inFlight = null;
}
}
}
class GameCatalogRepositoryImpl implements GameCatalogRepository {
GameCatalogRepositoryImpl(this._api);
final ApiClient _api;
final GameCatalogStore store = GameCatalogStore();
final GameCatalogStore featuredStore = GameCatalogStore();
GameCatalogStore _store({required bool featured}) =>
featured ? featuredStore : store;
@override
Future<List<GameCatalogItem>> list({bool? featured}) async {
List<GameCatalogItem>? peekCached({bool featured = false}) =>
_store(featured: featured).peekFresh();
@override
List<GameCatalogItem>? peekLast({bool featured = false}) =>
_store(featured: featured).peekLast();
@override
void invalidate() {
store.invalidate();
featuredStore.invalidate();
}
@override
Future<List<GameCatalogItem>> list({bool? featured, bool force = false}) {
final isFeatured = featured == true;
return _store(featured: isFeatured).get(
() => _fetch(featured: isFeatured),
force: force,
);
}
Future<List<GameCatalogItem>> _fetch({required bool featured}) async {
try {
final res = await _api.dio.get(
'/api/v1/games',
queryParameters: {
if (featured == true) 'featured': true,
if (featured) 'featured': true,
},
);
final data = res.data;

View File

@ -3,30 +3,66 @@ import '../../core/network/api_client.dart';
import '../models/share_card_models.dart';
import 'package:dio/dio.dart';
/// In-flight coalescing + short TTL for share-card admin/user flags.
/// Not a blind cache: [invalidate] after a ledger mutation (deposit, withdraw…).
class ShareConfigStore {
ShareCardConfig? _cached;
DateTime? _cachedAt;
Future<ShareCardConfig>? _inFlight;
static const ttl = Duration(minutes: 1);
int fetchStarts = 0;
void invalidate() {
_cached = null;
_cachedAt = null;
}
Future<ShareCardConfig> get(
Future<ShareCardConfig> Function() fetch, {
bool force = false,
}) async {
final now = DateTime.now();
if (!force &&
_cached != null &&
_cachedAt != null &&
now.difference(_cachedAt!) < ttl) {
return _cached!;
}
if (_inFlight != null) return _inFlight!;
fetchStarts++;
final future = fetch().then((value) {
_cached = value;
_cachedAt = DateTime.now();
return value;
});
_inFlight = future;
try {
return await future;
} finally {
if (identical(_inFlight, future)) _inFlight = null;
}
}
}
class ShareCardRepository {
ShareCardRepository(this._api);
final ApiClient _api;
ShareCardConfig? _cachedConfig;
DateTime? _cachedAt;
final ShareConfigStore configStore = ShareConfigStore();
Future<ShareCardConfig> getConfig({bool force = false}) async {
final now = DateTime.now();
if (!force &&
_cachedConfig != null &&
_cachedAt != null &&
now.difference(_cachedAt!) < const Duration(minutes: 1)) {
return _cachedConfig!;
}
try {
final res = await _api.dio.get<Map<String, dynamic>>('/api/v1/share-cards/config');
final config = ShareCardConfig.fromJson(res.data ?? {});
_cachedConfig = config;
_cachedAt = now;
return config;
} on DioException catch (e) {
throw AppException.fromDio(e);
}
void invalidateConfig() => configStore.invalidate();
Future<ShareCardConfig> getConfig({bool force = false}) {
return configStore.get(() async {
try {
final res = await _api.dio.get<Map<String, dynamic>>('/api/v1/share-cards/config');
return ShareCardConfig.fromJson(res.data ?? {});
} on DioException catch (e) {
throw AppException.fromDio(e);
}
}, force: force);
}
Future<ShareCardPayload> getBetShareCard(String betId) async {

View File

@ -9,8 +9,34 @@ import '../models/transaction_model.dart';
import '../models/wallet_type_model.dart';
import '../../core/network/api_client.dart';
/// Wallet data access used by [WalletBloc] (real API or test fake).
abstract class WalletRepository {
Future<List<WalletTypeModel>> getWalletTypes();
Future<List<BalanceModel>> getBalances();
Future<DepositAddressResult> getDepositAddress(String walletType);
Future<List<TransactionModel>> getTransactions({
int limit = 50,
int offset = 0,
String? category,
});
Future<WithdrawResult> withdraw(
String walletType,
String toAddress,
String amount, {
String? totpCode,
});
Future<TransferResult> transfer(
String toEmail,
String walletType,
String amount, {
String? totpCode,
});
Future<TestWalletStatusModel> getTestWalletStatus();
Future<TestWalletCreditResult> requestTestCredits();
}
/// Repository for wallet types, balances, transactions, and money movement.
class WalletRepositoryImpl {
class WalletRepositoryImpl implements WalletRepository {
WalletRepositoryImpl(this._api);
final ApiClient _api;

View File

@ -1,5 +1,11 @@
import '../../data/models/advertisement_models.dart';
abstract class AdvertisementRepository {
Future<List<AdvertisementModel>> list({String? placement});
Future<List<AdvertisementModel>> list({String? placement, bool force = false});
List<AdvertisementModel>? peekCached({String? placement});
List<AdvertisementModel>? peekLast({String? placement});
void invalidate({String? placement});
}

View File

@ -1,5 +1,13 @@
import '../../data/models/game_catalog_models.dart';
abstract class GameCatalogRepository {
Future<List<GameCatalogItem>> list({bool? featured});
Future<List<GameCatalogItem>> list({bool? featured, bool force = false});
/// Fresh catalog snapshot (within TTL), or null.
List<GameCatalogItem>? peekCached({bool featured = false});
/// Last snapshot even if stale — used to paint immediately on return.
List<GameCatalogItem>? peekLast({bool featured = false});
void invalidate();
}

View File

@ -22,6 +22,7 @@ import '../../../shared/widgets/pred_card.dart';
import '../../../shared/widgets/prediqo_logo.dart';
import '../utils/home_navigation.dart';
import '../../prediction/bloc/prediction_bloc.dart';
import '../../wallet/bloc/wallet_bloc.dart';
import '../../prediction/utils/game_catalog_ui.dart';
import 'widgets/home_ad_carousel.dart';
@ -45,11 +46,23 @@ class _HomeScreenState extends State<HomeScreen> {
@override
void initState() {
super.initState();
final cachedGames = sl<GameCatalogRepository>().peekLast();
if (cachedGames != null && cachedGames.isNotEmpty) {
_games = cachedGames;
}
final cachedAds = sl<AdvertisementRepository>().peekLast(placement: 'home_hero');
if (cachedAds != null && cachedAds.isNotEmpty) {
_heroAds = cachedAds;
}
if (_heroAds.isNotEmpty || _games.isNotEmpty) {
_loading = false;
}
_load();
_checkAppUpdate();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
context.read<PredictionBloc>().add(const PredictionLoadRequested(ifStale: true));
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
_checkAppUpdate();
});
}
@ -59,46 +72,77 @@ class _HomeScreenState extends State<HomeScreen> {
setState(() => _updateAvailable = available);
}
Future<void> _load() async {
setState(() {
_loading = true;
_error = null;
});
Future<T?> _soft<T>(Future<T> future) async {
try {
// Soft-wrap so parallel 401s (expired session) are not reported as
// unhandled async errors before we await them.
Future<T?> soft<T>(Future<T> future) async {
try {
return await future;
} catch (_) {
return null;
}
}
return await future;
} catch (_) {
return null;
}
}
final adsFuture = soft(sl<AdvertisementRepository>().list(placement: 'home_hero'));
final gamesFuture = soft(sl<GameCatalogRepository>().list());
final referralFuture = soft(sl<ReferralRepository>().getDashboard(maxDepth: 1));
final notifFuture = soft(sl<NotificationRepository>().list(limit: 1));
final profileFuture = soft(sl<AuthRepository>().getProfile());
Future<void> _refreshUnread() async {
final page = await _soft(sl<NotificationRepository>().list(limit: 1));
if (!mounted || page == null) return;
setState(() => _unreadNotifications = page.unreadCount);
}
Future<void> _refreshTotp() async {
final profile = await _soft(sl<AuthRepository>().getProfile());
if (!mounted || profile == null) return;
setState(() => _totpEnabled = profile.totpEnabled);
}
Future<void> _load({bool force = false}) async {
final keep = (_heroAds.isNotEmpty || _games.isNotEmpty) && !force;
if (!keep) {
setState(() {
_loading = true;
_error = null;
});
}
try {
final adsFuture = _soft(
sl<AdvertisementRepository>().list(placement: 'home_hero', force: force),
);
final gamesFuture = _soft(sl<GameCatalogRepository>().list(force: force));
final extrasFuture = () async {
final referral = await _soft(sl<ReferralRepository>().getDashboard(maxDepth: 1));
final notifPage = await _soft(sl<NotificationRepository>().list(limit: 1));
final profile = await _soft(sl<AuthRepository>().getProfile());
if (!mounted) return;
setState(() {
if (referral != null) _referral = referral;
if (notifPage != null) _unreadNotifications = notifPage.unreadCount;
if (profile != null) _totpEnabled = profile.totpEnabled;
});
}();
adsFuture.then((ads) {
if (!mounted || ads == null) return;
setState(() {
_heroAds = ads;
_loading = false;
_error = null;
});
});
gamesFuture.then((games) {
if (!mounted || games == null) return;
setState(() {
_games = games;
_loading = false;
});
});
final ads = await adsFuture;
final games = await gamesFuture;
final referral = await referralFuture;
final notifPage = await notifFuture;
final profile = await profileFuture;
if (!mounted) return;
setState(() {
_heroAds = ads ?? const [];
_games = games ?? const [];
_referral = referral;
_unreadNotifications = notifPage?.unreadCount ?? 0;
_totpEnabled = profile?.totpEnabled ?? false;
_loading = false;
if (ads == null && games == null) {
if (ads == null && games == null && _heroAds.isEmpty && _games.isEmpty) {
_error = AppException.connectionFailedMessage;
}
});
await extrasFuture;
} catch (e) {
if (!mounted) return;
setState(() {
@ -127,7 +171,7 @@ class _HomeScreenState extends State<HomeScreen> {
Widget build(BuildContext context) {
final s = context.strings;
return RefreshIndicator(
onRefresh: _load,
onRefresh: () => _load(force: true),
child: CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
@ -176,7 +220,7 @@ class _HomeScreenState extends State<HomeScreen> {
badgeLabel: _unreadNotifications > 9 ? '9+' : '$_unreadNotifications',
onPressed: () async {
await context.push('/notifications');
if (mounted) _load();
if (mounted) _refreshUnread();
},
),
const SizedBox(width: 4),
@ -204,27 +248,35 @@ class _HomeScreenState extends State<HomeScreen> {
padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
sliver: SliverList(
delegate: SliverChildListDelegate([
HomeAdCarousel(ads: _heroAds, loading: _loading)
.animate()
.fadeIn(duration: 350.ms)
.slideY(begin: 0.04, end: 0),
_heroAds.isEmpty
? HomeAdCarousel(
ads: _heroAds,
loading: _loading && _heroAds.isEmpty,
)
.animate()
.fadeIn(duration: 350.ms)
.slideY(begin: 0.04, end: 0)
: HomeAdCarousel(
ads: _heroAds,
loading: false,
),
const SizedBox(height: 22),
_SectionTitle(title: s.playNow, subtitle: s.playNowSubtitle),
const SizedBox(height: 12),
if (_loading)
const SizedBox(
height: 110,
child: Center(child: CircularProgressIndicator(strokeWidth: 2.5)),
)
else if (_games.isEmpty)
_FeaturedPredictCard(onTap: () => context.go('/predict'))
else
if (_games.isNotEmpty)
..._games.take(4).map(
(g) => Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _GameCard(game: g, onTap: () => _openGame(g)),
),
),
)
else if (_loading)
const SizedBox(
height: 110,
child: Center(child: CircularProgressIndicator(strokeWidth: 2.5)),
)
else
_FeaturedPredictCard(onTap: () => context.go('/predict')),
const SizedBox(height: 8),
_SectionTitle(title: s.shortcuts, subtitle: s.shortcutsSubtitle),
const SizedBox(height: 12),
@ -263,7 +315,7 @@ class _HomeScreenState extends State<HomeScreen> {
_TwoFaPromptCard(
onTap: () async {
await context.push('/totp-setup');
if (mounted) _load();
if (mounted) _refreshTotp();
},
),
],

View File

@ -67,6 +67,9 @@ class _HomeAdCarouselState extends State<HomeAdCarousel> {
@override
Widget build(BuildContext context) {
final s = context.strings;
if (widget.ads.isNotEmpty) {
return _buildCarousel();
}
if (widget.loading) {
return Container(
height: 200,
@ -78,33 +81,33 @@ class _HomeAdCarouselState extends State<HomeAdCarousel> {
);
}
if (widget.ads.isEmpty) {
return Container(
height: 180,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
AppColors.primary.withValues(alpha: 0.22),
AppColors.surfaceCard,
],
),
border: Border.all(color: AppColors.border),
return Container(
height: 180,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
AppColors.primary.withValues(alpha: 0.22),
AppColors.surfaceCard,
],
),
alignment: Alignment.center,
child: Text(
s.promotionsComingSoon,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: AppColors.textSecondary,
),
),
);
}
border: Border.all(color: AppColors.border),
),
alignment: Alignment.center,
child: Text(
s.promotionsComingSoon,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: AppColors.textSecondary,
),
),
);
}
Widget _buildCarousel() {
return Column(
children: [
SizedBox(
@ -188,6 +191,12 @@ class _AdSlide extends StatelessWidget {
Image.network(
ad.imageUrl!,
fit: BoxFit.cover,
gaplessPlayback: true,
filterQuality: FilterQuality.low,
cacheWidth: (MediaQuery.sizeOf(context).width *
MediaQuery.devicePixelRatioOf(context))
.round()
.clamp(240, 1080),
opacity: const AlwaysStoppedAnimation(0.38),
errorBuilder: (_, __, ___) => const SizedBox.shrink(),
),

View File

@ -8,6 +8,7 @@ import '../../../data/models/prediction_models.dart';
import '../../../data/repositories/prediction_repository_impl.dart';
import '../../../data/repositories/wallet_repository_impl.dart';
import '../../../domain/repositories/prediction_repository.dart';
import '../utils/prediction_history_filter_store.dart';
import '../utils/server_adjusted_countdown.dart';
part 'prediction_event.dart';
@ -39,8 +40,8 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
on<PredictionRefreshTick>(_onRefreshTick, transformer: _sequential());
on<PredictionWsMessageReceived>(_onWsMessage);
on<PredictionSocketStatusChanged>(_onSocketStatusChanged);
on<PredictionHistoryPageRequested>(_onHistoryPage);
on<PredictionHistoryFilterChanged>(_onHistoryFilterChanged);
on<PredictionHistoryPageRequested>(_onHistoryPage, transformer: _sequential());
on<PredictionHistoryFilterChanged>(_onHistoryFilterChanged, transformer: _sequential());
on<PredictionCandlesOlderRequested>(_onOlderCandles);
on<PredictionPaused>(_onPaused);
on<PredictionResumed>(_onResumed);
@ -66,14 +67,139 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
static const historyPageSize = 5;
static const _pollJitterRatio = 0.12;
Future<PredictionsPageModel> _fetchHistoryPage(int page) {
final historyFilterStore = PredictionHistoryFilterStore();
String _historyKey({
int? intervalMinutes,
required String? wallet,
required String? status,
}) =>
PredictionHistoryFilterStore.key(
intervalMinutes: intervalMinutes ?? state.selectedIntervalMinutes,
wallet: wallet,
status: status,
);
bool _isCurrentHistoryContext({
required int intervalMinutes,
String? wallet,
String? status,
}) =>
state.selectedIntervalMinutes == intervalMinutes &&
state.historyWalletFilter == wallet &&
state.historyStatusFilter == status;
void _rememberHistory(
List<PredictionModel> items, {
required int page,
required int totalPages,
int? intervalMinutes,
String? wallet,
String? status,
}) {
historyFilterStore.put(
_historyKey(
intervalMinutes: intervalMinutes,
wallet: wallet ?? state.historyWalletFilter,
status: status ?? state.historyStatusFilter,
),
PredictionHistoryFilterPage(
items: items,
page: page,
totalPages: totalPages,
),
);
}
List<PredictionModel> _applyLiveHistoryOverlays(List<PredictionModel> items) {
final liveMulti = state.gameState?.userMultiBet;
final liveBet = state.gameState?.userBet;
var next = items;
if (liveMulti != null) {
next = _historyWithMultiProgress(next, liveMulti);
}
if (liveBet != null) {
next = _historyWithPrediction(next, liveBet);
}
return next;
}
Future<PredictionsPageModel> _fetchHistoryPage(
int page, {
int? intervalMinutes,
String? wallet,
String? status,
}) {
return _repo.getMyBets(
page: page,
pageSize: historyPageSize,
intervalMinutes: state.selectedIntervalMinutes,
intervalMinutes: intervalMinutes ?? state.selectedIntervalMinutes,
stakeAccountKind: wallet ?? state.historyWalletFilter,
status: status ?? state.historyStatusFilter,
);
}
Future<void> _refreshHistoryFromServer(
Emitter<PredictionState> emit, {
int page = 1,
bool append = false,
bool showSpinnerIfEmpty = true,
}) async {
final interval = state.selectedIntervalMinutes;
final wallet = state.historyWalletFilter;
final status = state.historyStatusFilter;
if (append || (showSpinnerIfEmpty && state.history.isEmpty)) {
emit(state.copyWith(isLoadingHistory: true));
}
try {
final result = await _fetchHistoryPage(
page,
intervalMinutes: interval,
wallet: wallet,
status: status,
);
if (!_isCurrentHistoryContext(
intervalMinutes: interval,
wallet: wallet,
status: status,
)) {
return;
}
final merged = append
? [
...state.history,
...result.items.where((item) => state.history.every((h) => h.id != item.id)),
]
: result.items;
final items = append ? merged : _applyLiveHistoryOverlays(merged);
final reachedEnd = append && result.items.isEmpty;
final nextPage = reachedEnd ? state.historyPage : result.page;
final nextTotal = reachedEnd ? state.historyTotalPages : result.totalPages;
_rememberHistory(
items,
page: nextPage,
totalPages: nextTotal,
intervalMinutes: interval,
wallet: wallet,
status: status,
);
emit(state.copyWith(
history: items,
historyPage: nextPage,
historyTotalPages: nextTotal,
isLoadingHistory: false,
));
} catch (_) {
if (_isCurrentHistoryContext(
intervalMinutes: interval,
wallet: wallet,
status: status,
)) {
emit(state.copyWith(isLoadingHistory: false));
}
}
}
bool _matchesHistoryFilters(PredictionModel p) {
if (state.historyWalletFilter != null &&
p.stakeAccountKind != state.historyWalletFilter) {
@ -349,8 +475,15 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
try {
final interval = state.selectedIntervalMinutes;
final historyWallet = state.historyWalletFilter;
final historyStatus = state.historyStatusFilter;
final stateFuture = _repo.getState(intervalMinutes: interval);
final historyFuture = _soft(_fetchHistoryPage(1));
final historyFuture = _soft(_fetchHistoryPage(
1,
intervalMinutes: interval,
wallet: historyWallet,
status: historyStatus,
));
final balancesFuture = _soft(_loadBalances(state.gameState?.config.walletTypeCode));
final gameState = await stateFuture;
@ -400,28 +533,45 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
final history = await historyFuture;
final labels = await balancesFuture;
final liveMulti = state.gameState?.userMultiBet;
final historyItems = history == null
? state.history
: (liveMulti != null
? _historyWithMultiProgress(history.items, liveMulti)
: history.items);
emit(state.copyWith(
history: historyItems,
historyPage: history?.page,
historyTotalPages: history?.totalPages,
mainBalanceLabel: labels?.mainLabel,
bonusBalanceLabel: labels?.bonusLabel,
testBalanceLabel: labels?.testLabel,
mainAvailable: labels?.main,
bonusAvailable: labels?.bonus,
testAvailable: labels?.test,
));
if (_isCurrentHistoryContext(
intervalMinutes: interval,
wallet: historyWallet,
status: historyStatus,
) &&
history != null) {
final historyItems = _applyLiveHistoryOverlays(history.items);
_rememberHistory(
historyItems,
page: history.page,
totalPages: history.totalPages,
intervalMinutes: interval,
wallet: historyWallet,
status: historyStatus,
);
emit(state.copyWith(
history: historyItems,
historyPage: history.page,
historyTotalPages: history.totalPages,
mainBalanceLabel: labels?.mainLabel,
bonusBalanceLabel: labels?.bonusLabel,
testBalanceLabel: labels?.testLabel,
mainAvailable: labels?.main,
bonusAvailable: labels?.bonus,
testAvailable: labels?.test,
));
} else if (labels != null) {
emit(state.copyWith(
mainBalanceLabel: labels.mainLabel,
bonusBalanceLabel: labels.bonusLabel,
testBalanceLabel: labels.testLabel,
mainAvailable: labels.main,
bonusAvailable: labels.bonus,
testAvailable: labels.test,
));
}
_lastFullStateSyncMs = DateTime.now().millisecondsSinceEpoch;
_healthyPollSkips = 0;
await _fillHistoryUntilFilterMatches(emit);
_startPolling();
} catch (e) {
emit(state.copyWith(
@ -502,11 +652,22 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
Future<void> _onIntervalChanged(PredictionIntervalChanged event, Emitter<PredictionState> emit) async {
final prevInterval = state.selectedIntervalMinutes;
final gs = state.gameState;
final cached = historyFilterStore.peek(
_historyKey(
intervalMinutes: event.minutes,
wallet: state.historyWalletFilter,
status: state.historyStatusFilter,
),
);
emit(state.copyWith(
selectedIntervalMinutes: event.minutes,
candles: const [],
hasMoreOlderCandles: true,
isLoadingOlderCandles: true,
history: cached?.items ?? const [],
historyPage: cached?.page ?? 1,
historyTotalPages: cached?.totalPages ?? 1,
isLoadingHistory: cached == null,
gameState: gs?.copyWith(
selectedIntervalMinutes: event.minutes,
clearRound: true,
@ -735,6 +896,7 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
? _parseStakeKind(multi.stakeAccountKind)
: state.stakeAccountKind,
));
_rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages);
_lastFullStateSyncMs = nowMs;
if (hasActiveMulti || multi != null || autoOn || userBetChanged || autoPlaced) {
@ -803,6 +965,7 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
? _parseStakeKind(next.userMultiBet!.stakeAccountKind)
: state.stakeAccountKind,
));
_rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages);
if (next.autoSettings?.enabled == true) {
_startPolling();
}
@ -875,6 +1038,7 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
playMode: PredictionPlayMode.multi,
stakeAccountKind: _parseStakeKind(parsed.stakeAccountKind),
));
_rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages);
_startPolling();
} else if (multi == null) {
emit(state.copyWith(gameState: gs.copyWith(clearUserMultiBet: true)));
@ -955,6 +1119,7 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
? _parseStakeKind(bet.stakeAccountKind)
: state.stakeAccountKind,
));
_rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages);
}
add(const PredictionBalancesRefreshRequested());
add(const PredictionHistoryPageRequested(1));
@ -1003,74 +1168,39 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
}
Future<void> _onHistoryPage(PredictionHistoryPageRequested event, Emitter<PredictionState> emit) async {
emit(state.copyWith(isLoadingHistory: true));
try {
final page = await _fetchHistoryPage(event.page);
final nextHistory = event.append
? [
...state.history,
...page.items.where((item) => state.history.every((h) => h.id != item.id)),
]
: page.items;
final reachedEnd = event.append && page.items.isEmpty;
emit(state.copyWith(
history: nextHistory,
historyPage: reachedEnd ? state.historyPage : page.page,
historyTotalPages: reachedEnd ? state.historyPage : page.totalPages,
isLoadingHistory: false,
));
await _fillHistoryUntilFilterMatches(emit);
} catch (_) {
emit(state.copyWith(isLoadingHistory: false));
}
await _refreshHistoryFromServer(
emit,
page: event.page,
append: event.append,
showSpinnerIfEmpty: !event.append,
);
}
Future<void> _onHistoryFilterChanged(
PredictionHistoryFilterChanged event,
Emitter<PredictionState> emit,
) async {
final cached = historyFilterStore.peek(
_historyKey(
wallet: event.walletFilter,
status: event.statusFilter,
),
);
emit(state.copyWith(
historyWalletFilter: event.walletFilter,
historyStatusFilter: event.statusFilter,
clearHistoryWalletFilter: event.walletFilter == null,
clearHistoryStatusFilter: event.statusFilter == null,
history: cached?.items ?? const [],
historyPage: cached?.page ?? 1,
historyTotalPages: cached?.totalPages ?? 1,
isLoadingHistory: cached == null,
));
await _fillHistoryUntilFilterMatches(emit);
}
/// When a filter is active and the loaded pages have no matches, keep loading
/// older pages until a match appears or the history is fully loaded.
Future<void> _fillHistoryUntilFilterMatches(Emitter<PredictionState> emit) async {
final hasFilter =
state.historyWalletFilter != null || state.historyStatusFilter != null;
if (!hasFilter) return;
var guard = 0;
while (guard < 50) {
guard++;
if (state.history.any(_matchesHistoryFilters)) return;
if (state.historyPage >= state.historyTotalPages) return;
emit(state.copyWith(isLoadingHistory: true));
try {
final page = await _fetchHistoryPage(state.historyPage + 1);
final nextHistory = [
...state.history,
...page.items.where((item) => state.history.every((h) => h.id != item.id)),
];
final reachedEnd = page.items.isEmpty;
emit(state.copyWith(
history: nextHistory,
historyPage: reachedEnd ? state.historyPage : page.page,
historyTotalPages: reachedEnd ? state.historyPage : page.totalPages,
isLoadingHistory: false,
));
if (reachedEnd) return;
} catch (_) {
emit(state.copyWith(isLoadingHistory: false));
return;
}
}
await _refreshHistoryFromServer(
emit,
page: 1,
showSpinnerIfEmpty: cached == null,
);
}
Future<void> _onOlderCandles(PredictionCandlesOlderRequested event, Emitter<PredictionState> emit) async {

View File

@ -25,36 +25,53 @@ class _PredictionGamesScreenState extends State<PredictionGamesScreen> {
bool _loading = true;
String? _error;
List<GameCatalogItem> _games = [];
bool _predictionPrefetchScheduled = false;
@override
void initState() {
super.initState();
final cached = sl<GameCatalogRepository>().peekLast();
if (cached != null && cached.isNotEmpty) {
_games = cached;
_loading = false;
_schedulePredictionPrefetch();
}
_load();
}
void _schedulePredictionPrefetch() {
if (_predictionPrefetchScheduled) return;
_predictionPrefetchScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
context.read<PredictionBloc>().add(const PredictionLoadRequested(ifStale: true));
});
}
Future<void> _load() async {
setState(() {
_loading = true;
_error = null;
});
Future<void> _load({bool force = false}) async {
final keepList = _games.isNotEmpty && !force;
if (!keepList) {
setState(() {
_loading = true;
_error = null;
});
}
try {
final games = await sl<GameCatalogRepository>().list();
final games = await sl<GameCatalogRepository>().list(force: force);
if (!mounted) return;
setState(() {
_games = games;
_loading = false;
_error = null;
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
_error = keepList ? _error : e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
_loading = false;
});
}
_schedulePredictionPrefetch();
}
void _openGame(GameCatalogItem game) {
@ -71,7 +88,7 @@ class _PredictionGamesScreenState extends State<PredictionGamesScreen> {
return Scaffold(
key: const Key('prediction_games_screen'),
body: RefreshIndicator(
onRefresh: _load,
onRefresh: () => _load(force: true),
child: CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
@ -108,7 +125,7 @@ class _PredictionGamesScreenState extends State<PredictionGamesScreen> {
children: [
Text(_error!, textAlign: TextAlign.center),
const SizedBox(height: 12),
FilledButton(onPressed: _load, child: Text(s.retry)),
FilledButton(onPressed: () => _load(force: true), child: Text(s.retry)),
],
),
),

View File

@ -238,27 +238,14 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
const SizedBox(height: 12),
Builder(
builder: (context) {
final filtered = state.history.where((p) {
if (state.historyWalletFilter != null &&
p.stakeAccountKind != state.historyWalletFilter) {
return false;
}
if (state.historyStatusFilter != null &&
p.status != state.historyStatusFilter) {
return false;
}
return true;
}).toList();
final filtered = state.history;
final canLoadMore = state.historyPage < state.historyTotalPages;
final hasFilters = state.historyWalletFilter != null ||
state.historyStatusFilter != null;
// End label only after a multi-page history was fully loaded.
final showEndLabel = !canLoadMore &&
state.historyTotalPages > 1 &&
filtered.isNotEmpty;
// While a filter has no matches, auto-load hides the manual button.
final showLoadMore = canLoadMore &&
!(hasFilters && filtered.isEmpty);
final showLoadMore = canLoadMore;
if (state.isLoadingHistory && state.history.isEmpty) {
return const Padding(

View File

@ -0,0 +1,38 @@
import '../../../data/models/prediction_models.dart';
class PredictionHistoryFilterPage {
const PredictionHistoryFilterPage({
required this.items,
required this.page,
required this.totalPages,
});
final List<PredictionModel> items;
final int page;
final int totalPages;
}
/// Last known Recent-predictions page, keyed by interval + chip filters.
/// Not a blind TTL skip: opening a chip always refetches; this only paints instantly.
class PredictionHistoryFilterStore {
final Map<String, PredictionHistoryFilterPage> _pages = {};
static String key({
required int intervalMinutes,
String? wallet,
String? status,
}) =>
'$intervalMinutes|${wallet ?? ''}|${status ?? ''}';
PredictionHistoryFilterPage? peek(String key) => _pages[key];
void put(String key, PredictionHistoryFilterPage page) => _pages[key] = page;
void invalidate([String? key]) {
if (key == null) {
_pages.clear();
} else {
_pages.remove(key);
}
}
}

View File

@ -6,13 +6,21 @@ import 'package:equatable/equatable.dart';
import 'package:dio/dio.dart';
import '../../../core/errors/app_exception.dart';
import '../../../data/models/balance_model.dart';
import '../../../data/models/test_wallet_models.dart';
import '../../../data/models/transaction_model.dart';
import '../../../data/models/wallet_type_model.dart';
import '../../../data/repositories/share_card_repository.dart';
import '../../../data/repositories/wallet_repository_impl.dart';
import '../../../domain/repositories/health_repository.dart';
import '../../../domain/repositories/referral_repository.dart';
part 'wallet_event.dart';
part 'wallet_state.dart';
EventTransformer<E> _sequential<E>() {
return (events, mapper) => events.asyncExpand(mapper);
}
/// Extracts a user-friendly message from an error (e.g. API {"error": "..."}).
String _errorMessage(Object e) {
if (e is DioException) {
@ -30,36 +38,291 @@ String? _errorCode(Object e) {
/// Manages wallet data and money-movement operations via [WalletRepositoryImpl].
class WalletBloc extends Bloc<WalletEvent, WalletState> {
/// Creates a [WalletBloc] backed by [walletRepo].
WalletBloc(this._walletRepo) : super(const WalletState.initial()) {
on<WalletLoadRequested>(_onLoad);
/// Creates a [WalletBloc] backed by wallet, health, and referral APIs.
WalletBloc(
this._walletRepo,
this._healthRepo,
this._referralRepo, {
ShareCardRepository? shareCards,
}) : _shareCards = shareCards,
super(const WalletState.initial()) {
on<WalletLoadRequested>(_onLoad, transformer: _sequential());
on<WalletActivityRequested>(_onActivity, transformer: _sequential());
on<WalletActivityMoreRequested>(_onActivityMore, transformer: _sequential());
on<WalletDepositAddressRequested>(_onDepositAddress);
on<WalletWithdrawRequested>(_onWithdraw);
on<WalletTransferRequested>(_onTransfer);
on<WalletClearFeedback>(_onClearFeedback);
}
final WalletRepositoryImpl _walletRepo;
final WalletRepository _walletRepo;
final HealthRepository _healthRepo;
final ReferralRepository _referralRepo;
final ShareCardRepository? _shareCards;
/// Loads wallet types, balances, and recent transactions from the API.
Future<void> _onLoad(WalletLoadRequested event, Emitter<WalletState> emit) async {
emit(state.copyWith(isLoading: true, clearError: true));
static const activityPageSize = 10;
static const _freshBalanceSyncMs = 5000;
static const _freshActivitySyncMs = 45000;
int _lastFullStateSyncMs = 0;
final Map<String, int> _lastActivitySyncMs = {};
Future<T?> _soft<T>(Future<T> future) async {
try {
final types = await _walletRepo.getWalletTypes();
final balances = await _walletRepo.getBalances();
final txs = await _walletRepo.getTransactions(limit: 30);
return await future;
} catch (_) {
return null;
}
}
bool _activityIsFresh(String category) {
final page = state.activityFor(category);
final lastMs = _lastActivitySyncMs[category] ?? 0;
return page.loaded &&
DateTime.now().millisecondsSinceEpoch - lastMs < _freshActivitySyncMs;
}
void _invalidateAfterLedgerMutation() {
_lastActivitySyncMs.clear();
_shareCards?.invalidateConfig();
}
/// Warm Withdrawals / Transfers after the first paint. Never Predictions.
void _scheduleQuietActivityPrefetch() {
if (!_activityIsFresh('withdrawals')) {
add(const WalletActivityRequested(category: 'withdrawals'));
}
if (!_activityIsFresh('transfers')) {
add(const WalletActivityRequested(category: 'transfers'));
}
}
Future<void> _emitDepositsPrefetch(
Emitter<WalletState> emit, {
required bool force,
}) async {
if (!force && _activityIsFresh('deposits')) return;
final page = state.deposits;
if (page.loading) return;
emit(state.copyWith(
deposits: page.copyWith(loading: page.items.isEmpty, clearError: true),
));
try {
final list = await _walletRepo.getTransactions(
limit: activityPageSize,
offset: 0,
category: 'deposits',
);
emit(state.copyWith(
deposits: WalletActivityPage(
items: list,
loaded: true,
loading: false,
hasMore: list.length >= activityPageSize,
),
));
_lastActivitySyncMs['deposits'] = DateTime.now().millisecondsSinceEpoch;
} catch (e) {
emit(state.copyWith(
deposits: page.copyWith(loading: false, error: _errorMessage(e)),
));
}
}
/// Loads types + balances + extras in parallel. Prefetches Deposits only.
Future<void> _onLoad(WalletLoadRequested event, Emitter<WalletState> emit) async {
final nowMs = DateTime.now().millisecondsSinceEpoch;
final balancesFresh = state.balances.isNotEmpty &&
nowMs - _lastFullStateSyncMs < _freshBalanceSyncMs;
if (event.ifStale && balancesFresh) {
if (!_activityIsFresh('deposits')) {
await _emitDepositsPrefetch(emit, force: false);
}
_scheduleQuietActivityPrefetch();
return;
}
if (!event.ifStale) {
_invalidateAfterLedgerMutation();
}
final keepExistingUi = state.balances.isNotEmpty;
if (!keepExistingUi) {
emit(state.copyWith(isLoading: true, clearError: true));
} else {
emit(state.copyWith(clearError: true));
}
try {
final typesFuture = _soft(_walletRepo.getWalletTypes());
final balancesFuture = _walletRepo.getBalances();
final extrasFuture = _loadExtras();
final depositsFuture = _walletRepo.getTransactions(
limit: activityPageSize,
offset: 0,
category: 'deposits',
);
final depositsPage = state.deposits;
if (depositsPage.items.isEmpty) {
emit(state.copyWith(
deposits: depositsPage.copyWith(loading: true, clearError: true),
));
}
final balances = await balancesFuture;
emit(state.copyWith(
walletTypes: types,
balances: balances,
transactions: txs,
isLoading: false,
clearError: true,
));
try {
final list = await depositsFuture;
emit(state.copyWith(
deposits: WalletActivityPage(
items: list,
loaded: true,
loading: false,
hasMore: list.length >= activityPageSize,
),
));
_lastActivitySyncMs['deposits'] = DateTime.now().millisecondsSinceEpoch;
} catch (_) {}
_scheduleQuietActivityPrefetch();
final types = await typesFuture;
if (types != null && types.isNotEmpty) {
emit(state.copyWith(walletTypes: types));
}
final extras = await extrasFuture;
emit(state.copyWith(
testWalletStatus: extras.testWalletStatus,
bonusWithdrawable: extras.bonusWithdrawable,
withdrawalsEnabled: extras.withdrawalsEnabled,
withdrawalFeeRaw: extras.withdrawalFeeRaw,
healthLoaded: extras.healthLoaded,
));
_lastFullStateSyncMs = DateTime.now().millisecondsSinceEpoch;
} catch (e) {
emit(state.copyWith(isLoading: false, errorMessage: _errorMessage(e)));
emit(state.copyWith(
isLoading: false,
errorMessage: keepExistingUi ? state.errorMessage : _errorMessage(e),
));
}
}
Future<
({
TestWalletStatusModel? testWalletStatus,
bool? bonusWithdrawable,
bool withdrawalsEnabled,
String withdrawalFeeRaw,
bool healthLoaded,
})> _loadExtras() async {
final testFuture = _soft(_walletRepo.getTestWalletStatus());
final bonusFuture = _soft(_referralRepo.getBonusBalances());
final healthFuture = _soft(_healthRepo.getHealth());
final test = await testFuture;
final bonus = await bonusFuture;
final health = await healthFuture;
return (
testWalletStatus: test ?? state.testWalletStatus,
bonusWithdrawable: bonus?.bonusWithdrawable ?? state.bonusWithdrawable,
withdrawalsEnabled: health?.withdrawalsEnabled ?? state.withdrawalsEnabled,
withdrawalFeeRaw: health?.withdrawalNetworkFeeRaw ?? state.withdrawalFeeRaw,
healthLoaded: health != null || state.healthLoaded,
);
}
Future<void> _onActivity(
WalletActivityRequested event,
Emitter<WalletState> emit,
) async {
final category = event.category;
if (!_isActivityCategory(category)) return;
final nowMs = DateTime.now().millisecondsSinceEpoch;
final page = state.activityFor(category);
final lastMs = _lastActivitySyncMs[category] ?? 0;
if (!event.force &&
page.loaded &&
nowMs - lastMs < _freshActivitySyncMs) {
return;
}
if (page.loading && !event.force) return;
emit(state.copyWithActivity(
category,
page.copyWith(loading: page.items.isEmpty, clearError: true),
));
try {
final list = await _walletRepo.getTransactions(
limit: activityPageSize,
offset: 0,
category: category,
);
emit(state.copyWithActivity(
category,
WalletActivityPage(
items: list,
loaded: true,
loading: false,
hasMore: list.length >= activityPageSize,
),
));
_lastActivitySyncMs[category] = DateTime.now().millisecondsSinceEpoch;
} catch (e) {
emit(state.copyWithActivity(
category,
page.copyWith(loading: false, error: _errorMessage(e)),
));
}
}
Future<void> _onActivityMore(
WalletActivityMoreRequested event,
Emitter<WalletState> emit,
) async {
final category = event.category;
if (!_isActivityCategory(category)) return;
final page = state.activityFor(category);
if (page.loading || page.loadingMore || !page.hasMore) return;
emit(state.copyWithActivity(category, page.copyWith(loadingMore: true)));
try {
final list = await _walletRepo.getTransactions(
limit: activityPageSize,
offset: page.items.length,
category: category,
);
emit(state.copyWithActivity(
category,
page.copyWith(
items: [...page.items, ...list],
hasMore: list.length >= activityPageSize,
loadingMore: false,
loaded: true,
),
));
} catch (e) {
emit(state.copyWithActivity(
category,
page.copyWith(loadingMore: false, error: _errorMessage(e)),
));
}
}
bool _isActivityCategory(String category) {
return category == 'deposits' ||
category == 'withdrawals' ||
category == 'transfers' ||
category == 'predictions';
}
/// Fetches a blockchain deposit address for the given wallet type code.
Future<void> _onDepositAddress(WalletDepositAddressRequested event, Emitter<WalletState> emit) async {
final s = state;
@ -90,6 +353,7 @@ class WalletBloc extends Bloc<WalletEvent, WalletState> {
);
emit(state.copyWith(withdrawTxId: result.transactionId, withdrawStatus: result.status));
add(const WalletLoadRequested());
add(const WalletActivityRequested(category: 'withdrawals', force: true));
} catch (e) {
emit(state.copyWith(
errorMessage: _errorMessage(e),
@ -115,6 +379,7 @@ class WalletBloc extends Bloc<WalletEvent, WalletState> {
);
emit(state.copyWith(transferTxId: result.transactionId, transferStatus: result.status));
add(const WalletLoadRequested());
add(const WalletActivityRequested(category: 'transfers', force: true));
} catch (e) {
emit(state.copyWith(
errorMessage: _errorMessage(e),

View File

@ -7,9 +7,36 @@ abstract class WalletEvent extends Equatable {
List<Object?> get props => [];
}
/// Reloads wallet types, balances, and recent transactions.
/// Reloads wallet types, balances, and extras (not Activity lists).
class WalletLoadRequested extends WalletEvent {
const WalletLoadRequested();
const WalletLoadRequested({this.ifStale = false});
/// Skip the network round-trip when a sync finished a few seconds ago.
final bool ifStale;
@override
List<Object?> get props => [ifStale];
}
/// Loads one Activity tab on demand (deposits / withdrawals / transfers / predictions).
class WalletActivityRequested extends WalletEvent {
const WalletActivityRequested({required this.category, this.force = false});
final String category;
final bool force;
@override
List<Object?> get props => [category, force];
}
/// Appends the next Activity page for [category].
class WalletActivityMoreRequested extends WalletEvent {
const WalletActivityMoreRequested({required this.category});
final String category;
@override
List<Object?> get props => [category];
}
/// Requests a deposit address for the given asset code (e.g. TRX, USDT).

View File

@ -1,11 +1,61 @@
part of 'wallet_bloc.dart';
/// One Activity tab (cached in the app-scoped [WalletBloc]).
class WalletActivityPage extends Equatable {
const WalletActivityPage({
this.items = const [],
this.loading = false,
this.loadingMore = false,
this.loaded = false,
this.hasMore = true,
this.error,
});
final List<TransactionModel> items;
final bool loading;
final bool loadingMore;
final bool loaded;
final bool hasMore;
final String? error;
WalletActivityPage copyWith({
List<TransactionModel>? items,
bool? loading,
bool? loadingMore,
bool? loaded,
bool? hasMore,
String? error,
bool clearError = false,
}) {
return WalletActivityPage(
items: items ?? this.items,
loading: loading ?? this.loading,
loadingMore: loadingMore ?? this.loadingMore,
loaded: loaded ?? this.loaded,
hasMore: hasMore ?? this.hasMore,
error: clearError ? null : (error ?? this.error),
);
}
@override
List<Object?> get props => [items, loading, loadingMore, loaded, hasMore, error];
}
/// Immutable wallet UI state: balances, transactions, and operation results.
class WalletState extends Equatable {
const WalletState({
this.walletTypes = const [],
this.balances = const [],
this.transactions = const [],
this.deposits = const WalletActivityPage(),
this.withdrawals = const WalletActivityPage(),
this.transfers = const WalletActivityPage(),
this.predictions = const WalletActivityPage(),
this.testWalletStatus,
this.bonusWithdrawable,
this.withdrawalsEnabled = false,
this.withdrawalFeeRaw = '0',
this.healthLoaded = false,
this.depositAddress,
this.depositWalletType,
this.withdrawTxId,
@ -37,6 +87,15 @@ class WalletState extends Equatable {
final List<WalletTypeModel> walletTypes;
final List<BalanceModel> balances;
final List<TransactionModel> transactions;
final WalletActivityPage deposits;
final WalletActivityPage withdrawals;
final WalletActivityPage transfers;
final WalletActivityPage predictions;
final TestWalletStatusModel? testWalletStatus;
final bool? bonusWithdrawable;
final bool withdrawalsEnabled;
final String withdrawalFeeRaw;
final bool healthLoaded;
final String? depositAddress;
final WalletTypeModel? depositWalletType;
final String? withdrawTxId;
@ -47,6 +106,19 @@ class WalletState extends Equatable {
final String? errorCode;
final bool isLoading;
WalletActivityPage activityFor(String category) {
switch (category) {
case 'withdrawals':
return withdrawals;
case 'transfers':
return transfers;
case 'predictions':
return predictions;
default:
return deposits;
}
}
/// Whether wallet types have been loaded and the bloc is not in a loading state.
bool get isLoaded => walletTypes.isNotEmpty && !isLoading;
@ -55,6 +127,15 @@ class WalletState extends Equatable {
List<WalletTypeModel>? walletTypes,
List<BalanceModel>? balances,
List<TransactionModel>? transactions,
WalletActivityPage? deposits,
WalletActivityPage? withdrawals,
WalletActivityPage? transfers,
WalletActivityPage? predictions,
TestWalletStatusModel? testWalletStatus,
bool? bonusWithdrawable,
bool? withdrawalsEnabled,
String? withdrawalFeeRaw,
bool? healthLoaded,
String? depositAddress,
WalletTypeModel? depositWalletType,
String? withdrawTxId,
@ -73,6 +154,15 @@ class WalletState extends Equatable {
walletTypes: walletTypes ?? this.walletTypes,
balances: balances ?? this.balances,
transactions: transactions ?? this.transactions,
deposits: deposits ?? this.deposits,
withdrawals: withdrawals ?? this.withdrawals,
transfers: transfers ?? this.transfers,
predictions: predictions ?? this.predictions,
testWalletStatus: testWalletStatus ?? this.testWalletStatus,
bonusWithdrawable: bonusWithdrawable ?? this.bonusWithdrawable,
withdrawalsEnabled: withdrawalsEnabled ?? this.withdrawalsEnabled,
withdrawalFeeRaw: withdrawalFeeRaw ?? this.withdrawalFeeRaw,
healthLoaded: healthLoaded ?? this.healthLoaded,
depositAddress: clearDeposit ? null : (depositAddress ?? this.depositAddress),
depositWalletType: clearDeposit ? null : (depositWalletType ?? this.depositWalletType),
withdrawTxId: clearWithdraw ? null : (withdrawTxId ?? this.withdrawTxId),
@ -85,11 +175,33 @@ class WalletState extends Equatable {
);
}
WalletState copyWithActivity(String category, WalletActivityPage page) {
switch (category) {
case 'withdrawals':
return copyWith(withdrawals: page);
case 'transfers':
return copyWith(transfers: page);
case 'predictions':
return copyWith(predictions: page);
default:
return copyWith(deposits: page);
}
}
@override
List<Object?> get props => [
walletTypes,
balances,
transactions,
deposits,
withdrawals,
transfers,
predictions,
testWalletStatus,
bonusWithdrawable,
withdrawalsEnabled,
withdrawalFeeRaw,
healthLoaded,
depositAddress,
depositWalletType,
withdrawTxId,

View File

@ -22,7 +22,7 @@ class _DepositAssetSelectScreenState extends State<DepositAssetSelectScreen> {
@override
void initState() {
super.initState();
context.read<WalletBloc>().add(const WalletLoadRequested());
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
}
@override

View File

@ -38,7 +38,7 @@ class _TransferScreenState extends State<TransferScreen> {
@override
void initState() {
super.initState();
context.read<WalletBloc>().add(const WalletLoadRequested());
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
_loadSecurityContext();
}

View File

@ -11,8 +11,8 @@ import '../../../core/utils/amount_utils.dart';
import '../../../data/models/balance_model.dart';
import '../../../data/models/test_wallet_models.dart';
import '../../../data/models/transaction_model.dart';
import '../../../data/repositories/share_card_repository.dart';
import '../../../data/repositories/wallet_repository_impl.dart';
import '../../../domain/repositories/health_repository.dart';
import '../../../domain/repositories/referral_repository.dart';
import '../../../l10n/app_strings.dart';
import '../../../shared/widgets/app_snackbar.dart';
@ -41,57 +41,27 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
late final TabController _tabController;
bool _hideBalance = false;
bool _prefsLoaded = false;
TestWalletStatusModel? _testWalletStatus;
bool _requestingTestCredits = false;
bool? _bonusWithdrawable;
bool _transferringBonus = false;
bool _withdrawalsEnabled = false;
String _withdrawalFeeRaw = '0';
bool _healthLoaded = false;
final Map<String, _CategoryHistory> _histories = {
'deposits': _CategoryHistory(),
'withdrawals': _CategoryHistory(),
'transfers': _CategoryHistory(),
'predictions': _CategoryHistory(),
};
static const _categories = ['deposits', 'withdrawals', 'transfers', 'predictions'];
static const _pageSize = 10;
@override
void initState() {
super.initState();
_tabController = TabController(length: 4, vsync: this);
_tabController.addListener(_onTabChanged);
context.read<WalletBloc>().add(const WalletLoadRequested());
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
_loadHidePreference();
_loadTestWalletStatus();
_loadBonusPolicy();
_loadWithdrawHealth();
WidgetsBinding.instance.addPostFrameCallback((_) {
_ensureCategoryLoaded(_categories[_tabController.index]);
if (!mounted) return;
sl<ShareCardRepository>().getConfig();
context.read<WalletBloc>().add(
WalletActivityRequested(category: _categories[_tabController.index]),
);
});
}
Future<void> _loadWithdrawHealth() async {
try {
final health = await sl<HealthRepository>().getHealth();
if (!mounted) return;
setState(() {
_withdrawalsEnabled = health.withdrawalsEnabled;
_withdrawalFeeRaw = health.withdrawalNetworkFeeRaw;
_healthLoaded = true;
});
} catch (_) {
if (!mounted) return;
setState(() {
_withdrawalsEnabled = false;
_healthLoaded = true;
});
}
}
@override
void dispose() {
_tabController.removeListener(_onTabChanged);
@ -108,26 +78,6 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
});
}
Future<void> _loadTestWalletStatus() async {
try {
final status = await sl<WalletRepositoryImpl>().getTestWalletStatus();
if (!mounted) return;
setState(() => _testWalletStatus = status);
} catch (_) {
// Best-effort: keep the card usable without the request button status.
}
}
Future<void> _loadBonusPolicy() async {
try {
final result = await sl<ReferralRepository>().getBonusBalances();
if (!mounted) return;
setState(() => _bonusWithdrawable = result.bonusWithdrawable);
} catch (_) {
// Best-effort: leave transfer option hidden until policy is known.
}
}
Future<void> _transferBonusToMain(BalanceModel balance) async {
if (_transferringBonus) return;
final amountRaw = balance.bonusAvailable;
@ -141,7 +91,6 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
if (!mounted) return;
showSuccessSnackBar(context, context.strings.bonusTransferSuccess);
context.read<WalletBloc>().add(const WalletLoadRequested());
await _loadBonusPolicy();
} catch (e) {
if (!mounted) return;
showErrorSnackBar(context, _friendlyError(e));
@ -158,7 +107,6 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
if (!mounted) return;
showSuccessSnackBar(context, result.message);
context.read<WalletBloc>().add(const WalletLoadRequested());
await _loadTestWalletStatus();
} catch (e) {
if (!mounted) return;
showErrorSnackBar(context, _friendlyError(e));
@ -177,82 +125,23 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
void _onTabChanged() {
if (_tabController.indexIsChanging) return;
setState(() {});
_ensureCategoryLoaded(_categories[_tabController.index]);
context.read<WalletBloc>().add(
WalletActivityRequested(category: _categories[_tabController.index]),
);
}
Future<void> _ensureCategoryLoaded(String category, {bool force = false}) async {
final history = _histories[category]!;
if (!force && (history.loading || history.loaded)) return;
setState(() {
history.loading = true;
history.error = null;
if (force) {
history.items = [];
history.loaded = false;
history.hasMore = true;
}
});
try {
final list = await sl<WalletRepositoryImpl>().getTransactions(
limit: _pageSize,
offset: 0,
category: category,
);
if (!mounted) return;
setState(() {
history.items = list;
history.loaded = true;
history.loading = false;
history.hasMore = list.length >= _pageSize;
});
} catch (e) {
if (!mounted) return;
setState(() {
history.loading = false;
history.error = _friendlyError(e);
});
}
}
Future<void> _loadMore(String category) async {
final history = _histories[category]!;
if (history.loading || history.loadingMore || !history.hasMore) return;
setState(() => history.loadingMore = true);
try {
final list = await sl<WalletRepositoryImpl>().getTransactions(
limit: _pageSize,
offset: history.items.length,
category: category,
);
if (!mounted) return;
setState(() {
history.items = [...history.items, ...list];
history.hasMore = list.length >= _pageSize;
history.loadingMore = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
history.loadingMore = false;
history.error = _friendlyError(e);
});
}
void _loadMore(String category) {
context.read<WalletBloc>().add(WalletActivityMoreRequested(category: category));
}
Future<void> _refreshAll() async {
context.read<WalletBloc>().add(const WalletLoadRequested());
await Future.wait([
_loadTestWalletStatus(),
_loadBonusPolicy(),
_loadWithdrawHealth(),
]);
for (final key in _histories.keys) {
final history = _histories[key]!;
history.loaded = false;
history.hasMore = true;
history.loadingMore = false;
final bloc = context.read<WalletBloc>();
bloc.add(const WalletLoadRequested());
final category = _categories[_tabController.index];
if (category != 'deposits') {
bloc.add(WalletActivityRequested(category: category, force: true));
}
await _ensureCategoryLoaded(_categories[_tabController.index], force: true);
await Future<void>.delayed(const Duration(milliseconds: 350));
}
BalanceModel? _usdtBalance(List<BalanceModel> balances) {
@ -277,7 +166,7 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
final balance = _usdtBalance(state.balances);
final loading = state.isLoading && state.balances.isEmpty;
final category = _categories[_tabController.index];
final history = _histories[category]!;
final history = state.activityFor(category);
// Single CustomScrollView (no NestedScrollView) — NestedScrollView + TabBarView
// triggers a known Android overscroll assertion (`activity!.isScrolling`).
@ -321,10 +210,10 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
(t) => t.withdrawEnabled == true,
);
final eligibility = computeWithdrawEligibility(
withdrawalsEnabled: _withdrawalsEnabled,
withdrawalsEnabled: state.withdrawalsEnabled,
hasWithdrawNetwork: hasRail,
availableRaw: balance.available,
feeRaw: _withdrawalFeeRaw,
feeRaw: state.withdrawalFeeRaw,
);
String? withdrawReason;
if (!eligibility.allowed) {
@ -373,9 +262,9 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
_WalletAction(
icon: Icons.south_west_rounded,
label: s.withdraw,
enabled: _healthLoaded && eligibility.allowed,
enabled: state.healthLoaded && eligibility.allowed,
onTap: () {
if (!_healthLoaded || !eligibility.allowed) {
if (!state.healthLoaded || !eligibility.allowed) {
showAppSnackBar(
context,
message: withdrawReason ??
@ -416,7 +305,7 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
icon: Icons.card_giftcard_rounded,
footer: _BonusWalletFooter(
bonusAvailableRaw: balance.bonusAvailable,
bonusWithdrawable: _bonusWithdrawable,
bonusWithdrawable: state.bonusWithdrawable,
transferring: _transferringBonus,
onTransfer: () => _transferBonusToMain(balance),
),
@ -434,7 +323,7 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
accentDeep: AppColors.walletTestDeep,
icon: Icons.science_rounded,
footer: _TestWalletRequestFooter(
status: _testWalletStatus,
status: state.testWalletStatus,
requesting: _requestingTestCredits,
onRequest: _requestTestCredits,
),
@ -481,7 +370,7 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
List<Widget> _historySlivers({
required BuildContext context,
required _CategoryHistory history,
required WalletActivityPage history,
required String category,
required BalanceModel? balance,
}) {
@ -595,15 +484,6 @@ class _WalletOverviewScreenState extends State<WalletOverviewScreen>
}
}
class _CategoryHistory {
List<TransactionModel> items = [];
bool loading = false;
bool loadingMore = false;
bool loaded = false;
bool hasMore = true;
String? error;
}
enum _HistoryMode { status, prediction }
class _WalletAction {

View File

@ -36,7 +36,7 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
@override
void initState() {
super.initState();
context.read<WalletBloc>().add(const WalletLoadRequested());
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
_loadNetworkFee();
}

View File

@ -34,8 +34,22 @@ class _WelcomeScreenState extends State<WelcomeScreen> {
@override
void initState() {
super.initState();
final cachedGames = sl<GameCatalogRepository>().peekLast();
if (cachedGames != null && cachedGames.isNotEmpty) {
_games = cachedGames;
}
final cachedAds = sl<AdvertisementRepository>().peekLast(placement: 'home_hero');
if (cachedAds != null && cachedAds.isNotEmpty) {
_heroAds = cachedAds;
}
if (_heroAds.isNotEmpty || _games.isNotEmpty) {
_loading = false;
}
_load();
_checkAppUpdate();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_checkAppUpdate();
});
}
Future<void> _checkAppUpdate() async {
@ -44,23 +58,36 @@ class _WelcomeScreenState extends State<WelcomeScreen> {
setState(() => _updateAvailable = available);
}
Future<void> _load() async {
setState(() => _loading = true);
Future<void> _load({bool force = false}) async {
final keep = (_heroAds.isNotEmpty || _games.isNotEmpty) && !force;
if (!keep) {
setState(() => _loading = true);
}
try {
final results = await Future.wait([
sl<AdvertisementRepository>().list(placement: 'home_hero').catchError(
(_) => <AdvertisementModel>[],
),
sl<GameCatalogRepository>().list().catchError(
(_) => <GameCatalogItem>[],
),
]);
if (!mounted) return;
setState(() {
_heroAds = results[0] as List<AdvertisementModel>;
_games = results[1] as List<GameCatalogItem>;
_loading = false;
final adsFuture = sl<AdvertisementRepository>()
.list(placement: 'home_hero', force: force)
.catchError((_) => _heroAds);
final gamesFuture =
sl<GameCatalogRepository>().list(force: force).catchError((_) => _games);
adsFuture.then((ads) {
if (!mounted) return;
setState(() {
_heroAds = ads;
_loading = false;
});
});
gamesFuture.then((games) {
if (!mounted) return;
setState(() {
_games = games;
_loading = false;
});
});
await Future.wait([adsFuture, gamesFuture]);
if (!mounted) return;
setState(() => _loading = false);
} catch (_) {
if (!mounted) return;
setState(() => _loading = false);
@ -181,7 +208,7 @@ class _WelcomeScreenState extends State<WelcomeScreen> {
const SizedBox(height: 22),
HomeAdCarousel(
ads: _heroAds,
loading: _loading,
loading: _loading && _heroAds.isEmpty,
onAdTap: (_) => _goLogin(),
),
const SizedBox(height: 22),
@ -227,12 +254,22 @@ class _WelcomeScreenState extends State<WelcomeScreen> {
),
),
const SizedBox(height: 12),
if (_loading)
if (_games.isNotEmpty)
..._games.take(4).map(
(g) => Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _WelcomeGameCard(
game: g,
onTap: _goLogin,
),
),
)
else if (_loading)
const SizedBox(
height: 80,
child: Center(child: CircularProgressIndicator(strokeWidth: 2.5)),
)
else if (_games.isEmpty)
else
PredCard(
onTap: _goLogin,
padding: const EdgeInsets.all(16),
@ -251,17 +288,7 @@ class _WelcomeScreenState extends State<WelcomeScreen> {
),
],
),
)
else
..._games.take(4).map(
(g) => Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _WelcomeGameCard(
game: g,
onTap: _goLogin,
),
),
),
),
const SizedBox(height: 22),
PredCard(
onTap: () => context.push('/faq'),

View File

@ -63,11 +63,57 @@ class _FallbackMark extends StatelessWidget {
borderRadius: BorderRadius.circular(size * 0.22),
border: Border.all(color: AppColors.accentGold, width: 1.5),
),
child: Icon(
Icons.auto_awesome_rounded,
size: size * 0.45,
color: AppColors.primaryLight,
child: CustomPaint(
size: Size(size, size),
painter: _TlMarkPainter(),
),
);
}
}
/// Fallback fused T+L mark when the brand PNG is unavailable.
class _TlMarkPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final s = size.shortestSide;
final paint = Paint()
..color = AppColors.primary
..style = PaintingStyle.fill;
final path = Path()
..moveTo(s * 0.28, s * 0.19)
..lineTo(s * 0.66, s * 0.19)
..cubicTo(s * 0.74, s * 0.19, s * 0.80, s * 0.25, s * 0.80, s * 0.32)
..cubicTo(s * 0.80, s * 0.39, s * 0.74, s * 0.45, s * 0.66, s * 0.45)
..lineTo(s * 0.42, s * 0.45)
..lineTo(s * 0.42, s * 0.56)
..lineTo(s * 0.61, s * 0.56)
..cubicTo(s * 0.70, s * 0.56, s * 0.76, s * 0.62, s * 0.76, s * 0.70)
..cubicTo(s * 0.76, s * 0.77, s * 0.70, s * 0.83, s * 0.61, s * 0.83)
..lineTo(s * 0.28, s * 0.83)
..cubicTo(s * 0.20, s * 0.83, s * 0.13, s * 0.77, s * 0.13, s * 0.70)
..lineTo(s * 0.13, s * 0.32)
..cubicTo(s * 0.13, s * 0.25, s * 0.20, s * 0.19, s * 0.28, s * 0.19)
..close();
canvas.drawPath(path, paint);
final spark = Paint()..color = AppColors.accentGold;
final c = Offset(s * 0.50, s * 0.35);
final r = s * 0.035;
final star = Path()
..moveTo(c.dx, c.dy - r * 1.6)
..lineTo(c.dx + r * 0.35, c.dy - r * 0.35)
..lineTo(c.dx + r * 1.6, c.dy)
..lineTo(c.dx + r * 0.35, c.dy + r * 0.35)
..lineTo(c.dx, c.dy + r * 1.6)
..lineTo(c.dx - r * 0.35, c.dy + r * 0.35)
..lineTo(c.dx - r * 1.6, c.dy)
..lineTo(c.dx - r * 0.35, c.dy - r * 0.35)
..close();
canvas.drawPath(star, spark);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

View File

@ -44,6 +44,7 @@ dev_dependencies:
flutter_launcher_icons:
android: true
ios: true
remove_alpha_ios: true
image_path: assets/brand/prediqo-app-icon.png
adaptive_icon_background: "#0B0F1A"
adaptive_icon_foreground: assets/brand/prediqo-app-icon.png

View File

@ -0,0 +1,65 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:prediqo_mobile/data/models/advertisement_models.dart';
import 'package:prediqo_mobile/data/repositories/advertisement_repository_impl.dart';
AdvertisementModel _ad(String id) => AdvertisementModel(
id: id,
placement: 'home_hero',
title: 'Welcome bonus',
accentColor: '#10B981',
sortOrder: 0,
);
void main() {
test('coalesces parallel list() into a single fetch', () async {
final store = AdvertisementStore();
var fetches = 0;
Future<List<AdvertisementModel>> fetch() async {
fetches++;
await Future<void>.delayed(const Duration(milliseconds: 20));
return [_ad('a1')];
}
final results = await Future.wait([
store.get(fetch),
store.get(fetch),
store.get(fetch),
]);
expect(fetches, 1);
expect(store.fetchStarts, 1);
expect(results, everyElement(hasLength(1)));
});
test('returns the fresh snapshot without refetching', () async {
final store = AdvertisementStore();
var fetches = 0;
Future<List<AdvertisementModel>> fetch() async {
fetches++;
return [_ad('a1')];
}
await store.get(fetch);
final again = await store.get(fetch);
expect(fetches, 1);
expect(again.single.id, 'a1');
expect(store.peekFresh(), isNotNull);
expect(store.peekLast(), isNotNull);
});
test('force bypasses the fresh cache', () async {
final store = AdvertisementStore();
var fetches = 0;
Future<List<AdvertisementModel>> fetch() async {
fetches++;
return [_ad('a$fetches')];
}
await store.get(fetch);
final forced = await store.get(fetch, force: true);
expect(fetches, 2);
expect(forced.single.id, 'a2');
});
}

View File

@ -0,0 +1,79 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:prediqo_mobile/data/models/game_catalog_models.dart';
import 'package:prediqo_mobile/data/repositories/game_catalog_repository_impl.dart';
GameCatalogItem _item(String id) => GameCatalogItem(
id: id,
slug: 'candle-predict',
title: 'Candle Predict',
category: 'prediction',
accentColor: '#10B981',
status: 'active',
isFeatured: true,
sortOrder: 0,
implementationKey: 'candle-predict',
);
void main() {
test('coalesces parallel list() into a single fetch', () async {
final store = GameCatalogStore();
var fetches = 0;
Future<List<GameCatalogItem>> fetch() async {
fetches++;
await Future<void>.delayed(const Duration(milliseconds: 20));
return [_item('g1')];
}
final results = await Future.wait([
store.get(fetch),
store.get(fetch),
store.get(fetch),
]);
expect(fetches, 1);
expect(store.fetchStarts, 1);
expect(results, everyElement(hasLength(1)));
});
test('returns the fresh snapshot without refetching', () async {
final store = GameCatalogStore();
var fetches = 0;
Future<List<GameCatalogItem>> fetch() async {
fetches++;
return [_item('g1')];
}
await store.get(fetch);
final again = await store.get(fetch);
expect(fetches, 1);
expect(again.single.id, 'g1');
expect(store.peekFresh(), isNotNull);
expect(store.peekLast(), isNotNull);
});
test('peekLast keeps the last list after invalidate of freshness only via TTL miss', () async {
final store = GameCatalogStore();
await store.get(() async => [_item('g1')]);
expect(store.peekLast()?.single.id, 'g1');
store.invalidate();
expect(store.peekLast(), isNull);
expect(store.peekFresh(), isNull);
});
test('force bypasses the fresh cache', () async {
final store = GameCatalogStore();
var fetches = 0;
Future<List<GameCatalogItem>> fetch() async {
fetches++;
return [_item('g$fetches')];
}
await store.get(fetch);
final forced = await store.get(fetch, force: true);
expect(fetches, 2);
expect(forced.single.id, 'g2');
expect(store.peekLast()?.single.id, 'g2');
});
}

View File

@ -0,0 +1,182 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:prediqo_mobile/core/config/app_config.dart';
import 'package:prediqo_mobile/core/network/api_client.dart';
import 'package:prediqo_mobile/core/realtime/game_socket_service.dart';
import 'package:prediqo_mobile/data/models/prediction_models.dart';
import 'package:prediqo_mobile/data/repositories/wallet_repository_impl.dart';
import 'package:prediqo_mobile/domain/repositories/prediction_repository.dart';
import 'package:prediqo_mobile/features/prediction/bloc/prediction_bloc.dart';
PredictionModel _bet({
required String id,
String wallet = 'main',
String status = 'won',
}) =>
PredictionModel(
id: id,
direction: 'long',
stakeDisplay: 1,
status: status,
payoutDisplay: 1.9,
createdAt: '2026-09-24T18:00:00.000Z',
stakeAccountKind: wallet,
);
class _RecordingPredictionRepo implements PredictionRepository {
final calls = <({int page, String? wallet, String? status})>[];
Duration delay = const Duration(milliseconds: 20);
Map<String, List<PredictionModel>> pagesByFilter = {};
String _key(String? wallet, String? status) => '${wallet ?? ''}|${status ?? ''}';
@override
Future<PredictionsPageModel> getMyBets({
int page = 1,
int pageSize = 5,
int? intervalMinutes,
String? stakeAccountKind,
String? status,
}) async {
calls.add((page: page, wallet: stakeAccountKind, status: status));
await Future<void>.delayed(delay);
final items = pagesByFilter[_key(stakeAccountKind, status)] ?? const [];
return PredictionsPageModel(
items: items,
total: items.length,
page: page,
totalPages: 1,
);
}
@override
Future<GameStateModel> getState({int? intervalMinutes}) async =>
throw UnimplementedError();
@override
Future<CandlesPageModel> getCandlesPage({
int? intervalMinutes,
int limit = 60,
int? beforeOpenMs,
}) async =>
throw UnimplementedError();
@override
Future<void> placeBet({
required String direction,
required double stakeAmount,
required int intervalMinutes,
String stakeAccountKind = 'main',
}) async {}
@override
Future<void> placeMultiBet({
required int level,
required List<String> sequence,
required double stakeAmount,
required int intervalMinutes,
String stakeAccountKind = 'main',
}) async {}
@override
Future<AutoSettingsModel> saveAutoSettings(Map<String, dynamic> body) async =>
throw UnimplementedError();
}
PredictionBloc _bloc(_RecordingPredictionRepo repo) {
const config = AppConfig(
apiBaseUrl: 'http://localhost',
isProduction: false,
wsEnabled: false,
);
final api = ApiClient(config: config);
return PredictionBloc(
repo,
GameSocketService(config, api),
WalletRepositoryImpl(api),
);
}
void main() {
test('sends wallet and status filters to the server on chip change', () async {
final repo = _RecordingPredictionRepo()
..pagesByFilter = {
'test|': [_bet(id: 't1', wallet: 'test')],
'|won': [_bet(id: 'w1', status: 'won')],
};
final bloc = _bloc(repo);
bloc.add(const PredictionHistoryFilterChanged(walletFilter: 'test'));
await bloc.stream.firstWhere(
(s) => s.historyWalletFilter == 'test' && s.history.any((p) => p.id == 't1'),
);
expect(repo.calls.single.wallet, 'test');
expect(repo.calls.single.status, isNull);
expect(repo.calls.single.page, 1);
bloc.add(const PredictionHistoryFilterChanged(statusFilter: 'won'));
await bloc.stream.firstWhere(
(s) => s.historyStatusFilter == 'won' && s.history.any((p) => p.id == 'w1'),
);
expect(repo.calls.last.wallet, isNull);
expect(repo.calls.last.status, 'won');
expect(repo.calls.where((c) => c.page > 1), isEmpty);
await bloc.close();
});
test('paints the last list immediately then refreshes that chip', () async {
final repo = _RecordingPredictionRepo()
..pagesByFilter = {
'|': [_bet(id: 'all1')],
'test|': [_bet(id: 't-old', wallet: 'test')],
};
final bloc = _bloc(repo);
bloc.add(const PredictionHistoryFilterChanged(walletFilter: 'test'));
await bloc.stream.firstWhere((s) => s.history.any((p) => p.id == 't-old'));
bloc.add(const PredictionHistoryFilterChanged());
await bloc.stream.firstWhere((s) => s.historyWalletFilter == null && s.history.any((p) => p.id == 'all1'));
repo.pagesByFilter['test|'] = [_bet(id: 't-fresh', wallet: 'test')];
repo.delay = const Duration(milliseconds: 30);
bloc.add(const PredictionHistoryFilterChanged(walletFilter: 'test'));
final painted = await bloc.stream.firstWhere((s) => s.historyWalletFilter == 'test');
expect(painted.history.single.id, 't-old');
expect(painted.isLoadingHistory, isFalse);
final refreshed = await bloc.stream.firstWhere(
(s) => s.history.any((p) => p.id == 't-fresh'),
);
expect(refreshed.history.single.id, 't-fresh');
expect(
repo.calls.where((c) => c.wallet == 'test').every((c) => c.page == 1),
isTrue,
);
await bloc.close();
});
test('first visit of a chip shows a spinner instead of another chip list', () async {
final repo = _RecordingPredictionRepo()
..pagesByFilter = {
'|': [_bet(id: 'all1')],
'main|': [_bet(id: 'm1')],
};
final bloc = _bloc(repo);
bloc.add(const PredictionHistoryPageRequested(1));
await bloc.stream.firstWhere((s) => s.history.any((p) => p.id == 'all1'));
bloc.add(const PredictionHistoryFilterChanged(walletFilter: 'main'));
final switching = await bloc.stream.firstWhere((s) => s.historyWalletFilter == 'main');
expect(switching.history, isEmpty);
expect(switching.isLoadingHistory, isTrue);
final loaded = await bloc.stream.firstWhere((s) => s.history.any((p) => p.id == 'm1'));
expect(loaded.history.single.id, 'm1');
await bloc.close();
});
}

View File

@ -0,0 +1,71 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:prediqo_mobile/data/models/share_card_models.dart';
import 'package:prediqo_mobile/data/repositories/share_card_repository.dart';
ShareCardConfig _config({bool hasDeposited = false}) => ShareCardConfig(
enabled: true,
allowMainWallet: true,
allowBonusWallet: true,
allowTestWallet: true,
allowWon: true,
allowLost: true,
allowRefunded: true,
walletOpsEnabled: true,
allowDeposit: true,
allowWithdrawal: true,
allowTransfer: true,
testWalletShareRequiresRealDeposit: true,
hasDeposited: hasDeposited,
);
void main() {
test('coalesces parallel getConfig into a single fetch', () async {
final store = ShareConfigStore();
var fetches = 0;
Future<ShareCardConfig> fetch() async {
fetches++;
await Future<void>.delayed(const Duration(milliseconds: 20));
return _config();
}
final results = await Future.wait([
store.get(fetch),
store.get(fetch),
store.get(fetch),
]);
expect(fetches, 1);
expect(store.fetchStarts, 1);
expect(results, everyElement(isA<ShareCardConfig>()));
});
test('TTL cache returns the same snapshot without a second fetch', () async {
final store = ShareConfigStore();
var fetches = 0;
Future<ShareCardConfig> fetch() async {
fetches++;
return _config();
}
await store.get(fetch);
await store.get(fetch);
expect(fetches, 1);
});
test('invalidate drops cache so a mutation can see hasDeposited', () async {
final store = ShareConfigStore();
var fetches = 0;
Future<ShareCardConfig> fetch() async {
fetches++;
return _config(hasDeposited: fetches > 1);
}
final first = await store.get(fetch);
expect(first.hasDeposited, isFalse);
store.invalidate();
final second = await store.get(fetch);
expect(second.hasDeposited, isTrue);
expect(fetches, 2);
});
}

View File

@ -13,6 +13,7 @@ import 'package:prediqo_mobile/data/models/prediction_models.dart';
import 'package:prediqo_mobile/data/models/referral_models.dart';
import 'package:prediqo_mobile/data/repositories/admin_repository_impl.dart';
import 'package:prediqo_mobile/data/repositories/auth_repository_impl.dart';
import 'package:prediqo_mobile/data/repositories/share_card_repository.dart';
import 'package:prediqo_mobile/data/repositories/wallet_repository_impl.dart';
import 'package:prediqo_mobile/domain/repositories/advertisement_repository.dart';
import 'package:prediqo_mobile/domain/repositories/faq_repository.dart';
@ -400,7 +401,16 @@ class FakeFaqRepository implements FaqRepository {
class FakeAdvertisementRepository implements AdvertisementRepository {
@override
Future<List<AdvertisementModel>> list({String? placement}) async => const [
List<AdvertisementModel>? peekCached({String? placement}) => null;
@override
List<AdvertisementModel>? peekLast({String? placement}) => null;
@override
void invalidate({String? placement}) {}
@override
Future<List<AdvertisementModel>> list({String? placement, bool force = false}) async => const [
AdvertisementModel(
id: 'ad-1',
placement: 'home_hero',
@ -432,7 +442,16 @@ class FakeNotificationRepository implements NotificationRepository {
class FakeGameCatalogRepository implements GameCatalogRepository {
@override
Future<List<GameCatalogItem>> list({bool? featured}) async => const [
List<GameCatalogItem>? peekCached({bool featured = false}) => null;
@override
List<GameCatalogItem>? peekLast({bool featured = false}) => null;
@override
void invalidate() {}
@override
Future<List<GameCatalogItem>> list({bool? featured, bool force = false}) async => const [
GameCatalogItem(
id: 'g1',
slug: 'candle-predict',
@ -482,8 +501,17 @@ Future<void> setupE2eDependencies({bool loggedIn = false, bool wsEnabled = false
sl.registerLazySingleton<GameCatalogRepository>(() => FakeGameCatalogRepository());
sl.registerLazySingleton<GameSocketService>(() => GameSocketService(sl(), sl()));
sl.registerLazySingleton<WalletRepositoryImpl>(() => WalletRepositoryImpl(sl()));
sl.registerLazySingleton<WalletRepository>(() => sl<WalletRepositoryImpl>());
sl.registerLazySingleton<ShareCardRepository>(() => ShareCardRepository(sl()));
sl.registerLazySingleton<AdminRepositoryImpl>(() => AdminRepositoryImpl(sl()));
sl.registerFactory<AuthBloc>(() => AuthBloc(sl())..add(const AuthCheckRequested()));
sl.registerFactory<WalletBloc>(() => WalletBloc(sl<WalletRepositoryImpl>()));
sl.registerFactory<WalletBloc>(
() => WalletBloc(
sl<WalletRepository>(),
sl<HealthRepository>(),
sl<ReferralRepository>(),
shareCards: sl<ShareCardRepository>(),
),
);
sl.registerFactory<PredictionBloc>(() => PredictionBloc(sl(), sl(), sl()));
}

View File

@ -0,0 +1,315 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:prediqo_mobile/data/models/balance_model.dart';
import 'package:prediqo_mobile/data/models/referral_models.dart';
import 'package:prediqo_mobile/data/models/test_wallet_models.dart';
import 'package:prediqo_mobile/data/models/transaction_model.dart';
import 'package:prediqo_mobile/data/models/wallet_type_model.dart';
import 'package:prediqo_mobile/data/repositories/wallet_repository_impl.dart';
import 'package:prediqo_mobile/domain/repositories/health_repository.dart';
import 'package:prediqo_mobile/domain/repositories/referral_repository.dart';
import 'package:prediqo_mobile/features/wallet/bloc/wallet_bloc.dart';
const _usdt = WalletTypeModel(
id: 1,
code: 'USDT_TRC20',
name: 'USDT',
network: 'TRON',
decimals: 6,
);
BalanceModel _balance({String available = '10690000'}) => BalanceModel(
walletType: _usdt,
available: available,
locked: '0',
bonusAvailable: '0',
testAvailable: '5000000',
);
TransactionModel _tx(String id) => TransactionModel(
id: id,
walletTypeId: 1,
type: 'deposit',
amount: '1000000',
fee: '0',
status: 'completed',
createdAt: '2026-09-24T10:00:00.000Z',
);
class _FakeWalletRepo implements WalletRepository {
int typesCalls = 0;
int balancesCalls = 0;
int txCalls = 0;
final List<String?> txCategories = [];
final List<int> txOffsets = [];
Completer<void>? typesHold;
Completer<void>? extrasHold;
List<TransactionModel> page = [_tx('d1')];
@override
Future<List<WalletTypeModel>> getWalletTypes() async {
typesCalls++;
if (typesHold != null) await typesHold!.future;
return const [_usdt];
}
@override
Future<List<BalanceModel>> getBalances() async {
balancesCalls++;
return [_balance()];
}
@override
Future<List<TransactionModel>> getTransactions({
int limit = 50,
int offset = 0,
String? category,
}) async {
txCalls++;
txCategories.add(category);
txOffsets.add(offset);
return page;
}
@override
Future<TestWalletStatusModel> getTestWalletStatus() async {
if (extrasHold != null) await extrasHold!.future;
return const TestWalletStatusModel(
enabled: true,
balanceRaw: '5000000',
walletTypeId: 1,
decimals: 6,
creditAmountRaw: '10000000',
maxRequests: 3,
requestsUsed: 0,
canRequest: true,
);
}
@override
Future<TestWalletCreditResult> requestTestCredits() async {
throw UnimplementedError();
}
@override
Future<DepositAddressResult> getDepositAddress(String walletType) async {
throw UnimplementedError();
}
@override
Future<WithdrawResult> withdraw(
String walletType,
String toAddress,
String amount, {
String? totpCode,
}) async {
return const WithdrawResult(transactionId: 'w1', status: 'pending');
}
@override
Future<TransferResult> transfer(
String toEmail,
String walletType,
String amount, {
String? totpCode,
}) async {
throw UnimplementedError();
}
}
class _FakeHealth implements HealthRepository {
Completer<void>? hold;
@override
Future<HealthStatus> getHealth() async {
if (hold != null) await hold!.future;
return const HealthStatus(
network: 'mainnet',
withdrawalsEnabled: true,
env: 'test',
withdrawalNetworkFeeRaw: '1000000',
);
}
}
class _FakeReferral implements ReferralRepository {
@override
Future<ReferralDashboardModel> getDashboard({int maxDepth = 10}) async {
throw UnimplementedError();
}
@override
Future<ReferralCommissionsPage> getCommissions({int limit = 25, int offset = 0}) {
throw UnimplementedError();
}
@override
Future<({List<BonusBalanceModel> balances, bool bonusWithdrawable})> getBonusBalances() async =>
(balances: <BonusBalanceModel>[], bonusWithdrawable: true);
@override
Future<void> transferBonusToMain({
required int walletTypeId,
required String amountRaw,
}) async {}
}
Future<void> _settle() => Future<void>.delayed(const Duration(milliseconds: 20));
void main() {
late _FakeWalletRepo wallet;
late _FakeHealth health;
late WalletBloc bloc;
setUp(() {
wallet = _FakeWalletRepo();
health = _FakeHealth();
bloc = WalletBloc(wallet, health, _FakeReferral());
});
tearDown(() async {
await bloc.close();
});
test('emits balances before slower wallet-types (soldes d’abord)', () async {
wallet.typesHold = Completer<void>();
bloc.add(const WalletLoadRequested());
await bloc.stream.firstWhere((s) => s.balances.isNotEmpty);
expect(bloc.state.balances.single.available, '10690000');
expect(bloc.state.isLoading, isFalse);
expect(bloc.state.walletTypes, isEmpty);
wallet.typesHold!.complete();
await bloc.stream.firstWhere((s) => s.walletTypes.isNotEmpty);
expect(bloc.state.walletTypes, isNotEmpty);
});
test('full load prefetches Deposits then Withdrawals and Transfers, not Predictions', () async {
bloc.add(const WalletLoadRequested());
await bloc.stream.firstWhere(
(s) => s.deposits.loaded && s.withdrawals.loaded && s.transfers.loaded,
);
await _settle();
expect(wallet.balancesCalls, 1);
expect(wallet.txCategories, containsAll(['deposits', 'withdrawals', 'transfers']));
expect(wallet.txCategories, isNot(contains('predictions')));
expect(bloc.state.predictions.loaded, isFalse);
});
test('ifStale skips a second load within the short cache window', () async {
bloc.add(const WalletLoadRequested());
await bloc.stream.firstWhere((s) => s.healthLoaded);
await _settle();
expect(wallet.balancesCalls, 1);
bloc.add(const WalletLoadRequested(ifStale: true));
await _settle();
expect(wallet.balancesCalls, 1);
});
test('Predictions stay on-demand and do not reload balances', () async {
bloc.add(const WalletLoadRequested());
await bloc.stream.firstWhere(
(s) => s.deposits.loaded && s.withdrawals.loaded && s.transfers.loaded,
);
final balanceCalls = wallet.balancesCalls;
final txBeforePredictions = wallet.txCalls;
bloc.add(const WalletActivityRequested(category: 'predictions'));
await bloc.stream.firstWhere((s) => s.predictions.loaded);
expect(wallet.txCategories, contains('predictions'));
expect(wallet.txCalls, txBeforePredictions + 1);
expect(wallet.balancesCalls, balanceCalls);
});
test('Activity cache skips a repeat visit within the short window', () async {
bloc.add(const WalletActivityRequested(category: 'deposits'));
await bloc.stream.firstWhere((s) => s.deposits.loaded);
expect(wallet.txCalls, 1);
bloc.add(const WalletActivityRequested(category: 'deposits'));
await _settle();
expect(wallet.txCalls, 1);
});
test('Activity force refetch ignores the short cache', () async {
bloc.add(const WalletActivityRequested(category: 'deposits'));
await bloc.stream.firstWhere((s) => s.deposits.loaded);
wallet.page = [_tx('forced')];
bloc.add(const WalletActivityRequested(category: 'deposits', force: true));
await bloc.stream.firstWhere((s) =>
s.deposits.items.length == 1 && s.deposits.items.single.id == 'forced');
expect(wallet.txCalls, 2);
});
test('Activity more appends the next page without a full wallet load', () async {
wallet.page = List.generate(10, (i) => _tx('p$i'));
bloc.add(const WalletActivityRequested(category: 'deposits'));
await bloc.stream.firstWhere((s) => s.deposits.loaded);
expect(bloc.state.deposits.hasMore, isTrue);
wallet.page = [_tx('extra')];
bloc.add(const WalletActivityMoreRequested(category: 'deposits'));
await bloc.stream.firstWhere((s) => s.deposits.items.length == 11);
expect(wallet.txOffsets, [0, 10]);
expect(wallet.balancesCalls, 0);
expect(bloc.state.deposits.hasMore, isFalse);
});
test('WalletBloc can be constructed with the WalletRepository interface', () async {
final extra = WalletBloc(wallet, health, _FakeReferral());
expect(extra, isA<WalletBloc>());
await extra.close();
});
test('slow extras do not block the first balances emit', () async {
health.hold = Completer<void>();
wallet.extrasHold = Completer<void>();
bloc.add(const WalletLoadRequested());
await bloc.stream.firstWhere((s) => s.balances.isNotEmpty);
expect(bloc.state.healthLoaded, isFalse);
expect(bloc.state.testWalletStatus, isNull);
health.hold!.complete();
wallet.extrasHold!.complete();
await bloc.stream.firstWhere((s) => s.healthLoaded);
expect(bloc.state.bonusWithdrawable, isTrue);
});
test('a withdrawal force-refetches the Withdrawals tab so the action is visible', () async {
bloc.add(const WalletLoadRequested());
await bloc.stream.firstWhere((s) => s.walletTypes.isNotEmpty && s.withdrawals.loaded);
wallet.page = [_tx('new-withdrawal')];
bloc.add(const WalletWithdrawRequested(
walletType: 'USDT_TRC20',
toAddress: 'Txyz',
amount: '1000000',
));
await bloc.stream.firstWhere(
(s) => s.withdrawals.items.any((t) => t.id == 'new-withdrawal'),
);
});
test('force load invalidates Activity TTL and refetches Deposits', () async {
bloc.add(const WalletLoadRequested());
await bloc.stream.firstWhere((s) => s.deposits.loaded);
final txAfterWarm = wallet.txCalls;
wallet.page = [_tx('after-mutation')];
bloc.add(const WalletLoadRequested());
await bloc.stream.firstWhere(
(s) => s.deposits.items.any((t) => t.id == 'after-mutation'),
);
expect(wallet.txCalls, greaterThan(txAfterWarm));
});
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 427 B

After

Width:  |  Height:  |  Size: 641 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

After

Width:  |  Height:  |  Size: 168 KiB

View File

@ -2,9 +2,11 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/favicon.png" sizes="192x192" />
<link rel="icon" type="image/png" href="/favicon-48.png" sizes="48x48" />
<link rel="icon" type="image/png" href="/favicon-32.png" sizes="32x32" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/png" href="/brand/prediqo-mark.png" />
<link rel="apple-touch-icon" href="/brand/prediqo-app-icon.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="theme-color" content="#0B0F1A" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tloto</title>

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

After

Width:  |  Height:  |  Size: 411 KiB

Some files were not shown because too many files have changed in this diff Show More