refactor: share the send fee logic across platforms
What changed, and why it matters
This commit is a code cleanup that moves fee-calculation logic out of several send screens into a single shared module. It does not change what the app does; it only reorganizes how fee estimates are computed and displayed across mobile and desktop. There is no indication this introduces a security vulnerability.
Treat as a normal refactor review. Verify that the new shared fee providers preserve the previous behavior for edge cases such as Firo Spark/private balances, Xelis zero-fee handling, and custom fee rate state. No security-specific action is required based on the supplied materials.
Security signals we found
Large refactor (+835 -2195) with no new dependencies or permissions
No changes to key handling, seed storage, network calls, or authentication
No new external input parsing or serialization
No changes to transaction signing or broadcast paths
No vendor security disclosure or advisory referenced in commit
Evidence from the diff
The commit refactors send-fee handling across Stack Wallet. It extracts duplicated fee-estimate code from send_view.dart, token_send_view.dart, sol_token_send_view.dart, and their desktop equivalents into a new send_fee_providers.dart and a reusable SendFeeForm mixin. UI widgets now consume shared providers (pFeeRateType, SendFeeRates, SendFeeAmount) instead of maintaining local Future
Changed components
lib/pages/send_view/send_view.dartlib/pages/send_view/token_send_view.dartlib/pages/send_view/sol_token_send_view.dartlib/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dartlib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dartlib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send_fee_form.dartlib/providers/wallet/send_fee_providers.dartlib/providers/ui/fee_rate_type_state_provider.dartlib/widgets/calculating_future_builder.dartInspect captured patch +835 / −2195
### lib/pages/send_view/send_view.dart
@@ -30,6 +30,7 @@ import '../../providers/providers.dart';
import '../../providers/ui/fee_rate_type_state_provider.dart';
import '../../providers/ui/preview_tx_button_state_provider.dart';
import '../../providers/wallet/public_private_balance_state_provider.dart';
+import '../../providers/wallet/send_fee_providers.dart';
import '../../route_generator.dart';
import '../../services/openalias/open_alias_service.dart';
import '../../services/spark_names_service.dart';
@@ -55,21 +56,18 @@ import '../../utilities/show_loading.dart';
import '../../utilities/text_styles.dart';
import '../../utilities/util.dart';
import '../../wallets/crypto_currency/crypto_currency.dart';
-import '../../wallets/crypto_currency/intermediate/cryptonote_currency.dart';
-import '../../wallets/crypto_currency/intermediate/nano_currency.dart';
import '../../wallets/isar/providers/wallet_info_provider.dart';
import '../../wallets/models/tx_data.dart';
import '../../wallets/wallet/impl/epiccash_wallet.dart';
import '../../wallets/wallet/impl/firo_wallet.dart';
import '../../wallets/wallet/impl/mimblewimblecoin_wallet.dart';
import '../../wallets/wallet/impl/salvium_wallet.dart';
-import '../../wallets/wallet/intermediate/cryptonote_wallet.dart';
import '../../wallets/wallet/wallet_mixin_interfaces/coin_control_interface.dart';
import '../../wallets/wallet/wallet_mixin_interfaces/mweb_interface.dart';
import '../../wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart';
import '../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart';
-import '../../widgets/animated_text.dart';
import '../../widgets/background.dart';
+import '../../widgets/calculating_future_builder.dart';
import '../../widgets/custom_buttons/app_bar_icon_button.dart';
import '../../widgets/custom_buttons/blue_text_button.dart';
import '../../widgets/dialogs/firo_exchange_address_dialog.dart';
@@ -118,14 +116,7 @@ class SendView extends ConsumerStatefulWidget {
ConsumerState<SendView> createState() => _SendViewState();
}
-class _SendViewState extends ConsumerState<SendView> {
- static const stringsToLoopThrough = [
- "Calculating",
- "Calculating.",
- "Calculating..",
- "Calculating...",
- ];
-
+class _SendViewState extends ConsumerState<SendView> with SendFeeForm {
late final String walletId;
late final CryptoCurrency coin;
late final ClipboardInterface clipboard;
@@ -608,12 +599,8 @@ class _SendViewState extends ConsumerState<SendView> {
cryptoAmountController.text = "";
_cryptoAmountChangeLock = false;
}
- // setState(() {
- // _calculateFeesFuture = calculateFees(
- // Format.decimalAmountToSatoshis(
- // _amountToSend!));
- // });
ref.read(pSendAmount.notifier).state = amount;
+ _syncFeeAmount(amount);
}
bool _xelisSendAll = false;
@@ -667,46 +654,10 @@ class _SendViewState extends ConsumerState<SendView> {
}
ref.read(pSendAmount.notifier).state = amount;
-
- _cryptoAmountChangedFeeUpdateTimer?.cancel();
- _cryptoAmountChangedFeeUpdateTimer = Timer(updateFeesTimerDuration, () {
- if (coin is! Epiccash &&
- coin is! Mimblewimblecoin &&
- !_baseFocus.hasFocus) {
- setState(() {
- _calculateFeesFuture = calculateFees(
- amount ?? 0.toAmountAsRaw(fractionDigits: coin.fractionDigits),
- );
- });
- }
- });
+ _syncFeeAmount(amount);
}
}
- final updateFeesTimerDuration = const Duration(milliseconds: 500);
-
- Timer? _cryptoAmountChangedFeeUpdateTimer;
- Timer? _baseAmountChangedFeeUpdateTimer;
-
- void _baseAmountChanged() {
- _baseAmountChangedFeeUpdateTimer?.cancel();
- _baseAmountChangedFeeUpdateTimer = Timer(updateFeesTimerDuration, () {
- if (coin is! Epiccash &&
- coin is! Mimblewimblecoin &&
- !_cryptoFocus.hasFocus) {
- setState(() {
- _calculateFeesFuture = calculateFees(
- ref.read(pSendAmount) == null
- ? 0.toAmountAsRaw(fractionDigits: coin.fractionDigits)
- : ref.read(pSendAmount)!,
- );
- });
- }
- });
- }
-
- late Amount _currentFee;
-
void _setValidAddressProviders(String? address) {
if (_recipientIndexes != null) {
ref.read(pValidSendToAddress.notifier).state = _multiRecipients!
@@ -744,140 +695,16 @@ class _SendViewState extends ConsumerState<SendView> {
}
}
- late Future<Amount> _calculateFeesFuture;
-
- final Map<(Amount, FeeRateType), Amount> cachedFees = {};
- final Map<(Amount, FeeRateType), Amount> cachedFiroSparkFees = {};
- final Map<(Amount, FeeRateType), Amount> cachedFiroPublicFees = {};
-
void _setOpReturnData(String? data) {
if (!mounted) {
return;
}
ref.read(pOpReturnData.notifier).state = data;
}
- Amount _addOpReturnFeeIfNeeded({
- required Amount fee,
- required BigInt feeRate,
- required FiroWallet wallet,
- }) {
- final opReturnData = ref.read(pOpReturnData);
- if (opReturnData == null ||
- opReturnData.isEmpty ||
- ref.read(publicPrivateBalanceStateProvider) != BalanceType.public) {
- return fee;
- }
-
- final extraOutputVSize = AddressUtils.opReturnOutputVSizeFromHex(
- opReturnData,
- );
- final extraFee = wallet.estimateTxFee(
- vSize: extraOutputVSize,
- feeRatePerKB: feeRate,
- );
-
- return fee +
- Amount(
- rawValue: BigInt.from(extraFee),
- fractionDigits: coin.fractionDigits,
- );
- }
-
- Future<Amount> calculateFees(Amount amount) async {
+ void _syncFeeAmount(Amount? amount) {
// Xelis obtains the exact fee when preparing the reviewed transaction.
- if (coin is Xelis) {
- return Amount.zeroWith(fractionDigits: coin.fractionDigits);
- }
- final feeRateType = ref.read(feeRateTypeMobileStateProvider);
- final cacheKey = (amount, feeRateType);
- final hasOpReturnData =
- isFiro &&
- ref.read(publicPrivateBalanceStateProvider) == BalanceType.public &&
- (ref.read(pOpReturnData)?.isNotEmpty ?? false);
-
- if (isFiro) {
- switch (ref.read(publicPrivateBalanceStateProvider.state).state) {
- case BalanceType.public:
- if (!hasOpReturnData && cachedFiroPublicFees[cacheKey] != null) {
- return cachedFiroPublicFees[cacheKey]!;
- }
- break;
- case BalanceType.private:
- if (cachedFiroSparkFees[cacheKey] != null) {
- return cachedFiroSparkFees[cacheKey]!;
- }
- break;
- }
- } else if (cachedFees[cacheKey] != null) {
- return cachedFees[cacheKey]!;
- }
-
- final wallet = ref.read(pWallets).getWallet(walletId);
- final feeObject = await wallet.fees;
-
- late final BigInt feeRate;
-
- switch (feeRateType) {
- case FeeRateType.fast:
- feeRate = feeObject.fast;
- break;
- case FeeRateType.average:
- feeRate = feeObject.medium;
- break;
- case FeeRateType.slow:
- feeRate = feeObject.slow;
- break;
- default:
- feeRate = BigInt.from(-1);
- }
-
- Amount fee;
- if (coin is CryptonoteCurrency) {
- final int specialMoneroId;
- switch (feeRateType) {
- case FeeRateType.fast:
- specialMoneroId = (wallet as CryptonoteWallet).getTxPriorityHigh();
- break;
- case FeeRateType.average:
- specialMoneroId = (wallet as CryptonoteWallet).getTxPriorityMedium();
- break;
- case FeeRateType.slow:
- specialMoneroId = (wallet as CryptonoteWallet).getTxPriorityNormal();
- break;
- default:
- throw ArgumentError("custom fee not available for monero");
- }
-
- fee = await wallet.estimateFeeFor(amount, BigInt.from(specialMoneroId));
- cachedFees[cacheKey] = fee;
- return fee;
- } else if (isFiro) {
- final firoWallet = wallet as FiroWallet;
-
- switch (ref.read(publicPrivateBalanceStateProvider.state).state) {
- case BalanceType.public:
- fee = await firoWallet.estimateFeeFor(amount, feeRate);
- fee = _addOpReturnFeeIfNeeded(
- fee: fee,
- feeRate: feeRate,
- wallet: firoWallet,
- );
- if (!hasOpReturnData) {
- cachedFiroPublicFees[cacheKey] = fee;
- }
- return fee;
-
- case BalanceType.private:
- fee = await firoWallet.estimateFeeForSpark(amount);
- cachedFiroSparkFees[cacheKey] = fee;
- return fee;
- }
- } else {
- fee = await wallet.estimateFeeFor(amount, feeRate);
- cachedFees[cacheKey] = fee;
- return fee;
- }
+ if (hasFees && coin is! Xelis) followFeeAmount(amount);
}
Future<void> _createSlatepack() async {
@@ -1231,7 +1058,7 @@ class _SendViewState extends ConsumerState<SendView> {
final time = Future<dynamic>.delayed(const Duration(milliseconds: 2500));
Future<TxData> txDataFuture;
- final feeRateType = ref.read(feeRateTypeMobileStateProvider);
+ final feeRateType = ref.read(pFeeRateType);
final satsPerVByte = feeRateType.customSatsPerVByte(customFeeRate);
if (isPaynymSend) {
@@ -1553,40 +1380,7 @@ class _SendViewState extends ConsumerState<SendView> {
late final bool hasFees;
- void _onFeeSelectPressed() {
- showModalBottomSheet<dynamic>(
- backgroundColor: Colors.transparent,
- context: context,
- shape: const RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
- ),
- builder: (_) => TransactionFeeSelectionSheet(
- walletId: walletId,
- amount:
- ref.read(pSendAmount) ??
- Amount.zeroWith(fractionDigits: coin.fractionDigits),
- updateChosen: (feeRateType, fee) {
- if (feeRateType.isCustom) {
- return;
- }
-
- setState(() {
- if (fee != null) {
- _currentFee = fee;
- _calculateFeesFuture = Future.value(fee);
- } else {
- _calculateFeesFuture = calculateFees(
- ref.read(pSendAmount) ??
- Amount.zeroWith(fractionDigits: coin.fractionDigits),
- );
- }
- customFeeRate = 1;
- _ethFee.value = null;
- });
- },
- ),
- );
- }
+ void _onFeeSelectPressed() => showFeeSheet(this);
@override
void initState() {
@@ -1597,18 +1391,16 @@ class _SendViewState extends ConsumerState<SendView> {
_data = widget.autoFillData;
walletId = widget.walletId;
+ fees = SendFeeRates(ref.read, walletId: walletId, isToken: false);
clipboard = widget.clipboard;
WidgetsBinding.instance.addPostFrameCallback((_) {
- ref.refresh(feeSheetSessionCacheProvider);
ref.refresh(pIsExchangeAddress);
});
- hasFees = coin is! Epiccash && coin is! NanoCurrency && coin is! Tezos;
- _currentFee = 0.toAmountAsRaw(fractionDigits: coin.fractionDigits);
-
- _calculateFeesFuture = calculateFees(
- 0.toAmountAsRaw(fractionDigits: coin.fractionDigits),
- );
+ hasFees = hasSendFee(coin);
+ if (hasFees && coin is! Xelis) {
+ retryFeeOnFocusLoss([_cryptoFocus, _baseFocus]);
+ }
sendToController = TextEditingController();
cryptoAmountController = TextEditingController();
@@ -1620,7 +1412,6 @@ class _SendViewState extends ConsumerState<SendView> {
onCryptoAmountChanged = _cryptoAmountChanged;
cryptoAmountController.addListener(onCryptoAmountChanged);
- baseAmountController.addListener(_baseAmountChanged);
if (_data != null) {
final hasAmount = _data.amount != null;
@@ -1656,48 +1447,14 @@ class _SendViewState extends ConsumerState<SendView> {
);
}
- // if (coin is! Epiccash) {
- // _cryptoFocus.addListener(() {
- // if (!_cryptoFocus.hasFocus && !_baseFocus.hasFocus) {
- // if (_amountToSend == null) {
- // setState(() {
- // _calculateFeesFuture = calculateFees(0);
- // });
- // } else {
- // setState(() {
- // _calculateFeesFuture = calculateFees(
- // Format.decimalAmountToSatoshis(_amountToSend!, coin));
- // });
- // }
- // }
- // });
-
- // _baseFocus.addListener(() {
- // if (!_cryptoFocus.hasFocus && !_baseFocus.hasFocus) {
- // if (_amountToSend == null) {
- // setState(() {
- // _calculateFeesFuture = calculateFees(0);
- // });
- // } else {
- // setState(() {
- // _calculateFeesFuture = calculateFees(
- // Format.decimalAmountToSatoshis(_amountToSend!, coin));
- // });
- // }
- // }
- // });
- // }
super.initState();
}
@override
void dispose() {
- _cryptoAmountChangedFeeUpdateTimer?.cancel();
- _baseAmountChangedFeeUpdateTimer?.cancel();
_ethFee.dispose();
cryptoAmountController.removeListener(onCryptoAmountChanged);
- baseAmountController.removeListener(_baseAmountChanged);
sendToController.dispose();
cryptoAmountController.dispose();
@@ -1719,7 +1476,11 @@ class _SendViewState extends ConsumerState<SendView> {
@override
Widget build(BuildContext context) {
debugPrint("BUILD: $runtimeType");
- final isCustomFee = ref.watch(feeRateTypeMobileStateProvider).isCustom;
+ final isCustomFee = ref.watch(pFeeRateType).isCustom;
+ listenForCustomFeeLevel(ref, coin, () {
+ customFeeRate = 1;
+ _ethFee.value = null;
+ });
final String locale = ref.watch(
localeServiceChangeNotifierProvider.select((value) => value.locale),
);
@@ -1743,6 +1504,8 @@ class _SendViewState extends ConsumerState<SendView> {
final amountFormatter = ref.watch(pAmountFormatter(coin));
final balType = ref.watch(publicPrivateBalanceStateProvider);
+ final canPick = canPickFeeRateType(coin, balType);
+ final hasCustomFee = isCustomFee && canPick;
// ethFee is checked in the ValueListenableBuilder around the preview
// button so fee keystrokes don't rebuild this whole view.
final previewEnabled =
@@ -1769,18 +1532,7 @@ class _SendViewState extends ConsumerState<SendView> {
ref.listen(publicPrivateBalanceStateProvider, (previous, next) {
selectedUTXOs = {};
-
- if (ref.read(pSendAmount) == null) {
- setState(() {
- _calculateFeesFuture = calculateFees(
- 0.toAmountAsRaw(fractionDigits: coin.fractionDigits),
- );
- });
- } else {
- setState(() {
- _calculateFeesFuture = calculateFees(ref.read(pSendAmount)!);
- });
- }
+ retryFee();
if (previous != next &&
next == BalanceType.private &&
@@ -2725,7 +2477,12 @@ class _SendViewState extends ConsumerState<SendView> {
if (spendable == amount) {
// this is now a send all
} else {
- amount += _currentFee;
+ amount +=
+ shownFee ??
+ Amount.zeroWith(
+ fractionDigits:
+ coin.fractionDigits,
+ );
}
}
@@ -2869,22 +2626,15 @@ class _SendViewState extends ConsumerState<SendView> {
),
),
const SizedBox(height: 12),
- if (coin is! Epiccash &&
- coin is! Mimblewimblecoin &&
- coin is! NanoCurrency &&
- coin is! Tezos)
+ if (hasFees)
Text(
- coin is Xelis
+ coin is Xelis || hasCustomFee
? "Transaction fee"
: "Transaction fee (estimated)",
style: STextStyles.smallMed12(context),
textAlign: TextAlign.left,
),
- if (coin is! Epiccash &&
- coin is! Mimblewimblecoin &&
- coin is! NanoCurrency &&
- coin is! Tezos)
- const SizedBox(height: 8),
+ if (hasFees) const SizedBox(height: 8),
if (coin is Xelis)
Padding(
padding: const EdgeInsets.all(12),
@@ -2893,10 +2643,7 @@ class _SendViewState extends ConsumerState<SendView> {
style: STextStyles.itemSubtitle(context),
),
)
- else if (coin is! Epiccash &&
- coin is! Mimblewimblecoin &&
- coin is! NanoCurrency &&
- coin is! Tezos)
+ else if (hasFees)
Stack(
children: [
TextField(
@@ -2925,149 +2672,74 @@ class _SendViewState extends ConsumerState<SendView> {
Constants.size.circularBorderRadius,
),
),
- onPressed:
- isFiro &&
- ref
- .watch(
- publicPrivateBalanceStateProvider
- .state,
- )
- .state !=
- BalanceType.public
- ? null
- : _onFeeSelectPressed,
- child:
- (isFiro &&
- ref
+ onPressed: canPick
+ ? _onFeeSelectPressed
+ : null,
+ child: Row(
+ mainAxisAlignment:
+ MainAxisAlignment.spaceBetween,
+ children: [
+ Row(
+ children: [
+ if (canPick) ...[
+ Text(
+ ref
.watch(
- publicPrivateBalanceStateProvider
- .state,
+ pFeeRateType.state,
)
- .state !=
- BalanceType.public)
- ? Row(
- children: [
- FutureBuilder(
- future:
- _calculateFeesFuture,
- builder: (context, snapshot) {
- if (snapshot.connectionState ==
- ConnectionState
- .done &&
- snapshot.hasData) {
- _currentFee =
- snapshot.data!;
- final formattedFee =
- amountFormatter.format(
- snapshot.data!,
- withUnitName:
- true,
- indicatePrecisionLoss:
- false,
- );
- return Text(
- "~$formattedFee",
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- } else {
- return AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- }
- },
+ .state
+ .prettyName,
+ style:
+ STextStyles.itemSubtitle12(
+ context,
+ ),
),
+ const SizedBox(width: 10),
],
- )
- : Row(
- mainAxisAlignment:
- MainAxisAlignment
- .spaceBetween,
- children: [
- Row(
- children: [
- Text(
- ref
- .watch(
- feeRateTypeMobileStateProvider
- .state,
- )
- .state
- .prettyName,
- style:
- STextStyles.itemSubtitle12(
- context,
- ),
- ),
- const SizedBox(width: 10),
- FutureBuilder(
- future:
- _calculateFeesFuture,
- builder: (context, snapshot) {
- if (snapshot.connectionState ==
- ConnectionState
- .done &&
- snapshot
- .hasData) {
- _currentFee =
- snapshot.data!;
- final formattedFee =
- amountFormatter.format(
- snapshot
- .data!,
- withUnitName:
- true,
- indicatePrecisionLoss:
- false,
- );
- return Text(
- isCustomFee
- ? ""
- : "~$formattedFee",
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- } else {
- return AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- }
- },
+ CalculatingFutureBuilder(
+ future: watchFee(),
+ style:
+ STextStyles.itemSubtitle(
+ context,
),
- ],
- ),
- SvgPicture.asset(
- Assets.svg.chevronDown,
- width: 8,
- height: 4,
- color: Theme.of(context)
- .extension<
- StackColors
- >()!
- .textSubtitle2,
- ),
- ],
+ builder: (fee) {
+ final formattedFee =
+ amountFormatter.format(
+ fee,
+ withUnitName: true,
+ indicatePrecisionLoss:
+ false,
+ );
+ return Text(
+ hasCustomFee
+ ? ""
+ : "~$formattedFee",
+ style:
+ STextStyles.itemSubtitle(
+ context,
+ ),
+ );
+ },
+ ),
+ ],
+ ),
+ if (canPick)
+ SvgPicture.asset(
+ Assets.svg.chevronDown,
+ width: 8,
+ height: 4,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textSubtitle2,
),
+ ],
+ ),
),
),
),
],
),
- if (isCustomFee && !isEth)
+ if (hasCustomFee && !isEth)
Padding(
padding: const EdgeInsets.only(
bottom: 12,
### lib/pages/send_view/sol_token_send_view.dart
@@ -21,6 +21,7 @@ import '../../models/send_view_auto_fill_data.dart';
import '../../providers/providers.dart';
import '../../providers/ui/fee_rate_type_state_provider.dart';
import '../../providers/ui/preview_tx_button_state_provider.dart';
+import '../../providers/wallet/send_fee_providers.dart';
import '../../route_generator.dart';
import '../../themes/stack_colors.dart';
import '../../utilities/address_utils.dart';
@@ -43,8 +44,8 @@ import '../../wallets/isar/providers/solana/current_sol_token_wallet_provider.da
import '../../wallets/isar/providers/solana/sol_token_balance_provider.dart';
import '../../wallets/isar/providers/wallet_info_provider.dart';
import '../../wallets/models/tx_data.dart';
-import '../../widgets/animated_text.dart';
import '../../widgets/background.dart';
+import '../../widgets/calculating_future_builder.dart';
import '../../widgets/custom_buttons/app_bar_icon_button.dart';
import '../../widgets/icon_widgets/clipboard_icon.dart';
import '../../widgets/icon_widgets/qrcode_icon.dart';
@@ -93,7 +94,8 @@ class SolTokenSendView extends ConsumerStatefulWidget {
ConsumerState<SolTokenSendView> createState() => _SolTokenSendViewState();
}
-class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
+class _SolTokenSendViewState extends ConsumerState<SolTokenSendView>
+ with SendFeeForm {
late final String walletId;
late final String tokenMint;
late final ClipboardInterface clipboard;
@@ -122,12 +124,6 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
bool _cryptoAmountChangeLock = false;
late VoidCallback onCryptoAmountChanged;
- final updateFeesTimerDuration = const Duration(milliseconds: 500);
-
- Timer? _cryptoAmountChangedFeeUpdateTimer;
- Timer? _baseAmountChangedFeeUpdateTimer;
- late Future<Amount> _calculateFeesFuture;
-
void _onTokenSendViewPasteAddressFieldButtonPressed() async {
final ClipboardData? data = await clipboard.getData(Clipboard.kTextPlain);
if (data?.text != null && data!.text!.isNotEmpty) {
@@ -294,6 +290,7 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
_cryptoAmountChangeLock = false;
}
_updatePreviewButtonState(_address, _amountToSend);
+ followFeeAmount(_amountToSend);
}
// Controller assignments used for display must not edit the stored amount.
@@ -347,29 +344,10 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
}
_updatePreviewButtonState(_address, _amountToSend);
-
- _cryptoAmountChangedFeeUpdateTimer?.cancel();
- _cryptoAmountChangedFeeUpdateTimer = Timer(updateFeesTimerDuration, () {
- if (mounted) {
- setState(() {
- _calculateFeesFuture = calculateFees();
- });
- }
- });
+ followFeeAmount(_amountToSend);
}
}
- void _baseAmountChanged() {
- _baseAmountChangedFeeUpdateTimer?.cancel();
- _baseAmountChangedFeeUpdateTimer = Timer(updateFeesTimerDuration, () {
- if (mounted && !_cryptoFocus.hasFocus) {
- setState(() {
- _calculateFeesFuture = calculateFees();
- });
- }
- });
- }
-
String? _updateInvalidAddressText(String address) {
if (_data != null && _data.contactLabel == address) {
return null;
@@ -391,48 +369,6 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
(isValidAddress && amount != null && amount > Amount.zero);
}
- Future<Amount> calculateFees() async {
- final solana = Solana(CryptoCurrencyNetwork.main);
- final minimumFee = Amount(
- rawValue: BigInt.from(5000),
- fractionDigits: solana.fractionDigits,
- );
- try {
- final wallet = ref.read(pCurrentSolanaTokenWallet);
- if (wallet == null) {
- return minimumFee;
- }
-
- final feeObject = await wallet.fees;
-
- late final BigInt feeRate;
-
- switch (ref.read(feeRateTypeMobileStateProvider.state).state) {
- case FeeRateType.fast:
- feeRate = feeObject.fast;
- break;
- case FeeRateType.average:
- feeRate = feeObject.medium;
- break;
- case FeeRateType.slow:
- feeRate = feeObject.slow;
- break;
- default:
- feeRate = BigInt.from(-1);
- }
-
- final Amount fee = await wallet.estimateFeeFor(Amount.zero, feeRate);
- return fee;
- } catch (e, s) {
- Logging.instance.w(
- "Failed to calculate Solana token fees: ",
- error: e,
- stackTrace: s,
- );
- return minimumFee;
- }
- }
-
Future<void> _previewTransaction() async {
// wait for keyboard to disappear
FocusScope.of(context).unfocus();
@@ -520,7 +456,7 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
),
],
memo: memoController.text.isEmpty ? null : memoController.text,
- feeRateType: ref.read(feeRateTypeMobileStateProvider),
+ feeRateType: ref.read(pFeeRateType),
note: noteController.text,
),
);
@@ -606,15 +542,14 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
@override
void initState() {
- ref.refresh(feeSheetSessionCacheProvider);
-
WidgetsBinding.instance.addPostFrameCallback((_) {
- ref.read(feeRateTypeMobileStateProvider.state).state = FeeRateType.slow;
+ ref.read(pFeeRateType.state).state = FeeRateType.slow;
});
- _calculateFeesFuture = calculateFees();
_data = widget.autoFillData;
walletId = widget.walletId;
+ fees = SendFeeRates(ref.read, walletId: walletId, isToken: true);
+ retryFeeOnFocusLoss([_cryptoFocus, _baseFocus]);
tokenMint = widget.tokenMint;
clipboard = widget.clipboard;
@@ -627,7 +562,6 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
onCryptoAmountChanged = _cryptoAmountChanged;
cryptoAmountController.addListener(onCryptoAmountChanged);
- baseAmountController.addListener(_baseAmountChanged);
if (_data != null) {
if (_data.amount != null) {
@@ -651,11 +585,7 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
@override
void dispose() {
- _cryptoAmountChangedFeeUpdateTimer?.cancel();
- _baseAmountChangedFeeUpdateTimer?.cancel();
-
cryptoAmountController.removeListener(onCryptoAmountChanged);
- baseAmountController.removeListener(_baseAmountChanged);
sendToController.dispose();
memoController.dispose();
@@ -1284,36 +1214,7 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
Constants.size.circularBorderRadius,
),
),
- onPressed: () {
- showModalBottomSheet<dynamic>(
- backgroundColor: Colors.transparent,
- context: context,
- shape: const RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(
- top: Radius.circular(20),
- ),
- ),
- builder: (_) =>
- TransactionFeeSelectionSheet(
- walletId: walletId,
- isToken: true,
- amount:
- _amountToSend ??
- Amount.zeroWith(
- fractionDigits: tokenWallet
- .tokenDecimals,
- ),
- updateChosen: (_, fee) {
- setState(() {
- _calculateFeesFuture =
- fee == null
- ? calculateFees()
- : Future.value(fee);
- });
- },
- ),
- );
- },
+ onPressed: () => showFeeSheet(this),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
@@ -1322,52 +1223,40 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
children: [
Text(
ref
- .watch(
- feeRateTypeMobileStateProvider
- .state,
- )
+ .watch(pFeeRateType.state)
.state
.prettyName,
style: STextStyles.itemSubtitle12(
context,
),
),
const SizedBox(width: 10),
- FutureBuilder(
- future: _calculateFeesFuture,
- builder: (context, snapshot) {
- if (snapshot.connectionState ==
- ConnectionState.done &&
- snapshot.hasData) {
- final formattedFee =
- amountFormatter.format(
- snapshot.data!,
- withUnitName: true,
- indicatePrecisionLoss:
- false,
- );
- return Text(
- "~$formattedFee",
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- } else {
- return AnimatedText(
- stringsToLoopThrough:
- const [
- "Calculating",
- "Calculating.",
- "Calculating..",
- "Calculating...",
- ],
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- }
+ CalculatingFutureBuilder(
+ future: watchFee(),
+ style: STextStyles.itemSubtitle(
+ context,
+ ),
+ fallback: Amount(
+ rawValue: BigInt.from(5000),
+ fractionDigits: tokenWallet
+ .cryptoCurrency
+ .fractionDigits,
+ ),
+ builder: (fee) {
+ final formattedFee =
+ amountFormatter.format(
+ fee,
+ withUnitName: true,
+ indicatePrecisionLoss:
+ false,
+ );
+ return Text(
+ "~$formattedFee",
+ style:
+ STextStyles.itemSubtitle(
+ context,
+ ),
+ );
},
),
],
### lib/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart
@@ -11,54 +11,37 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
-import '../../../models/paymint/fee_object_model.dart';
-import '../../../providers/providers.dart';
import '../../../providers/ui/fee_rate_type_state_provider.dart';
-import '../../../providers/ui/preview_tx_button_state_provider.dart';
-import '../../../providers/wallet/public_private_balance_state_provider.dart';
+import '../../../providers/wallet/send_fee_providers.dart';
import '../../../themes/stack_colors.dart';
-import '../../../utilities/address_utils.dart';
import '../../../utilities/amount/amount.dart';
import '../../../utilities/amount/amount_formatter.dart';
import '../../../utilities/constants.dart';
import '../../../utilities/enums/fee_rate_type_enum.dart';
import '../../../utilities/text_styles.dart';
import '../../../wallets/crypto_currency/crypto_currency.dart';
-import '../../../wallets/crypto_currency/intermediate/cryptonote_currency.dart';
-import '../../../wallets/isar/providers/eth/current_token_wallet_provider.dart';
-import '../../../wallets/isar/providers/wallet_info_provider.dart';
-import '../../../wallets/wallet/impl/firo_wallet.dart';
-import '../../../wallets/wallet/intermediate/cryptonote_wallet.dart';
-import '../../../wallets/wallet/wallet.dart';
-import '../../../wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart';
-import '../../../widgets/animated_text.dart';
-
-final feeSheetSessionCacheProvider =
- ChangeNotifierProvider<FeeSheetSessionCache>((ref) {
- return FeeSheetSessionCache();
- });
-
-class FeeSheetSessionCache extends ChangeNotifier {
- final Map<Amount, Amount> fast = {};
- final Map<Amount, Amount> average = {};
- final Map<Amount, Amount> slow = {};
-
- void notify() => notifyListeners();
-}
+import '../../../widgets/calculating_future_builder.dart';
+
+Future<void> showFeeSheet(SendFeeForm form) => form.chooseFee(
+ (fees, amount) => showModalBottomSheet<dynamic>(
+ backgroundColor: Colors.transparent,
+ context: form.context,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
+ ),
+ builder: (_) => TransactionFeeSelectionSheet(fees: fees, amount: amount),
+ ),
+);
class TransactionFeeSelectionSheet extends ConsumerStatefulWidget {
const TransactionFeeSelectionSheet({
super.key,
- required this.walletId,
+ required this.fees,
required this.amount,
- required this.updateChosen,
- this.isToken = false,
});
- final String walletId;
- final Amount amount;
- final void Function(FeeRateType feeRateType, Amount? fee) updateChosen;
- final bool isToken;
+ final SendFeeRates fees;
+ final Amount? amount;
@override
ConsumerState<TransactionFeeSelectionSheet> createState() =>
@@ -67,249 +50,90 @@ class TransactionFeeSelectionSheet extends ConsumerStatefulWidget {
class _TransactionFeeSelectionSheetState
extends ConsumerState<TransactionFeeSelectionSheet> {
- late final String walletId;
- late final Amount amount;
-
- FeeObject? feeObject;
-
- final stringsToLoopThrough = [
- "Calculating",
- "Calculating.",
- "Calculating..",
- "Calculating...",
- ];
-
- void _selectFeeRate(FeeRateType feeRateType) {
- ref.read(feeRateTypeMobileStateProvider.state).state = feeRateType;
- widget.updateChosen(
- feeRateType,
- feeRateType.isCustom ? null : getAmount(feeRateType),
- );
-
- Navigator.of(context).pop();
- }
-
- Amount _addFiroOpReturnFee({
- required Amount fee,
- required BigInt feeRate,
- required FiroWallet wallet,
- required CryptoCurrency coin,
- }) {
- final opReturnData = ref.read(pOpReturnData);
- if (opReturnData == null ||
- opReturnData.isEmpty ||
- ref.read(publicPrivateBalanceStateProvider) != BalanceType.public) {
- return fee;
+ Widget _feeRateRow(FeeRateType feeRateType) {
+ final coin = widget.fees.coin;
+ final style = STextStyles.itemSubtitle(context);
+ final fee = feeRateType.isCustom
+ ? null
+ : widget.fees.estimate(ref.watch, feeRateType, amount: widget.amount);
+ void select() {
+ ref.read(pFeeRateType.state).state = feeRateType;
+
+ Navigator.of(context).pop();
}
- final extraOutputVSize = AddressUtils.opReturnOutputVSizeFromHex(
- opReturnData,
- );
- final extraFee = wallet.estimateTxFee(
- vSize: extraOutputVSize,
- feeRatePerKB: feeRate,
+ return GestureDetector(
+ onTap: select,
+ child: Container(
+ color: Colors.transparent,
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Column(
+ children: [
+ SizedBox(
+ width: 20,
+ height: 20,
+ child: Radio(
+ activeColor: Theme.of(context)
+ .extension<StackColors>()!
+ .radioButtonIconEnabled,
+ value: feeRateType,
+ groupValue: ref.watch(pFeeRateType.state).state,
+ onChanged: (_) => select(),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(width: 12),
+ Flexible(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Text(
+ feeRateType.prettyName,
+ style: STextStyles.titleBold12(context),
+ textAlign: TextAlign.left,
+ ),
+ const SizedBox(width: 2),
+ if (fee != null)
+ CalculatingFutureBuilder(
+ future: fee,
+ style: style,
+ builder: (fee) => Text(
+ "(~${ref.watch(pAmountFormatter(coin)).format(fee, indicatePrecisionLoss: false)})",
+ style: style,
+ textAlign: TextAlign.left,
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 2),
+ if (fee != null && coin is! Ethereum)
+ CalculatingFutureBuilder(
+ future: widget.fees.rates,
+ style: style,
+ builder: (rates) => Text(
+ sendFeeTime(coin, rates, feeRateType),
+ style: style,
+ textAlign: TextAlign.left,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
);
-
- return fee +
- Amount(
- rawValue: BigInt.from(extraFee),
- fractionDigits: coin.fractionDigits,
- );
- }
-
- Future<Amount> feeFor({
- required Amount amount,
- required FeeRateType feeRateType,
- required BigInt feeRate,
- required CryptoCurrency coin,
- }) async {
- if (!widget.isToken &&
- coin is Firo &&
- ref.read(publicPrivateBalanceStateProvider) == BalanceType.public &&
- (ref.read(pOpReturnData)?.isNotEmpty ?? false)) {
- final wallet = ref.read(pWallets).getWallet(walletId) as FiroWallet;
- final fee = await wallet.estimateFeeFor(amount, feeRate);
- return _addFiroOpReturnFee(
- fee: fee,
- feeRate: feeRate,
- wallet: wallet,
- coin: coin,
- );
- }
-
- switch (feeRateType) {
- case FeeRateType.fast:
- if (ref.read(feeSheetSessionCacheProvider).fast[amount] == null) {
- if (widget.isToken == false) {
- final wallet = ref.read(pWallets).getWallet(walletId);
-
- if (coin is CryptonoteCurrency) {
- final fee = await wallet.estimateFeeFor(
- amount,
- BigInt.from((wallet as CryptonoteWallet).getTxPriorityHigh()),
- );
- ref.read(feeSheetSessionCacheProvider).fast[amount] = fee;
- } else if (coin is Firo) {
- final Amount fee;
- switch (ref.read(publicPrivateBalanceStateProvider.state).state) {
- case BalanceType.private:
- fee = await (wallet as FiroWallet).estimateFeeForSpark(
- amount,
- );
- case BalanceType.public:
- fee = await (wallet as FiroWallet).estimateFeeFor(
- amount,
- feeRate,
- );
- }
-
- ref.read(feeSheetSessionCacheProvider).fast[amount] = fee;
- } else {
- ref.read(feeSheetSessionCacheProvider).fast[amount] = await wallet
- .estimateFeeFor(amount, feeRate);
- }
- } else {
- final Wallet wallet;
- if (coin is Ethereum) {
- wallet = ref.read(pCurrentTokenWallet)!;
- } else {
- wallet = ref.read(pWallets).getWallet(walletId);
- }
- final fee = await wallet.estimateFeeFor(amount, feeRate);
- ref.read(feeSheetSessionCacheProvider).fast[amount] = fee;
- }
- }
- return ref.read(feeSheetSessionCacheProvider).fast[amount]!;
-
- case FeeRateType.average:
- if (ref.read(feeSheetSessionCacheProvider).average[amount] == null) {
- if (widget.isToken == false) {
- final wallet = ref.read(pWallets).getWallet(walletId);
- if (coin is CryptonoteCurrency) {
- final fee = await wallet.estimateFeeFor(
- amount,
- BigInt.from((wallet as CryptonoteWallet).getTxPriorityMedium()),
- );
- ref.read(feeSheetSessionCacheProvider).average[amount] = fee;
- } else if (coin is Firo) {
- final Amount fee;
- switch (ref.read(publicPrivateBalanceStateProvider.state).state) {
- case BalanceType.private:
- fee = await (wallet as FiroWallet).estimateFeeForSpark(
- amount,
- );
- case BalanceType.public:
- fee = await (wallet as FiroWallet).estimateFeeFor(
- amount,
- feeRate,
- );
- }
- ref.read(feeSheetSessionCacheProvider).average[amount] = fee;
- } else {
- ref.read(feeSheetSessionCacheProvider).average[amount] =
- await wallet.estimateFeeFor(amount, feeRate);
- }
- } else {
- final Wallet wallet;
- if (coin is Ethereum) {
- wallet = ref.read(pCurrentTokenWallet)!;
- } else {
- wallet = ref.read(pWallets).getWallet(walletId);
- }
- final fee = await wallet.estimateFeeFor(amount, feeRate);
- ref.read(feeSheetSessionCacheProvider).average[amount] = fee;
- }
- }
- return ref.read(feeSheetSessionCacheProvider).average[amount]!;
-
- case FeeRateType.slow:
- if (ref.read(feeSheetSessionCacheProvider).slow[amount] == null) {
- if (widget.isToken == false) {
- final wallet = ref.read(pWallets).getWallet(walletId);
- if (coin is CryptonoteCurrency) {
- final fee = await wallet.estimateFeeFor(
- amount,
- BigInt.from((wallet as CryptonoteWallet).getTxPriorityNormal()),
- );
- ref.read(feeSheetSessionCacheProvider).slow[amount] = fee;
- } else if (coin is Firo) {
- final Amount fee;
- switch (ref.read(publicPrivateBalanceStateProvider.state).state) {
- case BalanceType.private:
- fee = await (wallet as FiroWallet).estimateFeeForSpark(
- amount,
- );
- case BalanceType.public:
- fee = await (wallet as FiroWallet).estimateFeeFor(
- amount,
- feeRate,
- );
- }
- ref.read(feeSheetSessionCacheProvider).slow[amount] = fee;
- } else {
- ref.read(feeSheetSessionCacheProvider).slow[amount] = await wallet
- .estimateFeeFor(amount, feeRate);
- }
- } else {
- final Wallet wallet;
- if (coin is Ethereum) {
- wallet = ref.read(pCurrentTokenWallet)!;
- } else {
- wallet = ref.read(pWallets).getWallet(walletId);
- }
- final fee = await wallet.estimateFeeFor(amount, feeRate);
- ref.read(feeSheetSessionCacheProvider).slow[amount] = fee;
- }
- }
- return ref.read(feeSheetSessionCacheProvider).slow[amount]!;
-
- default:
- return Amount.zero;
- }
- }
-
- String estimatedTimeToBeIncludedInNextBlock(
- int targetBlockTime,
- int estimatedNumberOfBlocks,
- ) {
- final int time = targetBlockTime * estimatedNumberOfBlocks;
-
- final int hours = (time / 3600).floor();
- if (hours > 1) {
- return "~$hours hours";
- } else if (hours == 1) {
- return "~$hours hour";
- }
-
- // less than an hour
-
- final string = (time / 60).toStringAsFixed(1);
-
- if (string == "1.0") {
- return "~1 minute";
- } else {
- if (string.endsWith(".0")) {
- return "~${(time / 60).floor()} minutes";
- }
- return "~$string minutes";
- }
- }
-
- @override
- void initState() {
- walletId = widget.walletId;
- amount = widget.amount;
- super.initState();
}
@override
Widget build(BuildContext context) {
debugPrint("BUILD: $runtimeType");
- final wallet = ref.watch(pWallets).getWallet(walletId);
-
- final coin = ref.watch(pWalletCoin(walletId));
-
return Container(
decoration: BoxDecoration(
color: Theme.of(context).extension<StackColors>()!.popupBG,
@@ -342,448 +166,20 @@ class _TransactionFeeSelectionSheetState
),
),
const SizedBox(height: 36),
- FutureBuilder(
- future: widget.isToken
- ? (coin is Ethereum
- ? ref.read(pCurrentTokenWallet)!.fees
- : wallet.fees)
- : wallet.fees,
- builder: (context, AsyncSnapshot<FeeObject> snapshot) {
- if (snapshot.connectionState == ConnectionState.done &&
- snapshot.hasData) {
- feeObject = snapshot.data!;
- }
-
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- "Fee rate",
- style: STextStyles.pageTitleH2(context),
- textAlign: TextAlign.left,
- ),
- const SizedBox(height: 16),
- GestureDetector(
- onTap: () => _selectFeeRate(FeeRateType.fast),
- child: Container(
- color: Colors.transparent,
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Column(
- mainAxisAlignment: MainAxisAlignment.start,
- children: [
- SizedBox(
- width: 20,
- height: 20,
- child: Radio(
- activeColor: Theme.of(context)
- .extension<StackColors>()!
- .radioButtonIconEnabled,
- value: FeeRateType.fast,
- groupValue: ref
- .watch(
- feeRateTypeMobileStateProvider
- .state,
- )
- .state,
- onChanged: (_) =>
- _selectFeeRate(FeeRateType.fast),
- ),
- ),
- ],
- ),
- const SizedBox(width: 12),
- Flexible(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Text(
- FeeRateType.fast.prettyName,
- style: STextStyles.titleBold12(
- context,
- ),
- textAlign: TextAlign.left,
- ),
- const SizedBox(width: 2),
- if (feeObject == null)
- AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style: STextStyles.itemSubtitle(
- context,
- ),
- ),
- if (feeObject != null)
- FutureBuilder(
- future: feeFor(
- coin: coin,
- feeRateType: FeeRateType.fast,
- feeRate: feeObject!.fast,
- amount: amount,
- ),
- builder: (_, AsyncSnapshot<Amount> snapshot) {
- if (snapshot.connectionState ==
- ConnectionState.done &&
- snapshot.hasData) {
- return Text(
- "(~${ref.watch(pAmountFormatter(coin)).format(snapshot.data!, indicatePrecisionLoss: false)})",
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- textAlign: TextAlign.left,
- );
- } else {
- return AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- }
- },
- ),
- ],
- ),
- const SizedBox(height: 2),
- if (feeObject == null && coin is! Ethereum)
- AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style: STextStyles.itemSubtitle(
- context,
- ),
- ),
- if (feeObject != null && coin is! Ethereum)
- Text(
- estimatedTimeToBeIncludedInNextBlock(
- coin.targetBlockTimeSeconds,
- feeObject!.numberOfBlocksFast,
- ),
- style: STextStyles.itemSubtitle(
- context,
- ),
- textAlign: TextAlign.left,
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- ),
- const SizedBox(height: 16),
- GestureDetector(
- onTap: () => _selectFeeRate(FeeRateType.average),
- child: Container(
- color: Colors.transparent,
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Column(
- children: [
- SizedBox(
- width: 20,
- height: 20,
- child: Radio(
- activeColor: Theme.of(context)
- .extension<StackColors>()!
- .radioButtonIconEnabled,
- value: FeeRateType.average,
- groupValue: ref
- .watch(
- feeRateTypeMobileStateProvider
- .state,
- )
- .state,
- onChanged: (_) =>
- _selectFeeRate(FeeRateType.average),
- ),
- ),
- ],
- ),
- const SizedBox(width: 12),
- Flexible(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Text(
- FeeRateType.average.prettyName,
- style: STextStyles.titleBold12(
- context,
- ),
- textAlign: TextAlign.left,
- ),
- const SizedBox(width: 2),
- if (feeObject == null)
- AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style: STextStyles.itemSubtitle(
- context,
- ),
- ),
- if (feeObject != null)
- FutureBuilder(
- future: feeFor(
- coin: coin,
- feeRateType: FeeRateType.average,
- feeRate: feeObject!.medium,
- amount: amount,
- ),
- builder: (_, AsyncSnapshot<Amount> snapshot) {
- if (snapshot.connectionState ==
- ConnectionState.done &&
- snapshot.hasData) {
- return Text(
- "(~${ref.watch(pAmountFormatter(coin)).format(snapshot.data!, indicatePrecisionLoss: false)})",
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- textAlign: TextAlign.left,
- );
- } else {
- return AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- }
- },
- ),
- ],
- ),
- const SizedBox(height: 2),
- if (feeObject == null && coin is! Ethereum)
- AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style: STextStyles.itemSubtitle(
- context,
- ),
- ),
- if (feeObject != null && coin is! Ethereum)
- Text(
- estimatedTimeToBeIncludedInNextBlock(
- coin.targetBlockTimeSeconds,
- feeObject!.numberOfBlocksAverage,
- ),
- style: STextStyles.itemSubtitle(
- context,
- ),
- textAlign: TextAlign.left,
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- ),
- const SizedBox(height: 16),
- GestureDetector(
- onTap: () => _selectFeeRate(FeeRateType.slow),
- child: Container(
- color: Colors.transparent,
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Column(
- children: [
- SizedBox(
- width: 20,
- height: 20,
- child: Radio(
- activeColor: Theme.of(context)
- .extension<StackColors>()!
- .radioButtonIconEnabled,
- value: FeeRateType.slow,
- groupValue: ref
- .watch(
- feeRateTypeMobileStateProvider
- .state,
- )
- .state,
- onChanged: (_) =>
- _selectFeeRate(FeeRateType.slow),
- ),
- ),
- ],
- ),
- const SizedBox(width: 12),
- Flexible(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Text(
- FeeRateType.slow.prettyName,
- style: STextStyles.titleBold12(
- context,
- ),
- textAlign: TextAlign.left,
- ),
- const SizedBox(width: 2),
- if (feeObject == null)
- AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style: STextStyles.itemSubtitle(
- context,
- ),
- ),
- if (feeObject != null)
- FutureBuilder(
- future: feeFor(
- coin: coin,
- feeRateType: FeeRateType.slow,
- feeRate: feeObject!.slow,
- amount: amount,
- ),
- builder: (_, AsyncSnapshot<Amount> snapshot) {
- if (snapshot.connectionState ==
- ConnectionState.done &&
- snapshot.hasData) {
- return Text(
- "(~${ref.watch(pAmountFormatter(coin)).format(snapshot.data!, indicatePrecisionLoss: false)})",
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- textAlign: TextAlign.left,
- );
- } else {
- return AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- }
- },
- ),
- ],
- ),
- const SizedBox(height: 2),
- if (feeObject == null && coin is! Ethereum)
- AnimatedText(
- stringsToLoopThrough:
- stringsToLoopThrough,
- style: STextStyles.itemSubtitle(
- context,
- ),
- ),
- if (feeObject != null && coin is! Ethereum)
- Text(
- estimatedTimeToBeIncludedInNextBlock(
- coin.targetBlockTimeSeconds,
- feeObject!.numberOfBlocksSlow,
- ),
- style: STextStyles.itemSubtitle(
- context,
- ),
- textAlign: TextAlign.left,
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- ),
- const SizedBox(height: 24),
- if (wallet is ElectrumXInterface || coin is Ethereum)
- GestureDetector(
- onTap: () => _selectFeeRate(FeeRateType.custom),
- child: Container(
- color: Colors.transparent,
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Column(
- children: [
- SizedBox(
- width: 20,
- height: 20,
- child: Radio(
- activeColor: Theme.of(context)
- .extension<StackColors>()!
- .radioButtonIconEnabled,
- value: FeeRateType.custom,
- groupValue: ref
- .watch(
- feeRateTypeMobileStateProvider
- .state,
- )
- .state,
- onChanged: (_) =>
- _selectFeeRate(FeeRateType.custom),
- ),
- ),
- ],
- ),
- const SizedBox(width: 12),
- Flexible(
- child: Column(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Text(
- FeeRateType.custom.prettyName,
- style: STextStyles.titleBold12(
- context,
- ),
- textAlign: TextAlign.left,
- ),
- ],
- ),
- const SizedBox(height: 2),
- ],
- ),
- ),
- ],
- ),
- ),
- ),
- if (wallet is ElectrumXInterface || coin is Ethereum)
- const SizedBox(height: 24),
- ],
- );
- },
+ Text(
+ "Fee rate",
+ style: STextStyles.pageTitleH2(context),
+ textAlign: TextAlign.left,
),
+ for (final feeRateType in sendFeeRateTypes(widget.fees.coin)) ...[
+ SizedBox(height: feeRateType.isCustom ? 24 : 16),
+ _feeRateRow(feeRateType),
+ ],
+ const SizedBox(height: 24),
],
),
),
),
);
}
-
- Amount? getAmount(FeeRateType feeRateType) {
- switch (feeRateType) {
- case FeeRateType.fast:
- return ref.read(feeSheetSessionCacheProvider).fast[amount];
- case FeeRateType.average:
- return ref.read(feeSheetSessionCacheProvider).average[amount];
- case FeeRateType.slow:
- return ref.read(feeSheetSessionCacheProvider).slow[amount];
- case FeeRateType.custom:
- return null;
- }
- }
}
### lib/pages/send_view/token_send_view.dart
@@ -21,6 +21,7 @@ import '../../models/send_view_auto_fill_data.dart';
import '../../providers/providers.dart';
import '../../providers/ui/fee_rate_type_state_provider.dart';
import '../../providers/ui/preview_tx_button_state_provider.dart';
+import '../../providers/wallet/send_fee_providers.dart';
import '../../route_generator.dart';
import '../../themes/stack_colors.dart';
import '../../utilities/address_utils.dart';
@@ -45,8 +46,8 @@ import '../../wallets/isar/providers/eth/current_token_wallet_provider.dart';
import '../../wallets/isar/providers/eth/token_balance_provider.dart';
import '../../wallets/isar/providers/wallet_info_provider.dart';
import '../../wallets/models/tx_data.dart';
-import '../../widgets/animated_text.dart';
import '../../widgets/background.dart';
+import '../../widgets/calculating_future_builder.dart';
import '../../widgets/custom_buttons/app_bar_icon_button.dart';
import '../../widgets/eth_fee_form.dart';
import '../../widgets/icon_widgets/addressbook_icon.dart';
@@ -85,7 +86,8 @@ class TokenSendView extends ConsumerStatefulWidget {
ConsumerState<TokenSendView> createState() => _TokenSendViewState();
}
-class _TokenSendViewState extends ConsumerState<TokenSendView> {
+class _TokenSendViewState extends ConsumerState<TokenSendView>
+ with SendFeeForm {
late final String walletId;
late final CryptoCurrency coin;
late final EthContract tokenContract;
@@ -113,12 +115,6 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
bool _cryptoAmountChangeLock = false;
late VoidCallback onCryptoAmountChanged;
- final updateFeesTimerDuration = const Duration(milliseconds: 500);
-
- Timer? _cryptoAmountChangedFeeUpdateTimer;
- Timer? _baseAmountChangedFeeUpdateTimer;
- late Future<Amount> _calculateFeesFuture;
-
final _ethFee = ValueNotifier<EthEIP1559Fee?>(null);
void _onTokenSendViewPasteAddressFieldButtonPressed() async {
@@ -287,12 +283,8 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
cryptoAmountController.text = "";
_cryptoAmountChangeLock = false;
}
- // setState(() {
- // _calculateFeesFuture = calculateFees(
- // Format.decimalAmountToSatoshis(
- // _amountToSend!));
- // });
_updatePreviewButtonState(_address, _amountToSend);
+ followFeeAmount(_amountToSend);
}
// Controller assignments used for display must not edit the stored amount.
@@ -344,29 +336,10 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
}
_updatePreviewButtonState(_address, _amountToSend);
-
- _cryptoAmountChangedFeeUpdateTimer?.cancel();
- _cryptoAmountChangedFeeUpdateTimer = Timer(updateFeesTimerDuration, () {
- if (mounted && coin is! Epiccash && !_baseFocus.hasFocus) {
- setState(() {
- _calculateFeesFuture = calculateFees();
- });
- }
- });
+ followFeeAmount(_amountToSend);
}
}
- void _baseAmountChanged() {
- _baseAmountChangedFeeUpdateTimer?.cancel();
- _baseAmountChangedFeeUpdateTimer = Timer(updateFeesTimerDuration, () {
- if (mounted && coin is! Epiccash && !_cryptoFocus.hasFocus) {
- setState(() {
- _calculateFeesFuture = calculateFees();
- });
- }
- });
- }
-
String? _updateInvalidAddressText(String address) {
if (_data != null && _data.contactLabel == address) {
return null;
@@ -392,30 +365,6 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
(isValidAddress && amount != null && amount > Amount.zero);
}
- Future<Amount> calculateFees() async {
- final wallet = ref.read(pCurrentTokenWallet)!;
- final feeObject = await wallet.fees;
-
- late final BigInt feeRate;
-
- switch (ref.read(feeRateTypeMobileStateProvider.state).state) {
- case FeeRateType.fast:
- feeRate = feeObject.fast;
- break;
- case FeeRateType.average:
- feeRate = feeObject.medium;
- break;
- case FeeRateType.slow:
- feeRate = feeObject.slow;
- break;
- default:
- feeRate = BigInt.from(-1);
- }
-
- final Amount fee = await wallet.estimateFeeFor(Amount.zero, feeRate);
- return fee;
- }
-
Future<void> _previewTransaction() async {
// wait for keyboard to disappear
FocusScope.of(context).unfocus();
@@ -516,7 +465,7 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
)!,
),
],
- feeRateType: ref.read(feeRateTypeMobileStateProvider),
+ feeRateType: ref.read(pFeeRateType),
note: noteController.text,
ethEIP1559Fee: _ethFee.value,
),
@@ -602,11 +551,10 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
@override
void initState() {
- ref.refresh(feeSheetSessionCacheProvider);
-
- _calculateFeesFuture = calculateFees();
_data = widget.autoFillData;
walletId = widget.walletId;
+ fees = SendFeeRates(ref.read, walletId: walletId, isToken: true);
+ retryFeeOnFocusLoss([_cryptoFocus, _baseFocus]);
coin = widget.coin;
tokenContract = widget.tokenContract;
clipboard = widget.clipboard;
@@ -619,7 +567,6 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
onCryptoAmountChanged = _cryptoAmountChanged;
cryptoAmountController.addListener(onCryptoAmountChanged);
- baseAmountController.addListener(_baseAmountChanged);
if (_data != null) {
if (_data.amount != null) {
@@ -639,12 +586,9 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
@override
void dispose() {
- _cryptoAmountChangedFeeUpdateTimer?.cancel();
- _baseAmountChangedFeeUpdateTimer?.cancel();
_ethFee.dispose();
cryptoAmountController.removeListener(onCryptoAmountChanged);
- baseAmountController.removeListener(_baseAmountChanged);
sendToController.dispose();
cryptoAmountController.dispose();
@@ -662,7 +606,8 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
@override
Widget build(BuildContext context) {
debugPrint("BUILD: $runtimeType");
- final isCustomFee = ref.watch(feeRateTypeMobileStateProvider).isCustom;
+ final isCustomFee = ref.watch(pFeeRateType).isCustom;
+ listenForCustomFeeLevel(ref, coin, () => _ethFee.value = null);
final String locale = ref.watch(
localeServiceChangeNotifierProvider.select((value) => value.locale),
);
@@ -1219,44 +1164,7 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
Constants.size.circularBorderRadius,
),
),
- onPressed: () {
- showModalBottomSheet<dynamic>(
- backgroundColor: Colors.transparent,
- context: context,
- shape: const RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(
- top: Radius.circular(20),
- ),
- ),
- builder: (_) =>
- TransactionFeeSelectionSheet(
- walletId: walletId,
- isToken: true,
- amount:
- _amountToSend ??
- Amount.zeroWith(
- fractionDigits:
- tokenContract.decimals,
- ),
- updateChosen: (feeRateType, fee) {
- if (feeRateType.isCustom) {
- return;
- }
-
- setState(() {
- if (fee != null) {
- _calculateFeesFuture =
- Future.value(fee);
- } else {
- _calculateFeesFuture =
- calculateFees();
- }
- _ethFee.value = null;
- });
- },
- ),
- );
- },
+ onPressed: () => showFeeSheet(this),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
@@ -1265,57 +1173,39 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
children: [
Text(
ref
- .watch(
- feeRateTypeMobileStateProvider
- .state,
- )
+ .watch(pFeeRateType.state)
.state
.prettyName,
style: STextStyles.itemSubtitle12(
context,
),
),
const SizedBox(width: 10),
- FutureBuilder(
- future: _calculateFeesFuture,
- builder: (context, snapshot) {
- if (snapshot.connectionState ==
- ConnectionState.done &&
- snapshot.hasData) {
- final formattedFee = ref
- .watch(
- pAmountFormatter(coin),
- )
- .format(
- snapshot.data!,
- withUnitName: true,
- indicatePrecisionLoss:
- false,
- );
- return Text(
- isCustomFee
- ? ""
- : "~$formattedFee",
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- } else {
- return AnimatedText(
- stringsToLoopThrough:
- const [
- "Calculating",
- "Calculating.",
- "Calculating..",
- "Calculating...",
- ],
- style:
- STextStyles.itemSubtitle(
- context,
- ),
- );
- }
+ CalculatingFutureBuilder(
+ future: watchFee(),
+ style: STextStyles.itemSubtitle(
+ context,
+ ),
+ builder: (fee) {
+ final formattedFee = ref
+ .watch(
+ pAmountFormatter(coin),
+ )
+ .format(
+ fee,
+ withUnitName: true,
+ indicatePrecisionLoss:
+ false,
+ );
+ return Text(
+ isCustomFee
+ ? ""
+ : "~$formattedFee",
+ style:
+ STextStyles.itemSubtitle(
+ context,
+ ),
+ );
},
),
],
### lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_sol_token_view.dart
@@ -12,7 +12,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
-import '../../../pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart';
import '../../../pages/token_view/solana_token_contract_details_view.dart';
import '../../../pages/token_view/sub_widgets/token_transaction_list_widget_sol.dart';
import '../../../services/event_bus/events/global/wallet_sync_status_changed_event.dart';
@@ -93,7 +92,6 @@ class _DesktopTokenViewState extends ConsumerState<DesktopSolTokenView> {
.topNavIconPrimary,
),
onPressed: () {
- ref.refresh(feeSheetSessionCacheProvider);
Navigator.of(context).pop();
},
),
### lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_token_view.dart
@@ -13,7 +13,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
-import '../../../pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart';
import '../../../pages/token_view/sub_widgets/token_transaction_list_widget.dart';
import '../../../pages/token_view/token_contract_details_view.dart';
import '../../../pages/wallet_view/transaction_views/tx_v2/all_transactions_v2_view.dart';
@@ -93,7 +92,6 @@ class _DesktopTokenViewState extends ConsumerState<DesktopTokenView> {
.topNavIconPrimary,
),
onPressed: () {
- ref.refresh(feeSheetSessionCacheProvider);
Navigator.of(context).pop();
},
),
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart
@@ -32,12 +32,11 @@ import '../../../../pages/send_view/sub_widgets/building_transaction_dialog.dart
import '../../../../pages/send_view/sub_widgets/epic_slatepack_dialog.dart';
import '../../../../pages/send_view/sub_widgets/multi_recipient.dart';
import '../../../../pages/send_view/sub_widgets/mwc_slatepack_dialog.dart';
-import '../../../../pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart';
import '../../../../providers/providers.dart';
import '../../../../providers/ui/fee_rate_type_state_provider.dart';
import '../../../../providers/ui/preview_tx_button_state_provider.dart';
-import '../../../../providers/wallet/desktop_fee_providers.dart';
import '../../../../providers/wallet/public_private_balance_state_provider.dart';
+import '../../../../providers/wallet/send_fee_providers.dart';
import '../../../../services/openalias/open_alias_service.dart';
import '../../../../services/spark_names_service.dart';
import '../../../../themes/stack_colors.dart';
@@ -59,7 +58,6 @@ import '../../../../utilities/show_loading.dart';
import '../../../../utilities/text_styles.dart';
import '../../../../utilities/util.dart';
import '../../../../wallets/crypto_currency/crypto_currency.dart';
-import '../../../../wallets/crypto_currency/intermediate/nano_currency.dart';
import '../../../../wallets/isar/providers/wallet_info_provider.dart';
import '../../../../wallets/models/tx_data.dart';
import '../../../../wallets/wallet/impl/epiccash_wallet.dart';
@@ -683,7 +681,7 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
TxData txData;
Future<TxData> txDataFuture;
- final feeRateType = ref.read(feeRateTypeDesktopStateProvider);
+ final feeRateType = ref.read(pFeeRateType);
final satsPerVByte = feeRateType.customSatsPerVByte(customFeeRate);
if (isPaynymSend) {
@@ -983,9 +981,10 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
setState(() {});
}
+ final _feeAmount = SendFeeAmount();
+
void _syncFeeAmount(Amount? amount) {
- ref.read(sendAmountProvider.notifier).state =
- amount ?? Amount.zeroWith(fractionDigits: coin.fractionDigits);
+ if (mounted) _feeAmount.sync(amount);
}
void _setOpReturnData(String? data) {
@@ -1049,6 +1048,7 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
}
ref.read(pSendAmount.notifier).state = amount;
+ _feeAmount.typed(amount);
}
}
@@ -1284,7 +1284,6 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
? ""
: ref.read(pAmountFormatter(coin)).formatEditable(total);
ref.read(pSendAmount.notifier).state = total;
- _syncFeeAmount(total);
_setValidAddressProviders(_address);
}
@@ -1499,6 +1498,7 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
// _amountToSend!));
// });
ref.read(pSendAmount.notifier).state = amount;
+ _feeAmount.typed(amount);
}
String _getSendAllTitle(bool showCoinControl, Set<UTXO> selectedUTXOs) {
@@ -1555,7 +1555,6 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
- ref.refresh(feeSheetSessionCacheProvider);
ref.refresh(pIsExchangeAddress);
ref.read(pValidSendToAddress.state).state = false;
ref.read(pValidSparkSendToAddress.state).state = false;
@@ -1613,23 +1612,13 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
_cryptoFocus.addListener(() {
if (!_cryptoFocus.hasFocus && !_baseFocus.hasFocus) {
- if (ref.read(pSendAmount) == null) {
- if (ref.read(sendAmountProvider) != Amount.zero && mounted) {
- ref.read(sendAmountProvider.state).state = Amount.zero;
- }
- } else {
- ref.read(sendAmountProvider.state).state = ref.read(pSendAmount)!;
- }
+ _syncFeeAmount(ref.read(pSendAmount));
}
});
_baseFocus.addListener(() {
if (!_cryptoFocus.hasFocus && !_baseFocus.hasFocus) {
- if (ref.read(pSendAmount) == null) {
- ref.refresh(sendAmountProvider);
- } else {
- ref.read(sendAmountProvider.state).state = ref.read(pSendAmount)!;
- }
+ _syncFeeAmount(ref.read(pSendAmount));
}
});
@@ -1640,6 +1629,7 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
void dispose() {
cryptoAmountController.removeListener(onCryptoAmountChanged);
_ethFee.dispose();
+ _feeAmount.dispose();
sendToController.dispose();
cryptoAmountController.dispose();
@@ -1678,7 +1668,11 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
_xelisSendAll = xelisSendAll;
}
});
- final isCustomFee = ref.watch(feeRateTypeDesktopStateProvider).isCustom;
+ final isCustomFee = ref.watch(pFeeRateType).isCustom;
+ listenForCustomFeeLevel(ref, coin, () {
+ customFeeRate = 1;
+ _ethFee.value = null;
+ });
// ethFee is checked in the ValueListenableBuilder around the preview
// button so fee keystrokes don't rebuild this whole view.
final previewEnabled = ref.watch(pPreviewTxButtonEnabled(coin));
@@ -2504,18 +2498,12 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
),
),
if (!isPaynymSend) const SizedBox(height: 20),
- if (coin is! NanoCurrency &&
- coin is! Epiccash &&
- coin is! Tezos &&
- coin is! Mimblewimblecoin)
+ if (hasSendFee(coin))
DesktopSendFeeForm(
walletId: walletId,
isToken: false,
+ amount: _feeAmount,
onCustomFeeSliderChanged: (value) => customFeeRate = value,
- onCustomFeeOptionChanged: () {
- customFeeRate = 1;
- _ethFee.value = null;
- },
onCustomEip1559FeeOptionChanged: (value) {
_ethFee.value = value;
},
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send_fee_form.dart
@@ -1,126 +1,122 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
-import '../../../../models/paymint/fee_object_model.dart';
-import '../../../../pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart';
import '../../../../providers/providers.dart';
import '../../../../providers/ui/fee_rate_type_state_provider.dart';
-import '../../../../providers/ui/preview_tx_button_state_provider.dart';
-import '../../../../providers/wallet/desktop_fee_providers.dart';
import '../../../../providers/wallet/public_private_balance_state_provider.dart';
+import '../../../../providers/wallet/send_fee_providers.dart';
import '../../../../themes/stack_colors.dart';
-import '../../../../utilities/address_utils.dart';
import '../../../../utilities/amount/amount.dart';
import '../../../../utilities/enums/fee_rate_type_enum.dart';
import '../../../../utilities/eth_commons.dart';
import '../../../../utilities/text_styles.dart';
import '../../../../wallets/crypto_currency/crypto_currency.dart';
-import '../../../../wallets/crypto_currency/interfaces/electrumx_currency_interface.dart';
-import '../../../../wallets/crypto_currency/intermediate/cryptonote_currency.dart';
-import '../../../../wallets/isar/providers/eth/current_token_wallet_provider.dart';
import '../../../../wallets/isar/providers/wallet_info_provider.dart';
-import '../../../../wallets/wallet/impl/firo_wallet.dart';
-import '../../../../wallets/wallet/intermediate/cryptonote_wallet.dart';
-import '../../../../widgets/animated_text.dart';
import '../../../../widgets/conditional_parent.dart';
import '../../../../widgets/custom_buttons/blue_text_button.dart';
import '../../../../widgets/desktop/desktop_fee_dialog.dart';
import '../../../../widgets/eth_fee_form.dart';
import '../../../../widgets/fee_slider.dart';
+class SendFeeAmount extends ChangeNotifier {
+ Amount? _value;
+ bool _isTyped = false;
+
+ Amount? get value => _value;
+
+ /// Whether the fee follows [value] once typing pauses.
+ bool get isTyped => _isTyped;
+
+ void typed(Amount? amount) => _set(amount, isTyped: true);
+
+ /// Each sync notifies, so a fee that failed is retried on the same amount
+ /// too.
+ void sync(Amount? amount) => _set(amount, isTyped: false);
+
+ void _set(Amount? amount, {required bool isTyped}) {
+ _value = amount;
+ _isTyped = isTyped;
+ notifyListeners();
+ }
+}
+
class DesktopSendFeeForm extends ConsumerStatefulWidget {
const DesktopSendFeeForm({
super.key,
required this.walletId,
required this.isToken,
+ required this.amount,
required this.onCustomFeeSliderChanged,
- required this.onCustomFeeOptionChanged,
this.onCustomEip1559FeeOptionChanged,
});
final String walletId;
final bool isToken;
+ final SendFeeAmount amount;
final void Function(int) onCustomFeeSliderChanged;
- final VoidCallback onCustomFeeOptionChanged;
final void Function(EthEIP1559Fee?)? onCustomEip1559FeeOptionChanged;
@override
ConsumerState<DesktopSendFeeForm> createState() => _DesktopSendFeeFormState();
}
-class _DesktopSendFeeFormState extends ConsumerState<DesktopSendFeeForm> {
- final stringsToLoopThrough = [
- "Calculating",
- "Calculating.",
- "Calculating..",
- "Calculating...",
- ];
-
+class _DesktopSendFeeFormState extends ConsumerState<DesktopSendFeeForm>
+ with SendFeeForm {
late final CryptoCurrency cryptoCurrency;
- Future<FeeObject>? _fees;
bool get isEth => cryptoCurrency is Ethereum;
- (FeeRateType, String?, String?)? feeSelectionResult;
-
- Amount _addFiroOpReturnFee({
- required Amount fee,
- required BigInt feeRate,
- required FiroWallet wallet,
- }) {
- final opReturnData = ref.read(pOpReturnData);
- if (opReturnData == null ||
- opReturnData.isEmpty ||
- ref.read(publicPrivateBalanceStateProvider) != BalanceType.public) {
- return fee;
- }
-
- final extraOutputVSize = AddressUtils.opReturnOutputVSizeFromHex(
- opReturnData,
- );
- final extraFee = wallet.estimateTxFee(
- vSize: extraOutputVSize,
- feeRatePerKB: feeRate,
- );
-
- return fee +
- Amount(
- rawValue: BigInt.from(extraFee),
- fractionDigits: cryptoCurrency.fractionDigits,
- );
- }
-
@override
void initState() {
super.initState();
cryptoCurrency = ref.read(pWalletCoin(widget.walletId));
+ fees = SendFeeRates(
+ ref.read,
+ walletId: widget.walletId,
+ isToken: widget.isToken,
+ );
+ feeAmount = widget.amount.value;
+ widget.amount.addListener(_amountChanged);
- // The fee rate type provider is global and never disposed. Reset it here
- // so a stale custom selection from another wallet/send form can't cause a
- // send using an unset custom fee rate.
+ // A send form opened over another one shares its fee rate type, and a
+ // Custom level picked in the other form has no custom fee rate in this one.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
- ref.read(feeRateTypeDesktopStateProvider.state).state =
- FeeRateType.average;
+ ref.read(pFeeRateType.state).state = FeeRateType.average;
}
});
}
+ void _amountChanged() => widget.amount.isTyped
+ ? followFeeAmount(widget.amount.value)
+ : setFeeAmount(widget.amount.value);
+
+ void _editFee() => chooseFee(
+ (fees, amount) => showDialog<void>(
+ context: context,
+ builder: (_) => DesktopFeeDialog(fees: fees, amount: amount),
+ ),
+ );
+
+ @override
+ void dispose() {
+ widget.amount.removeListener(_amountChanged);
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
- // Keep the send amount alive for the fee estimates.
- ref.listen(sendAmountProvider, (_, __) {});
- final isCustomFee = ref.watch(feeRateTypeDesktopStateProvider).isCustom;
+ ref.listen(publicPrivateBalanceStateProvider, (_, __) => retryFee());
+ final feeRateType = ref.watch(pFeeRateType);
+ final isCustomFee = feeRateType.isCustom;
final locale = ref.watch(
localeServiceChangeNotifierProvider.select((value) => value.locale),
);
- final canEditFees =
- isEth ||
- cryptoCurrency is Solana ||
- (cryptoCurrency is ElectrumXCurrencyInterface &&
- !(((cryptoCurrency is Firo) &&
- (ref.watch(publicPrivateBalanceStateProvider.state).state ==
- BalanceType.private))));
+ final canPick = canPickFeeRateType(
+ cryptoCurrency,
+ ref.watch(publicPrivateBalanceStateProvider.state).state,
+ );
+ final canEditFees = canPick && cryptoCurrency is! Xelis;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -131,34 +127,13 @@ class _DesktopSendFeeFormState extends ConsumerState<DesktopSendFeeForm> {
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
child,
- CustomTextButton(
- text: "Edit",
- onTap: () async {
- final wasCustomFee = isCustomFee;
- feeSelectionResult =
- await showDialog<(FeeRateType, String?, String?)?>(
- context: context,
- builder: (_) => DesktopFeeDialog(
- walletId: widget.walletId,
- isToken: widget.isToken,
- ),
- );
-
- if (feeSelectionResult != null) {
- final selectedIsCustomFee = feeSelectionResult!.$1.isCustom;
- if (wasCustomFee != selectedIsCustomFee) {
- widget.onCustomFeeOptionChanged.call();
- }
- }
-
- setState(() {});
- },
- ),
+ CustomTextButton(text: "Edit", onTap: _editFee),
],
),
child: Text(
- "Transaction fee"
- "${isCustomFee ? "" : " (${isEth ? "max" : "estimated"})"}",
+ isCustomFee && canPick || cryptoCurrency is Xelis
+ ? "Transaction fee"
+ : "Transaction fee (${isEth ? "max" : "estimated"})",
style: STextStyles.desktopTextExtraSmall(context).copyWith(
color: Theme.of(context)
.extension<StackColors>()!
@@ -173,188 +148,15 @@ class _DesktopSendFeeFormState extends ConsumerState<DesktopSendFeeForm> {
padding: EdgeInsets.all(10),
child: Text('Calculated when reviewing'),
)
- else if (!isCustomFee)
+ else if (!isCustomFee || !canPick)
Padding(
padding: const EdgeInsets.all(10),
- child: (feeSelectionResult?.$2 == null)
- ? FutureBuilder(
- future: _fees ??= ref
- .read(pWallets)
- .getWallet(widget.walletId)
- .fees,
- builder: (context, snapshot) {
- if (snapshot.connectionState == ConnectionState.done &&
- snapshot.hasError) {
- _fees = null;
- }
- if (snapshot.connectionState == ConnectionState.done &&
- snapshot.hasData) {
- return DesktopFeeItem(
- feeObject: snapshot.data,
- feeRateType: FeeRateType.average,
- walletId: widget.walletId,
- isButton: false,
- feeFor:
- ({
- required Amount amount,
- required FeeRateType feeRateType,
- required BigInt feeRate,
- required CryptoCurrency coin,
- }) async {
- if (!widget.isToken &&
- coin is Firo &&
- ref.read(
- publicPrivateBalanceStateProvider,
- ) ==
- BalanceType.public &&
- (ref.read(pOpReturnData)?.isNotEmpty ??
- false)) {
- final wallet =
- ref
- .read(pWallets)
- .getWallet(widget.walletId)
- as FiroWallet;
- final fee = await wallet.estimateFeeFor(
- amount,
- feeRate,
- );
- return _addFiroOpReturnFee(
- fee: fee,
- feeRate: feeRate,
- wallet: wallet,
- );
- }
-
- if (ref
- .read(
- widget.isToken
- ? tokenFeeSessionCacheProvider
- : feeSheetSessionCacheProvider,
- )
- .average[amount] ==
- null) {
- if (widget.isToken == false) {
- final wallet = ref
- .read(pWallets)
- .getWallet(widget.walletId);
-
- if (coin is CryptonoteCurrency) {
- final fee = await wallet.estimateFeeFor(
- amount,
- BigInt.from(
- (wallet as CryptonoteWallet)
- .getTxPriorityMedium(),
- ),
- );
- ref
- .read(
- feeSheetSessionCacheProvider,
- )
- .average[amount] =
- fee;
- } else if ((coin is Firo) &&
- ref
- .read(
- publicPrivateBalanceStateProvider
- .state,
- )
- .state !=
- BalanceType.public) {
- final firoWallet = wallet as FiroWallet;
-
- if (ref
- .read(
- publicPrivateBalanceStateProvider
- .state,
- )
- .state ==
- BalanceType.private) {
- ref
- .read(feeSheetSessionCacheProvider)
- .average[amount] = await firoWallet
- .estimateFeeForSpark(amount);
- }
- } else {
- ref
- .read(feeSheetSessionCacheProvider)
- .average[amount] = await wallet
- .estimateFeeFor(amount, feeRate);
- }
- } else {
- // Token fee estimation (works for ERC20 and SOL tokens).
- try {
- final tokenWallet = ref.read(
- pCurrentTokenWallet,
- )!;
- final fee = await tokenWallet
- .estimateFeeFor(amount, feeRate);
- ref
- .read(
- tokenFeeSessionCacheProvider,
- )
- .average[amount] =
- fee;
- } catch (_) {
- // Token wallet not available.
- debugPrint(
- "Token fee estimation not available",
- );
- }
- }
- }
- return ref
- .read(
- widget.isToken
- ? tokenFeeSessionCacheProvider
- : feeSheetSessionCacheProvider,
- )
- .average[amount]!;
- },
- isSelected: true,
- );
- } else {
- return Row(
- children: [
- AnimatedText(
- stringsToLoopThrough: stringsToLoopThrough,
- style:
- STextStyles.desktopTextExtraExtraSmall(
- context,
- ).copyWith(
- color: Theme.of(context)
- .extension<StackColors>()!
- .textFieldActiveText,
- ),
- ),
- ],
- );
- }
- },
- )
- : Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(
- feeSelectionResult?.$2 ?? "",
- style: STextStyles.desktopTextExtraExtraSmall(context)
- .copyWith(
- color: Theme.of(context)
- .extension<StackColors>()!
- .textFieldActiveText,
- ),
- textAlign: TextAlign.left,
- ),
- Text(
- feeSelectionResult?.$3 ?? "",
- style: STextStyles.desktopTextExtraExtraSmall(context)
- .copyWith(
- color: Theme.of(context)
- .extension<StackColors>()!
- .textFieldActiveSearchIconRight,
- ),
- ),
- ],
- ),
+ child: DesktopFeeItem(
+ fees: fees,
+ feeRateType: canPick ? feeRateType : FeeRateType.average,
+ amount: feeAmount,
+ isButton: false,
+ ),
),
if (isCustomFee && isEth)
EthFeeForm(
@@ -365,7 +167,7 @@ class _DesktopSendFeeFormState extends ConsumerState<DesktopSendFeeForm> {
stateChanged: (value) =>
widget.onCustomEip1559FeeOptionChanged?.call(value),
),
- if (isCustomFee && !isEth)
+ if (isCustomFee && canPick && !isEth)
Padding(
padding: const EdgeInsets.only(bottom: 12, top: 16),
child: FeeSlider(
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_sol_token_send.dart
@@ -643,7 +643,6 @@ class _DesktopSolTokenSendState extends ConsumerState<DesktopSolTokenSend> {
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
- // ref.refresh(tokenFeeSessionCacheProvider); // Ethereum-specific
ref.read(previewTokenTxButtonStateProvider.state).state = false;
});
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart
@@ -23,7 +23,7 @@ import '../../../../pages/send_view/sub_widgets/building_transaction_dialog.dart
import '../../../../providers/providers.dart';
import '../../../../providers/ui/fee_rate_type_state_provider.dart';
import '../../../../providers/ui/preview_tx_button_state_provider.dart';
-import '../../../../providers/wallet/desktop_fee_providers.dart';
+import '../../../../providers/wallet/send_fee_providers.dart';
import '../../../../themes/stack_colors.dart';
import '../../../../utilities/address_utils.dart';
import '../../../../utilities/amount/amount.dart';
@@ -256,7 +256,7 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
)!,
),
],
- feeRateType: ref.read(feeRateTypeDesktopStateProvider),
+ feeRateType: ref.read(pFeeRateType),
nonce: nonce,
ethEIP1559Fee: _ethFee.value,
),
@@ -368,10 +368,10 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
}
}
+ final _feeAmount = SendFeeAmount();
+
void _syncFeeAmount(Amount? amount) {
- final tokenDecimals = ref.read(pCurrentTokenWallet)!.tokenContract.decimals;
- ref.read(sendAmountProvider.notifier).state =
- amount ?? Amount.zeroWith(fractionDigits: tokenDecimals);
+ if (mounted) _feeAmount.sync(amount);
}
// Controller assignments used for display must not edit the stored amount.
@@ -427,6 +427,7 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
}
_updatePreviewButtonState(_address, _amountToSend);
+ _feeAmount.typed(_amountToSend);
}
}
@@ -607,6 +608,7 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
}
_updatePreviewButtonState(_address, _amountToSend);
+ _feeAmount.typed(_amountToSend);
}
Future<void> sendAllTapped() async {
@@ -626,7 +628,6 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
- ref.refresh(tokenFeeSessionCacheProvider);
ref.read(previewTokenTxButtonStateProvider.state).state = false;
});
@@ -662,25 +663,13 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
_cryptoFocus.addListener(() {
if (!_cryptoFocus.hasFocus && !_baseFocus.hasFocus) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (_amountToSend == null) {
- ref.refresh(sendAmountProvider);
- } else {
- ref.read(sendAmountProvider.state).state = _amountToSend!;
- }
- });
+ _syncFeeAmount(_amountToSend);
}
});
_baseFocus.addListener(() {
if (!_cryptoFocus.hasFocus && !_baseFocus.hasFocus) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (_amountToSend == null) {
- ref.refresh(sendAmountProvider);
- } else {
- ref.read(sendAmountProvider.state).state = _amountToSend!;
- }
- });
+ _syncFeeAmount(_amountToSend);
}
});
@@ -691,6 +680,7 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
void dispose() {
cryptoAmountController.removeListener(onCryptoAmountChanged);
_ethFee.dispose();
+ _feeAmount.dispose();
sendToController.dispose();
cryptoAmountController.dispose();
@@ -722,7 +712,8 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
});
}
});
- final isCustomFee = ref.watch(feeRateTypeDesktopStateProvider).isCustom;
+ final isCustomFee = ref.watch(pFeeRateType).isCustom;
+ listenForCustomFeeLevel(ref, coin, () => _ethFee.value = null);
// ethFee is checked in the ValueListenableBuilder around the preview
// button so fee keystrokes don't rebuild this whole view.
final previewEnabled = ref
@@ -1105,10 +1096,8 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
DesktopSendFeeForm(
walletId: walletId,
isToken: true,
+ amount: _feeAmount,
onCustomFeeSliderChanged: (value) => {},
- onCustomFeeOptionChanged: () {
- _ethFee.value = null;
- },
onCustomEip1559FeeOptionChanged: (value) {
_ethFee.value = value;
},
### lib/providers/ui/fee_rate_type_state_provider.dart
@@ -12,10 +12,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../utilities/enums/fee_rate_type_enum.dart';
-final feeRateTypeMobileStateProvider = StateProvider.autoDispose<FeeRateType>(
- (_) => FeeRateType.average,
-);
-
-final feeRateTypeDesktopStateProvider = StateProvider<FeeRateType>(
+final pFeeRateType = StateProvider.autoDispose<FeeRateType>(
(_) => FeeRateType.average,
);
### lib/providers/wallet/desktop_fee_providers.dart
@@ -1,23 +0,0 @@
-/*
- * 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:flutter_riverpod/flutter_riverpod.dart';
-
-import '../../pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart';
-import '../../utilities/amount/amount.dart';
-
-final tokenFeeSessionCacheProvider =
- ChangeNotifierProvider<FeeSheetSessionCache>((ref) {
- return FeeSheetSessionCache();
- });
-
-final sendAmountProvider = StateProvider.autoDispose<Amount>(
- (_) => Amount.zero,
-);
### lib/providers/wallet/send_fee_providers.dart
@@ -0,0 +1,330 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/widgets.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+
+import '../../models/paymint/fee_object_model.dart';
+import '../../services/event_bus/events/global/wallet_sync_status_changed_event.dart';
+import '../../services/event_bus/global_event_bus.dart';
+import '../../utilities/address_utils.dart';
+import '../../utilities/amount/amount.dart';
+import '../../utilities/enums/fee_rate_type_enum.dart';
+import '../../utilities/logger.dart';
+import '../../wallets/crypto_currency/crypto_currency.dart';
+import '../../wallets/crypto_currency/interfaces/electrumx_currency_interface.dart';
+import '../../wallets/crypto_currency/intermediate/cryptonote_currency.dart';
+import '../../wallets/crypto_currency/intermediate/nano_currency.dart';
+import '../../wallets/isar/providers/eth/current_token_wallet_provider.dart';
+import '../../wallets/isar/providers/wallet_info_provider.dart';
+import '../../wallets/wallet/impl/firo_wallet.dart';
+import '../../wallets/wallet/wallet.dart';
+import '../../wallets/wallet/wallet_mixin_interfaces/sync_dependent_fee_estimate_interface.dart';
+import '../global/wallets_provider.dart';
+import '../ui/fee_rate_type_state_provider.dart';
+import '../ui/preview_tx_button_state_provider.dart';
+import 'public_private_balance_state_provider.dart';
+
+typedef _FeeKey = ({
+ FeeRateType feeRateType,
+ Amount? amount,
+ bool isSpark,
+ String? opReturnData,
+ Object spendable,
+});
+
+class _Request<T extends Object> {
+ _Request(this.future) {
+ future.then<void>((answer) {
+ value = answer;
+ // A FutureBuilder given the request later builds its answer at once.
+ future = SynchronousFuture(answer);
+ }, onError: (Object _) {});
+ }
+
+ Future<T> future;
+ T? value;
+}
+
+class SendFeeRates {
+ SendFeeRates(this._read, {required this._walletId, required this._isToken})
+ : _feesByRate = {};
+
+ SendFeeRates._refreshed(SendFeeRates previous)
+ : _read = previous._read,
+ _walletId = previous._walletId,
+ _isToken = previous._isToken,
+ _feesByRate = previous._feesByRate;
+
+ final Reader _read;
+ final String _walletId;
+ final bool _isToken;
+
+ /// Fees estimated at each fee rate, so fresh rates at the same rate reuse
+ /// them, and Spark fees.
+ final Map<Object, Amount> _feesByRate;
+ final _estimates = <_FeeKey, _Request<Amount>>{};
+ _Request<FeeObject>? _rates;
+
+ Wallet get _wallet => _read(pWallets).getWallet(_walletId);
+
+ Wallet get _feeWallet =>
+ _isToken && coin is Ethereum ? _read(pCurrentTokenWallet)! : _wallet;
+
+ late final CryptoCurrency coin = _wallet.cryptoCurrency;
+
+ Future<FeeObject> get rates =>
+ (_rates ??= _Request(_logged(() => _feeWallet.fees))).future;
+
+ SendFeeRates refreshed() => SendFeeRates._refreshed(this);
+
+ /// The rates and fees that have not arrived are asked again.
+ void _retry() {
+ if (_rates?.value == null) _rates = null;
+ _estimates.removeWhere((_, estimate) => estimate.value == null);
+ }
+
+ /// One request for everything the fee depends on, which [read] reads.
+ Future<Amount> estimate(
+ Reader read,
+ FeeRateType feeRateType, {
+ Amount? amount,
+ }) {
+ final key = _key(read, feeRateType, amount);
+ if (_wallet case SyncDependentFeeEstimateInterface(canEstimateFee: false)
+ when !_estimates.containsKey(key)) {
+ // The wallet's next sync status rebuilds the widget [read] belongs to,
+ // which asks again.
+ read(_pWalletSyncStatusChange(_walletId));
+ return Completer<Amount>().future;
+ }
+ return _estimates.putIfAbsent(key, () => _Request(_estimate(key))).future;
+ }
+
+ _FeeKey _key(Reader read, FeeRateType feeRateType, Amount? amount) {
+ final isSpark = _isSparkFee(coin, read(publicPrivateBalanceStateProvider));
+ final balance = isSpark ? pWalletBalanceTertiary : pWalletBalance;
+ final spendable = read(balance(_walletId)).spendable;
+ return (
+ feeRateType: feeRateType,
+ amount:
+ _isFeeAmountIndependent(coin) ||
+ amount == null ||
+ amount.raw == BigInt.zero
+ ? null
+ : amount,
+ isSpark: isSpark,
+ opReturnData: coin is Firo && !isSpark ? read(pOpReturnData) : null,
+ // The fee depends on the coins the wallet can spend, or only on having
+ // some when it ignores the amount.
+ spendable: _isFeeAmountIndependent(coin)
+ ? spendable.raw > BigInt.zero
+ : spendable,
+ );
+ }
+
+ Future<Amount> _estimate(_FeeKey key) async {
+ // The form may be closed once the rates arrive.
+ final (wallet, feeWallet) = (_wallet, _feeWallet);
+ final zero = Amount.zeroWith(fractionDigits: coin.fractionDigits);
+ final amount = key.amount ?? zero;
+ if (key.isSpark) {
+ return _feesByRate[(key.amount, key.spendable)] ??= await _logged(
+ () => (wallet as FiroWallet).estimateFeeForSpark(amount),
+ );
+ }
+ if (key.feeRateType.isCustom) {
+ if (coin is CryptonoteCurrency) {
+ throw ArgumentError("custom fee not available for monero");
+ }
+ // The send forms hide the estimated fee at the Custom level.
+ return zero;
+ }
+
+ final rates = await this.rates;
+ final feeRate = switch (key.feeRateType) {
+ FeeRateType.fast => rates.fast,
+ FeeRateType.slow => rates.slow,
+ _ => rates.medium,
+ };
+ final byRate = (feeRate, key.amount, key.opReturnData, key.spendable);
+ final known = _feesByRate[byRate];
+ if (known != null) return known;
+
+ final fee = await _logged(() => feeWallet.estimateFeeFor(amount, feeRate));
+ final opReturnData = key.opReturnData ?? "";
+ final opReturnFee = wallet is FiroWallet && opReturnData.isNotEmpty
+ ? wallet.estimateTxFee(
+ vSize: AddressUtils.opReturnOutputVSizeFromHex(opReturnData),
+ feeRatePerKB: feeRate,
+ )
+ : 0;
+ return _feesByRate[byRate] =
+ fee + opReturnFee.toAmountAsRaw(fractionDigits: fee.fractionDigits);
+ }
+
+ Future<T> _logged<T>(Future<T> Function() request) async {
+ try {
+ return await request();
+ } catch (error, stackTrace) {
+ Logging.instance.w(
+ "Failed to calculate ${coin.prettyName}${_isToken ? " token" : ""} "
+ "fees: ",
+ error: error,
+ stackTrace: stackTrace,
+ );
+ rethrow;
+ }
+ }
+}
+
+final _pWalletSyncStatusChange = StreamProvider.autoDispose
+ .family<WalletSyncStatusChangedEvent, String>(
+ (ref, walletId) => GlobalEventBus.instance
+ .on<WalletSyncStatusChangedEvent>()
+ .where((event) => event.walletId == walletId),
+ );
+
+bool _isSparkFee(CryptoCurrency coin, BalanceType balanceType) =>
+ coin is Firo && balanceType == BalanceType.private;
+
+bool _isFeeAmountIndependent(CryptoCurrency coin) =>
+ coin is Ethereum || coin is Solana || coin is Stellar || coin is Cardano;
+
+/// Stellar and Cardano give the same fee at every rate.
+bool canPickFeeRateType(CryptoCurrency coin, BalanceType balanceType) =>
+ !_isSparkFee(coin, balanceType) && coin is! Stellar && coin is! Cardano;
+
+bool canUseCustomFee(CryptoCurrency coin) =>
+ coin is ElectrumXCurrencyInterface || coin is Ethereum;
+
+Iterable<FeeRateType> sendFeeRateTypes(CryptoCurrency coin) =>
+ FeeRateType.values.where((e) => !e.isCustom || canUseCustomFee(coin));
+
+/// The custom fee inputs start over each time the Custom level shows, and any
+/// send form can change the level. They also start over once the balance sent
+/// from hides them.
+void listenForCustomFeeLevel(
+ WidgetRef ref,
+ CryptoCurrency coin,
+ VoidCallback onToggled,
+) {
+ ref.listen<FeeRateType>(pFeeRateType, (previous, next) {
+ if (previous?.isCustom != next.isCustom) onToggled();
+ });
+ ref.listen<BalanceType>(publicPrivateBalanceStateProvider, (_, next) {
+ if (!canPickFeeRateType(coin, next)) onToggled();
+ });
+}
+
+bool hasSendFee(CryptoCurrency coin) =>
+ coin is! Epiccash &&
+ coin is! Mimblewimblecoin &&
+ coin is! NanoCurrency &&
+ coin is! Tezos;
+
+String estimatedTimeToBeIncludedInNextBlock(
+ int targetBlockTime,
+ int estimatedNumberOfBlocks,
+) {
+ final time = targetBlockTime * estimatedNumberOfBlocks;
+ final hours = (time / 3600).floor();
+ if (hours > 0) return "~$hours hour${hours > 1 ? "s" : ""}";
+ final minutes = (time / 60).toStringAsFixed(1);
+ if (minutes == "1.0") return "~1 minute";
+ return "~${minutes.endsWith(".0") ? (time / 60).floor() : minutes} minutes";
+}
+
+String sendFeeTime(
+ CryptoCurrency coin,
+ FeeObject rates,
+ FeeRateType feeRateType,
+) => estimatedTimeToBeIncludedInNextBlock(
+ coin.targetBlockTimeSeconds,
+ switch (feeRateType) {
+ FeeRateType.fast => rates.numberOfBlocksFast,
+ FeeRateType.slow => rates.numberOfBlocksSlow,
+ _ => rates.numberOfBlocksAverage,
+ },
+);
+
+/// Amount edits and balance switches ask again for a fee that failed or
+/// hangs.
+mixin SendFeeForm<T extends ConsumerStatefulWidget> on ConsumerState<T> {
+ late SendFeeRates fees;
+ Amount? feeAmount;
+ Amount? _typedFeeAmount;
+ Timer? _typing;
+ Object? _feeChoice;
+
+ bool get _isTyping => _typing?.isActive ?? false;
+
+ void followFeeAmount(Amount? amount) {
+ _typedFeeAmount = amount;
+ _typing?.cancel();
+ _typing = Timer(
+ const Duration(milliseconds: 500),
+ () => setFeeAmount(amount),
+ );
+ }
+
+ void setFeeAmount(Amount? amount) {
+ _typing?.cancel();
+ setState(() {
+ fees._retry();
+ feeAmount = amount;
+ });
+ }
+
+ void retryFee() => setFeeAmount(_isTyping ? _typedFeeAmount : feeAmount);
+
+ /// Leaving the amount [fields] applies the amount being typed at once.
+ void retryFeeOnFocusLoss(List<FocusNode> fields) {
+ for (final field in fields) {
+ field.addListener(() {
+ if (mounted && !fields.any((field) => field.hasFocus)) retryFee();
+ });
+ }
+ }
+
+ Future<Amount> watchFee() =>
+ fees.estimate(ref.watch, ref.watch(pFeeRateType), amount: feeAmount);
+
+ /// Null until the fee of [watchFee] arrives.
+ Amount? get shownFee => fees
+ ._estimates[fees._key(ref.read, ref.read(pFeeRateType), feeAmount)]
+ ?.value;
+
+ /// The form takes over the choice's fresh rates once the chosen fee arrives
+ /// at them, so a refresh that fails keeps the fee shown.
+ Future<void> chooseFee(
+ Future<void> Function(SendFeeRates fees, Amount? amount) show,
+ ) async {
+ if (_isTyping) setFeeAmount(_typedFeeAmount);
+ final choice = _feeChoice = Object();
+ final amount = feeAmount;
+ final refreshed = fees.refreshed();
+ await show(refreshed, amount);
+ final feeRateType = ref.read(pFeeRateType);
+ final chosen = await refreshed
+ .estimate(ref.read, feeRateType, amount: amount)
+ .then<Amount?>((fee) => fee, onError: (Object _) => null);
+ // The latest choice wins.
+ if (!mounted || !identical(_feeChoice, choice) || chosen == null) return;
+ // The Custom level has its fee before the rates arrive.
+ if (refreshed._rates?.value == null) return;
+ // The fee may follow another amount by now, and the same fee gains
+ // nothing.
+ if (fees._key(ref.read, feeRateType, amount) ==
+ fees._key(ref.read, feeRateType, feeAmount) &&
+ shownFee != chosen) {
+ setState(() => fees = refreshed);
+ }
+ }
+
+ @override
+ void dispose() {
+ _typing?.cancel();
+ super.dispose();
+ }
+}
### lib/wallets/wallet/impl/monero_wallet.dart
@@ -8,17 +8,23 @@ import '../../../wl_gen/interfaces/cs_salvium_interface.dart'
show WrappedWallet;
import '../../crypto_currency/crypto_currency.dart';
import '../intermediate/lib_monero_wallet.dart';
+import '../wallet_mixin_interfaces/sync_dependent_fee_estimate_interface.dart';
-class MoneroWallet extends LibMoneroWallet {
+class MoneroWallet extends LibMoneroWallet
+ implements SyncDependentFeeEstimateInterface {
MoneroWallet(CryptoCurrencyNetwork network)
: super(Monero(network), lib_monero_compat.WalletType.monero);
@override
bool get supportsMultiRecipient => true;
+ @override
+ bool get canEstimateFee =>
+ wallet != null && syncStatus is lib_monero_compat.SyncedSyncStatus;
+
@override
Future<Amount> estimateFeeFor(Amount amount, BigInt feeRate) async {
- if (wallet == null || syncStatus is! lib_monero_compat.SyncedSyncStatus) {
+ if (!canEstimateFee) {
return Amount.zeroWith(fractionDigits: cryptoCurrency.fractionDigits);
}
### lib/wallets/wallet/impl/wownero_wallet.dart
@@ -11,14 +11,20 @@ import '../../../wl_gen/interfaces/cs_wownero_interface.dart';
import '../../crypto_currency/crypto_currency.dart';
import '../../models/tx_data.dart';
import '../intermediate/lib_wownero_wallet.dart';
+import '../wallet_mixin_interfaces/sync_dependent_fee_estimate_interface.dart';
-class WowneroWallet extends LibWowneroWallet {
+class WowneroWallet extends LibWowneroWallet
+ implements SyncDependentFeeEstimateInterface {
WowneroWallet(CryptoCurrencyNetwork network)
: super(Wownero(network), lib_monero_compat.WalletType.wownero);
+ @override
+ bool get canEstimateFee =>
+ wallet != null && syncStatus is lib_monero_compat.SyncedSyncStatus;
+
@override
Future<Amount> estimateFeeFor(Amount amount, BigInt feeRate) async {
- if (wallet == null || syncStatus is! lib_monero_compat.SyncedSyncStatus) {
+ if (!canEstimateFee) {
return Amount.zeroWith(fractionDigits: cryptoCurrency.fractionDigits);
}
### lib/wallets/wallet/intermediate/cryptonote_wallet.dart
@@ -59,7 +59,5 @@ abstract class CryptonoteWallet<T extends CryptonoteCurrency>
Future<void> internalCommitTx(CsPendingTransaction tx);
// tx prio forwarding
- int getTxPriorityHigh();
- int getTxPriorityMedium();
int getTxPriorityNormal();
}
### lib/wallets/wallet/intermediate/lib_monero_wallet.dart
@@ -1485,12 +1485,6 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
)
: csMonero.getRefreshFromBlockHeight(wallet!);
- @override
- int getTxPriorityHigh() => csMonero.getTxPriorityHigh();
-
- @override
- int getTxPriorityMedium() => csMonero.getTxPriorityMedium();
-
@override
int getTxPriorityNormal() => csMonero.getTxPriorityNormal();
### lib/wallets/wallet/intermediate/lib_salvium_wallet.dart
@@ -1414,12 +1414,6 @@ abstract class LibSalviumWallet<T extends CryptonoteCurrency>
)
: csSalvium.getRefreshFromBlockHeight(wallet!);
- @override
- int getTxPriorityHigh() => csSalvium.getTxPriorityHigh();
-
- @override
- int getTxPriorityMedium() => csSalvium.getTxPriorityMedium();
-
@override
int getTxPriorityNormal() => csSalvium.getTxPriorityNormal();
### lib/wallets/wallet/intermediate/lib_wownero_wallet.dart
@@ -1426,12 +1426,6 @@ abstract class LibWowneroWallet<T extends CryptonoteCurrency>
)
: csWownero.getRefreshFromBlockHeight(wallet!);
- @override
- int getTxPriorityHigh() => csWownero.getTxPriorityHigh();
-
- @override
- int getTxPriorityMedium() => csWownero.getTxPriorityMedium();
-
@override
int getTxPriorityNormal() => csWownero.getTxPriorityNormal();
### lib/wallets/wallet/wallet_mixin_interfaces/sync_dependent_fee_estimate_interface.dart
@@ -0,0 +1,4 @@
+mixin SyncDependentFeeEstimateInterface {
+ /// The wallet estimates a zero fee while this is false.
+ bool get canEstimateFee;
+}
### lib/widgets/calculating_future_builder.dart
@@ -0,0 +1,42 @@
+import 'package:flutter/widgets.dart';
+
+import 'animated_text.dart';
+
+/// Shows "Calculating" until [future] answers.
+class CalculatingFutureBuilder<T extends Object> extends StatelessWidget {
+ const CalculatingFutureBuilder({
+ super.key,
+ required this.future,
+ required this.style,
+ required this.builder,
+ this.fallback,
+ });
+
+ final Future<T> future;
+ final TextStyle style;
+ final Widget Function(T answer) builder;
+
+ /// Built with when [future] fails.
+ final T? fallback;
+
+ @override
+ Widget build(BuildContext context) => FutureBuilder(
+ future: future,
+ builder: (_, snapshot) {
+ final answer = snapshot.connectionState == ConnectionState.done
+ ? snapshot.data ?? fallback
+ : null;
+ return answer == null
+ ? AnimatedText(
+ stringsToLoopThrough: const [
+ "Calculating",
+ "Calculating.",
+ "Calculating..",
+ "Calculating...",
+ ],
+ style: style,
+ )
+ : builder(answer);
+ },
+ );
+}
### lib/widgets/custom_buttons/blue_text_button.dart
@@ -147,7 +147,9 @@ class CustomTextButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return _CustomTextButton(
- key: UniqueKey(),
+ // The state starts from these, and is kept through other rebuilds so
+ // that a click in progress lasts.
+ key: ValueKey((enabled, Theme.of(context).extension<StackColors>()!)),
text: text,
enabledColor: Theme.of(context)
.extension<StackColors>()!
### lib/widgets/desktop/desktop_fee_dialog.dart
@@ -1,263 +1,53 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
-import '../../models/models.dart';
-import '../../pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart';
-import '../../providers/global/wallets_provider.dart';
import '../../providers/ui/fee_rate_type_state_provider.dart';
-import '../../providers/wallet/desktop_fee_providers.dart';
-import '../../providers/wallet/public_private_balance_state_provider.dart';
+import '../../providers/wallet/send_fee_providers.dart';
import '../../themes/stack_colors.dart';
import '../../utilities/amount/amount.dart';
import '../../utilities/amount/amount_formatter.dart';
import '../../utilities/enums/fee_rate_type_enum.dart';
import '../../utilities/text_styles.dart';
import '../../wallets/crypto_currency/crypto_currency.dart';
-import '../../wallets/isar/providers/eth/current_token_wallet_provider.dart';
-import '../../wallets/wallet/impl/firo_wallet.dart';
-import '../../wallets/wallet/intermediate/cryptonote_wallet.dart';
-import '../animated_text.dart';
+import '../calculating_future_builder.dart';
import '../conditional_parent.dart';
import 'desktop_dialog.dart';
import 'desktop_dialog_close_button.dart';
-class DesktopFeeDialog extends ConsumerStatefulWidget {
- const DesktopFeeDialog({
- super.key,
- required this.walletId,
- this.isToken = false,
- });
+class DesktopFeeDialog extends StatelessWidget {
+ const DesktopFeeDialog({super.key, required this.fees, required this.amount});
- final String walletId;
- final bool isToken;
-
- @override
- ConsumerState<DesktopFeeDialog> createState() => _DesktopFeeDialogState();
-}
-
-class _DesktopFeeDialogState extends ConsumerState<DesktopFeeDialog> {
- late final String walletId;
-
- FeeObject? feeObject;
- FeeRateType feeRateType = FeeRateType.average;
-
- Future<Amount> feeFor({
- required Amount amount,
- required FeeRateType feeRateType,
- required BigInt feeRate,
- required CryptoCurrency coin,
- }) async {
- switch (feeRateType) {
- case FeeRateType.fast:
- if (ref
- .read(
- widget.isToken
- ? tokenFeeSessionCacheProvider
- : feeSheetSessionCacheProvider,
- )
- .fast[amount] ==
- null) {
- if (widget.isToken == false) {
- final wallet = ref.read(pWallets).getWallet(walletId);
-
- if (wallet is CryptonoteWallet) {
- final fee = await wallet.estimateFeeFor(
- amount,
- BigInt.from(wallet.getTxPriorityHigh()),
- );
- ref.read(feeSheetSessionCacheProvider).fast[amount] = fee;
- } else if (coin is Firo) {
- final Amount fee;
- switch (ref.read(publicPrivateBalanceStateProvider.state).state) {
- case BalanceType.private:
- fee = await (wallet as FiroWallet).estimateFeeForSpark(
- amount,
- );
- case BalanceType.public:
- fee = await (wallet as FiroWallet).estimateFeeFor(
- amount,
- feeRate,
- );
- }
- ref.read(feeSheetSessionCacheProvider).fast[amount] = fee;
- } else {
- ref.read(feeSheetSessionCacheProvider).fast[amount] = await wallet
- .estimateFeeFor(amount, feeRate);
- }
- } else {
- final tokenWallet = ref.read(pCurrentTokenWallet)!;
- final fee = await tokenWallet.estimateFeeFor(amount, feeRate);
- ref.read(tokenFeeSessionCacheProvider).fast[amount] = fee;
- }
- }
- return ref
- .read(
- widget.isToken
- ? tokenFeeSessionCacheProvider
- : feeSheetSessionCacheProvider,
- )
- .fast[amount]!;
-
- case FeeRateType.average:
- if (ref
- .read(
- widget.isToken
- ? tokenFeeSessionCacheProvider
- : feeSheetSessionCacheProvider,
- )
- .average[amount] ==
- null) {
- if (widget.isToken == false) {
- final wallet = ref.read(pWallets).getWallet(walletId);
-
- if (wallet is CryptonoteWallet) {
- final fee = await wallet.estimateFeeFor(
- amount,
- BigInt.from(wallet.getTxPriorityMedium()),
- );
- ref.read(feeSheetSessionCacheProvider).average[amount] = fee;
- } else if (coin is Firo) {
- final Amount fee;
- switch (ref.read(publicPrivateBalanceStateProvider.state).state) {
- case BalanceType.private:
- fee = await (wallet as FiroWallet).estimateFeeForSpark(
- amount,
- );
- case BalanceType.public:
- fee = await (wallet as FiroWallet).estimateFeeFor(
- amount,
- feeRate,
- );
- }
- ref.read(feeSheetSessionCacheProvider).average[amount] = fee;
- } else {
- ref.read(feeSheetSessionCacheProvider).average[amount] =
- await wallet.estimateFeeFor(amount, feeRate);
- }
- } else {
- final tokenWallet = ref.read(pCurrentTokenWallet)!;
- final fee = await tokenWallet.estimateFeeFor(amount, feeRate);
- ref.read(tokenFeeSessionCacheProvider).average[amount] = fee;
- }
- }
- return ref
- .read(
- widget.isToken
- ? tokenFeeSessionCacheProvider
- : feeSheetSessionCacheProvider,
- )
- .average[amount]!;
-
- case FeeRateType.slow:
- if (ref
- .read(
- widget.isToken
- ? tokenFeeSessionCacheProvider
- : feeSheetSessionCacheProvider,
- )
- .slow[amount] ==
- null) {
- if (widget.isToken == false) {
- final wallet = ref.read(pWallets).getWallet(walletId);
-
- if (wallet is CryptonoteWallet) {
- final fee = await wallet.estimateFeeFor(
- amount,
- BigInt.from(wallet.getTxPriorityNormal()),
- );
- ref.read(feeSheetSessionCacheProvider).slow[amount] = fee;
- } else if (coin is Firo) {
- final Amount fee;
- switch (ref.read(publicPrivateBalanceStateProvider.state).state) {
- case BalanceType.private:
- fee = await (wallet as FiroWallet).estimateFeeForSpark(
- amount,
- );
- case BalanceType.public:
- fee = await (wallet as FiroWallet).estimateFeeFor(
- amount,
- feeRate,
- );
- }
- ref.read(feeSheetSessionCacheProvider).slow[amount] = fee;
- } else {
- ref.read(feeSheetSessionCacheProvider).slow[amount] = await wallet
- .estimateFeeFor(amount, feeRate);
- }
- } else {
- final tokenWallet = ref.read(pCurrentTokenWallet)!;
- final fee = await tokenWallet.estimateFeeFor(amount, feeRate);
- ref.read(tokenFeeSessionCacheProvider).slow[amount] = fee;
- }
- }
- return ref
- .read(
- widget.isToken
- ? tokenFeeSessionCacheProvider
- : feeSheetSessionCacheProvider,
- )
- .slow[amount]!;
- default:
- return Amount.zero;
- }
- }
-
- @override
- void initState() {
- walletId = widget.walletId;
- super.initState();
- }
+ final SendFeeRates fees;
+ final Amount? amount;
@override
Widget build(BuildContext context) {
return DesktopDialog(
maxWidth: 450,
maxHeight: double.infinity,
- child: FutureBuilder(
- future: ref.watch(
- pWallets.select((value) => value.getWallet(walletId).fees),
- ),
- builder: (context, snapshot) {
- if (snapshot.connectionState == ConnectionState.done &&
- snapshot.hasData) {
- feeObject = snapshot.data!;
- }
-
- return Column(
+ child: Column(
+ children: [
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Padding(
- padding: const EdgeInsets.only(left: 32),
- child: Text(
- "Choose fee",
- style: STextStyles.desktopH3(context),
- ),
- ),
- const DesktopDialogCloseButton(),
- ],
- ),
- ...FeeRateType.values.map(
- (e) => Padding(
- padding: const EdgeInsets.only(
- left: 32,
- right: 32,
- bottom: 16,
- ),
- child: DesktopFeeItem(
- feeObject: feeObject,
- feeRateType: e,
- walletId: walletId,
- feeFor: feeFor,
- isSelected: false,
- ),
+ Padding(
+ padding: const EdgeInsets.only(left: 32),
+ child: Text(
+ "Choose fee",
+ style: STextStyles.desktopH3(context),
),
),
- const SizedBox(height: 16),
+ const DesktopDialogCloseButton(),
],
- );
- },
+ ),
+ ...sendFeeRateTypes(fees.coin).map(
+ (e) => Padding(
+ padding: const EdgeInsets.only(left: 32, right: 32, bottom: 16),
+ child: DesktopFeeItem(fees: fees, feeRateType: e, amount: amount),
+ ),
+ ),
+ const SizedBox(height: 16),
+ ],
),
);
}
@@ -266,190 +56,82 @@ class _DesktopFeeDialogState extends ConsumerState<DesktopFeeDialog> {
class DesktopFeeItem extends ConsumerStatefulWidget {
const DesktopFeeItem({
super.key,
- required this.feeObject,
+ required this.fees,
required this.feeRateType,
- required this.walletId,
- required this.feeFor,
- required this.isSelected,
+ required this.amount,
this.isButton = true,
});
- final FeeObject? feeObject;
+ final SendFeeRates fees;
final FeeRateType feeRateType;
- final String walletId;
- final Future<Amount> Function({
- required Amount amount,
- required FeeRateType feeRateType,
- required BigInt feeRate,
- required CryptoCurrency coin,
- })
- feeFor;
- final bool isSelected;
+ final Amount? amount;
final bool isButton;
@override
ConsumerState<DesktopFeeItem> createState() => _DesktopFeeItemState();
}
class _DesktopFeeItemState extends ConsumerState<DesktopFeeItem> {
- String? feeString;
- String? timeString;
-
- static const stringsToLoopThrough = [
- "Calculating",
- "Calculating.",
- "Calculating..",
- "Calculating...",
- ];
-
- String estimatedTimeToBeIncludedInNextBlock(
- int targetBlockTime,
- int estimatedNumberOfBlocks,
- ) {
- final int time = targetBlockTime * estimatedNumberOfBlocks;
-
- final int hours = (time / 3600).floor();
- if (hours > 1) {
- return "~$hours hours";
- } else if (hours == 1) {
- return "~$hours hour";
- }
-
- // less than an hour
-
- final string = (time / 60).toStringAsFixed(1);
-
- if (string == "1.0") {
- return "~1 minute";
- } else {
- if (string.endsWith(".0")) {
- return "~${(time / 60).floor()} minutes";
- }
- return "~$string minutes";
- }
- }
-
@override
Widget build(BuildContext context) {
debugPrint("BUILD: $runtimeType : ${widget.feeRateType}");
+ final (fees, feeRateType) = (widget.fees, widget.feeRateType);
+ final colors = Theme.of(context).extension<StackColors>()!;
+ final style = STextStyles.desktopTextExtraExtraSmall(context)
+ .copyWith(color: colors.textFieldActiveText);
+ final coin = fees.coin;
+ final fee = feeRateType.isCustom
+ ? null
+ : fees.estimate(ref.watch, feeRateType, amount: widget.amount);
return ConditionalParent(
condition: widget.isButton,
builder: (child) => MaterialButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
onPressed: () {
- ref.read(feeRateTypeDesktopStateProvider.state).state =
- widget.feeRateType;
- Navigator.of(
- context,
- ).pop((widget.feeRateType, feeString, timeString));
+ ref.read(pFeeRateType.state).state = feeRateType;
+ Navigator.of(context).pop();
},
child: child,
),
- child: Builder(
- builder: (_) {
- if (widget.feeRateType == FeeRateType.custom) {
- return Row(
+ child: fee == null
+ ? Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
- widget.feeRateType.prettyName,
- style: STextStyles.desktopTextExtraExtraSmall(context)
- .copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldActiveText,
- ),
+ feeRateType.prettyName,
+ style: style,
textAlign: TextAlign.left,
),
],
- );
- }
-
- final wallet = ref.watch(
- pWallets.select((value) => value.getWallet(widget.walletId)),
- );
-
- if (widget.feeObject == null) {
- return AnimatedText(
- stringsToLoopThrough: stringsToLoopThrough,
- style: STextStyles.desktopTextExtraExtraSmall(context).copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldActiveText,
- ),
- );
- } else {
- return FutureBuilder(
- future: widget.feeFor(
- coin: wallet.info.coin,
- feeRateType: widget.feeRateType,
- feeRate: widget.feeRateType == FeeRateType.fast
- ? widget.feeObject!.fast
- : widget.feeRateType == FeeRateType.slow
- ? widget.feeObject!.slow
- : widget.feeObject!.medium,
- amount: ref.watch(sendAmountProvider.state).state,
- ),
- builder: (_, AsyncSnapshot<Amount> snapshot) {
- if (snapshot.connectionState == ConnectionState.done &&
- snapshot.hasData) {
- feeString =
- "${widget.feeRateType.prettyName} "
- "(~${ref.watch(pAmountFormatter(wallet.info.coin)).format(snapshot.data!, indicatePrecisionLoss: false)})";
-
- timeString = wallet.info.coin is Ethereum
- ? ""
- : estimatedTimeToBeIncludedInNextBlock(
- wallet.info.coin.targetBlockTimeSeconds,
- widget.feeRateType == FeeRateType.fast
- ? widget.feeObject!.numberOfBlocksFast
- : widget.feeRateType == FeeRateType.slow
- ? widget.feeObject!.numberOfBlocksSlow
- : widget.feeObject!.numberOfBlocksAverage,
- );
-
- return Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(
- feeString!,
- style: STextStyles.desktopTextExtraExtraSmall(context)
- .copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldActiveText,
- ),
- textAlign: TextAlign.left,
+ )
+ : FutureBuilder(
+ future: fees.rates,
+ builder: (_, rates) => CalculatingFutureBuilder(
+ future: fee,
+ style: style,
+ builder: (fee) => Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(
+ "${feeRateType.prettyName} "
+ "(~${ref.watch(pAmountFormatter(coin)).format(fee, indicatePrecisionLoss: false)})",
+ style: style,
+ textAlign: TextAlign.left,
+ ),
+ Text(
+ // A Spark fee shows while the fee rates load or fail.
+ coin is Ethereum || !rates.hasData
+ ? ""
+ : sendFeeTime(coin, rates.data!, feeRateType),
+ style: style.copyWith(
+ color: colors.textFieldActiveSearchIconRight,
),
- if (widget.feeObject != null)
- Text(
- timeString!,
- style: STextStyles.desktopTextExtraExtraSmall(context)
- .copyWith(
- color: Theme.of(context)
- .extension<StackColors>()!
- .textFieldActiveSearchIconRight,
- ),
- ),
- ],
- );
- } else {
- return AnimatedText(
- stringsToLoopThrough: stringsToLoopThrough,
- style: STextStyles.desktopTextExtraExtraSmall(context)
- .copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldActiveText,
- ),
- );
- }
- },
- );
- }
- },
- ),
+ ),
+ ],
+ ),
+ ),
+ ),
);
}
}
### test/pages/send_view/open_alias_preview_test.dart
@@ -113,12 +113,6 @@ class _Wallet extends Fake implements CryptonoteWallet {
slow: BigInt.one,
);
@override
- int getTxPriorityHigh() => 3;
- @override
- int getTxPriorityMedium() => 2;
- @override
- int getTxPriorityNormal() => 1;
- @override
Future<Amount> estimateFeeFor(Amount value, BigInt feeRate) async =>
amount(10);
@overrideWhy this scored 11/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.