-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathexchange_provider_option.dart
More file actions
490 lines (461 loc) · 18.6 KB
/
exchange_provider_option.dart
File metadata and controls
490 lines (461 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
* This file is part of Stack Wallet.
*
* Copyright (c) 2023 Cypher Stack
* All Rights Reserved.
* The code is distributed under GPLv3 license, see LICENSE file for details.
* Generated by Cypher Stack on 2023-05-26
*
*/
import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import '../../../app_config.dart';
import '../../../models/exchange/aggregate_currency.dart';
import '../../../models/exchange/response_objects/estimate.dart';
import '../../../providers/exchange/exchange_form_state_provider.dart';
import '../../../providers/global/locale_provider.dart';
import '../../../services/exchange/exchange.dart';
import '../../../services/exchange/trocador/trocador_exchange.dart';
import '../../../themes/stack_colors.dart';
import '../../../utilities/amount/amount.dart';
import '../../../utilities/amount/amount_formatter.dart';
import '../../../utilities/amount/amount_unit.dart';
import '../../../utilities/assets.dart';
import '../../../utilities/enums/exchange_rate_type_enum.dart';
import '../../../utilities/logger.dart';
import '../../../utilities/text_styles.dart';
import '../../../utilities/util.dart';
import '../../../wallets/crypto_currency/crypto_currency.dart';
import '../../../widgets/animated_text.dart';
import '../../../widgets/conditional_parent.dart';
import '../../../widgets/custom_buttons/blue_text_button.dart';
import '../../../widgets/desktop/primary_button.dart';
import '../../../widgets/dialogs/basic_dialog.dart';
import '../../../widgets/exchange/trocador/trocador_kyc_info_button.dart';
import '../../../widgets/exchange/trocador/trocador_rating_type_enum.dart';
class ExchangeOption extends ConsumerStatefulWidget {
const ExchangeOption({
super.key,
required this.exchange,
required this.fixedRate,
required this.reversed,
});
final Exchange exchange;
final bool fixedRate;
final bool reversed;
@override
ConsumerState<ExchangeOption> createState() => _ExchangeOptionState();
}
class _ExchangeOptionState extends ConsumerState<ExchangeOption> {
final isDesktop = Util.isDesktop;
@override
Widget build(BuildContext context) {
final sendCurrency = ref.watch(
efCurrencyPairProvider.select((value) => value.send),
);
final receivingCurrency = ref.watch(
efCurrencyPairProvider.select((value) => value.receive),
);
final reversed = ref.watch(efReversedProvider);
final amount = reversed
? ref.watch(efReceiveAmountProvider)
: ref.watch(efSendAmountProvider);
final data = ref.watch(efEstimatesListProvider(widget.exchange.name));
final estimates = data?.item1.value;
final pair = sendCurrency != null && receivingCurrency != null
? (from: sendCurrency, to: receivingCurrency)
: null;
return AnimatedSize(
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOutCubicEmphasized,
child: Builder(
builder: (_) {
if (ref.watch(efRefreshingProvider)) {
// show loading
return ExchProviderOption(
exchange: widget.exchange,
estimate: null,
pair: pair,
rateString: "",
loadingString: true,
);
} else if (sendCurrency != null &&
receivingCurrency != null &&
amount != null &&
amount > Decimal.zero) {
if (estimates != null && estimates.isNotEmpty) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
for (int i = 0; i < estimates.length; i++)
Builder(
builder: (context) {
final e = estimates[i];
int decimals;
try {
decimals = AppConfig.getCryptoCurrencyForTicker(
receivingCurrency.ticker,
)!.fractionDigits;
} catch (_) {
decimals = 8; // some reasonable alternative
}
Amount rate;
if (e.reversed) {
rate = (amount / e.estimatedAmount)
.toDecimal(scaleOnInfinitePrecision: 18)
.toAmount(fractionDigits: decimals);
} else {
rate = (e.estimatedAmount / amount)
.toDecimal(scaleOnInfinitePrecision: 18)
.toAmount(fractionDigits: decimals);
}
CryptoCurrency? coin;
try {
coin = AppConfig.getCryptoCurrencyForTicker(
receivingCurrency.ticker,
);
} catch (_) {
coin = null;
}
final String rateString;
if (coin != null) {
rateString =
"1 ${sendCurrency.ticker.toUpperCase()} "
"~ ${ref.watch(pAmountFormatter(coin)).format(rate)}";
} else {
final formatter = AmountFormatter(
unit: AmountUnit.normal,
locale: ref.watch(
localeServiceChangeNotifierProvider.select(
(value) => value.locale,
),
),
coin: Bitcoin(
CryptoCurrencyNetwork.main,
), // some sane default
maxDecimals: 8, // some sane default
);
rateString =
"1 ${sendCurrency.ticker.toUpperCase()} "
"~ ${formatter.format(rate, withUnitName: false)}"
" ${receivingCurrency.ticker.toUpperCase()}";
}
return ConditionalParent(
condition: i > 0,
builder: (child) => Column(
mainAxisSize: MainAxisSize.min,
children: [
isDesktop
? Container(
height: 1,
color: Theme.of(
context,
).extension<StackColors>()!.background,
)
: const SizedBox(height: 16),
child,
],
),
child: ExchProviderOption(
key: Key(widget.exchange.name + e.exchangeProvider),
exchange: widget.exchange,
pair: pair,
estimate: e,
rateString: rateString,
kycRating: e.kycRating,
),
);
},
),
],
);
} else {
Logging.instance.w(
"$runtimeType rate unavailable for ${widget.exchange.name}: $data",
);
return Consumer(
builder: (_, ref, __) {
String? message;
final range = data?.item2;
if (range != null) {
if (range.min != null && amount < range.min!) {
message ??= "Amount too small";
} else if (range.max != null && amount > range.max!) {
message ??= "Amount too large";
}
} else if (data?.item1.value == null) {
final rateType =
ref.watch(efRateTypeProvider) ==
ExchangeRateType.estimated
? "estimated"
: "fixed";
message ??= "Pair unavailable on $rateType rate flow";
}
return ExchProviderOption(
exchange: widget.exchange,
estimate: null,
pair: pair,
rateString: message ?? "Failed to fetch rate",
rateColor: Theme.of(
context,
).extension<StackColors>()!.textError,
);
},
);
}
} else {
// show n/a
return ExchProviderOption(
exchange: widget.exchange,
estimate: null,
pair: pair,
rateString: "n/a",
);
}
},
),
);
}
}
class ExchProviderOption extends ConsumerStatefulWidget {
const ExchProviderOption({
super.key,
required this.exchange,
required this.estimate,
required this.pair,
required this.rateString,
this.kycRating,
this.loadingString = false,
this.rateColor,
});
final Exchange exchange;
final Estimate? estimate;
final ({AggregateCurrency from, AggregateCurrency to})? pair;
final String rateString;
final String? kycRating;
final bool loadingString;
final Color? rateColor;
@override
ConsumerState<ExchProviderOption> createState() => _ProviderOptionState();
}
class _ProviderOptionState extends ConsumerState<ExchProviderOption> {
final isDesktop = Util.isDesktop;
late final String _id;
final Set<ProviderWarning> _warnings = {};
bool _warningLock = false;
void _showNoSparkWarning() async {
if (_warningLock) return;
_warningLock = true;
try {
await showDialog<void>(
context: context,
builder: (context) {
return BasicDialog(
title: _warnings.map((e) => e.message).join(" and "),
message: _warnings.map((e) => e.messageDetail).join(" "),
canPopWithBackButton: true,
flex: true,
desktopHeight: 400,
rightButton: PrimaryButton(
label: "OK",
buttonHeight: isDesktop ? ButtonHeight.l : null,
onPressed: Navigator.of(context).pop,
),
);
},
);
} finally {
_warningLock = false;
}
}
@override
void initState() {
super.initState();
_id =
"${widget.exchange.name} (${widget.estimate?.exchangeProvider ?? widget.exchange.name})";
if (widget.exchange.name == TrocadorExchange.exchangeName &&
widget.pair != null) {
final from = widget.pair!.from.forExchange(widget.exchange.name);
final to = widget.pair!.to.forExchange(widget.exchange.name);
if (from != null) {
final firoWarning = TrocadorExchange.checkFiro(from);
if (firoWarning != null) _warnings.add(firoWarning);
final ltcWarning = TrocadorExchange.checkLtc(from);
if (ltcWarning != null) _warnings.add(ltcWarning);
}
if (to != null) {
final firoWarning = TrocadorExchange.checkFiro(to);
if (firoWarning != null) _warnings.add(firoWarning);
final ltcWarning = TrocadorExchange.checkLtc(to);
if (ltcWarning != null) _warnings.add(ltcWarning);
}
}
}
@override
Widget build(BuildContext context) {
String groupValue = ref.watch(currentCombinedExchangeIdProvider);
if (ref.watch(efExchangeProvider).name ==
(widget.estimate?.exchangeProvider ?? widget.exchange.name)) {
groupValue = _id;
}
return ConditionalParent(
condition: isDesktop,
builder: (child) =>
MouseRegion(cursor: SystemMouseCursors.click, child: child),
child: GestureDetector(
onTap: () {
ref.read(efExchangeProvider.notifier).state = widget.exchange;
ref.read(efExchangeProviderNameProvider.notifier).state =
widget.estimate?.exchangeProvider ?? widget.exchange.name;
},
child: Container(
color: Colors.transparent,
child: Padding(
padding: isDesktop
? const EdgeInsets.all(16)
: const EdgeInsets.all(0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 20,
height: 20,
child: Padding(
padding: EdgeInsets.only(top: isDesktop ? 20.0 : 15.0),
child: Radio(
activeColor: Theme.of(
context,
).extension<StackColors>()!.radioButtonIconEnabled,
value: _id,
groupValue: groupValue,
onChanged: (_) {
ref.read(efExchangeProvider.notifier).state =
widget.exchange;
ref
.read(efExchangeProviderNameProvider.notifier)
.state =
widget.estimate?.exchangeProvider ??
widget.exchange.name;
},
),
),
),
const SizedBox(width: 14),
Padding(
padding: const EdgeInsets.only(top: 5.0),
child: SizedBox(
width: isDesktop ? 32 : 24,
height: isDesktop ? 32 : 24,
child:
widget.estimate?.exchangeProviderLogo != null &&
widget.estimate!.exchangeProviderLogo!.isNotEmpty
? ClipRRect(
borderRadius: BorderRadius.circular(5),
child: Image.network(
widget.estimate!.exchangeProviderLogo!,
loadingBuilder:
(context, child, loadingProgress) {
if (loadingProgress == null) {
return child;
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
errorBuilder: (context, error, stackTrace) {
return SvgPicture.asset(
Assets.exchange.getIconFor(
exchangeName: widget.exchange.name,
),
width: isDesktop ? 32 : 24,
height: isDesktop ? 32 : 24,
);
},
width: isDesktop ? 32 : 24,
height: isDesktop ? 32 : 24,
),
)
: SvgPicture.asset(
Assets.exchange.getIconFor(
exchangeName: widget.exchange.name,
),
width: isDesktop ? 32 : 24,
height: isDesktop ? 32 : 24,
),
),
),
const SizedBox(width: 10),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ConditionalParent(
condition: _warnings.isNotEmpty,
builder: (child) => Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
child,
CustomTextButton(
text: _warnings.first.value,
onTap: () {
_showNoSparkWarning();
},
),
],
),
child: Text(
widget.estimate?.exchangeProvider ??
widget.exchange.name,
style: STextStyles.titleBold12(context).copyWith(
color: Theme.of(
context,
).extension<StackColors>()!.textDark2,
),
),
),
widget.loadingString
? AnimatedText(
stringsToLoopThrough: const [
"Loading",
"Loading.",
"Loading..",
"Loading...",
],
style: STextStyles.itemSubtitle12(context)
.copyWith(
color: Theme.of(
context,
).extension<StackColors>()!.textSubtitle1,
),
)
: Text(
widget.rateString,
style: STextStyles.itemSubtitle12(context)
.copyWith(
color:
widget.rateColor ??
Theme.of(context)
.extension<StackColors>()!
.textSubtitle1,
),
),
],
),
),
if (widget.kycRating != null)
TrocadorKYCInfoButton(
kycType: TrocadorKYCType.fromString(widget.kycRating!),
),
],
),
),
),
),
);
}
}