Connect customer quotations and payment execution to Sendico (#50)

This commit is contained in:
Stephan D committed 2026-10-16 09:57:28 +02:00
1 parent 5d67c25c8e
commit 7a6510d1a8
45 files changed
+2696 -45

No files matched your search

+9 -1
View File
@@ -15,7 +15,15 @@ flutter run -d chrome
A responsive login/sign-up preview with a themed brand panel, email and password validation, password visibility controls, keyboard submission, and inline feedback. Sign-up additionally asks for a name and matching password confirmation. The 12-character sign-up minimum is a UI preview policy and must be aligned with the backend when authentication is integrated.
No authentication endpoint is configured. Submission validates locally and calls the shared dummy authentication services; it never creates an account, starts a session, sends credentials, or persists them. Passwords are cleared when switching modes. Password managers/autofill integration is deferred until real authentication exists. LoginProvider and SignupProvider own loading/results/errors; SxchngeApp accepts injected loginService and signupService implementations. Dummy completion is explicitly labeled and does not establish a real session.
Without backend configuration the app uses dummy services. The existing
`SXCHNGE_API_URL` and `SXCHNGE_CLIENT_ID` select authenticated backend auth,
identity, limits and wallet adapters. Wallet operations use Sendico through the
BFF after the provider prerequisites and dedicated customer resource bindings
are provisioned; they do not use demo balances in backend mode. LoginProvider,
SignupProvider and shared wallet providers own loading/results/errors.
SxchngeApp retains explicit service injection for tests and previews. See
[quotation/payment integration](../../docs/payments.md) for setup, supported
funding/destinations, authorization, reconciliation and rollout.
The interface uses `ColorScheme` and `TextTheme` roles from `sxchnge_theme`; the desktop brand panel installs the package's dark theme locally. Entrance animation respects reduced-motion preferences. The public website remains separate in `website/`.
+13 -1
View File
@@ -277,5 +277,17 @@
"kycOperationMaximum": "Per operation maximum",
"kycErrorAccess": "Verification is unavailable for this account. Contact support if this continues.",
"kycUpgradePendingTitle": "Limits upgrade pending",
"kycUpgradePendingBody": "Your identity review is approved. We are waiting for confirmation of the limits upgrade. You do not need to submit your photos again."
"kycUpgradePendingBody": "Your identity review is approved. We are waiting for confirmation of the limits upgrade. You do not need to submit your photos again.",
"wNoPayoutMethod": "No payout destination is set up for this account. Contact support to add one.",
"wNoFundingMethod": "No funding method is set up for this account. Contact support for funding instructions.",
"wLivePending": "Your payment is awaiting a final outcome. Refresh to see its latest status and balance.",
"wLiveFailed": "Your payment did not complete. Refresh your accounts to see the current available balance.",
"wLiveQuoteNotice": "Quote expires in {seconds} seconds.",
"@wLiveQuoteNotice": {
"placeholders": {
"seconds": {
"type": "int"
}
}
}
}
+13 -1
View File
@@ -277,5 +277,17 @@
"kycOperationMaximum": "Максимум на операцию",
"kycErrorAccess": "Проверка недоступна для этого аккаунта. Если это повторяется, обратитесь в поддержку.",
"kycUpgradePendingTitle": "Ожидается повышение лимитов",
"kycUpgradePendingBody": "Проверка личности одобрена. Ожидается подтверждение повышения лимитов. Отправлять фото повторно не нужно."
"kycUpgradePendingBody": "Проверка личности одобрена. Ожидается подтверждение повышения лимитов. Отправлять фото повторно не нужно.",
"wNoPayoutMethod": "Для этого счёта не настроен способ вывода. Обратитесь в поддержку.",
"wNoFundingMethod": "Для этого счёта не настроен способ пополнения. Обратитесь в поддержку за инструкциями.",
"wLivePending": "Ожидается окончательный результат платежа. Обновите страницу, чтобы проверить статус и баланс.",
"wLiveFailed": "Платёж не завершён. Обновите счета, чтобы проверить доступный баланс.",
"wLiveQuoteNotice": "Предложение истекает через {seconds} сек.",
"@wLiveQuoteNotice": {
"placeholders": {
"seconds": {
"type": "int"
}
}
}
}
+24 -6
View File
@@ -63,8 +63,11 @@ class _SxchngeAppState extends State<SxchngeApp> {
late final _locale = widget.localeProvider ?? LocaleProvider();
late final _analytics = widget.analyticsService ?? DummyAnalyticsService();
late final _factors =
late final _authFactors =
widget.backend ?? widget.twoFactorService ?? DummyTwoFactorService();
late final _factors = _walletService is BackendWalletService
? WalletFactorService(_walletService, _authFactors)
: _authFactors;
late final _security = SecurityProvider(_factors, _analytics);
late final _identity =
widget.identityService ??
@@ -76,11 +79,16 @@ class _SxchngeAppState extends State<SxchngeApp> {
));
late final _walletService =
widget.walletService ??
DummyWalletService(
_identity,
initialLocale: _locale.locale.languageCode,
factors: _factors,
);
(widget.backend != null
? BackendWalletService(
baseUri: widget.backend!.baseUri,
accessToken: () => widget.backend!.session?.accessToken,
)
: DummyWalletService(
_identity,
initialLocale: _locale.locale.languageCode,
factors: _authFactors,
));
late final _wallet = WalletProvider(
_walletService,
_analytics,
@@ -109,14 +117,21 @@ class _SxchngeAppState extends State<SxchngeApp> {
: () => widget.backend!.session != null,
)..routeInformationProvider.addListener(_routeChanged);
String _previousPath = '/';
String? _walletCustomer;
@override
void initState() {
super.initState();
_previousPath = _router.routeInformationProvider.value.uri.path;
_walletCustomer = widget.backend?.session?.userId;
}
void _routeChanged() {
final customer = widget.backend?.session?.userId;
if (customer != _walletCustomer) {
_walletCustomer = customer;
_wallet.reset();
}
final path = _router.routeInformationProvider.value.uri.path;
if (path == '/' && _previousPath != '/' && _previousPath != '/two-factor') {
_journeys.abandon(JourneyExit.navigation);
@@ -130,6 +145,9 @@ class _SxchngeAppState extends State<SxchngeApp> {
_router.dispose();
_journeys.dispose();
_wallet.dispose();
if (_walletService is BackendWalletService) {
_walletService.close();
}
_security.dispose();
if (_identity is BackendIdentityService) {
_identity.close();
+19 -11
View File
@@ -28,17 +28,25 @@ String statusText(AppLocalizations l, OperationStatus s) => switch (s) {
OperationStatus.completed => l.wCompleted,
OperationStatus.failed => l.wFailed,
};
String fundsText(AppLocalizations l, WalletOperation o) =>
switch ((o.status, o.quote.request.kind)) {
(OperationStatus.pending, TransferKind.topUp) => l.wPendingTopUp,
(OperationStatus.pending, TransferKind.exchange) => l.wPendingExchange,
(OperationStatus.pending, TransferKind.payout) => l.wPendingPayout,
(OperationStatus.completed, TransferKind.topUp) => l.wCompleteTopUp,
(OperationStatus.completed, TransferKind.exchange) => l.wCompleteExchange,
(OperationStatus.completed, TransferKind.payout) => l.wCompletePayout,
(OperationStatus.failed, TransferKind.topUp) => l.wFailedTopUp,
_ => l.wFailedOutgoing,
};
String fundsText(
AppLocalizations l,
WalletOperation o, {
bool simulated = true,
}) => !simulated && o.status == OperationStatus.pending
? l.wLivePending
: !simulated && o.status == OperationStatus.failed
? l.wLiveFailed
: switch ((o.status, o.quote.request.kind)) {
(OperationStatus.pending, TransferKind.topUp) => l.wPendingTopUp,
(OperationStatus.pending, TransferKind.exchange) => l.wPendingExchange,
(OperationStatus.pending, TransferKind.payout) => l.wPendingPayout,
(OperationStatus.completed, TransferKind.topUp) => l.wCompleteTopUp,
(OperationStatus.completed, TransferKind.exchange) =>
l.wCompleteExchange,
(OperationStatus.completed, TransferKind.payout) => l.wCompletePayout,
(OperationStatus.failed, TransferKind.topUp) => l.wFailedTopUp,
_ => l.wFailedOutgoing,
};
String walletError(AppLocalizations l, WalletError e) => switch (e) {
WalletError.invalidAmount => l.wInvalidAmount,
WalletError.insufficientFunds => l.wInsufficient,
+1 -1
View File
@@ -97,7 +97,7 @@ class _OperationPageState extends State<OperationPage> {
),
const SizedBox(height: 16),
Text(
fundsText(l, o),
fundsText(l, o, simulated: p.service.isSimulated),
style: TextStyle(
color: o.status == OperationStatus.failed
? c.onErrorContainer
+45 -10
View File
@@ -133,6 +133,15 @@ class TransferPageState extends State<TransferPage> {
final t = Theme.of(context);
final accounts = wallet.data?.accounts ?? [];
final source = wallet.account(p.source);
final live = !wallet.service.isSimulated;
final expiresIn =
p.quote?.expiresAt.difference(DateTime.now()).inSeconds ?? 0;
final unavailableMethod =
live &&
((widget.kind == TransferKind.payout &&
(source?.payoutMethod.isEmpty ?? true)) ||
(widget.kind == TransferKind.topUp &&
!(source?.canFund ?? false)));
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Center(
@@ -207,7 +216,15 @@ class TransferPageState extends State<TransferPage> {
] else if (p.quote != null) ...[
TransferSummary(quote: p.quote!),
const SizedBox(height: 16),
Text(p.expired ? l.wExpired : l.wQuoteNotice),
Text(
p.expired
? l.wExpired
: live
? l.wLiveQuoteNotice(
expiresIn < 0 ? 0 : expiresIn,
)
: l.wQuoteNotice,
),
const SizedBox(height: 20),
if (p.expired)
FilledButton(
@@ -299,21 +316,39 @@ class TransferPageState extends State<TransferPage> {
),
if (widget.kind == TransferKind.payout) ...[
const SizedBox(height: 20),
TextField(
key: const ValueKey('transfer-recipient'),
controller: _recipient,
enabled: !p.busy,
decoration: InputDecoration(
labelText: l.wRecipient,
hintText: l.wRecipientHint,
if (live && source?.payoutMethod.isNotEmpty == true)
InputDecorator(
decoration: InputDecoration(
labelText: l.wRecipient,
),
child: Text(source!.payoutLabel),
),
onChanged: (v) => p.change(recipient: v),
if (!live)
TextField(
key: const ValueKey('transfer-recipient'),
controller: _recipient,
enabled: !p.busy,
decoration: InputDecoration(
labelText: l.wRecipient,
hintText: l.wRecipientHint,
),
onChanged: (v) => p.change(recipient: v),
),
],
if (unavailableMethod) ...[
const SizedBox(height: 12),
Text(
widget.kind == TransferKind.payout
? l.wNoPayoutMethod
: l.wNoFundingMethod,
),
],
const SizedBox(height: 28),
FilledButton(
key: const ValueKey('transfer-review'),
onPressed: p.busy ? null : p.review,
onPressed: p.busy || unavailableMethod
? null
: p.review,
child: Text(l.wReview),
),
if (p.error == WalletError.limitExceeded)
+101
View File
@@ -0,0 +1,101 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sxchnge_kyc/sxchnge_kyc.dart';
import 'package:sxchnge_wallet/sxchnge_wallet.dart';
import 'package:sxchnge_app/main.dart';
const destinationLabel =
'Saved bank ending 1234 — Personal current account for daily transfers and reimbursements';
class LiveWallet extends DummyWalletService {
LiveWallet({this.hasMethod = true})
: super(DummyIdentityService(delay: Duration.zero), delay: Duration.zero);
final bool hasMethod;
String? received;
@override
bool get isSimulated => false;
@override
Future<WalletSnapshot> fetch() async => WalletSnapshot(
accounts: [
CurrencyAccount(
id: 'real-account',
currency: 'EUR',
precision: 2,
available: 7500,
payoutMethod: hasMethod ? 'method-ref' : '',
payoutLabel: hasMethod ? destinationLabel : '',
canFund: false,
),
],
operations: [],
);
@override
Future<Quote> quote(TransferRequest request) async {
received = request.recipient;
return Quote(
id: 'quote',
request: TransferRequest(
kind: request.kind,
source: request.source,
amount: request.amount,
recipient: destinationLabel,
),
fee: 100,
debit: request.amount + 100,
credit: request.amount,
expiresAt: DateTime.now().add(const Duration(minutes: 5)),
rateNumerator: 1,
rateDenominator: 1,
);
}
}
void main() {
for (final hasMethod in [true, false]) {
testWidgets(
'backend payout ${hasMethod ? 'reviews saved destination' : 'explains missing destination'} at narrow width',
(t) async {
t.view.physicalSize = const Size(320, 1100);
t.view.devicePixelRatio = 1;
t.platformDispatcher.textScaleFactorTestValue = 1.6;
t.platformDispatcher.defaultRouteNameTestValue = '/payout';
addTearDown(t.view.resetPhysicalSize);
addTearDown(t.view.resetDevicePixelRatio);
addTearDown(t.platformDispatcher.clearTextScaleFactorTestValue);
addTearDown(t.platformDispatcher.clearDefaultRouteNameTestValue);
final wallet = LiveWallet(hasMethod: hasMethod);
await t.pumpWidget(SxchngeApp(walletService: wallet));
await t.pumpAndSettle();
expect(find.byKey(const ValueKey('transfer-recipient')), findsNothing);
await t.enterText(find.byKey(const ValueKey('transfer-amount')), '20');
final review = find.byKey(const ValueKey('transfer-review'));
await t.ensureVisible(review);
if (hasMethod) {
expect(find.text(destinationLabel), findsOneWidget);
await t.tap(review);
await t.pumpAndSettle();
expect(wallet.received, 'method-ref');
expect(find.text(destinationLabel), findsOneWidget);
expect(
find.byKey(const ValueKey('transfer-confirm')),
findsOneWidget,
);
} else {
expect(t.widget<FilledButton>(review).onPressed, isNull);
expect(
find.text(
'No payout destination is set up for this account. Contact support to add one.',
),
findsOneWidget,
);
}
expect(t.takeException(), isNull);
await t.pumpWidget(const SizedBox.shrink());
},
);
}
}
+3 -2
View File
@@ -32,8 +32,9 @@ wallet state changes. The adapter reuses the KYC package's limit DTO and mapper.
## Integration boundary
Replace `WalletService` and `LimitsService` together with authenticated backend
adapters. The backend must provide authorization, authoritative quotes/balances,
Backend mode now uses `BackendWalletService` and `WalletFactorService` with the
authenticated BFF; `BackendLimitsService` supplies the reviewed platform projection.
See [payment provisioning and rollout](../../../docs/payments.md). The backend must provide authorization, authoritative quotes/balances,
atomic limits enforcement, durable idempotency and operation reconciliation.
Add supported payment methods and validated recipients from that contract, rather
than interpreting the demo input as production bank validation. Replace profile
@@ -0,0 +1,52 @@
import 'package:sxchnge_auth/sxchnge_auth.dart';
import '../models/wallet.dart';
import '../transport/backend.dart';
import '../transport/wallet.dart';
abstract final class BackendMapper {
static Map<String, Object?> request(TransferRequest r) => {
'kind': r.kind.name,
'source': r.source,
'destination': r.destination ?? '',
'amount': r.amount,
'recipient': r.recipient,
};
static WalletSnapshot snapshot(BackendDTO d) => WalletSnapshot(
accounts: d.accounts.map(WalletMapper.account).toList(),
operations: d.operations.map(WalletMapper.operation).toList(),
);
static Quote quote(BackendDTO d) => WalletMapper.quote(d.quoteValue);
static WalletOperation? operation(BackendDTO d) => d.operationValue == null
? null
: WalletMapper.operation(d.operationValue!);
static AccountProfile profile(BackendDTO d) =>
WalletMapper.profile(ProfileDTO(d.locale));
static FactorChallenge challenge(
BackendDTO d,
FactorPurpose purpose,
String operation,
) {
final c = d.challenge;
return FactorChallenge(
id: c.id,
purpose: purpose,
operation: operation,
target: c.target,
expiresAt: c.expires,
resendAt: c.resend,
);
}
static WalletError failure(BackendDTO d) =>
WalletError.values.where((v) => v.name == d.error).firstOrNull ??
WalletError.unavailable;
static FactorError factorFailure(BackendDTO d) => switch (d.error) {
'factorInvalid' => FactorError.invalid,
'factorExpired' || 'expiredQuote' => FactorError.expired,
'factorLocked' => FactorError.locked,
'factorCooldown' => FactorError.cooldown,
'factorRequired' => FactorError.required,
_ => FactorError.unavailable,
};
}
@@ -25,9 +25,14 @@ class CurrencyAccount {
required this.currency,
required this.precision,
required this.available,
this.payoutMethod = '',
this.payoutLabel = '',
this.canFund = true,
});
final String id, currency;
final int precision, available;
final String payoutMethod, payoutLabel;
final bool canFund;
/// Locale-aware decimal input, integer money. Grouping/exponents are rejected.
int? parse(String input) {
@@ -19,6 +19,8 @@ class TransferProvider extends ChangeNotifier {
.firstOrNull
?.id ??
'usd';
wallet.addListener(_walletChanged);
_syncAccounts();
final op = recorder.begin(
journey,
JourneyStep.transferDraft,
@@ -26,6 +28,30 @@ class TransferProvider extends ChangeNotifier {
);
recorder.finish(op, simulated: wallet.service.isSimulated);
}
void _syncAccounts() {
final accounts = wallet.data?.accounts;
if (accounts == null ||
accounts.isEmpty ||
busy ||
uncertain ||
quote != null)
return;
if (!accounts.any((a) => a.id == source)) source = accounts.first.id;
if (!accounts.any((a) => a.id == destination) || destination == source) {
destination = accounts.where((a) => a.id != source).firstOrNull?.id;
}
if (!wallet.service.isSimulated && kind == TransferKind.payout) {
recipient = wallet.account(source)?.payoutMethod ?? '';
}
}
void _walletChanged() {
if (_disposed) return;
final previous = source;
_syncAccounts();
if (source != previous) notifyListeners();
}
final WalletProvider wallet;
final TransferKind kind;
final JourneyRecorder recorder;
@@ -45,7 +71,8 @@ class TransferProvider extends ChangeNotifier {
TransferKind.exchange => JourneyKind.exchange,
TransferKind.payout => JourneyKind.payout,
};
bool get hasDraft => amount.isNotEmpty || recipient.isNotEmpty;
bool get hasDraft =>
amount.isNotEmpty || (wallet.service.isSimulated && recipient.isNotEmpty);
bool get expired =>
quote != null && !DateTime.now().isBefore(quote!.expiresAt);
void change({
@@ -59,6 +86,7 @@ class TransferProvider extends ChangeNotifier {
this.destination = destination ?? this.destination;
this.amount = amount ?? this.amount;
this.recipient = recipient ?? this.recipient;
if (source != null) _syncAccounts();
quote = null;
noSubmission = false;
error = null;
@@ -171,6 +199,7 @@ class TransferProvider extends ChangeNotifier {
error = null;
factorError = null;
notifyListeners();
_key ??= approval?.token;
_key ??= List.generate(
16,
(_) => Random.secure().nextInt(256).toRadixString(16).padLeft(2, '0'),
@@ -266,6 +295,7 @@ class TransferProvider extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
wallet.removeListener(_walletChanged);
recipient = '';
if (!_handedOff) recorder.dispose();
super.dispose();
@@ -140,6 +140,21 @@ class WalletProvider extends ChangeNotifier {
return !saveFailed;
}
/// Drop account-scoped state when the authenticated customer changes.
void reset() {
_revision++;
_poll?.cancel();
for (final pair in _settlements.values) {
pair.$1.dispose(abandonActive: false);
}
_settlements.clear();
data = null;
preferredLocale = null;
loading = failed = profileLoading = profileFailed = saving = saveFailed =
false;
notifyListeners();
}
@override
void dispose() {
_disposed = true;
@@ -0,0 +1,130 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:sxchnge_auth/sxchnge_auth.dart';
import '../mappers/backend.dart';
import '../models/wallet.dart';
import '../transport/backend.dart';
import 'contracts.dart';
import 'http/client.dart';
class BackendWalletService implements WalletService {
BackendWalletService({
required this.baseUri,
required this.accessToken,
http.Client? client,
}) : _client = client ?? createClient() {
if (!baseUri.hasAuthority ||
baseUri.hasQuery ||
baseUri.hasFragment ||
baseUri.userInfo.isNotEmpty ||
(baseUri.scheme != 'https' &&
!(baseUri.scheme == 'http' &&
['localhost', '127.0.0.1'].contains(baseUri.host))))
throw ArgumentError('Valid wallet API URL required');
}
final Uri baseUri;
final String? Function() accessToken;
final http.Client _client;
@override
bool get isSimulated => false;
Future<BackendDTO> send(
String path, {
Map<String, Object?>? body,
bool factor = false,
}) async {
final token = accessToken();
if (token == null) throw const WalletException(WalletError.unavailable);
final uri = baseUri.replace(
path:
'${baseUri.path.replaceFirst(RegExp(r"/$"), "")}/accounts/wallet$path',
);
final request = http.Request(body == null ? 'GET' : 'POST', uri)
..followRedirects = false;
request.headers.addAll({
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
if (kIsWeb) 'X-CSRF-Protection': '1',
});
if (body != null) request.body = jsonEncode(body);
try {
final response = await _client
.send(request)
.then(http.Response.fromStream)
.timeout(const Duration(seconds: 40));
if (token != accessToken())
throw const WalletException(WalletError.unavailable);
final dto = BackendDTO.decode(response.body);
if (response.statusCode < 200 ||
response.statusCode >= 300 ||
!dto.accepted) {
if (factor || dto.error.startsWith('factor'))
throw FactorException(BackendMapper.factorFailure(dto));
throw WalletException(BackendMapper.failure(dto));
}
return dto;
} on FactorException {
rethrow;
} on WalletException {
rethrow;
} catch (_) {
throw const WalletException(WalletError.unavailable);
}
}
Future<T> _mapped<T>(
Future<BackendDTO> dto,
T Function(BackendDTO) map,
) async {
try {
return map(await dto);
} on FactorException {
rethrow;
} on WalletException {
rethrow;
} catch (_) {
throw const WalletException(WalletError.unavailable);
}
}
@override
Future<WalletSnapshot> fetch() => _mapped(send(''), BackendMapper.snapshot);
@override
Future<Quote> quote(TransferRequest request) => _mapped(
send('/quote', body: BackendMapper.request(request)),
BackendMapper.quote,
);
@override
Future<WalletOperation> submit(
String quoteId,
String idempotencyKey, {
String? approval,
}) async {
final value = await _mapped(
send(
'/submit',
body: {'quoteId': quoteId, 'idempotencyKey': idempotencyKey},
),
BackendMapper.operation,
);
if (value == null) throw const WalletException(WalletError.uncertain);
return value;
}
@override
Future<WalletOperation?> findSubmission(String idempotencyKey) => _mapped(
send('/submission', body: {'idempotencyKey': idempotencyKey}),
BackendMapper.operation,
);
@override
Future<AccountProfile> profile() =>
_mapped(send('/profile'), BackendMapper.profile);
@override
Future<AccountProfile> saveLocale(String locale) async =>
throw const WalletException(WalletError.unsupported);
void close() => _client.close();
}
@@ -0,0 +1,149 @@
import 'dart:math';
import 'package:sxchnge_auth/sxchnge_auth.dart';
import '../mappers/backend.dart';
import '../transport/backend.dart';
import 'backend.dart';
/// Composes authentication factors with quote-bound payment authorization.
/// Money codes authorize a durable BFF intent; raw verification proofs remain
/// server-side and cannot be reused as login grants.
class WalletFactorService implements TwoFactorService {
WalletFactorService(this.wallet, this.auth);
final BackendWalletService wallet;
final TwoFactorService auth;
final _challenges = <String, FactorChallenge>{};
final _keys = <String, String>{};
final _resends = <String, String>{};
String _key() => List.generate(
24,
(_) => Random.secure().nextInt(256).toRadixString(16).padLeft(2, '0'),
).join();
String? _token;
@override
bool get isSimulated => false;
void _session({bool required = true}) {
final token = wallet.accessToken();
if (token != _token) {
_challenges.clear();
_keys.clear();
_resends.clear();
_token = token;
}
if (required && token == null)
throw const FactorException(FactorError.unavailable);
}
Future<T> _mapped<T>(
Future<BackendDTO> dto,
T Function(BackendDTO) map,
) async {
final token = wallet.accessToken();
try {
final value = await dto;
if (token != wallet.accessToken())
throw const FactorException(FactorError.unavailable);
return map(value);
} on FactorException {
rethrow;
} catch (_) {
throw const FactorException(FactorError.unavailable);
}
}
@override
Future<FactorChallenge?> begin(
FactorPurpose purpose,
String operation,
) async {
if (![
FactorPurpose.topUp,
FactorPurpose.exchange,
FactorPurpose.payout,
].contains(purpose))
return auth.begin(purpose, operation);
_session();
final c = await _mapped(
wallet.send('/challenge', body: {'quoteId': operation}, factor: true),
(d) => BackendMapper.challenge(d, purpose, operation),
);
_session();
_challenges[c.id] = c;
_keys.putIfAbsent(
operation,
() => List.generate(
24,
(_) => Random.secure().nextInt(256).toRadixString(16).padLeft(2, '0'),
).join(),
);
return c;
}
@override
Future<FactorChallenge> resend(String challengeId) async {
_session(required: false);
final c = _challenges[challengeId];
if (c == null) return auth.resend(challengeId);
final result = await _mapped(
wallet.send(
'/resend',
body: {
'quoteId': c.operation,
'challengeId': c.id,
'idempotencyKey': _resends.putIfAbsent(c.id, _key),
},
factor: true,
),
(d) => BackendMapper.challenge(d, c.purpose, c.operation),
);
_session();
_resends.remove(c.id);
_challenges[result.id] = result;
return result;
}
@override
Future<FactorGrant> verify(String challengeId, String code) async {
_session(required: false);
final c = _challenges[challengeId];
if (c == null) return auth.verify(challengeId, code);
final key = _keys[c.operation]!;
return _mapped(
wallet.send(
'/verify',
body: {
'quoteId': c.operation,
'challengeId': c.id,
'code': code,
'idempotencyKey': key,
},
factor: true,
),
(d) {
if (d.key != key) throw const FactorException(FactorError.unavailable);
return FactorGrant(key);
},
);
}
@override
Future<FactorSettings> fetch() => auth.fetch();
@override
Future<FactorSettings> setEnabled(bool enabled, String grant) =>
auth.setEnabled(enabled, grant);
@override
Future<void> authorize(
FactorPurpose purpose,
String operation,
String? grant,
) async {
if ([
FactorPurpose.topUp,
FactorPurpose.exchange,
FactorPurpose.payout,
].contains(purpose))
throw const FactorException(FactorError.required);
await auth.authorize(purpose, operation, grant);
}
}
@@ -0,0 +1,4 @@
import 'package:http/browser_client.dart';
import 'package:http/http.dart' as http;
http.Client createClient() => BrowserClient()..withCredentials = true;
@@ -0,0 +1 @@
export 'native.dart' if (dart.library.js_interop) 'browser.dart';
@@ -0,0 +1,3 @@
import 'package:http/http.dart' as http;
http.Client createClient() => http.Client();
@@ -0,0 +1,78 @@
import 'dart:convert';
import 'wallet.dart';
/// Local BFF transport only; provider and widgets never parse response maps.
class BackendDTO {
BackendDTO.decode(String body) {
final envelope = jsonDecode(body) as Map<String, dynamic>;
accepted = envelope['status'] == 'success';
data = envelope['data'];
}
late final bool accepted;
late final dynamic data;
String get error =>
(data as Map<String, dynamic>?)?['error'] as String? ?? 'unavailable';
String get locale => (data as Map<String, dynamic>)['locale'] as String;
String get key => (data as Map<String, dynamic>)['idempotencyKey'] as String;
List<AccountDTO> get accounts =>
((data as Map<String, dynamic>)['accounts'] as List).map((v) {
final d = v as Map<String, dynamic>;
return AccountDTO(
d['id'] as String,
d['currency'] as String,
d['precision'] as int,
d['available'] as int,
payoutMethod: d['payoutMethod'] as String,
payoutLabel: d['payoutLabel'] as String,
canFund: d['canFund'] as bool,
);
}).toList();
List<OperationDTO> get operations =>
((data as Map<String, dynamic>)['operations'] as List)
.map((v) => operation(v as Map<String, dynamic>))
.toList();
QuoteDTO get quoteValue => quote(data as Map<String, dynamic>);
OperationDTO? get operationValue =>
data == null ? null : operation(data as Map<String, dynamic>);
static QuoteDTO quote(Map<String, dynamic> d) {
final r = d['request'] as Map<String, dynamic>;
return QuoteDTO(
d['id'] as String,
RequestDTO(
r['kind'] as String,
r['source'] as String,
(r['destination'] as String?)?.isEmpty == true
? null
: r['destination'] as String?,
r['amount'] as int,
r['recipient'] as String? ?? '',
),
d['fee'] as int,
d['debit'] as int,
d['credit'] as int,
DateTime.parse(d['expiresAt'] as String),
d['rateNumerator'] as int,
d['rateDenominator'] as int,
);
}
static OperationDTO operation(Map<String, dynamic> d) => OperationDTO(
d['id'] as String,
quote(d['quote'] as Map<String, dynamic>),
DateTime.parse(d['createdAt'] as String),
DateTime.parse(d['createdAt'] as String),
status: d['status'] as String,
);
ChallengeDTO get challenge => ChallengeDTO(data as Map<String, dynamic>);
}
class ChallengeDTO {
ChallengeDTO(Map<String, dynamic> d)
: id = d['challengeId'] as String,
target = d['target'] as String,
expires = DateTime.parse(d['expiresAt'] as String),
resend = DateTime.parse(d['resendAt'] as String);
final String id, target;
final DateTime expires, resend;
}
@@ -1,7 +1,17 @@
import '../models/wallet.dart';
class AccountDTO {
AccountDTO(this.id, this.currency, this.precision, this.available);
AccountDTO(
this.id,
this.currency,
this.precision,
this.available, {
this.payoutMethod = '',
this.payoutLabel = '',
this.canFund = true,
});
final String payoutMethod, payoutLabel;
final bool canFund;
final String id, currency;
final int precision;
int available;
@@ -64,6 +74,9 @@ abstract final class WalletMapper {
currency: d.currency,
precision: d.precision,
available: d.available,
payoutMethod: d.payoutMethod,
payoutLabel: d.payoutLabel,
canFund: d.canFund,
);
static RequestDTO request(TransferRequest r) =>
RequestDTO(r.kind.name, r.source, r.destination, r.amount, r.recipient);
@@ -4,3 +4,5 @@ export 'src/providers/transfer.dart';
export 'src/services/contracts.dart';
export 'src/services/dummy.dart';
export 'src/providers/limits.dart';
export 'src/services/backend.dart';
export 'src/services/factors.dart';
@@ -6,6 +6,7 @@ environment:
sdk: '>=3.13.0 <4.0.0'
flutter: '>=3.47.0'
dependencies:
http: ^1.6.0
flutter:
sdk: flutter
sxchnge_auth:
@@ -0,0 +1,245 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:sxchnge_analytics/sxchnge_analytics.dart';
import 'package:sxchnge_auth/sxchnge_auth.dart';
import 'package:sxchnge_wallet/sxchnge_wallet.dart';
Map<String, Object?> quoteData() => {
'id': 'local-quote',
'request': {
'kind': 'payout',
'source': 'ledger',
'destination': '',
'recipient': 'Saved bank ending 1234',
'amount': 2001,
},
'fee': 100,
'debit': 2101,
'credit': 2001,
'expiresAt': DateTime.now()
.add(const Duration(minutes: 5))
.toUtc()
.toIso8601String(),
'rateNumerator': 1,
'rateDenominator': 1,
};
Map<String, Object?> operationData(String status) => {
'id': 'local-quote',
'quote': quoteData(),
'status': status,
'createdAt': DateTime.now().toUtc().toIso8601String(),
};
http.Response success(Object? data) =>
http.Response(jsonEncode({'status': 'success', 'data': data}), 200);
void main() {
test('backend wallet maps accounts, authoritative quote, execution and reconciliation', () async {
final requests = <http.Request>[];
final service = BackendWalletService(
baseUri: Uri.parse('https://bff.example/api/v1'),
accessToken: () => 'session',
client: MockClient((r) async {
requests.add(r);
expect(r.headers['Authorization'], 'Bearer session');
expect(r.followRedirects, false);
switch (r.url.path) {
case '/api/v1/accounts/wallet':
return success({
'accounts': [
{
'id': 'ledger',
'currency': 'EUR',
'precision': 2,
'available': 7500,
'payoutMethod': 'method',
'payoutLabel': 'Saved bank ending 1234',
'canFund': false,
},
],
'operations': <Object>[],
});
case '/api/v1/accounts/wallet/quote':
expect(jsonDecode(r.body), {
'kind': 'payout',
'source': 'ledger',
'destination': '',
'amount': 2001,
'recipient': 'method',
});
return success(quoteData());
case '/api/v1/accounts/wallet/submit':
expect(jsonDecode(r.body), {
'quoteId': 'local-quote',
'idempotencyKey': 'authorized-key',
});
return success(operationData('pending'));
case '/api/v1/accounts/wallet/submission':
return success(operationData('completed'));
default:
return success({'locale': 'ru'});
}
}),
);
addTearDown(service.close);
expect(service.isSimulated, false);
final data = await service.fetch();
expect(data.accounts.single.available, 7500);
expect(data.accounts.single.payoutLabel, 'Saved bank ending 1234');
final q = await service.quote(
const TransferRequest(
kind: TransferKind.payout,
source: 'ledger',
recipient: 'method',
amount: 2001,
),
);
expect(q.debit, 2101);
expect(q.request.recipient, 'Saved bank ending 1234');
expect(
(await service.submit(q.id, 'authorized-key')).status,
OperationStatus.pending,
);
expect(
(await service.findSubmission('authorized-key'))!.status,
OperationStatus.completed,
);
expect((await service.profile()).locale, 'ru');
expect(requests.length, 5);
});
test('session replacement rejects late responses and never returns stale balances', () async {
String? token = 'one';
final response = Completer<http.Response>();
final service = BackendWalletService(
baseUri: Uri.parse('https://bff.example'),
accessToken: () => token,
client: MockClient((_) => response.future),
);
addTearDown(service.close);
final result = service.fetch();
token = 'two';
response.complete(success({'accounts': [], 'operations': []}));
await expectLater(result, throwsA(isA<WalletException>()));
token = null;
await expectLater(service.fetch(), throwsA(isA<WalletException>()));
});
test(
'malformed or unsuccessful responses cannot report payment success',
() async {
for (final response in [
http.Response('broken', 200),
http.Response('{"status":"error","data":{"error":"uncertain"}}', 503),
success(null),
]) {
final service = BackendWalletService(
baseUri: Uri.parse('https://bff.example'),
accessToken: () => 'session',
client: MockClient((_) async => response),
);
await expectLater(
service.submit('quote', 'key'),
throwsA(isA<WalletException>()),
);
service.close();
}
},
);
test(
'payment factor keeps authorization and resend keys stable across retry',
() async {
final bodies = <Map<String, dynamic>>[];
var fail = true;
final wallet = BackendWalletService(
baseUri: Uri.parse('https://bff.example'),
accessToken: () => 'session',
client: MockClient((r) async {
final body = jsonDecode(r.body) as Map<String, dynamic>;
bodies.add(body);
if (r.url.path.endsWith('/verify')) {
if (fail) {
fail = false;
return http.Response(
'{"status":"error","data":{"error":"factorInvalid"}}',
400,
);
}
return success({'idempotencyKey': body['idempotencyKey']});
}
return success({
'challengeId': 'challenge',
'target': 'a***@example.com',
'expiresAt': DateTime.now()
.add(const Duration(minutes: 1))
.toUtc()
.toIso8601String(),
'resendAt': DateTime.now().toUtc().toIso8601String(),
});
}),
);
addTearDown(wallet.close);
final factor = WalletFactorService(wallet, DummyTwoFactorService());
final challenge = (await factor.begin(FactorPurpose.payout, 'quote'))!;
await expectLater(
factor.verify(challenge.id, 'bad'),
throwsA(
isA<FactorException>().having(
(e) => e.code,
'code',
FactorError.invalid,
),
),
);
final grant = await factor.verify(challenge.id, '123456');
expect(grant.token, bodies[1]['idempotencyKey']);
expect(bodies[1]['idempotencyKey'], bodies[2]['idempotencyKey']);
await factor.resend(challenge.id);
expect(bodies.last['idempotencyKey'], isNotEmpty);
},
);
test('provider waits for real account IDs and submits with the authorized intent key', () async {
final service = BackendWalletService(
baseUri: Uri.parse('https://bff.example'),
accessToken: () => 'session',
client: MockClient((r) async {
if (r.url.path.endsWith('/quote')) return success(quoteData());
if (r.url.path.endsWith('/submit')) {
expect(jsonDecode(r.body)['idempotencyKey'], 'approved-intent-key');
return success(operationData('completed'));
}
return success({
'accounts': [
{
'id': 'ledger',
'currency': 'EUR',
'precision': 2,
'available': 7500,
'payoutMethod': 'method',
'payoutLabel': 'Saved bank ending 1234',
'canFund': false,
},
],
'operations': <Object>[],
});
}),
);
addTearDown(service.close);
final wallet = WalletProvider(service, DummyAnalyticsService());
addTearDown(wallet.dispose);
final draft = TransferProvider(wallet, TransferKind.payout);
addTearDown(draft.dispose);
await wallet.refresh();
expect(draft.source, 'ledger');
expect(draft.recipient, 'method');
expect(draft.hasDraft, false);
draft.change(amount: '20.01');
await draft.review();
await draft.submit(approval: const FactorGrant('approved-intent-key'));
expect(draft.result, isNotNull);
});
}