games_app/prediqo_mobile/lib/features/wallet/bloc/wallet_bloc.dart
2026-10-12 19:18:13 +02:00

395 lines
13 KiB
Dart

/// Wallet BLoC layer: balances, deposit addresses, withdrawals, and transfers.
library;
import 'package:flutter_bloc/flutter_bloc.dart';
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) {
return AppException.fromDio(e).message;
}
if (e is AppException) return e.message;
return e.toString().replaceFirst('Exception: ', '');
}
String? _errorCode(Object e) {
if (e is DioException) return AppException.fromDio(e).code;
if (e is AppException) return e.code;
return null;
}
/// Manages wallet data and money-movement operations via [WalletRepositoryImpl].
class WalletBloc extends Bloc<WalletEvent, WalletState> {
/// 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 WalletRepository _walletRepo;
final HealthRepository _healthRepo;
final ReferralRepository _referralRepo;
final ShareCardRepository? _shareCards;
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 {
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(
balances: balances,
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: 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;
if (s.walletTypes.isEmpty) return;
emit(s.copyWith(clearDeposit: true, clearError: true));
try {
final result = await _walletRepo.getDepositAddress(event.walletTypeCode);
emit(s.copyWith(depositAddress: result.address, depositWalletType: result.walletType));
} catch (e) {
emit(s.copyWith(errorMessage: _errorMessage(e)));
}
}
/// Submits a withdrawal and reloads wallet data on success.
Future<void> _onWithdraw(WalletWithdrawRequested event, Emitter<WalletState> emit) async {
final s = state;
if (s.walletTypes.isEmpty) {
emit(s.copyWith(errorMessage: 'Wallet data is still loading. Try again.'));
return;
}
emit(s.copyWith(clearError: true, clearTransfer: true, clearWithdraw: true));
try {
final result = await _walletRepo.withdraw(
event.walletType,
event.toAddress,
event.amount,
totpCode: event.totpCode,
);
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),
errorCode: _errorCode(e),
));
}
}
/// Submits an in-app transfer to another user and reloads wallet data on success.
Future<void> _onTransfer(WalletTransferRequested event, Emitter<WalletState> emit) async {
final s = state;
if (s.walletTypes.isEmpty) {
emit(s.copyWith(errorMessage: 'Wallet data is still loading. Try again.'));
return;
}
emit(s.copyWith(clearError: true, clearTransfer: true, clearWithdraw: true));
try {
final result = await _walletRepo.transfer(
event.toEmail,
event.walletType,
event.amount,
totpCode: event.totpCode,
);
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),
errorCode: _errorCode(e),
));
}
}
void _onClearFeedback(WalletClearFeedback event, Emitter<WalletState> emit) {
emit(state.copyWith(clearError: true, clearTransfer: true, clearWithdraw: true));
}
}