cw-1443-error-handling (#3410)
What changed, and why it matters
This is a large code-quality and error-handling refactor across the Cake Wallet app. It replaces generic 'throw Exception(...)' calls with a new family of specific exception types (CakeException subclasses), adds a custom lint rule to prevent future generic exceptions, and makes related CI/build cleanups. The change does not introduce new user-facing features or, on its own, fix a known exploitable bug. It improves maintainability and lays groundwork for better error diagnostics, but because it is a broad refactor touching many wallet modules, any mistake could affect how errors are caught and displayed to users.
Treat as a normal code-quality refactor. Review that all pre-existing catch blocks that matched Exception still catch the new CakeException subclasses (CakeException implements Exception, so they should). Verify no security-sensitive error paths now expose extra data in exception messages. Run the full test suite and lint checks before release; monitor for regressions in wallet open/restore/transaction error flows.
Security signals we found
Broad refactor of exception types across 174 files; risk of changed catch clauses or UI error handling breaking silently
New custom lint rule discourages generic Exception, which can reduce accidental swallowing of security-relevant failures
Typed exceptions may improve future ability to distinguish authentication, network, and transaction failures
No direct cryptographic, input-validation, or access-control changes observed
No vendor security disclosure or CVE references present in commit or supplied materials
Evidence from the diff
The commit introduces a centralized exception hierarchy rooted at CakeException in cw_core/lib/exceptions/cake_exception.dart and migrates most wallet, node, transaction, hardware, and exchange code from dart:core Exception to typed subclasses (WalletNotFoundException, TransactionGenerationException, ServerResponseException, BadChainIdException, etc.). A custom lint (UseCakeExceptionRule) is added to cw_custom_lints to warn on throw Exception(…). Several existing exception classes were refactored to extend CakeException, and some error messages were made more specific. The diff also contains CI/build noise (lint.sh moves, gradle.properties whitespace, analysis_options cleanup).
Changed components
cw_core/lib/exceptions/cake_exception.dartcw_core/lib/exceptions.dartcw_custom_lints/lib/use_cake_exception/use_cake_exception_rule.dartcw_bitcoin, cw_bitcoin_cash, cw_decred, cw_dogecoin, cw_evm, cw_monero, cw_mweb, cw_nano, cw_solana, cw_tron, cw_wownero, cw_zano, cw_zcash wallet/service/client codelib/exchange, lib/buy, lib/cake_pay, lib/view_model error handlingCI lint configuration filesInspect captured patch +1208 / −659
### android/gradle.properties
@@ -2,4 +2,4 @@ org.gradle.jvmargs=-Xmx6144M
android.useAndroidX=true
android.enableJetifier=true
-android.ndk.suppressMinSdkVersionError=21
+android.ndk.suppressMinSdkVersionError=21
\ No newline at end of file
### cw_bitcoin/lib/bitcoin_transaction_priority.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:flutter/foundation.dart';
@@ -28,7 +29,7 @@ class BitcoinTransactionPriority extends TransactionPriority {
return custom;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for BitcoinTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for BitcoinTransactionPriority deserialize');
}
return medium;
}
@@ -88,7 +89,7 @@ class LitecoinTransactionPriority extends BitcoinTransactionPriority {
return fast;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for LitecoinTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for LitecoinTransactionPriority deserialize');
}
return medium;
}
@@ -141,7 +142,7 @@ class BitcoinCashTransactionPriority extends BitcoinTransactionPriority {
return fast;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for BitcoinCashTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for BitcoinCashTransactionPriority deserialize');
}
return medium;
}
### cw_bitcoin/lib/bitcoin_wallet.dart
@@ -31,6 +31,7 @@ import 'package:cw_bitcoin/psbt/v0_finalizer.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/output_info.dart';
import 'package:cw_core/payjoin_session.dart';
import 'package:cw_core/pending_transaction.dart';
@@ -665,7 +666,7 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
}
Future<void> commitPsbtUR(List<String> urCodes) async {
- if (urCodes.isEmpty) throw Exception("No QR code got scanned");
+ if (urCodes.isEmpty) throw ScanValueException("No QR code got scanned");
bool isUr = urCodes.any((str) {
return str.startsWith("ur:psbt/");
});
### cw_bitcoin/lib/bitcoin_wallet_service.dart
@@ -5,6 +5,7 @@ import 'package:cw_bitcoin/bitcoin_mnemonics_bip39.dart';
import 'package:cw_bitcoin/mnemonic_is_incorrect_exception.dart';
import 'package:cw_bitcoin/bitcoin_wallet_creation_credentials.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/payjoin_session.dart';
import 'package:cw_core/unspent_coins_info.dart';
import 'package:cw_core/utils/zpub.dart';
@@ -83,7 +84,7 @@ class BitcoinWalletService extends WalletService<
Future<BitcoinWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
final wallet = await BitcoinWalletBase.open(
@@ -117,7 +118,7 @@ class BitcoinWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
### cw_bitcoin/lib/electrum.dart
@@ -4,6 +4,7 @@ import 'dart:io';
import 'dart:typed_data';
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:cw_bitcoin/bitcoin_amount_format.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_socket/abstract.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
@@ -213,7 +214,7 @@ class ElectrumClient {
}
if (throwOnError) {
- throw Exception('Invalid response format for getBalance');
+ throw ElectrumResponseException('Invalid response format for getBalance');
}
return <String, dynamic>{};
### cw_bitcoin/lib/electrum_wallet.dart
@@ -5,7 +5,9 @@ import 'dart:math' show Random;
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:cw_bitcoin/lightning/lightning_addres_type.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_bitcoin/lightning/lightning_wallet.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_bitcoin/locktime.dart';
import 'package:cw_core/hardware/hardware_wallet_service.dart';
import 'package:cw_core/root_dir.dart';
@@ -185,7 +187,7 @@ abstract class ElectrumWalletBase
DerivationInfo? derivationInfo,
HardwareWalletType? hardwareWalletType) {
if (seedBytes == null && xpub == null) {
- throw Exception(
+ throw ArgumentError(
"To create a Wallet you need either a seed or an xpub. This should not happen");
}
@@ -204,7 +206,7 @@ abstract class ElectrumWalletBase
case CryptoCurrency.doge:
return dogecoinHDWallet(seedBytes);
default:
- throw Exception("Unsupported currency");
+ throw (currency == null ? ArgumentError("no currency") : BadCurrencyException("Unsupported currency",currency!));
}
}
@@ -1909,7 +1911,7 @@ abstract class ElectrumWalletBase
}
if (key == null) {
- throw Exception(error);
+ throw TransactionGenerationException(error);
}
if (utxo.utxo.isP2tr()) {
@@ -2472,7 +2474,7 @@ abstract class ElectrumWalletBase
.fold<int>(0, (sum, output) => sum + output.amount.toInt());
if (receiverAmount == 0) {
- throw Exception("Receiver output not found.");
+ throw RbfException("Receiver output not found.");
}
final availableInputs =
@@ -2485,7 +2487,7 @@ abstract class ElectrumWalletBase
final input = bundle.originalTransaction.inputs[i];
final inputTransaction = bundle.ins[i];
if (inputTransaction == null) {
- throw Exception("Missing input transaction for fee calculation");
+ throw RbfException("Missing input transaction for fee calculation");
}
final vout = input.txIndex;
final outTransaction = inputTransaction.outputs[vout];
@@ -2516,7 +2518,7 @@ abstract class ElectrumWalletBase
final input = bundle.originalTransaction.inputs[i];
final inputTransaction = bundle.ins[i];
if (inputTransaction == null) {
- throw Exception("Missing input transaction for replace-by-fee");
+ throw RbfException("Missing input transaction for replace-by-fee");
}
final vout = input.txIndex;
final outTransaction = inputTransaction.outputs[vout];
@@ -2558,7 +2560,7 @@ abstract class ElectrumWalletBase
memo = utf8.decode(HEX.decode(opReturnData));
continue;
} catch (_) {
- throw Exception('Cannot decode OP_RETURN data');
+ throw RbfException('Cannot decode OP_RETURN data');
}
}
}
@@ -2575,7 +2577,7 @@ abstract class ElectrumWalletBase
var remainingFee = BigInt.from(newFee - currentFee);
if (remainingFee <= BigInt.zero) {
- throw Exception("New fee must be higher than the current fee.");
+ throw ArgumentError("New fee must be higher than the current fee.");
}
// Deduct fee from change outputs first, if possible
@@ -2677,7 +2679,7 @@ abstract class ElectrumWalletBase
// Final check if the remaining fee couldn't be deducted
if (remainingFee > BigInt.zero) {
- throw Exception("Not enough funds to cover the fee.");
+ throw RbfException("Not enough funds to cover the fee.");
}
// Identify all change outputs
@@ -2709,7 +2711,7 @@ abstract class ElectrumWalletBase
final key =
privateKeys.firstWhereOrNull((element) => element.getPublic().toHex() == publicKey);
if (key == null) {
- throw Exception("Cannot find private key");
+ throw WalletKeysException("Cannot find private key");
}
if (utxo.utxo.isP2tr()) {
@@ -3007,7 +3009,7 @@ abstract class ElectrumWalletBase
_missingHistoryQueue.putIfAbsent(txid, () => item);
}
}
-
+
Future<void> resolveQueuedTransactionDetails() {
final inProgress = _resolveMissingHistoryFuture;
if (inProgress != null) return inProgress;
@@ -4562,7 +4564,7 @@ abstract class ElectrumWalletBase
);
if (result == null) {
- throw Exception('Call mechanism test returned null');
+ throw ElectrumResponseException('Call mechanism test returned null');
}
SocketHealthLogger().logHealthCheck(
### cw_bitcoin/lib/electrum_wallet_addresses.dart
@@ -8,8 +8,10 @@ import 'package:blockchain_utils/blockchain_utils.dart';
import 'package:breez_sdk_spark_flutter/breez_sdk_spark.dart';
import 'package:cw_bitcoin/bitcoin_address_record.dart';
import 'package:cw_bitcoin/bitcoin_unspent.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_bitcoin/lightning/lightning_addres_type.dart';
import 'package:cw_bitcoin/lightning/lightning_wallet.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_bitcoin/electrum_derivations.dart';
import 'package:cw_core/unspent_coin_type.dart';
@@ -22,13 +24,8 @@ import 'package:mobx/mobx.dart';
part 'electrum_wallet_addresses.g.dart';
-class UnsupportedAddressTypeForAccountException implements Exception {
- UnsupportedAddressTypeForAccountException(this.message);
-
- final String message;
-
- @override
- String toString() => message;
+class UnsupportedAddressTypeForAccountException extends CakeException {
+ UnsupportedAddressTypeForAccountException(super.message);
}
abstract class ElectrumWalletAddresses = ElectrumWalletAddressesBase with _$ElectrumWalletAddresses;
@@ -522,7 +519,7 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
@action
BaseBitcoinAddressRecord generateNewAddress({String label = ''}) {
if (addressPageType is LightningAddressType) {
- throw Exception("Lightning addresses cannot be rotated");
+ throw ArgumentError("Lightning addresses cannot be rotated");
}
if (addressPageType == SilentPaymentsAddresType.p2sp && silentAddress != null) {
### cw_bitcoin/lib/electrum_wallet_exceptions.dart
@@ -0,0 +1,43 @@
+import "package:cw_core/exceptions/cake_exception.dart";
+import 'package:bitcoin_base/bitcoin_base.dart';
+
+class RbfException extends CakeException {
+ const RbfException(super.message);
+}
+
+class WalletKeysException extends CakeException {
+ const WalletKeysException(super.message);
+}
+
+class ElectrumResponseException extends ServerResponseException {
+ const ElectrumResponseException(super.message);
+}
+
+class PayjoinException extends CakeException {
+ const PayjoinException(super.message);
+}
+
+class PayjoinSenderInitException extends PayjoinException {
+ const PayjoinSenderInitException(super.message);
+}
+
+class PayjoinReceiverInitException extends PayjoinException {
+ const PayjoinReceiverInitException(super.message);
+}
+
+
+class PayjoinSenderException extends PayjoinException {
+ const PayjoinSenderException(super.message);
+}
+
+
+class BadAddressTypeException extends CakeException {
+ const BadAddressTypeException(super.message, this.addressType);
+
+ final BitcoinAddressType addressType;
+}
+
+
+class PayjoinReceiverException extends PayjoinException {
+ const PayjoinReceiverException(super.message);
+}
\ No newline at end of file
### cw_bitcoin/lib/hardware/litecoin_trezor_service.dart
@@ -95,6 +95,6 @@ String _getScriptType(BitcoinAddressType addressType) {
case SegwitAddresType.p2wpkh:
return "PAYTOWITNESS";
default:
- throw Exception("Unknown Address Type");
+ throw ArgumentError("Unknown Address Type");
}
}
### cw_bitcoin/lib/lightning/lightning_wallet.dart
@@ -9,6 +9,7 @@ import 'package:cw_bitcoin/lightning/pending_lightning_transaction.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_direction.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
@@ -243,7 +244,7 @@ class LightningWallet {
return res.payment.id;
} on SdkError_SparkError catch (e) {
if (e.field0.contains("AlreadyExists")) {
- throw Exception("Invoice already paid");
+ throw TransactionSendingException("Invoice already paid");
}
rethrow;
}
### cw_bitcoin/lib/litecoin_wallet.dart
@@ -5,8 +5,10 @@ import 'package:collection/collection.dart';
import 'package:crypto/crypto.dart';
import 'package:cw_bitcoin/address_from_output.dart';
import 'package:cw_bitcoin/bitcoin_transaction_credentials.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/cake_hive.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/mweb_utxo.dart';
import 'package:cw_core/unspent_coin_type.dart';
import 'package:cw_core/utils/print_verbose.dart';
@@ -650,7 +652,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
await _utxoStream?.cancel();
ResponseStream<Utxo>? responseStream = await CwMweb.utxos(req);
if (responseStream == null) {
- throw Exception("failed to get utxos stream!");
+ throw ElectrumResponseException("failed to get utxos stream!");
}
_utxoStream = responseStream.listen(
(Utxo sUtxo) async {
@@ -1028,7 +1030,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
bool isMweb = spendsMweb || paysToMweb;
if (isMweb && !mwebEnabled) {
- throw Exception("MWEB is not enabled! can't calculate fee without starting the mweb server!");
+ throw ArgumentError("MWEB is not enabled! can't calculate fee without starting the mweb server!");
// TODO: likely the change address is mweb and just not updated
}
@@ -1222,7 +1224,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
int confirmations = coin.confirmations ?? 0;
if (confirmations < 6) {
- throw Exception(
+ throw TransactionGenerationException(
"A transaction input is an MWEB peg-out and has less than 6 confirmations, please try again later.");
}
}
@@ -1285,7 +1287,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
printV(s);
if (e.toString().contains("commit failed")) {
printV(e);
- throw Exception("Transaction commit failed (no peers responded), please try again.");
+ throw TransactionSendingException("Transaction commit failed (no peers responded), please try again.");
}
rethrow;
}
@@ -1321,7 +1323,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
}
Future<void> commitPsbtUR(List<String> urCodes) async {
- if (urCodes.isEmpty) throw Exception("No QR code got scanned");
+ if (urCodes.isEmpty) throw ScanValueException("No QR code got scanned");
bool isUr = urCodes.any((str) {
return str.startsWith("ur:psbt/");
});
@@ -1387,7 +1389,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
printV(s);
if (e.toString().contains("commit failed")) {
printV(e);
- throw Exception("Transaction commit failed (no peers responded), please try again.");
+ throw TransactionSendingException("Transaction commit failed (no peers responded), please try again.");
}
rethrow;
}
### cw_bitcoin/lib/litecoin_wallet_service.dart
@@ -3,6 +3,7 @@ import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:cw_bitcoin/bitcoin_mnemonics_bip39.dart';
import 'package:cw_bitcoin/mnemonic_is_incorrect_exception.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/unspent_coins_info.dart';
import 'package:hive/hive.dart';
import 'package:cw_bitcoin/bitcoin_mnemonic.dart';
@@ -67,7 +68,7 @@ class LitecoinWalletService extends WalletService<
Future<LitecoinWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
@@ -100,7 +101,7 @@ class LitecoinWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
### cw_bitcoin/lib/payjoin/manager.dart
@@ -7,6 +7,7 @@ import 'dart:typed_data';
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:cw_bitcoin/bitcoin_wallet.dart';
import 'package:cw_bitcoin/bitcoin_wallet_addresses.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_bitcoin/payjoin/payjoin_persister.dart';
import 'package:cw_bitcoin/payjoin/payjoin_receive_worker.dart';
import 'package:cw_bitcoin/payjoin/payjoin_send_worker.dart';
@@ -120,7 +121,7 @@ class PayjoinManager {
return Sender.load(token: senderToken, persister: persister);
} catch (e) {
- throw Exception('Error initializing Payjoin Sender: $e');
+ throw PayjoinSenderInitException('Error initializing Payjoin Sender: $e');
}
}
### cw_bitcoin/lib/payjoin/payjoin_persister.dart
@@ -1,3 +1,4 @@
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:payjoin_flutter/src/generated/api/receive.dart';
import 'package:payjoin_flutter/src/generated/api/send.dart';
@@ -21,7 +22,7 @@ class PayjoinSenderPersister implements DartSenderPersister {
Future<FfiSender> load({required SenderToken token}) async {
final sender = _store[token.toBytes().toString()];
if (sender == null) {
- throw Exception('Sender not found for the provided token.');
+ throw PayjoinSenderException('Sender not found for the provided token.');
}
return sender;
}
@@ -53,7 +54,7 @@ class PayjoinReceiverPersister implements DartReceiverPersister {
Future<FfiReceiver> load({required ReceiverToken token}) async {
final receiver = _store[token.toBytes().toString()];
if (receiver == null) {
- throw Exception('Receiver not found for the provided token.');
+ throw PayjoinReceiverException('Receiver not found for the provided token.');
}
return receiver;
}
### cw_bitcoin/lib/payjoin/payjoin_send_worker.dart
@@ -59,9 +59,9 @@ class PayjoinSenderWorker {
return await _runSenderV1(sender);
} else if (e is HttpException) {
printV(e);
- throw Exception(PayjoinSessionError.recoverable(e.toString()));
+ throw PayjoinSessionError.recoverable(e.toString());
} else {
- throw Exception(PayjoinSessionError.unrecoverable(e.toString()));
+ throw PayjoinSessionError.unrecoverable(e.toString());
}
}
}
### cw_bitcoin/lib/payjoin/payjoin_session_errors.dart
@@ -1,7 +1,7 @@
-class PayjoinSessionError {
- final String message;
+import "package:cw_core/exceptions/cake_exception.dart";
- const PayjoinSessionError._(this.message);
+class PayjoinSessionError extends CakeException{
+ const PayjoinSessionError._(super.message);
factory PayjoinSessionError.recoverable(String message) = RecoverableError;
factory PayjoinSessionError.unrecoverable(String message) = UnrecoverableError;
### cw_bitcoin/lib/psbt/signer.dart
@@ -6,6 +6,7 @@ import 'package:collection/collection.dart';
import 'package:cw_bitcoin/bitcoin_address_record.dart';
import 'package:cw_bitcoin/bitcoin_unspent.dart';
import 'package:cw_bitcoin/bitcoin_wallet.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_bitcoin/utils.dart';
import 'package:ledger_bitcoin/psbt.dart';
import 'package:ledger_bitcoin/src/utils/buffer_writer.dart';
@@ -113,7 +114,7 @@ extension PsbtSigner on PsbtV2 {
Script _findLockingScript(UtxoWithAddress utxo, bool isTaproot) {
if (utxo.isMultiSig()) {
- throw Exception("MultiSig is not supported yet");
+ throw UnimplementedError("MultiSig is not supported yet");
}
final senderPub = utxo.public();
@@ -159,7 +160,7 @@ extension PsbtSigner on PsbtV2 {
}
return senderPub.toRedeemScript();
}
- throw Exception("invalid bitcoin address type");
+ throw BadAddressTypeException("invalid bitcoin address type", utxo.utxo.scriptType);
}
}
@@ -189,7 +190,7 @@ class UtxoWithPrivateKey extends UtxoWithAddress {
ECPrivateInfo? key;
if (inputPrivateKeyInfos.isEmpty) {
- throw Exception("No private keys generated.");
+ throw WalletKeysException("No private keys generated.");
} else {
key = inputPrivateKeyInfos.firstWhereOrNull((element) {
final elemPubkey = element.privkey.getPublic().toHex();
@@ -202,7 +203,7 @@ class UtxoWithPrivateKey extends UtxoWithAddress {
}
if (key == null) {
- throw Exception("${input.utxo.txHash} No Key found");
+ throw WalletKeysException("${input.utxo.txHash} No Key found");
}
return UtxoWithPrivateKey(
### cw_bitcoin/lib/psbt/v0_deserialize.dart
@@ -1,5 +1,6 @@
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:blockchain_utils/blockchain_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:flutter/foundation.dart';
import 'package:ledger_bitcoin/psbt.dart';
import 'package:ledger_bitcoin/src/psbt/map_extension.dart';
@@ -9,9 +10,8 @@ import 'package:ledger_bitcoin/src/utils/uint8list_extension.dart' as ext;
extension PsbtSigner on PsbtV2 {
void deserializeV0(Uint8List psbt) {
final bufferReader = BufferReader(psbt);
- if (!listEquals(
- bufferReader.readSlice(5), Uint8List.fromList([0x70, 0x73, 0x62, 0x74, 0xff]))) {
- throw Exception("Invalid magic bytes");
+ if (!listEquals(bufferReader.readSlice(5), Uint8List.fromList([0x70, 0x73, 0x62, 0x74, 0xff]))) {
+ throw DeserializeException("Invalid magic bytes");
}
while (_readKeyPair(globalMap, bufferReader)) {}
### cw_bitcoin_cash/lib/src/bitcoin_cash_wallet_service.dart
@@ -4,6 +4,7 @@ import 'package:bip39/bip39.dart';
import 'package:cw_bitcoin/bitcoin_mnemonics_bip39.dart';
import 'package:cw_bitcoin_cash/cw_bitcoin_cash.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/unspent_coins_info.dart';
import 'package:cw_core/wallet_info.dart';
@@ -50,7 +51,7 @@ class BitcoinCashWalletService extends WalletService<
Future<BitcoinCashWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
@@ -83,7 +84,7 @@ class BitcoinCashWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
### cw_core/lib/amount/money.dart
@@ -192,9 +192,7 @@ class Money implements Comparable<Money> {
///
/// The result is again [Money].
Money operator /(BigInt other) {
- if (other == BigInt.zero) {
- throw Exception("Division by zero.");
- }
+ if (other == BigInt.zero) throw ArgumentError('Division by zero.');
final neg = (amount.isNegative) ^ (other.isNegative);
final A = amount.abs();
### cw_core/lib/currency_for_wallet_type.dart
@@ -1,4 +1,5 @@
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_type.dart';
CryptoCurrency walletTypeToCryptoCurrency(WalletType type, {bool isTestnet = false, int? chainId}) {
@@ -51,8 +52,8 @@ CryptoCurrency walletTypeToCryptoCurrency(WalletType type, {bool isTestnet = fal
case WalletType.zcash:
return CryptoCurrency.zec;
case WalletType.none:
- throw Exception(
- 'Unexpected wallet type: ${type.toString()} for CryptoCurrency walletTypeToCryptoCurrency');
+ throw BadWalletTypeException(
+ 'Unexpected wallet type: ${type.toString()} for CryptoCurrency walletTypeToCryptoCurrency', type);
}
}
### cw_core/lib/db/sqlite.dart
@@ -1,6 +1,7 @@
import "dart:io";
import "package:cw_core/db/sqlite_debug.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
import "package:cw_core/root_dir.dart";
import "package:cw_core/utils/print_verbose.dart";
import "package:cw_core/wallet_type.dart";
@@ -32,6 +33,10 @@ Future<File> sqliteDebugMarkerFile() async {
return File(dbDebugMarker);
}
+class DebugMarkerException extends CakeException {
+ const DebugMarkerException() : super("Debug marker is present");
+}
+
Future<void> initDb({String? pathOverride}) async {
if (!kDebugMode && !kProfileMode) {
await _initDb(pathOverride: pathOverride);
@@ -40,7 +45,7 @@ Future<void> initDb({String? pathOverride}) async {
final dbDebugMarker = await sqliteDebugMarkerFile();
try {
if (dbDebugMarker.existsSync()) {
- throw Exception("Debug marker is present");
+ throw const DebugMarkerException();
}
await _initDb(pathOverride: pathOverride);
} catch (e, s) {
### cw_core/lib/enumerable_item.dart
@@ -9,6 +9,6 @@ abstract class EnumerableItem<T> {
}
mixin Serializable<T> on EnumerableItem<T> {
- static Serializable deserialize<T>({required T raw}) => throw Exception('Unimplemented');
+ static Serializable deserialize<T>({required T raw}) => throw UnimplementedError();
T serialize() => raw;
}
### cw_core/lib/exceptions.dart
@@ -1,89 +1,121 @@
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class TransactionWrongBalanceException extends TransactionGenerationException {
+ TransactionWrongBalanceException(this.currency, {this.amount}) : super( "wrong balance: ${currency.symbol} $amount");
-class TransactionWrongBalanceException implements Exception {
- TransactionWrongBalanceException(this.currency, {this.amount});
final CryptoCurrency currency;
final int? amount;
}
-class TransactionNoInputsException implements Exception {}
+class TransactionNoInputsException extends TransactionGenerationException {
-class TransactionNoFeeException implements Exception {}
+ TransactionNoInputsException() : super("Not enough inputs available. Please select more under Coin Control");
-class TransactionNoDustException implements Exception {}
+}
+class TransactionNoFeeException extends TransactionGenerationException {
+ TransactionNoFeeException() : super("cannot send with zero fee");
+}
-class TransactionNoDustOnChangeException implements Exception {
- TransactionNoDustOnChangeException(this.max, this.min);
+class TransactionNoDustException extends TransactionGenerationException {
+ TransactionNoDustException()
+ : super("The transaction is rejected by sending an amount too small. Please try increasing the amount.");
+}
+class TransactionNoDustOnChangeException extends TransactionGenerationException {
final String max;
final String min;
+
+ TransactionNoDustOnChangeException(this.max, this.min)
+ : super("The transaction is rejected with this amount. With these coins you can send ${min} without change or ${max} that returns change.");
}
-class TransactionCommitFailed implements Exception {
+class TransactionCommitFailed extends TransactionSendingException {
final String? errorMessage;
- TransactionCommitFailed({this.errorMessage});
-
- @override
- String toString() => errorMessage ?? "unknown error";
+ TransactionCommitFailed({this.errorMessage}) : super(errorMessage ?? "unknown error");
}
-class TransactionCommitFailedDustChange implements Exception {}
+class TransactionCommitFailedDustChange extends TransactionSendingException {
+ TransactionCommitFailedDustChange()
+ : super("Transaction rejected by network rules, low change amount (dust). Try sending ALL or reducing the amount.");
+}
-class TransactionCommitFailedDustOutput implements Exception {}
+class TransactionCommitFailedDustOutput extends TransactionSendingException {
+ TransactionCommitFailedDustOutput()
+ : super("Transaction rejected by network rules, low output amount (dust). Please increase the amount.");
+}
-class TransactionCommitFailedDustOutputSendAll implements Exception {}
+class TransactionCommitFailedDustOutputSendAll extends TransactionSendingException {
+ TransactionCommitFailedDustOutputSendAll()
+ : super("Transaction rejected by network rules, low output amount (dust). Please check the balance of coins selected under Coin Control.");
+}
-class TransactionCommitFailedVoutNegative implements Exception {}
+class TransactionCommitFailedVoutNegative extends TransactionSendingException {
+ TransactionCommitFailedVoutNegative()
+ : super("Not enough balance to pay for this transaction's fees. Please check the balance of coins under Coin Control.");
+}
-class TransactionCommitFailedBIP68Final implements Exception {}
+class TransactionCommitFailedBIP68Final extends TransactionSendingException {
+ TransactionCommitFailedBIP68Final()
+ : super("Transaction has unconfirmed inputs and failed to replace by fee.");
+}
-class TransactionCommitFailedLessThanMin implements Exception {}
+class TransactionCommitFailedLessThanMin extends TransactionSendingException {
+ TransactionCommitFailedLessThanMin()
+ : super("Selected Fee is less than the minimum, please increase the fees to be able to send the transaction");
+}
-class TransactionInputNotSupported implements Exception {}
+class TransactionInputNotSupported extends TransactionSendingException {
+ TransactionInputNotSupported()
+ : super("You are using the wrong input type for this type of payment");
+}
-class SignNativeTokenTransactionRentException implements Exception {}
+class SignNativeTokenTransactionRentException extends TransactionGenerationException {
+ SignNativeTokenTransactionRentException()
+ : super("Transaction cannot be completed. Insufficient SOL left for rent after transaction. Kindly top up your SOL balance or reduce the amount of SOL you are sending.");
+}
-class CreateAssociatedTokenAccountException implements Exception {
+class CreateAssociatedTokenAccountException extends CakeException {
final String errorMessage;
- CreateAssociatedTokenAccountException(this.errorMessage);
+ CreateAssociatedTokenAccountException(this.errorMessage)
+ : super("Error creating associated token account for receipient address. " + errorMessage);
}
-class SignSPLTokenTransactionRentException implements Exception {}
+class SignSPLTokenTransactionRentException extends CakeException {
+ SignSPLTokenTransactionRentException()
+ : super("Transaction cannot be completed. Insufficient SOL left for rent after transaction. Kindly top up your SOL balance.");
+}
-class NoAssociatedTokenAccountException implements Exception {}
+class NoAssociatedTokenAccountException extends CakeException {
+ NoAssociatedTokenAccountException()
+ : super("There is no associated token account for this address.");
+}
-class NotAnNFTException implements Exception {}
+class NotAnNFTException extends CakeException {
+ NotAnNFTException() : super("Not an NFT.");
+}
-class AmbiguousTokenSymbolException implements Exception {
- AmbiguousTokenSymbolException(this.symbol);
+class AmbiguousTokenSymbolException extends CakeException {
+ AmbiguousTokenSymbolException(this.symbol) : super("Ambigous token: $symbol");
final String symbol;
}
-class RestoreFromSeedException implements Exception {
- final String message;
-
- RestoreFromSeedException(this.message);
+class RestoreFromSeedException extends CakeException {
+ RestoreFromSeedException(String message) : super(message);
}
-class WalletDeprecationException implements Exception {
+class WalletDeprecationException extends CakeException {
final String seed;
final CryptoCurrency curr;
- @override
- String toString() => "Wallet type no longer supported";
-
- WalletDeprecationException({required this.seed, required this.curr});
+ WalletDeprecationException({required this.seed, required this.curr})
+ : super("Wallet type no longer supported");
}
-class WalletSwitchException implements Exception {
- WalletSwitchException(this.message);
-
- final String message;
-
- @override
- String toString() => message;
+class WalletSwitchException extends CakeException {
+ WalletSwitchException(super.message);
}
### cw_core/lib/exceptions/cake_exception.dart
@@ -0,0 +1,122 @@
+
+import "package:cw_core/currency.dart";
+import "package:cw_core/wallet_type.dart";
+
+abstract class CakeException implements Exception {
+ const CakeException(this.message);
+
+ final String message;
+
+ @override
+ String toString() => message;
+}
+
+class BadWalletTypeException extends CakeException {
+ const BadWalletTypeException(super.message, this.walletType);
+
+ final WalletType walletType;
+}
+
+class BadCurrencyException extends CakeException {
+
+ const BadCurrencyException(super.message, this.curr);
+ final Currency curr;
+}
+
+class BadCurrencyPairException extends CakeException {
+ const BadCurrencyPairException(super.message, this.from, this.to);
+
+ final Currency from;
+ final Currency to;
+}
+
+class ConnectionException extends CakeException {
+ const ConnectionException(super.message);
+}
+
+class ServerResponseException extends CakeException {
+ const ServerResponseException(super.message);
+}
+
+mixin ResponseCodeException {
+ int get code;
+}
+
+class CurrencyParseException extends CakeException {
+ const CurrencyParseException(super.message);
+}
+
+class DeserializeException extends CakeException {
+ const DeserializeException(super.message);
+}
+
+class WalletOpenException extends CakeException {
+ const WalletOpenException(super.message);
+}
+
+class WalletExistsException extends CakeException {
+ const WalletExistsException(super.message);
+}
+
+class WalletNotFoundException extends WalletOpenException {
+ const WalletNotFoundException({this.type, required this.name})
+ : super("Wallet not found");
+
+ final WalletType? type;
+ final String name;
+}
+
+class AccountNotFoundException extends CakeException {
+ const AccountNotFoundException(String name)
+ : name = name,
+ super("Account not found: $name");
+ final String name;
+}
+
+class WalletCreationException extends CakeException {
+ const WalletCreationException(super.message);
+}
+
+class BadWalletDataException extends WalletCreationException {
+ const BadWalletDataException(super.message);
+}
+
+class BadKeysException extends BadWalletDataException {
+ const BadKeysException(super.message);
+}
+
+class BadMnemonicException extends BadWalletDataException {
+ const BadMnemonicException(super.message);
+}
+
+class TransactionGenerationException extends CakeException {
+ const TransactionGenerationException(super.message);
+}
+
+class TransactionSendingException extends CakeException {
+ const TransactionSendingException(super.message);
+}
+
+class ScanValueException extends CakeException {
+ const ScanValueException(super.message);
+}
+
+class NodeLookupException extends CakeException {
+ const NodeLookupException(super.message);
+}
+
+class BadChainIdException extends CakeException {
+ const BadChainIdException(super.message);
+}
+
+class MessageSignException extends CakeException {
+ const MessageSignException(super.message);
+}
+
+class HardwareWalletNotConnectedException extends CakeException {
+ const HardwareWalletNotConnectedException(super.message);
+}
+
+class HardwareWalletResponseException extends CakeException {
+ const HardwareWalletResponseException(super.message);
+}
\ No newline at end of file
### cw_core/lib/get_height_by_date.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:intl/intl.dart';
import 'package:cw_core/get_height_by_date_xmr.dart';
@@ -95,7 +96,7 @@ Future<int> getHavenCurrentHeight() async {
final info = jsonDecode(stringResponse);
return info['data']['height'] as int;
} else {
- throw Exception('Failed to load current blockchain height');
+ throw ServerResponseException('Failed to load current blockchain height');
}
}
### cw_core/lib/lnurl.dart
@@ -3,11 +3,16 @@ import "dart:convert";
import "package:bech32/bech32.dart";
import "package:cw_core/amount/money.dart";
import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
import "package:cw_core/utils/proxy_wrapper.dart";
const _BOLT_PREFIXES = ["lnbcrt", "lntbs", "lnbc", "lntb"];
const _LUD17_PREFIXES = ["lnurlw", "lnurlc", "lnurlp", "keyauth"];
+class Bech32EncodeException extends CakeException {
+ const Bech32EncodeException(super.message);
+}
+
bool isBolt11ZeroInvoice(String invoice) {
try {
final request =
@@ -258,10 +263,10 @@ List<int> _convert(List<int> data, int inBits, int outBits, bool pad) {
}
} else {
if (bits >= inBits) {
- throw Exception("[BECH32] Excess padding");
+ throw Bech32EncodeException("Excess padding");
}
if ((value << (outBits - bits)) & maxV > 0) {
- throw Exception("[BECH32] Non-zero padding");
+ throw Bech32EncodeException("Non-zero padding");
}
}
### cw_core/lib/monero_transaction_priority.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:flutter/foundation.dart';
@@ -32,7 +33,7 @@ class MoneroTransactionPriority extends TransactionPriority {
return fastest;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for MoneroTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for MoneroTransactionPriority deserialize');
}
return medium;
}
### cw_core/lib/node.dart
@@ -3,6 +3,7 @@ import 'dart:io';
import 'dart:math' as math;
import 'package:blockchain_utils/hex/hex.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node_list.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_socket/abstract.dart';
@@ -301,7 +302,7 @@ class Node {
return Uri.parse(
"http${isSSL ? "s" : ""}://$uriRaw${path!.startsWith("/") || path!.isEmpty ? path : "/$path"}");
case WalletType.none:
- throw Exception('Unexpected type ${type.toString()} for Node uri');
+ throw BadWalletTypeException('Unexpected type ${type.toString()} for Node uri', type);
}
}
@@ -515,7 +516,7 @@ class Node {
data["error"] != null ||
data["balance"] == null ||
data["receivable"] == null) {
- throw Exception(
+ throw ServerResponseException(
"Error while trying to get balance! ${data["error"] != null ? data["error"] : ""}");
}
return true;
@@ -663,7 +664,7 @@ class DaemonRpc {
if (initialResponse.statusCode != 401 ||
!initialResponse.headers.containsKey('www-authenticate')) {
- throw Exception('Unexpected response: ${initialResponse.body}');
+ throw ServerResponseException('Unexpected response: ${initialResponse.body}');
}
// Extract Digest details from `WWW-Authenticate` header.
@@ -690,13 +691,13 @@ class DaemonRpc {
);
if (authenticatedResponse.statusCode != 200) {
- throw Exception('RPC call failed: ${authenticatedResponse.body}');
+ throw ServerResponseException('RPC call failed: ${authenticatedResponse.body}');
}
final Map<String, dynamic> result =
jsonDecode(authenticatedResponse.body) as Map<String, dynamic>;
if (result['error'] != null) {
- throw Exception('RPC Error: ${result['error']}');
+ throw ServerResponseException('RPC Error: ${result['error']}');
}
return result['result'] as Map<String, dynamic>;
### cw_core/lib/pathForWallet.dart
@@ -1,4 +1,5 @@
import 'dart:io';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/root_dir.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:path/path.dart' as p;
@@ -47,11 +48,11 @@ Future<void> copyWalletFilesTo({
final typeRoot = await pathForWalletTypeDir(type: type);
final sourceDir = Directory(p.join(typeRoot, fromName));
if (!sourceDir.existsSync()) {
- throw "Source wallet not found: $fromName $type";
+ throw WalletNotFoundException(name: fromName, type: type);
}
if (Directory(p.join(typeRoot, toName)).existsSync()) {
- throw Exception('Cannot rename wallet: "$toName" already exists');
+ throw WalletExistsException('Cannot rename wallet: "$toName" already exists');
}
final destinationDir = Directory(p.join(typeRoot, toName));
### cw_core/lib/transaction_direction.dart
@@ -1,3 +1,5 @@
+import "package:cw_core/exceptions/cake_exception.dart";
+
enum TransactionDirection { incoming, outgoing }
TransactionDirection parseTransactionDirectionFromInt(int raw) {
@@ -7,8 +9,7 @@ TransactionDirection parseTransactionDirectionFromInt(int raw) {
case 1:
return TransactionDirection.outgoing;
default:
- throw Exception(
- 'Unexpected token: raw for TransactionDirection parseTransactionDirectionFromInt');
+ throw DeserializeException('Unexpected token: raw for TransactionDirection parseTransactionDirectionFromInt');
}
}
@@ -19,7 +20,6 @@ TransactionDirection parseTransactionDirectionFromNumber(String raw) {
case "1":
return TransactionDirection.outgoing;
default:
- throw Exception(
- 'Unexpected token: raw for TransactionDirection parseTransactionDirectionFromNumber');
+ throw DeserializeException('Unexpected token: raw for TransactionDirection parseTransactionDirectionFromNumber');
}
}
### cw_core/lib/utils/proxy_wrapper.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/proxy_logger/abstract.dart';
import 'package:cw_core/utils/proxy_socket/abstract.dart';
import 'package:cw_core/utils/tor/abstract.dart';
@@ -213,7 +214,7 @@ class ProxyWrapper {
}
}
- throw Exception("Unable to connect to server");
+ throw ConnectionException("Unable to connect to server");
}
Future<Response> post({
@@ -293,7 +294,7 @@ class ProxyWrapper {
}
}
- throw Exception("Unable to connect to server");
+ throw ConnectionException("Unable to connect to server");
}
Future<Response> put({
@@ -360,7 +361,7 @@ class ProxyWrapper {
}
}
- throw Exception("Unable to connect to server");
+ throw ConnectionException("Unable to connect to server");
}
Future<Response> delete({
@@ -432,7 +433,7 @@ class ProxyWrapper {
}
}
- throw Exception("Unable to connect to server");
+ throw ConnectionException("Unable to connect to server");
}
}
### cw_core/lib/wallet_keys_file.dart
@@ -4,6 +4,7 @@ import 'dart:io';
import 'package:cw_core/balance.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/transaction_info.dart';
@@ -69,7 +70,7 @@ mixin WalletKeysFile<BalanceType extends Balance, HistoryType extends Transactio
var readPath = "$path.keys";
try {
- if (!File(readPath).existsSync()) throw Exception("No .keys file found for $name $type");
+ if (!File(readPath).existsSync()) throw WalletOpenException("No .keys file found for $name $type");
final jsonSource = await encryptionFileUtils.read(path: readPath, password: password);
final data = json.decode(jsonSource) as Map<String, dynamic>;
@@ -79,7 +80,7 @@ mixin WalletKeysFile<BalanceType extends Balance, HistoryType extends Transactio
readPath = "$readPath.backup";
if (!File(readPath).existsSync())
- throw Exception("No .keys nor a .keys.backup file found for $name $type");
+ throw WalletOpenException("No .keys nor a .keys.backup file found for $name $type");
final jsonSource = await encryptionFileUtils.read(path: readPath, password: password);
final data = json.decode(jsonSource) as Map<String, dynamic>;
### cw_core/lib/wallet_service.dart
@@ -13,6 +13,7 @@ import 'package:cw_core/wallet_credentials.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:path/path.dart' as p;
+import "package:cw_core/exceptions/cake_exception.dart";
abstract class WalletService<N extends WalletCredentials, RFS extends WalletCredentials,
RFK extends WalletCredentials, RFH extends WalletCredentials> {
@@ -39,7 +40,7 @@ abstract class WalletService<N extends WalletCredentials, RFS extends WalletCred
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception("Wallet not found");
+ throw WalletNotFoundException(name: currentName, type: getType());
}
await copyWalletFilesTo(fromName: currentName, toName: newName, type: getType());
### cw_core/lib/wallet_type.dart
@@ -1,4 +1,5 @@
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/hive_type_ids.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:hive/hive.dart';
@@ -199,7 +200,7 @@ WalletType deserializeFromInt(int raw) {
case 19:
return WalletType.robinhood;
default:
- throw Exception('Unexpected token: $raw for WalletType deserializeFromInt');
+ throw DeserializeException('Unexpected token: $raw for WalletType deserializeFromInt');
}
}
### cw_core/test/amount/money_test.dart
@@ -265,7 +265,7 @@ void main() {
test("throws Exception on division by zero", () {
expect(
() => Money(BigInt.from(5), CryptoCurrency.btc) / BigInt.zero,
- throwsA(isA<Exception>()),
+ throwsA(isA<ArgumentError>()),
);
});
### cw_custom_lints/lib/main.dart
@@ -8,6 +8,7 @@ import "package:cw_custom_lints/money_amount_to_string/money_amount_to_string_ru
import "package:cw_custom_lints/print_verbose/print_verbose_fix.dart";
import "package:cw_custom_lints/print_verbose/print_verbose_rule.dart";
import "package:cw_custom_lints/restricted_imports/restricted_imports_rule.dart";
+import "package:cw_custom_lints/use_cake_exception/use_cake_exception_rule.dart";
final plugin = CwCustomLintsPlugin();
@@ -23,6 +24,7 @@ class CwCustomLintsPlugin extends Plugin {
registry.registerWarningRule(ModernButtonSemanticsRule());
registry.registerWarningRule(ModalTopBarSemanticsRule());
registry.registerWarningRule(MoneyAmountToStringRule());
+ registry.registerWarningRule(UseCakeExceptionRule());
registry.registerFixForRule(PrintVerboseRule.code, ReplaceWithPrintV.new);
registry.registerFixForRule(MoneyAmountToStringRule.code, ReplaceWithMoneyToString.new);
### cw_custom_lints/lib/use_cake_exception/use_cake_exception_rule.dart
@@ -0,0 +1,51 @@
+import "package:analyzer/analysis_rule/analysis_rule.dart";
+import "package:analyzer/analysis_rule/rule_context.dart";
+import "package:analyzer/analysis_rule/rule_visitor_registry.dart";
+import "package:analyzer/dart/ast/ast.dart";
+import "package:analyzer/dart/ast/visitor.dart";
+import "package:analyzer/error/error.dart";
+
+class UseCakeExceptionRule extends AnalysisRule {
+ UseCakeExceptionRule()
+ : super(name: "use_cake_exception", description: "please use a CakeException subclass instead");
+
+ static const LintCode code = LintCode(
+ "use_cake_exception",
+ "please use a CakeException subclass instead",
+ severity: DiagnosticSeverity.WARNING,
+ );
+
+ @override
+ LintCode get diagnosticCode => code;
+
+ @override
+ void registerNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
+ registry.addThrowExpression(this, _Visitor(this));
+ }
+}
+
+class _Visitor extends SimpleAstVisitor<void> {
+ _Visitor(this.rule);
+
+ final AnalysisRule rule;
+
+ @override
+ void visitThrowExpression(ThrowExpression node) {
+ final thrown = node.expression;
+ if (thrown is! InstanceCreationExpression) {
+ return;
+ }
+
+ final type = thrown.constructorName.type;
+ if (type.name.lexeme != "Exception") {
+ return;
+ }
+
+ final library = type.element?.library;
+ if (library != null && !library.isDartCore) {
+ return;
+ }
+
+ rule.reportAtNode(node);
+ }
+}
### cw_decred/lib/api/libdcrwallet.dart
@@ -634,7 +634,9 @@ class Libwallet {
// nothing.
return null;
}
- checkErr(res.err);
+ if(res.err.isNotEmpty) {
+ throw DecredPayloadExecutionException(res.err);
+ }
return res.payload;
}
### cw_decred/lib/api/util.dart
@@ -1,4 +1,5 @@
import 'dart:ffi';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:ffi/ffi.dart';
import 'dart:convert';
@@ -10,6 +11,10 @@ class PayloadResult {
const PayloadResult(this.payload, this.err, this.errCode);
}
+class DecredPayloadExecutionException extends CakeException {
+ const DecredPayloadExecutionException(super.message);
+}
+
// Executes the provided fn and converts the string response to a PayloadResult.
// Returns payload, error code, and error.
PayloadResult executePayloadFn({
@@ -19,12 +24,12 @@ PayloadResult executePayloadFn({
}) {
final jsonStr = fn().toDartString();
freePointers(ptrsToFree);
- if (jsonStr == null) throw Exception("no json return from wallet library");
+ if (jsonStr == null) throw DecredPayloadExecutionException("no json return from wallet library");
final decoded = json.decode(jsonStr);
final err = decoded["error"] ?? "";
- if (!skipErrorCheck) {
- checkErr(err);
+ if (!skipErrorCheck && (err as String? ?? "").isNotEmpty) {
+ throw DecredPayloadExecutionException(err as String);
}
final payload = decoded["payload"] ?? "";
@@ -38,10 +43,6 @@ void freePointers(List<Pointer> ptrsToFree) {
}
}
-void checkErr(String err) {
- if (err == "") return;
- throw Exception(err);
-}
extension StringUtil on String {
Pointer<Char> toCString() => toNativeUtf8().cast<Char>();
### cw_decred/lib/transaction_priority.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:flutter/foundation.dart';
@@ -21,7 +22,7 @@ class DecredTransactionPriority extends TransactionPriority {
return fast;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for DecredTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for DecredTransactionPriority deserialize');
}
return medium;
}
### cw_decred/lib/wallet_service.dart
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:bip39/bip39.dart' as bip39;
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/wallet_keys_file.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_decred/api/libdcrwallet.dart';
import 'package:cw_decred/mnemonic_validation.dart';
import 'package:cw_decred/wallet_creation_credentials.dart';
@@ -133,7 +134,7 @@ class DecredWalletService extends WalletService<
Future<DecredWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
final di = await walletInfo.getDerivationInfo();
if (walletInfo.network == null || walletInfo.network == "") {
@@ -182,7 +183,7 @@ class DecredWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
}
@@ -191,7 +192,7 @@ class DecredWalletService extends WalletService<
Future<void> rename(String currentName, String password, String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName, type: getType());
}
final di = await currentWalletInfo.getDerivationInfo();
final network =
### cw_dogecoin/lib/src/dogecoin_transaction_priority.dart
@@ -1,5 +1,7 @@
import 'package:cw_bitcoin/bitcoin_transaction_priority.dart';
import 'package:flutter/foundation.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
+
class DogecoinTransactionPriority extends BitcoinTransactionPriority {
const DogecoinTransactionPriority({required String title, required int raw})
@@ -23,7 +25,7 @@ class DogecoinTransactionPriority extends BitcoinTransactionPriority {
return fast;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for DogecoinTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for DogecoinTransactionPriority deserialize');
}
return medium;
}
### cw_dogecoin/lib/src/dogecoin_wallet_service.dart
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:bip39/bip39.dart';
import 'package:cw_bitcoin/bitcoin_mnemonics_bip39.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/unspent_coins_info.dart';
import 'package:cw_core/wallet_info.dart';
@@ -51,7 +52,7 @@ class DogeCoinWalletService extends WalletService<
Future<DogeCoinWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
final wallet = await DogeCoinWalletBase.open(
@@ -83,7 +84,7 @@ class DogeCoinWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
@@ -114,7 +115,7 @@ class DogeCoinWalletService extends WalletService<
Future<DogeCoinWallet> restoreFromSeed(DogeCoinRestoreWalletFromSeedCredentials credentials,
{bool? isTestnet}) async {
if (!validateMnemonic(credentials.mnemonic)) {
- throw Exception('Invalid mnemonic: ${credentials.mnemonic}');
+ throw BadMnemonicException('Invalid mnemonic: ${credentials.mnemonic}');
}
final wallet = await DogeCoinWalletBase.create(
### cw_evm/lib/clients/evm_chain_client.dart
@@ -5,6 +5,7 @@ import 'dart:developer';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/erc20_token.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
@@ -547,12 +548,12 @@ class EVMChainClient {
return EVMChainERC20Balance(Money(balance, token));
} on RangeError catch (_) {
- throw Exception('Invalid token contract for this network.');
+ throw BadCurrencyException('Invalid token contract for this network.', token);
} catch (e) {
if (e.toString().contains("hostUnreachable")) {
return EVMChainERC20Balance(Money.zero(token));
}
- throw Exception('Could not fetch balances: ${e.toString()}');
+ throw ServerResponseException('Could not fetch balances: ${e.toString()}');
}
}
### cw_evm/lib/evm_chain_client_factory.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_evm/clients/arbitrum_client.dart';
import 'package:cw_evm/clients/base_client.dart';
import 'package:cw_evm/clients/bsc_client.dart';
@@ -18,7 +19,7 @@ class EVMChainClientFactory {
final config = _registry.getChainConfig(chainId);
if (config == null) {
- throw Exception('Chain config not found for chainId: $chainId');
+ throw BadChainIdException('Chain config not found for chainId: $chainId');
}
// Check if chain needs custom client
### cw_evm/lib/evm_chain_exceptions.dart
@@ -1,61 +1,46 @@
-import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
class EVMChainMnemonicIsIncorrectException implements Exception {
@override
String toString() =>
- 'EVM mnemonic has incorrect format. Mnemonic should contain 12 or 24 words separated by space.';
+ "EVM mnemonic has incorrect format. Mnemonic should contain 12 or 24 words separated by space.";
}
-class EVMChainTransactionCreationException implements Exception {
- final String exceptionMessage;
-
+class EVMChainTransactionCreationException extends TransactionGenerationException {
EVMChainTransactionCreationException(CryptoCurrency currency)
- : exceptionMessage = 'Wrong balance. Not enough ${currency.title} on your balance.';
-
- EVMChainTransactionCreationException.fromMessage(this.exceptionMessage);
+ : super("Wrong balance. Not enough ${currency.title} on your balance.");
- @override
- String toString() => exceptionMessage;
+ EVMChainTransactionCreationException.fromMessage(super.message);
}
-class EVMChainTransactionFeesException implements Exception {
- final String exceptionMessage;
-
- EVMChainTransactionFeesException(String message) : exceptionMessage = message;
+class EVMChainTransactionFeesException extends TransactionGenerationException {
+ EVMChainTransactionFeesException(super.message);
EVMChainTransactionFeesException.fromCurrency(String currency)
- : exceptionMessage =
- 'Transaction failed due to insufficient $currency balance to cover the fees.';
-
- @override
- String toString() => exceptionMessage;
+ : super("Transaction failed due to insufficient $currency balance to cover the fees.");
}
-class InsufficientGasFeeException implements Exception {
- final String exceptionMessage;
- final BigInt? requiredGasFee;
- final BigInt? currentBalance;
-
+class InsufficientGasFeeException extends TransactionGenerationException {
InsufficientGasFeeException({
this.requiredGasFee,
this.currentBalance,
- }) : exceptionMessage = _buildMessage(requiredGasFee, currentBalance);
+ }) : super(_buildMessage(requiredGasFee, currentBalance));
+ final BigInt? requiredGasFee;
+ final BigInt? currentBalance;
static String _buildMessage(BigInt? requiredGasFee, BigInt? currentBalance) {
- const baseMessage = 'Insufficient ETH for gas fees.';
- const addEthMessage = ' Please add ETH to your wallet to cover transaction fees.';
+ const baseMessage = "Insufficient ETH for gas fees.";
+ const addEthMessage = " Please add ETH to your wallet to cover transaction fees.";
if (requiredGasFee != null) {
final requiredEth = (requiredGasFee / BigInt.from(10).pow(18)).toStringAsFixed(8);
final balanceInfo = currentBalance != null
- ? ', Available: ${(currentBalance / BigInt.from(10).pow(18)).toStringAsFixed(8)} ETH'
- : '';
- return '$baseMessage Required: ~$requiredEth ETH$balanceInfo.$addEthMessage';
+ ? ", Available: ${(currentBalance / BigInt.from(10).pow(18)).toStringAsFixed(8)} ETH"
+ : "";
+ return "$baseMessage Required: ~$requiredEth ETH$balanceInfo.$addEthMessage";
}
- return '$baseMessage$addEthMessage';
+ return "$baseMessage$addEthMessage";
}
-
- @override
- String toString() => exceptionMessage;
}
### cw_evm/lib/evm_chain_transaction_priority.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:flutter/foundation.dart';
@@ -25,7 +26,7 @@ class EVMChainTransactionPriority extends TransactionPriority {
return fast;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for EVMChainTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for EVMChainTransactionPriority deserialize');
}
return medium;
}
### cw_evm/lib/evm_chain_wallet.dart
@@ -8,6 +8,7 @@ import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/erc20_token.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/pending_transaction.dart';
@@ -193,7 +194,7 @@ abstract class EVMChainWalletBase
@action
Future<void> selectChain(int chainId, {required Node node}) async {
if (EvmChainRegistry().getChainConfig(chainId) == null) {
- throw Exception('Chain config not found for chainId: $chainId');
+ throw BadChainIdException('Chain config not found for chainId: $chainId');
}
if (selectedChainId == chainId) return;
@@ -804,7 +805,7 @@ abstract class EVMChainWalletBase
final isConnected = _client.connect(node);
if (!isConnected) {
- throw Exception("${walletInfo.type.name.toUpperCase()} Node connection failed");
+ throw ConnectionException("${walletInfo.type.name.toUpperCase()} Node connection failed");
}
_client.setListeners(_evmChainPrivateKey.address, _onNewTransaction);
@@ -863,8 +864,8 @@ abstract class EVMChainWalletBase
currency.title == _credentials.currency.title &&
(currency.tag == _credentials.currency.tag ||
currency.tag == _credentials.currency.title),
- orElse: () => throw Exception(
- 'Currency ${_credentials.currency.title} ${_credentials.currency.tag} is not accessible in the wallet, try to enable it first.'));
+ orElse: () => throw BadCurrencyException(
+ 'Currency ${_credentials.currency.title} ${_credentials.currency.tag} is not accessible in the wallet, try to enable it first.', _credentials.currency));
final currencyBalance = balance[transactionCurrency]!;
final toAddress = _credentials.outputs.first.isParsedAddress
@@ -1028,7 +1029,7 @@ abstract class EVMChainWalletBase
}
if (requiredNative > nativeBal) {
- throw Exception('Not enough ${nativeCurrency.title} to cover value and fees.');
+ throw TransactionGenerationException('Not enough ${nativeCurrency.title} to cover value and fees.');
}
final cleanAddress = sourceTokenAddress?.toLowerCase() ?? '';
@@ -1042,14 +1043,14 @@ abstract class EVMChainWalletBase
.where((k) => k is Erc20Token && k.contractAddress.toLowerCase() == cleanAddress);
if (matchingTokens.isEmpty) {
- throw Exception('Insufficient token balance (Token not found in wallet).');
+ throw TransactionGenerationException('Insufficient token balance (Token not found in wallet).');
}
final tokenKey = matchingTokens.first;
final tokenBalance = balance[tokenKey]?.available ?? Money.zero(tokenKey);
if (tokenBalance < Money(sourceTokenAmount, tokenKey)) {
- throw Exception('Insufficient ${tokenKey.symbol} balance to cover the transaction amount.');
+ throw TransactionGenerationException('Insufficient ${tokenKey.symbol} balance to cover the transaction amount.');
}
}
@@ -1074,7 +1075,7 @@ abstract class EVMChainWalletBase
useBlinkProtection: useBlinkProtection,
);
} catch (_) {
- throw Exception('Failed to create the transaction.');
+ throw TransactionGenerationException('Failed to create the transaction.');
}
}
@@ -1528,15 +1529,15 @@ abstract class EVMChainWalletBase
// Get chainId from wallet type, use saved chainId if available (for chain switching)
final defaultChainId = registry.getChainConfigByWalletType(walletInfo.type)?.chainId;
if (defaultChainId == null) {
- throw Exception('Chain config not found for wallet type: ${walletInfo.type}');
+ throw BadWalletTypeException('Chain config not found for wallet type: ${walletInfo.type}', walletInfo.type);
}
// Use saved chainId if available, otherwise default to wallet type's chainId
final chainId = savedChainId ?? defaultChainId;
final chainConfig = registry.getChainConfig(chainId);
if (chainConfig == null) {
- throw Exception('Chain config not found for chainId: $chainId');
+ throw BadChainIdException('Chain config not found for chainId: $chainId');
}
final client = EVMChainClientFactory.createClient(chainId);
### cw_evm/lib/evm_chain_wallet_service.dart
@@ -2,6 +2,7 @@ import "dart:io";
import 'package:bip39/bip39.dart' as bip39;
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import "package:cw_core/erc20_token.dart";
import "package:cw_core/imported_nft.dart";
import 'package:cw_core/pathForWallet.dart';
@@ -65,7 +66,7 @@ class EVMChainWalletService extends WalletService<
Future<void> saveBackup(String name, {WalletInfo? walletInfo}) async {
final info = walletInfo ?? await _findWalletByName(name);
if (info == null) {
- throw Exception("Wallet not found: $name");
+ throw WalletNotFoundException(name: name);
}
final backupWalletDirPath = await pathForWalletDir(name: "$name.backup", type: info.type);
@@ -81,7 +82,7 @@ class EVMChainWalletService extends WalletService<
Future<void> restoreWalletFilesFromBackup(String name) async {
final walletInfo = await _findWalletByName(name);
if (walletInfo == null) {
- throw Exception("Wallet not found: $name");
+ throw WalletNotFoundException(name: name);
}
final backupWalletDirPath = await pathForWalletDir(name: "$name.backup", type: walletInfo.type);
@@ -102,7 +103,7 @@ class EVMChainWalletService extends WalletService<
// Get chainId from wallet type
final chainConfig = _registry.getChainConfigByWalletType(walletInfo.type);
if (chainConfig == null) {
- throw Exception("Chain config not found for wallet type: ${walletInfo.type}");
+ throw BadWalletTypeException('Chain config not found for wallet type: ${walletInfo.type}', walletInfo.type);
}
final initialChainId = chainConfig.chainId;
@@ -139,7 +140,7 @@ class EVMChainWalletService extends WalletService<
Future<EVMChainWallet> openWallet(String name, String password) async {
final walletInfo = await _findWalletByName(name);
if (walletInfo == null) {
- throw Exception("Wallet not found");
+ throw WalletNotFoundException(name: name);
}
try {
@@ -178,7 +179,7 @@ class EVMChainWalletService extends WalletService<
final currentWalletInfo = await _findWalletByName(currentName);
if (currentWalletInfo == null) {
- throw Exception("Wallet not found");
+ throw WalletNotFoundException(name: currentName);
}
final type = currentWalletInfo.type;
@@ -231,7 +232,7 @@ class EVMChainWalletService extends WalletService<
// Get chainId from wallet type
final chainConfig = _registry.getChainConfigByWalletType(walletInfo.type);
if (chainConfig == null) {
- throw Exception("Chain config not found for wallet type: ${walletInfo.type}");
+ throw BadWalletTypeException('Chain config not found for wallet type: ${walletInfo.type}', walletInfo.type);
}
final initialChainId = chainConfig.chainId;
@@ -272,7 +273,7 @@ class EVMChainWalletService extends WalletService<
// Get chainId from wallet type
final chainConfig = _registry.getChainConfigByWalletType(walletInfo.type);
if (chainConfig == null) {
- throw Exception("Chain config not found for wallet type: ${walletInfo.type}");
+ throw BadWalletTypeException('Chain config not found for wallet type: ${walletInfo.type}', walletInfo.type);
}
final initialChainId = chainConfig.chainId;
@@ -311,7 +312,7 @@ class EVMChainWalletService extends WalletService<
// Get chainId from wallet type
final chainConfig = _registry.getChainConfigByWalletType(walletInfo.type);
if (chainConfig == null) {
- throw Exception("Chain config not found for wallet type: ${walletInfo.type}");
+ throw BadWalletTypeException('Chain config not found for wallet type: ${walletInfo.type}', walletInfo.type);
}
final initialChainId = chainConfig.chainId;
@@ -354,7 +355,7 @@ class EVMChainWalletService extends WalletService<
Future<void> remove(String wallet) async {
final walletInfo = await _findWalletByName(wallet);
if (walletInfo == null) {
- throw Exception("Wallet not found");
+ throw WalletNotFoundException(name: wallet);
}
File(await pathForWalletDir(name: wallet, type: walletInfo.type)).delete(recursive: true);
@@ -381,7 +382,7 @@ class EVMChainWalletService extends WalletService<
final chainConfig = _registry.getChainConfigByWalletType(walletType);
if (chainConfig == null) {
- throw Exception("Chain config not found for wallet type: $walletType");
+ throw BadWalletTypeException('Chain config not found for wallet type: $walletType', walletInfo.type);
}
return EVMChainWallet(
### cw_evm/lib/hardware/evm_chain_ledger_credentials.dart
@@ -1,7 +1,9 @@
import 'dart:async';
import 'dart:typed_data';
-import 'package:cw_core/hardware/device_not_connected_exception.dart' as exception;
+import "package:cw_core/exceptions/cake_exception.dart";
+import 'package:cw_core/hardware/device_not_connected_exception.dart'
+ as exception;
import 'package:cw_core/utils/print_verbose.dart';
import 'package:ledger_ethereum/ledger_ethereum.dart';
import 'package:ledger_flutter_plus/ledger_flutter_plus.dart';
@@ -71,7 +73,7 @@ class EvmLedgerCredentials extends CredentialsWithKnownAddress {
final sig = await ethereumLedgerApp!.signMessage(payload);
- if (sig.isEmpty) throw Exception("No Signature received from device!");
+ if (sig.isEmpty) throw HardwareWalletResponseException("No Signature received from device!");
final r = sig.sublist(1, 1 + 32);
final s = sig.sublist(1 + 32, 1 + 32 + 32);
### cw_evm/lib/usdt0/usdt0_service.dart
@@ -1,5 +1,6 @@
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/erc20_token.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_evm/contract/erc20.dart';
import 'package:cw_evm/contract/oft.dart';
@@ -23,9 +24,15 @@ class USDT0Service {
final oftAddress = USDT0Config.getOftContractAddress(sourceChainId);
final dstEid = USDT0Config.getEndpointId(destinationChainId);
- if (oftAddress == null || dstEid == null) {
- throw Exception(
- 'USDT0 not supported for chain $sourceChainId -> $destinationChainId',
+ if (oftAddress == null) {
+ throw BadChainIdException(
+ 'USDT0 not supported for chain $sourceChainId'
+ );
+ }
+
+ if(dstEid == null) {
+ throw BadChainIdException(
+ 'USDT0 not supported for chain $destinationChainId'
);
}
@@ -58,9 +65,15 @@ class USDT0Service {
final oftAddress = USDT0Config.getOftContractAddress(sourceChainId);
final dstEid = USDT0Config.getEndpointId(destinationChainId);
- if (oftAddress == null || dstEid == null) {
- throw Exception(
- 'USDT0 not supported for chain $sourceChainId -> $destinationChainId',
+ if (oftAddress == null) {
+ throw BadChainIdException(
+ 'USDT0 not supported for chain $sourceChainId'
+ );
+ }
+
+ if(dstEid == null) {
+ throw BadChainIdException(
+ 'USDT0 not supported for chain $destinationChainId'
);
}
### cw_evm/lib/utils/rlp_decode.dart
@@ -1,11 +1,16 @@
import 'dart:typed_data';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:web3dart/crypto.dart';
/// RLP Decode
///
/// Adapted from https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/rlp
+class RlpDecodeException extends CakeException {
+ const RlpDecodeException(super.message);
+}
+
class _Decoded {
Uint8List remainder;
List data;
@@ -14,7 +19,7 @@ class _Decoded {
}
int _decodeLength(Uint8List v) {
- if (v[0] == 0) throw Exception('invalid RLP: extra zeros');
+ if (v[0] == 0) throw RlpDecodeException('invalid RLP: extra zeros');
return int.parse(bytesToHex(v), radix: 16);
}
@@ -33,7 +38,7 @@ _Decoded _decode(Uint8List input) {
final data = firstByte == 0x80 ? Uint8List(0) : input.sublist(1, length);
if (length == 2 && data[0] < 0x80) {
- throw Exception('invalid RLP encoding: invalid prefix, single byte < 0x80 are not prefixed');
+ throw RlpDecodeException('invalid RLP encoding: invalid prefix, single byte < 0x80 are not prefixed');
}
return _Decoded(data, input.sublist(length));
@@ -42,12 +47,12 @@ _Decoded _decode(Uint8List input) {
// followed by the length, followed by the string
final lLength = firstByte - 0xb6;
if (input.length - 1 < lLength) {
- throw Exception('invalid RLP: not enough bytes for string length');
+ throw RlpDecodeException('invalid RLP: not enough bytes for string length');
}
final length = _decodeLength(input.sublist(1, lLength));
if (length <= 55) {
- throw Exception('invalid RLP: expected string length to be greater than 55');
+ throw RlpDecodeException('invalid RLP: expected string length to be greater than 55');
}
final data = input.sublist(lLength, length + lLength);
@@ -71,12 +76,12 @@ _Decoded _decode(Uint8List input) {
final length = _decodeLength(input.sublist(1, lLength));
if (length < 56) {
- throw Exception('invalid RLP: encoded list too short');
+ throw RlpDecodeException('invalid RLP: encoded list too short');
}
final totalLength = lLength + length;
if (totalLength > input.length) {
- throw Exception('invalid RLP: total length is larger than the data');
+ throw RlpDecodeException('invalid RLP: total length is larger than the data');
}
var innerRemainder = input.sublist(lLength, totalLength);
@@ -95,7 +100,7 @@ _Decoded _decode(Uint8List input) {
List decode(Uint8List input) {
final decoded = _decode(input);
- if (decoded.remainder.isNotEmpty) throw Exception('invalid RLP: remainder must be zero');
+ if (decoded.remainder.isNotEmpty) throw RlpDecodeException('invalid RLP: remainder must be zero');
return decoded.data;
}
### cw_monero/lib/api/exceptions/wallet_creation_exception.dart
@@ -1,8 +0,0 @@
-class WalletCreationException implements Exception {
- WalletCreationException({required this.message});
-
- final String message;
-
- @override
- String toString() => message;
-}
### cw_monero/lib/api/wallet.dart
@@ -10,6 +10,7 @@ import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_monero/api/account_list.dart';
import 'package:cw_monero/api/exceptions/setup_wallet_exception.dart';
import 'package:cw_monero/api/get_all_unspent.dart';
+import "package:cw_monero/exceptions/monero_exceptions.dart";
import 'package:monero/monero.dart' as monero;
import 'package:mutex/mutex.dart';
import 'package:polyseed/polyseed.dart';
@@ -309,7 +310,7 @@ void setPasswordSync(String password) {
final status = currentWallet!.status();
if (status != 0) {
- throw Exception(currentWallet!.errorString());
+ throw MoneroWalletException(currentWallet!.errorString());
}
}
### cw_monero/lib/api/wallet_manager.dart
@@ -2,6 +2,7 @@ import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_monero/api/account_list.dart';
import 'package:cw_monero/api/exceptions/wallet_creation_exception.dart';
@@ -91,7 +92,7 @@ void createWallet(
int status = newW.status();
if (status != 0) {
- throw WalletCreationException(message: newW.errorString());
+ throw WalletCreationException(newW.errorString());
}
newW.store(path: path);
setupBackgroundSync(password, newW);
@@ -392,9 +393,9 @@ Future<void> loadWallet({required String path, required String password, int net
deviceType = 0;
}
- if (deviceType == 1) {
- if (gLedger == null) {
- throw Exception("Tried to open a ledger wallet with no ledger connected");
+ if (deviceType == 1) {
+ if (gLedger == null) {
+ throw HardwareWalletNotConnectedException("Tried to open a ledger wallet with no ledger connected");
}
enableLedgerExchange(gLedger!);
}
### cw_monero/lib/exceptions/monero_exceptions.dart
@@ -0,0 +1,14 @@
+
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class MoneroNodeResponseException extends ServerResponseException {
+ const MoneroNodeResponseException(super.message);
+}
+
+class KeyImageException extends CakeException {
+ const KeyImageException(super.message);
+}
+
+class MoneroWalletException extends CakeException {
+ const MoneroWalletException(super.message);
+}
\ No newline at end of file
### cw_monero/lib/exceptions/monero_transaction_creation_exception.dart
@@ -1,8 +1,5 @@
-class MoneroTransactionCreationException implements Exception {
- MoneroTransactionCreationException(this.message);
+import "package:cw_core/exceptions/cake_exception.dart";
- final String message;
-
- @override
- String toString() => message;
+class MoneroTransactionCreationException extends TransactionGenerationException {
+ const MoneroTransactionCreationException(super.message);
}
### cw_monero/lib/exceptions/monero_transaction_no_inputs_exception.dart
@@ -1,9 +1,9 @@
-class MoneroTransactionNoInputsException implements Exception {
- MoneroTransactionNoInputsException(this.inputsSize);
+import "package:cw_monero/exceptions/monero_transaction_creation_exception.dart";
- int inputsSize;
+class MoneroTransactionNoInputsException extends MoneroTransactionCreationException {
+ MoneroTransactionNoInputsException(int inputsSize)
+ : inputsSize = inputsSize,
+ super("Not enough inputs ($inputsSize) selected. Please select more under Coin Control");
- @override
- String toString() =>
- 'Not enough inputs ($inputsSize) selected. Please select more under Coin Control';
+ int inputsSize;
}
### cw_monero/lib/monero_wallet.dart
@@ -4,6 +4,7 @@ import 'dart:io';
import 'dart:isolate';
import 'package:cw_core/amount/money.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/transaction_priority.dart';
import 'package:cw_core/account.dart';
@@ -27,6 +28,7 @@ import 'package:cw_monero/api/structs/pending_transaction.dart';
import 'package:cw_monero/api/transaction_history.dart' as transaction_history;
import 'package:cw_monero/api/wallet.dart' as monero_wallet;
import 'package:cw_monero/api/wallet_manager.dart';
+import "package:cw_monero/exceptions/monero_exceptions.dart";
import 'package:cw_monero/exceptions/monero_transaction_creation_exception.dart';
import 'package:cw_monero/ledger.dart';
import 'package:cw_monero/monero_balance.dart';
@@ -355,7 +357,7 @@ abstract class MoneroWalletBase
final status = currentWallet!.status();
if (status != 0) {
final err = currentWallet!.errorString();
- throw Exception("unable to import key images: $err");
+ throw KeyImageException("unable to import key images: $err");
}
return retStatus;
}
@@ -394,17 +396,17 @@ abstract class MoneroWalletBase
MoneroTrezorService? trezorService;
- Trezor _getTrezor() => Trezor(trezorService ?? (throw Exception("Trezor not connected")));
+ Trezor _getTrezor() => Trezor(trezorService ?? (throw HardwareWalletNotConnectedException("Trezor not connected")));
Future<void> syncTrezor() async {
- if (trezorService == null) throw Exception("Trezor not connected");
+ if (trezorService == null) throw HardwareWalletNotConnectedException("Trezor not connected");
final ptr = Pointer<Void>.fromAddress(currentWallet!.ffiAddress());
final tdis = monero.Wallet_exportTrezorTdis(ptr);
final response = await _getTrezor().keyImageSync(tdis);
final success = monero.Wallet_importTrezorEncryptedKeyImagesJson(ptr, response);
- if (!success) throw Exception(monero.Wallet_errorString(ptr));
+ if (!success) throw MoneroWalletException(monero.Wallet_errorString(ptr));
}
Future<String> signTrezorTransaction(String json) => _getTrezor().signTransaction(json);
@@ -887,7 +889,7 @@ abstract class MoneroWalletBase
// the restore height is probably correct, so we do nothing:
if (height > MIN_RESTORE_HEIGHT) return;
- throw Exception("height isn't > $MIN_RESTORE_HEIGHT!");
+ throw MoneroWalletException("height isn't > $MIN_RESTORE_HEIGHT!");
}
void _setHeightFromDate({int tryNum = 0}) {
@@ -899,7 +901,7 @@ abstract class MoneroWalletBase
try {
height = _getHeightByDate(walletInfo.date.subtract(Duration(days: 14)));
if (height <= 0) {
- throw Exception("height is <= 0");
+ throw MoneroWalletException("height is <= 0");
}
monero_wallet.setRefreshFromBlockHeight(height: height);
} catch (_) {
@@ -930,7 +932,7 @@ abstract class MoneroWalletBase
if (nodeHeight <= 0) {
// the node returned 0 (an error state)
- throw Exception("nodeHeight is <= 0!");
+ throw MoneroWalletException("nodeHeight is <= 0!");
}
return nodeHeight - heightDistance;
### cw_monero/lib/monero_wallet_service.dart
@@ -3,6 +3,7 @@ import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/get_height_by_date.dart';
import 'package:cw_core/hardware/hardware_wallet_service.dart';
import 'package:cw_core/monero_wallet_utils.dart';
@@ -184,7 +185,7 @@ class MoneroWalletService extends WalletService<
await monero_wallet_manager.openWallet(path: path, password: password);
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
final wallet = MoneroWallet(
walletInfo: walletInfo,
@@ -239,7 +240,7 @@ class MoneroWalletService extends WalletService<
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
}
@@ -248,7 +249,7 @@ class MoneroWalletService extends WalletService<
Future<void> rename(String currentName, String password, String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName, type: getType());
}
final currentWallet = MoneroWallet(
walletInfo: currentWalletInfo,
@@ -556,7 +557,7 @@ class MoneroWalletService extends WalletService<
await monero_wallet_manager.openWallet(path: path, password: password);
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
final wallet = MoneroWallet(
walletInfo: walletInfo,
### cw_mweb/lib/cw_mweb.dart
@@ -4,6 +4,7 @@ import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
+import "package:cw_mweb/mweb_exceptions.dart";
import 'package:cw_mweb/mweb_ffi.dart';
import 'package:cw_mweb/print_verbose.dart';
import 'package:grpc/grpc.dart';
@@ -59,7 +60,7 @@ class CwMweb {
_port = MWebFfi.instance.start(appDir.path, nodeUriOverride ?? ltcNodeUri);
if (_port == null || _port == 0) {
- throw Exception("Failed to start server");
+ throw MwebConnectionException("Failed to start server");
}
printV("Attempting to connect to server on port: $_port");
@@ -83,7 +84,7 @@ class CwMweb {
final status = await _rpcClient!
.status(StatusRequest(), options: CallOptions(timeout: TIMEOUT_DURATION));
if (status.blockTime == 0) {
- throw Exception("blockTime shouldn't be 0! (this connection is likely broken)");
+ throw MwebConnectionException("blockTime shouldn't be 0! (this connection is likely broken)");
}
return _rpcClient!;
} on GrpcError catch (e) {
@@ -100,7 +101,7 @@ class CwMweb {
await Future.delayed(const Duration(seconds: 3));
}
}
- throw Exception("Failed to connect after $maxRetries attempts");
+ throw MwebConnectionException("Failed to connect after $maxRetries attempts");
}
static Future<void> stop() async {
### cw_mweb/lib/mweb_exceptions.dart
@@ -0,0 +1,8 @@
+class MwebConnectionException implements Exception {
+ const MwebConnectionException(this.message);
+
+ final String message;
+
+ @override
+ String toString() => message;
+}
\ No newline at end of file
### cw_nano/lib/nano_client.dart
@@ -3,12 +3,14 @@ import 'dart:convert';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/nano_account_info_response.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_nano/nano_block_info_response.dart';
import 'package:cw_core/n2_node.dart';
import 'package:cw_nano/nano_balance.dart';
+import "package:cw_nano/nano_exceptions.dart";
import 'package:cw_nano/nano_transaction_model.dart';
import 'package:cw_core/node.dart';
import 'package:nanoutil/nanoutil.dart';
@@ -84,7 +86,7 @@ class NanoClient {
data["error"] != null ||
data["balance"] == null ||
data["receivable"] == null) {
- throw Exception(
+ throw ServerResponseException(
"Error while trying to get balance! ${data["error"] != null ? data["error"] : ""}");
}
final currentBalance = data["balance"] as String;
@@ -149,7 +151,7 @@ class NanoClient {
AccountInfoResponse? accountInfo = await getAccountInfo(ourAddress);
if (accountInfo == null) {
- throw Exception(
+ throw NanoChangeRepException(
"error while getting account info, you can't change the rep of an unopened account");
}
@@ -184,7 +186,7 @@ class NanoClient {
try {
return await processBlock(changeBlock, "change");
} catch (e) {
- throw Exception("error while changing representative: $e");
+ throw NanoChangeRepException("error while changing representative: $e");
}
}
@@ -203,11 +205,11 @@ class NanoClient {
if (response.statusCode == 200) {
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
if (decoded.containsKey("error")) {
- throw Exception("Received error ${decoded["error"]}");
+ throw ServerResponseException("Received error ${decoded["error"]}");
}
return decoded["work"] as String;
} else {
- throw Exception("Received work error ${response.body}");
+ throw ServerResponseException("Received work error ${response.body}");
}
}
@@ -241,7 +243,7 @@ class NanoClient {
final Map<String, dynamic> decoded = jsonDecode(processResponse.body) as Map<String, dynamic>;
if (decoded.containsKey("error")) {
- throw Exception("Received error ${decoded["error"]}");
+ throw ServerResponseException("Received error ${decoded["error"]}");
}
// return the hash of the transaction:
@@ -268,7 +270,7 @@ class NanoClient {
// get the account info (we need the frontier and representative):
AccountInfoResponse? infoResponse = await getAccountInfo(publicAddress);
if (infoResponse == null) {
- throw Exception(
+ throw ServerResponseException(
"error while getting account info! (we probably don't have an open account yet)");
}
@@ -341,7 +343,7 @@ class NanoClient {
}
if ((BigInt.tryParse(amountRaw) ?? BigInt.zero) <= BigInt.zero) {
- throw Exception("amountRaw must be greater than zero");
+ throw ArgumentError("amountRaw must be greater than zero");
}
BlockContentsResponse? frontierContents;
@@ -351,7 +353,7 @@ class NanoClient {
frontierContents = await getBlockContents(frontier);
if (frontierContents == null) {
- throw Exception("error while getting frontier block info");
+ throw NanoBlockException("error while getting frontier block info");
}
final String frontierHash = NanoSignatures.computeStateHash(
@@ -370,7 +372,7 @@ class NanoClient {
);
if (!valid) {
- throw Exception(
+ throw NanoBlockException(
"Frontier block signature is invalid! Potentially malicious block detected!");
}
}
@@ -439,7 +441,7 @@ class NanoClient {
);
final Map<String, dynamic> decoded = json.decode(processResponse.body) as Map<String, dynamic>;
if (decoded.containsKey("error")) {
- throw Exception("Received error ${decoded["error"]}");
+ throw ServerResponseException("Received error ${decoded["error"]}");
}
}
### cw_nano/lib/nano_exceptions.dart
@@ -0,0 +1,11 @@
+
+
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class NanoChangeRepException extends CakeException {
+ const NanoChangeRepException(super.message);
+}
+
+class NanoBlockException extends CakeException {
+ const NanoBlockException(super.message);
+}
\ No newline at end of file
### cw_nano/lib/nano_mnemonic.dart
@@ -1,4 +1,5 @@
import 'package:bip39/bip39.dart' as bip39;
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:nanodart/nanodart.dart';
class NanoMnemonicIsIncorrectException implements Exception {
@@ -11,7 +12,7 @@ class NanoMnemomics {
/// Converts a nano seed to a 24-word mnemonic word list
static List<String> seedToMnemonic(String seed) {
if (!NanoSeeds.isValidSeed(seed)) {
- throw Exception('Invalid Seed');
+ throw BadMnemonicException('Invalid Seed');
}
String words = bip39.entropyToMnemonic(seed);
return words.split(' ');
@@ -20,7 +21,7 @@ class NanoMnemomics {
/// Convert a 24-word mnemonic word list to a nano seed
static String mnemonicListToSeed(List<String> words) {
if (words.length != 24) {
- throw Exception('Expected a 24-word list, got a ${words.length} list');
+ throw BadMnemonicException('Expected a 24-word list, got a ${words.length} list');
}
return bip39.mnemonicToEntropy(words.join(' ')).toUpperCase();
}
### cw_nano/lib/nano_wallet.dart
@@ -7,6 +7,7 @@ import 'package:cw_core/amount/money.dart';
import 'package:cw_core/cake_hive.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/n2_node.dart';
import 'package:cw_core/nano_account.dart';
import 'package:cw_core/nano_account_info_response.dart';
@@ -22,6 +23,7 @@ import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_keys_file.dart';
import 'package:cw_nano/nano_balance.dart';
import 'package:cw_nano/nano_client.dart';
+import "package:cw_nano/nano_exceptions.dart";
import 'package:cw_nano/nano_transaction_credentials.dart';
import 'package:cw_nano/nano_transaction_history.dart';
import 'package:cw_nano/nano_transaction_info.dart';
@@ -167,7 +169,7 @@ abstract class NanoWalletBase
syncStatus = ConnectingSyncStatus();
final isConnected = _client.connect(node);
if (!isConnected) {
- throw Exception("Nano Node connection failed");
+ throw ConnectionException("Nano Node connection failed");
}
try {
@@ -208,9 +210,8 @@ abstract class NanoWalletBase
amt = txOut.cryptoAmount.amount;
}
- if (balance[currency]?.currentBalance != null &&
- amt > balance[currency]!.currentBalance.amount) {
- throw Exception("Trying to send more than entire balance!");
+ if (balance[currency]?.currentBalance != null && amt > balance[currency]!.currentBalance.amount) {
+ throw TransactionGenerationException("Trying to send more than entire balance!");
}
runningBalance = runningBalance - amt;
@@ -236,9 +237,8 @@ abstract class NanoWalletBase
}
try {
- if (runningAmount > balance[currency]!.currentBalance.amount ||
- runningBalance < BigInt.zero) {
- throw Exception(("Trying to send more than entire balance!"));
+ if (runningAmount > balance[currency]!.currentBalance.amount || runningBalance < BigInt.zero) {
+ throw TransactionGenerationException(("Trying to send more than entire balance!"));
}
} catch (e) {
rethrow;
@@ -490,7 +490,7 @@ abstract class NanoWalletBase
} catch (e) {
// account not found:
_representativeAddress = await _client.getRepFromPrefs();
- throw Exception("Failed to get representative address $e");
+ throw NanoChangeRepException("Failed to get representative address $e");
}
repScore = await _client.getRepScore(_representativeAddress!);
@@ -526,7 +526,7 @@ abstract class NanoWalletBase
_representativeAddress = address;
}
} catch (e) {
- throw Exception("Failed to change representative address $e");
+ throw NanoChangeRepException("Failed to change representative address $e");
}
}
### cw_nano/lib/nano_wallet_service.dart
@@ -1,5 +1,6 @@
import 'dart:io';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/wallet_base.dart';
@@ -69,7 +70,7 @@ class NanoWalletService extends WalletService<
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
}
@@ -78,7 +79,7 @@ class NanoWalletService extends WalletService<
Future<void> rename(String currentName, String password, String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName, type: getType());
}
String randomWords =
@@ -105,10 +106,10 @@ class NanoWalletService extends WalletService<
Future<NanoWallet> restoreFromKeys(NanoRestoreWalletFromKeysCredentials credentials,
{bool? isTestnet}) async {
if (credentials.seedKey.contains(' ')) {
- throw Exception("Invalid key!");
+ throw BadKeysException("Invalid key!");
} else {
if (credentials.seedKey.length != 64 && credentials.seedKey.length != 128) {
- throw Exception("Invalid key length!");
+ throw BadKeysException("Invalid key length!");
}
}
@@ -119,7 +120,7 @@ class NanoWalletService extends WalletService<
try {
mnemonic = NanoDerivations.standardSeedToMnemonic(credentials.seedKey);
} catch (e) {
- throw Exception("Wasn't a valid nano style seed!");
+ throw BadMnemonicException("Wasn't a valid nano style seed!");
}
}
final derivationInfo = await credentials.walletInfo!.getDerivationInfo();
@@ -159,7 +160,7 @@ class NanoWalletService extends WalletService<
}
} else {
if (credentials.mnemonic.length != 64 && credentials.mnemonic.length != 128) {
- throw Exception("Invalid seed length");
+ throw BadMnemonicException("invalid seed length");
}
}
@@ -190,7 +191,7 @@ class NanoWalletService extends WalletService<
Future<NanoWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
### cw_solana/lib/solana_wallet.dart
@@ -4,6 +4,7 @@ import 'dart:convert';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/pending_transaction.dart';
@@ -222,7 +223,7 @@ abstract class SolanaWalletBase
final isConnected = _client.connect(node);
if (!isConnected) {
- throw Exception("Solana Node connection failed");
+ throw ConnectionException("Solana Node connection failed");
}
_setTransactionUpdateTimer();
@@ -311,8 +312,9 @@ abstract class SolanaWalletBase
.toList(growable: false);
if (matches.isEmpty) {
- throw Exception(
- "Currency ${requestedCurrency.title} ${requestedCurrency.tag} is not accessible in the wallet, try to enable it first.",
+ throw BadCurrencyException(
+ "Currency ${requestedCurrency.title} ${requestedCurrency
+ .tag} is not accessible in the wallet, try to enable it first.", requestedCurrency,
);
}
### cw_solana/lib/solana_wallet_service.dart
@@ -4,6 +4,7 @@ import 'package:bip39/bip39.dart' as bip39;
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/balance.dart';
import "package:cw_core/imported_nft.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/spl_token.dart';
import 'package:cw_core/transaction_history.dart';
@@ -58,7 +59,7 @@ class SolanaWalletService extends WalletService<
Future<SolanaWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
@@ -96,7 +97,7 @@ class SolanaWalletService extends WalletService<
await File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
final nameStillUsed = await WalletInfo.get(wallet, getType()) != null;
### cw_tron/lib/tron_client.dart
@@ -6,6 +6,7 @@ import 'package:blockchain_utils/blockchain_utils.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_tron/default_tron_tokens.dart';
@@ -380,7 +381,7 @@ class TronClient {
if (feeLimit > tronBalanceInt) {
final feeInTrx = TronHelper.fromSun(BigInt.parse(feeLimit.toString()));
- throw Exception(
+ throw TransactionGenerationException(
'You don\'t have enough TRX to cover the transaction fee for this transaction. Please top up.\nTransaction fee: $feeInTrx TRX',
);
}
@@ -409,7 +410,7 @@ class TronClient {
if (!request.isSuccess) {
log("Tron TRC20 error: ${request.error} \n ${request.respose}");
- throw Exception('An error occurred while creating the transfer request. Please try again.');
+ throw TransactionGenerationException('An error occurred while creating the transfer request. Please try again.');
}
final feeLimit = await getFeeLimit(
@@ -421,7 +422,7 @@ class TronClient {
if (feeLimit > tronBalance.toInt()) {
final feeInTrx = TronHelper.fromSun(BigInt.parse(feeLimit.toString()));
- throw Exception(
+ throw TransactionGenerationException(
'You don\'t have enough TRX to cover the transaction fee for this transaction. Please top up. Transaction fee: $feeInTrx TRX',
);
}
@@ -443,11 +444,11 @@ class TronClient {
if (txBroadcastResult.isSuccess) {
return txBroadcastResult.txId!;
} else {
- throw Exception(txBroadcastResult.error);
+ throw TransactionSendingException(txBroadcastResult.error??"");
}
} catch (e) {
log('Send block Exception: ${e.toString()}');
- throw Exception(e);
+ throw TransactionSendingException(e.toString());
}
}
### cw_tron/lib/tron_wallet.dart
@@ -7,6 +7,7 @@ import 'package:blockchain_utils/blockchain_utils.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/pending_transaction.dart';
@@ -254,7 +255,7 @@ abstract class TronWalletBase
final isConnected = _client.connect(node);
if (!isConnected) {
- throw Exception("${walletInfo.type.name.toUpperCase()} Node connection failed");
+ throw ConnectionException("${walletInfo.type.name.toUpperCase()} Node connection failed");
}
_getEstimatedFees();
@@ -337,7 +338,7 @@ abstract class TronWalletBase
(currency) =>
currency.title == tronCredentials.currency.title &&
currency.tag == tronCredentials.currency.tag,
- orElse: () => throw Exception(
+ orElse: () => throw TransactionGenerationException(
'Currency ${tronCredentials.currency.title} ${tronCredentials.currency.tag} is not accessible in the wallet, try to enable it first.'));
final walletBalanceForCurrency = balance[transactionCurrency]!.balance;
### cw_tron/lib/tron_wallet_service.dart
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:bip39/bip39.dart' as bip39;
import 'package:cw_core/balance.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/transaction_info.dart';
@@ -56,7 +57,7 @@ class TronWalletService extends WalletService<
Future<TronWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
@@ -143,7 +144,7 @@ class TronWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
final nameStillUsed = await WalletInfo.get(wallet, getType()) != null;
### cw_wownero/lib/wownero_wallet_service.dart
@@ -1,6 +1,7 @@
import 'dart:ffi';
import 'dart:io';
import 'package:cw_core/exceptions.dart' show WalletDeprecationException;
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/monero_wallet_utils.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/unspent_coins_info.dart';
@@ -231,7 +232,7 @@ class WowneroWalletService extends WalletService<
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet);
}
await WalletInfo.delete(walletInfo);
}
@@ -240,7 +241,7 @@ class WowneroWalletService extends WalletService<
Future<void> rename(String currentName, String password, String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName);
}
final currentWallet = WowneroWallet(
walletInfo: currentWalletInfo,
### cw_zano/lib/zano_wallet_api.dart
@@ -3,6 +3,7 @@ import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/zano_asset.dart';
@@ -505,18 +506,18 @@ mixin ZanoWalletApi {
if (responseData['error'] != null) {
printV('ZANO sign_message error: ${responseData['error']}');
- throw Exception('Zano sign_message failed: ${responseData['error']}');
+ throw MessageSignException('Zano sign_message failed: ${responseData['error']}');
}
final result = responseData['result'] as Map<String, dynamic>?;
if (result == null) {
- throw Exception('Invalid response from sign_message');
+ throw MessageSignException('Invalid response from sign_message');
}
final signature = result['sig'] as String?;
if (signature == null) {
- throw Exception('No signature in response');
+ throw MessageSignException('No signature in response');
}
return signature;
### cw_zano/lib/zano_wallet_service.dart
@@ -1,6 +1,7 @@
import 'dart:io';
import 'package:collection/collection.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/utils/print_verbose.dart';
@@ -88,7 +89,7 @@ class ZanoWalletService extends WalletService<
Future<ZanoWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
final wallet =
@@ -123,7 +124,7 @@ class ZanoWalletService extends WalletService<
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
}
@@ -132,7 +133,7 @@ class ZanoWalletService extends WalletService<
Future<void> rename(String currentName, String password, String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName, type: getType());
}
final currentWallet =
ZanoWallet(currentWalletInfo, await currentWalletInfo.getDerivationInfo(), password,
### cw_zcash/lib/src/migrate.dart
@@ -5,6 +5,7 @@ import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cw_zcash/cw_zcash.dart';
+import "package:cw_zcash/src/util/exceptions.dart";
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:path/path.dart' as p;
@@ -92,5 +93,5 @@ Future<void> migrateOldSqliteToZkool2({required final String walletName}) async
return;
}
- throw Exception("migration not finished (wallet name: $walletName not found)");
+ throw MigrationException("migration not finished (wallet name: $walletName not found)");
}
### cw_zcash/lib/src/util/exceptions.dart
@@ -0,0 +1,23 @@
+
+
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class WalletLockedException extends CakeException {
+ const WalletLockedException() : super("Zcash wallet locked! Please contact support");
+}
+
+class UpdateException extends CakeException {
+ const UpdateException(super.message);
+}
+
+class ZcashAccountException extends CakeException {
+ const ZcashAccountException(super.message);
+}
+
+class AddressRotationException extends CakeException {
+ const AddressRotationException(super.message);
+}
+
+class MigrationException extends CakeException {
+ const MigrationException(super.message);
+}
\ No newline at end of file
### cw_zcash/lib/src/zcash_taddress_rotation.dart
@@ -18,6 +18,7 @@ import 'package:cw_core/sync_status.dart';
import 'package:cw_core/transaction_direction.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_zcash/src/util/crc32.dart';
+import "package:cw_zcash/src/util/exceptions.dart";
import 'package:cw_zcash/src/zcash_wallet.dart';
import 'package:cw_zcash/src/zcash_wallet_service.dart';
import 'package:cw_zcash/src/zkool_compat.dart';
@@ -400,7 +401,7 @@ class ZcashTaddressRotation {
final addrs = await zkool_account.getAddresses(c: coin, uaPools: 7);
final orchard = addrs.oaddr;
if (orchard == null || orchard.isEmpty) {
- throw Exception('Orchard address unavailable for rotation sweep');
+ throw AddressRotationException('Orchard address unavailable for rotation sweep');
}
return orchard;
},
@@ -424,7 +425,7 @@ class ZcashTaddressRotation {
amount += note.value;
}
if (amount < BigInt.from(_sweepThreshold)) {
- throw Exception('rotation sweep: insufficient spendable transparent notes');
+ throw AddressRotationException('rotation sweep: insufficient spendable transparent notes');
}
final ironwood = await zkool_network.isIronwoodActive(c: coin);
final tx = await zkool_pay.prepare(
@@ -451,7 +452,7 @@ class ZcashTaddressRotation {
);
printV("rotation sweep broadcast: $result");
if (result.isEmpty) {
- throw Exception("rotation sweep broadcast failed");
+ throw AddressRotationException("rotation sweep broadcast failed");
}
await ZcashWalletService.addShieldedTx(result);
### cw_zcash/lib/src/zcash_wallet.dart
@@ -4,6 +4,7 @@ import 'dart:math';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/get_height_by_date_zec.dart';
import 'package:cw_core/monero_transaction_priority.dart';
import 'package:cw_core/node.dart';
@@ -20,6 +21,7 @@ import 'package:cw_core/wallet_type.dart';
import 'package:bip39/bip39.dart' as bip39;
import 'package:cw_zcash/cw_zcash.dart';
import 'package:cw_zcash/src/util/crc32.dart';
+import "package:cw_zcash/src/util/exceptions.dart";
import 'package:cw_zcash/src/zcash_mempool.dart';
import 'package:cw_zcash/src/zcash_taddress_rotation.dart';
import 'package:cw_zcash/src/zcash_wallet_addresses.dart';
@@ -943,7 +945,7 @@ abstract class ZcashWalletBase
final s = (await zkool_account.getAccountSeed(account: accountId, c: c));
if (s == null) {
- throw Exception("seed not found");
+ throw BadMnemonicException("seed not found");
}
final seedPhrase = s.mnemonic.split(" ");
if ([13, 25].contains(seedPhrase.length)) {
@@ -977,11 +979,11 @@ abstract class ZcashWalletBase
}
final currentWalletDir = Directory(await pathForWalletDir(name: fromName, type: _type));
if (!currentWalletDir.existsSync()) {
- throw Exception('Wallet directory not found: $fromName');
+ throw WalletNotFoundException(name: fromName, type: _type);
}
final newWalletDirPath = '${await pathForWalletTypeDir(type: _type)}/$toName';
if (Directory(newWalletDirPath).existsSync()) {
- throw Exception('Cannot rename wallet: "$toName" already exists');
+ throw BadWalletDataException('Cannot rename wallet: "$toName" already exists');
}
await currentWalletDir.rename(newWalletDirPath);
for (final suffix in const ['', '.v2']) {
@@ -1057,10 +1059,10 @@ abstract class ZcashWalletBase
final updated =
accounts.where((final a) => a.id == accountId).firstOrNull;
if (updated == null) {
- throw Exception('account $accountId not found after update');
+ throw UpdateException('account $accountId not found after update');
}
if (updated.birth != height) {
- throw Exception(
+ throw UpdateException(
'birth height did not persist: wanted $height, '
'database still has ${updated.birth}',
);
@@ -1517,7 +1519,7 @@ abstract class ZcashWalletBase
final fromSeedCredentials = credentials as ZcashFromSeedWalletCredentials;
final String? seed = fromSeedCredentials.seed;
if (seed == null || seed.isEmpty) {
- throw Exception('Seed phrase is required for wallet restoration');
+ throw BadMnemonicException('Seed phrase is required for wallet restoration');
}
final accountId = await restoreZcashWalletFromSeed(
@@ -1543,12 +1545,12 @@ abstract class ZcashWalletBase
final fromKeysCredentials = credentials as ZcashFromKeysWalletCredentials;
final String? keys = fromKeysCredentials.privateKey;
if (keys == null || keys.isEmpty) {
- throw Exception('Key is required for wallet restoration');
+ throw BadKeysException('Key is required for wallet restoration');
}
final zcashSecretExtendedKeyRegex = RegExp(r'^secret-extended-key-main1[a-z0-9]+$');
if (!zcashSecretExtendedKeyRegex.hasMatch(keys)) {
- throw Exception('Key is not in secret-extended-key-main1 format');
+ throw BadKeysException('Key is not in secret-extended-key-main1 format');
}
final accountId = await restoreZcashWalletFromSeed(
@@ -1580,7 +1582,7 @@ abstract class ZcashWalletBase
// }
final accountId = await getZcashAccountIdForName(name);
if (accountId == null) {
- throw Exception("accountId is null");
+ throw ZcashAccountException("accountId is null");
}
c = await c.setAccount(account: accountId);
final wallet = ZcashWallet(
@@ -1726,7 +1728,7 @@ abstract class ZcashWalletBase
c = await c.openDatabase(dbFilepath: dbFile.path, password: null);
printV("initWallet: ${dbFile.path}");
if (_password == null) {
- throw Exception("Zcash wallet locked! Please contact support");
+ throw WalletLockedException();
}
if (!dbFile.existsSync()) {
//TODO(mrcyjanek): copy-encrypt
### cw_zcash/lib/src/zcash_wallet_service.dart
@@ -1,6 +1,7 @@
import 'dart:io';
import 'package:bip39/bip39.dart' as bip39;
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
@@ -93,7 +94,7 @@ class ZcashWalletService
Future<ZcashWallet> openWallet(final String name, final String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
await ZcashWalletBase.$init(network: ZcashWalletBase.networkFor(walletInfo));
if (await isWalletExit(name)) {
@@ -137,7 +138,7 @@ class ZcashWalletService
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
}
@@ -146,10 +147,10 @@ class ZcashWalletService
Future<void> rename(final String currentName, final String password, final String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName, type: getType());
}
if (!await isWalletExit(currentName)) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName, type: getType());
}
await ZcashWalletBase.renameWalletFilesForName(fromName: currentName, toName: newName);
@@ -175,11 +176,11 @@ class ZcashWalletService
final bool? isTestnet,
}) async {
if (credentials.seed == null || credentials.seed!.isEmpty) {
- throw Exception("Seed is missing");
+ throw BadMnemonicException("Seed is missing");
}
if (!bip39.validateMnemonic(credentials.seed!)) {
- throw Exception("Seed is not valid bip39");
+ throw BadMnemonicException("Seed is not valid bip39");
}
return ZcashWalletBase.restore(credentials);
### lib/anonpay/anonpay_api.dart
@@ -7,6 +7,7 @@ import 'package:cake_wallet/core/fiat_conversion_service.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/wallet_type_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/crypto_currency.dart';
@@ -159,11 +160,11 @@ class AnonPayApi {
final responseJSON = json.decode(response.body) as List<dynamic>;
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ServerResponseException('Unexpected http status: ${response.statusCode}');
}
if (responseJSON.isEmpty) {
- throw Exception('No data');
+ throw ServerResponseException('No data');
}
final coinJson = responseJSON.first as Map<String, dynamic>;
### lib/anypay/anypay_api.dart
@@ -1,13 +1,18 @@
import 'dart:convert';
import 'package:cake_wallet/anypay/any_pay_payment_committed_info.dart';
import 'package:cake_wallet/utils/exception_handler.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:flutter/foundation.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cake_wallet/anypay/any_pay_payment.dart';
import 'package:cake_wallet/anypay/any_pay_trasnaction.dart';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+class AnyPayParseException extends CurrencyParseException {
+ const AnyPayParseException(super.message);
+}
+
class AnyPayApi {
static const contentTypePaymentRequest = 'application/payment-request';
static const contentTypePayment = 'application/payment';
@@ -36,7 +41,7 @@ class AnyPayApi {
case 'litecoin':
return CryptoCurrency.ltc;
default:
- throw Exception('Unexpected scheme: ${scheme}');
+ throw AnyPayParseException('Unexpected scheme: ${scheme}');
}
}
@@ -63,7 +68,7 @@ class AnyPayApi {
if (response.statusCode != 200) {
await ExceptionHandler.onError(FlutterErrorDetails(exception: response));
- throw Exception('Unexpected response http code: ${response.statusCode}');
+ throw ServerResponseException('Unexpected response http code: ${response.statusCode}');
}
final decodedBody = json.decode(response.body) as Map<String, dynamic>;
@@ -95,11 +100,11 @@ class AnyPayApi {
if (response.statusCode == 400) {
final decodedBody = json.decode(response.body) as Map<String, dynamic>;
- throw Exception(decodedBody['message'] as String? ?? 'Unexpected response\nError code: 400');
+ throw ServerResponseException(decodedBody['message'] as String? ?? 'Unexpected response\nError code: 400');
}
if (response.statusCode != 200) {
- throw Exception('Unexpected response');
+ throw ServerResponseException('Unexpected response');
}
final decodedBody = json.decode(response.body) as Map<String, dynamic>;
### lib/bitcoin/cw_bitcoin.dart
@@ -605,7 +605,7 @@ class CWBitcoin extends Bitcoin {
@override
bool isPayjoinAvailable(Object wallet) =>
- (wallet is BitcoinWallet) && (wallet as BitcoinWallet).isPayjoinAvailable;
+ (wallet is BitcoinWallet) && wallet.isPayjoinAvailable;
@override
BitcoinAddressType getOptionToType(ReceivePageOption option) {
@@ -897,28 +897,28 @@ class CWBitcoin extends Bitcoin {
@override
String? getBreezSdkError(Object exception) {
if (exception is SdkError_SparkError) {
- return (exception as SdkError_SparkError).field0.toString();
+ return exception.field0.toString();
}
if (exception is SdkError_InvalidUuid) {
- return (exception as SdkError_InvalidUuid).field0.toString();
+ return exception.field0.toString();
}
if (exception is SdkError_InvalidInput) {
- return (exception as SdkError_InvalidInput).field0.toString();
+ return exception.field0.toString();
}
if (exception is SdkError_NetworkError) {
- return (exception as SdkError_NetworkError).field0.toString();
+ return exception.field0.toString();
}
if (exception is SdkError_StorageError) {
- return (exception as SdkError_StorageError).field0.toString();
+ return exception.field0.toString();
}
if (exception is SdkError_ChainServiceError) {
- return (exception as SdkError_ChainServiceError).field0.toString();
+ return exception.field0.toString();
}
if (exception is SdkError_LnurlError) {
- return (exception as SdkError_LnurlError).field0.toString();
+ return exception.field0.toString();
}
if (exception is SdkError_Generic) {
- return (exception as SdkError_Generic).field0.toString();
+ return exception.field0.toString();
}
return null;
}
### lib/buy/buy_provider_description.dart
@@ -1,4 +1,9 @@
import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class BuyProviderDeserializeException extends DeserializeException {
+ BuyProviderDeserializeException(super.message);
+}
class BuyProviderDescription extends EnumerableItem<int> with Serializable<int> {
const BuyProviderDescription({required String title, required int raw, required this.image})
@@ -16,7 +21,7 @@ class BuyProviderDescription extends EnumerableItem<int> with Serializable<int>
case 1:
return moonPay;
default:
- throw Exception('Incorrect token $raw for BuyProviderDescription deserialize');
+ throw BuyProviderDeserializeException('Incorrect token $raw for BuyProviderDescription deserialize');
}
}
}
### lib/buy/buy_sell_exceptions.dart
@@ -0,0 +1,9 @@
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class BuySellProviderResponseException extends ServerResponseException {
+ const BuySellProviderResponseException(super.message);
+}
+
+class BuySellLaunchException extends CakeException {
+ const BuySellLaunchException(super.message);
+}
### lib/buy/dfx/dfx_buy_provider.dart
@@ -3,6 +3,7 @@ import 'dart:developer';
import 'package:cake_wallet/buy/buy_provider.dart';
import 'package:cake_wallet/buy/buy_quote.dart';
+import "package:cake_wallet/buy/buy_sell_exceptions.dart";
import 'package:cake_wallet/buy/pairs_utils.dart';
import 'package:cake_wallet/buy/payment_method.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
@@ -13,6 +14,7 @@ import 'package:cake_wallet/src/widgets/alert_with_one_action.dart';
import 'package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_model.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/wallet_base.dart';
@@ -123,10 +125,10 @@ class DFXBuyProvider extends BuyProvider {
return responseBody['accessToken'] as String;
} else if (response.statusCode == 403) {
final responseBody = jsonDecode(response.body);
- final message = responseBody['message'] ?? 'Service unavailable in your country';
- throw Exception(message);
+ final message = (responseBody['message'] as String?) ?? 'Service unavailable in your country';
+ throw BuySellProviderResponseException(message);
} else {
- throw Exception('Failed to sign up. ${_getErrorMessage(response.statusCode, response.body)}');
+ throw BuySellProviderResponseException('Failed to sign up. ${_getErrorMessage(response.statusCode, response.body)}');
}
}
@@ -148,7 +150,7 @@ class DFXBuyProvider extends BuyProvider {
case WalletType.zano:
return wallet.signMessage(message, address: walletAddress);
default:
- throw Exception("WalletType is not available for DFX ${wallet.type}");
+ throw BadWalletTypeException("WalletType is not available for DFX ${wallet.type}",wallet.type);
}
}
@@ -376,7 +378,7 @@ class DFXBuyProvider extends BuyProvider {
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else {
- throw Exception('Could not launch URL');
+ throw const BuySellLaunchException('Could not launch URL');
}
} catch (e) {
await showPopUp<void>(
### lib/buy/kryptonim/kryptonim.dart
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/buy/buy_provider.dart';
import 'package:cake_wallet/buy/buy_quote.dart';
+import "package:cake_wallet/buy/buy_sell_exceptions.dart";
import 'package:cake_wallet/buy/pairs_utils.dart';
import 'package:cake_wallet/buy/payment_method.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
@@ -185,7 +186,7 @@ class KryptonimBuyProvider extends BuyProvider {
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else {
- throw Exception('Could not launch URL');
+ throw BuySellLaunchException('Could not launch URL');
}
} catch (e) {
await showPopUp<void>(
### lib/buy/meld/meld_buy_provider.dart
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/buy/buy_provider.dart';
import 'package:cake_wallet/buy/buy_quote.dart';
+import "package:cake_wallet/buy/buy_sell_exceptions.dart";
import 'package:cake_wallet/buy/pairs_utils.dart';
import 'package:cake_wallet/buy/payment_method.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
@@ -180,7 +181,7 @@ class MeldBuyProvider extends BuyProvider {
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else {
- throw Exception('Could not launch URL');
+ throw BuySellLaunchException('Could not launch URL');
}
} catch (e) {
await showPopUp<void>(
### lib/buy/moonpay/moonpay_provider.dart
@@ -6,6 +6,7 @@ import "package:cake_wallet/buy/buy_exception.dart";
import "package:cake_wallet/buy/buy_provider.dart";
import "package:cake_wallet/buy/buy_provider_description.dart";
import "package:cake_wallet/buy/buy_quote.dart";
+import "package:cake_wallet/buy/buy_sell_exceptions.dart";
import "package:cake_wallet/buy/moonpay/moonpay_payment_methods.dart";
import "package:cake_wallet/buy/pairs_utils.dart";
import "package:cake_wallet/buy/payment_method.dart";
@@ -130,9 +131,8 @@ class MoonPayProvider extends BuyProvider {
printV(jsonDecode(response.body) as Map<String, dynamic>);
return (jsonDecode(response.body) as Map<String, dynamic>)["query"] as String;
} else {
- throw Exception(
- "Provider currently unavailable. Status: ${response.statusCode} ${response.body}",
- );
+ throw BuySellProviderResponseException(
+ 'Provider currently unavailable. Status: ${response.statusCode} ${response.body}');
}
}
@@ -329,7 +329,7 @@ class MoonPayProvider extends BuyProvider {
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else {
- throw Exception("Could not launch URL");
+ throw BuySellLaunchException('Could not launch URL');
}
} catch (e) {
if (context.mounted) {
### lib/buy/onramper/onramper_buy_provider.dart
@@ -4,6 +4,7 @@ import 'dart:developer';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/buy/buy_provider.dart';
import 'package:cake_wallet/buy/buy_quote.dart';
+import "package:cake_wallet/buy/buy_sell_exceptions.dart";
import 'package:cake_wallet/buy/pairs_utils.dart';
import 'package:cake_wallet/buy/payment_method.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
@@ -324,7 +325,7 @@ class OnRamperBuyProvider extends BuyProvider {
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else {
- throw Exception('Could not launch URL ${uri.toString()}');
+ throw BuySellLaunchException('Could not launch URL ${uri.toString()}');
}
}
### lib/buy/robinhood/robinhood_buy_provider.dart
@@ -4,6 +4,7 @@ import 'dart:developer';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/buy/buy_provider.dart';
import 'package:cake_wallet/buy/buy_quote.dart';
+import "package:cake_wallet/buy/buy_sell_exceptions.dart";
import 'package:cake_wallet/buy/pairs_utils.dart';
import 'package:cake_wallet/buy/payment_method.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
@@ -12,6 +13,7 @@ import 'package:cake_wallet/routes.dart';
import 'package:cake_wallet/src/screens/connect_device/connect_device_page.dart';
import 'package:cake_wallet/src/widgets/alert_with_one_action.dart';
import 'package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_model.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cw_core/crypto_currency.dart';
@@ -126,7 +128,7 @@ class RobinhoodBuyProvider extends BuyProvider {
case WalletType.zano:
case WalletType.zcash:
case WalletType.decred:
- throw Exception("Wallet Type ${wallet.type.name} is not available for Robinhood");
+ throw BadWalletTypeException("Wallet Type ${wallet.type.name} is not available for Robinhood",wallet.type);
}
}
@@ -149,7 +151,7 @@ class RobinhoodBuyProvider extends BuyProvider {
if (response.statusCode == 200) {
return (jsonDecode(response.body) as Map<String, dynamic>)['connectId'] as String;
} else {
- throw Exception('Provider currently unavailable. Status: ${response.statusCode}');
+ throw BuySellProviderResponseException('Provider currently unavailable. Status: ${response.statusCode}');
}
}
### lib/cake_pay/src/cake_pay_exceptions.dart
@@ -1,6 +1,14 @@
-class CakePayUnauthorizedException implements Exception {
- const CakePayUnauthorizedException();
+import "package:cw_core/exceptions/cake_exception.dart";
- @override
- String toString() => 'Cake Pay session is no longer valid, please log in again.';
+class CakePayUnauthorizedException extends CakeException {
+ const CakePayUnauthorizedException()
+ : super("Cake Pay session is no longer valid, please log in again.");
+}
+
+class CakePayResponseException extends ServerResponseException {
+ const CakePayResponseException(super.message);
+}
+
+class CakePayNoDataException extends CakeException {
+ const CakePayNoDataException(super.message);
}
### lib/cake_pay/src/services/cake_pay_api.dart
@@ -1,5 +1,6 @@
import 'dart:convert';
+import "package:cake_wallet/buy/buy_sell_exceptions.dart";
import 'package:cake_wallet/cake_pay/src/cake_pay_exceptions.dart';
import 'package:cake_wallet/cake_pay/src/models/cake_pay_order.dart';
import 'package:cake_wallet/cake_pay/src/models/cake_pay_user_credentials.dart';
@@ -39,7 +40,7 @@ class CakePayApi {
);
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw BuySellProviderResponseException('Unexpected http status: ${response.statusCode}');
}
final bodyJson = json.decode(response.body) as Map<String, dynamic>;
@@ -48,9 +49,9 @@ class CakePayApi {
return bodyJson['user']['email'] as String;
}
- throw Exception('Failed to authenticate user with error: $bodyJson');
+ throw BuySellProviderResponseException('Failed to authenticate user with error: $bodyJson');
} catch (e) {
- throw Exception('Failed to authenticate user with error: $e');
+ throw BuySellProviderResponseException('Failed to authenticate user with error: $e');
}
}
@@ -75,21 +76,21 @@ class CakePayApi {
);
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw CakePayResponseException('Unexpected http status: ${response.statusCode}');
}
final bodyJson = json.decode(response.body) as Map<String, dynamic>;
if (bodyJson.containsKey('error')) {
- throw Exception(bodyJson['error'] as String);
+ throw CakePayResponseException(bodyJson['error'] as String);
}
if (bodyJson.containsKey('token')) {
final token = bodyJson['token'] as String;
final userEmail = bodyJson['user']['email'] as String;
return CakePayUserCredentials(userEmail, token);
} else {
- throw Exception('E-mail verification failed.');
+ throw CakePayResponseException('E-mail verification failed.');
}
}
@@ -157,7 +158,7 @@ class CakePayApi {
} on FormatException {}
}
- throw Exception(message);
+ throw CakePayResponseException(message);
}
/// Get Order by ID
@@ -178,7 +179,7 @@ class CakePayApi {
}
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw CakePayResponseException('Unexpected http status: ${response.statusCode}');
}
final bodyJson = json.decode(response.body) as Map<String, dynamic>;
@@ -217,7 +218,7 @@ class CakePayApi {
}
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw CakePayResponseException('Unexpected http status: ${response.statusCode}');
}
final bodyJson = json.decode(response.body) as Map<String, dynamic>;
@@ -242,7 +243,7 @@ class CakePayApi {
);
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw CakePayResponseException('Unexpected http status: ${response.statusCode}');
}
} catch (e) {
printV('Caught exception: $e');
@@ -285,7 +286,7 @@ class CakePayApi {
var response = await ProxyWrapper().get(clearnetUri: uri, headers: headers);
if (response.statusCode != 200) {
- throw Exception(
+ throw CakePayResponseException(
'Failed to fetch vendors: statusCode - ${response.statusCode}, queryParams -$queryParams, response - ${response.body}');
}
### lib/core/address_resolver/address_resolver_exceptions.dart
@@ -0,0 +1,5 @@
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class AddressResolverServerResponseException extends ServerResponseException {
+ const AddressResolverServerResponseException(super.message);
+}
\ No newline at end of file
### lib/core/address_resolver/bip_353/bip_353_record.dart
@@ -3,9 +3,14 @@ import 'dart:isolate';
import 'package:basic_utils/basic_utils.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:dnssec_proof/dnssec_proof.dart';
+class Bip353FetchException extends CakeException {
+ const Bip353FetchException(super.message);
+}
+
class Bip353Record {
Bip353Record({
required this.uri,
@@ -59,13 +64,13 @@ class Bip353Record {
);
final proof = await fetchDnsProof(bip353Name);
if (proof == null) {
- throw Exception('DNSSEC proof not found');
+ throw Bip353FetchException('DNSSEC proof not found');
}
if (txtRecords == null) return null;
final assetName = CryptoCurrency.fromString(asset).fullName;
- if (assetName == null) throw Exception('Invalid asset name');
+ if (assetName == null) throw Bip353FetchException('Invalid asset name');
final formattedAssetName = assetName.toLowerCase().replaceAll(' ', '') + ':';
for (final record in txtRecords) {
### lib/core/address_resolver/mastodon/mastodon_api.dart
@@ -1,4 +1,5 @@
import 'dart:convert';
+import "package:cake_wallet/core/address_resolver/address_resolver_exceptions.dart";
import 'package:cake_wallet/core/address_resolver/mastodon/mastodon_user.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/utils/print_verbose.dart';
@@ -50,7 +51,7 @@ class MastodonAPI {
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode != 200) {
- throw Exception('Unexpected HTTP status: ${response.statusCode}');
+ throw AddressResolverServerResponseException('Unexpected HTTP status: ${response.statusCode}');
}
final List<dynamic> responseJSON = json.decode(response.body) as List<dynamic>;
### lib/core/address_resolver/twitter/twitter_api.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/core/address_resolver/address_resolver_exceptions.dart";
import 'package:cake_wallet/core/address_resolver/twitter/twitter_user.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
@@ -23,21 +24,20 @@ class TwitterApi {
path: userPath + userName,
queryParameters: queryParams);
- final response =
- await ProxyWrapper().get(clearnetUri: uri, headers: headers).catchError((error) {
- throw Exception('HTTP request failed: $error');
+ final response = await ProxyWrapper().get(clearnetUri: uri, headers: headers).catchError((error) {
+ throw AddressResolverServerResponseException('HTTP request failed: $error');
});
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw AddressResolverServerResponseException('Unexpected http status: ${response.statusCode}');
}
final Map<String, dynamic> responseJSON = jsonDecode(response.body) as Map<String, dynamic>;
if (responseJSON['errors'] != null &&
!responseJSON['errors'][0]['detail']
.toString()
.contains("Could not find tweet with pinned_tweet_id")) {
- throw Exception(responseJSON['errors'][0]['detail']);
+ throw AddressResolverServerResponseException(responseJSON['errors'][0]['detail'] as String? ?? "");
}
return TwitterUser.fromJson(responseJSON, _getPinnedTweet(responseJSON));
### lib/core/address_resolver/unstoppable/unstoppable_address_provider.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:cake_wallet/core/address_resolver/address_lookup_provider.dart';
+import "package:cake_wallet/core/address_resolver/address_resolver_exceptions.dart";
import 'package:cake_wallet/core/address_resolver/address_sources.dart';
import 'package:cake_wallet/core/address_resolver/openalias/openalias_record.dart';
import 'package:cake_wallet/core/address_resolver/parsed_address.dart';
@@ -217,13 +218,12 @@ class UnstoppableAddressProvider extends AddressLookupProvider {
final jsonParsed = json.decode(response.body) as Map<String, dynamic>;
if (jsonParsed["records"] == null) {
- throw Exception(".records response from $uri is empty");
- }
- ;
+ throw AddressResolverServerResponseException(".records response from $uri is empty");
+ };
final records = jsonParsed["records"] as Map<String, dynamic>;
final key = "crypto.${ticker.toUpperCase()}.address";
if (records[key] == null) {
- throw Exception(".records.${key} response from $uri is empty");
+ throw AddressResolverServerResponseException(".records.${key} response from $uri is empty");
}
return records[key] as String? ?? '';
### lib/core/backup_service.dart
@@ -4,6 +4,7 @@ import 'package:cake_wallet/core/secure_storage.dart';
import 'package:cake_wallet/entities/get_encryption_key.dart';
import 'package:cake_wallet/entities/transaction_description.dart';
import 'package:cake_wallet/themes/utils/theme_list.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/root_dir.dart';
import 'package:cake_wallet/utils/device_info.dart';
import 'package:cw_core/utils/print_verbose.dart';
@@ -27,6 +28,20 @@ import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/wallet_types.g.dart';
import 'package:cake_backup/backup.dart' as cake_backup;
+
+class BackupServiceException extends CakeException {
+ const BackupServiceException(super.message);
+}
+
+class UnknownBackupVersionException extends BackupServiceException {
+ const UnknownBackupVersionException() : super("unknown backup version");
+}
+
+class InvalidBackupException extends BackupServiceException {
+ const InvalidBackupException(super.message);
+}
+
+
class $BackupService {
$BackupService(
this._secureStorage, this.transactionDescriptionBox, this.keyService, this.sharedPreferences)
### lib/core/backup_service_v3.dart
@@ -147,19 +147,14 @@ class BackupMetadata {
}
}
-class IncompatibleBackupAppException implements Exception {
- IncompatibleBackupAppException({
+class IncompatibleBackupAppException extends InvalidBackupException {
+ const IncompatibleBackupAppException({
required this.sourceAppName,
required this.currentAppName,
- });
+ }) : super("This backup was created in $sourceAppName and cannot be restored in $currentAppName.");
final String sourceAppName;
final String currentAppName;
-
- @override
- String toString() {
- return 'This backup was created in $sourceAppName and cannot be restored in $currentAppName.';
- }
}
class BackupServiceV3 extends $BackupService {
@@ -181,7 +176,7 @@ class BackupServiceV3 extends $BackupService {
final bytesRead = raf.readIntoSync(buffer);
if (bytesRead == 0) {
- throw Exception('Invalid backup file: empty file');
+ throw InvalidBackupException('Invalid backup file: empty file');
}
// Check if first byte is version 1 or 2
@@ -221,7 +216,7 @@ class BackupServiceV3 extends $BackupService {
final version = getVersionFile(file);
switch (version) {
case BackupVersion.unknown:
- throw Exception('unknown_backup_version');
+ throw UnknownBackupVersionException();
case BackupVersion.v1:
final data = file.readAsBytesSync();
final backupBytes = data.toList()..removeAt(0);
@@ -251,7 +246,7 @@ class BackupServiceV3 extends $BackupService {
final metadataFile = archive.findFile('metadata.json');
if (metadataFile == null) {
- throw Exception('Invalid v3 backup: missing metadata.json');
+ throw InvalidBackupException('Invalid v3 backup: missing metadata.json');
}
final metadataBytes = metadataFile.rawContent!.readBytes();
final metadataString = utf8.decode(metadataBytes);
@@ -260,7 +255,7 @@ class BackupServiceV3 extends $BackupService {
final dataFile = archive.findFile('data.bin');
if (dataFile == null) {
- throw Exception('Invalid v3 backup: missing data.bin');
+ throw InvalidBackupException('Invalid v3 backup: missing data.bin');
}
final dataStream = dataFile.rawContent!.getStream();
@@ -279,8 +274,7 @@ class BackupServiceV3 extends $BackupService {
// readBytes stores position internally, so we don't need to think about it.
if (chunk.sha512sum.encrypted != chunkChecksum) {
- throw Exception(
- 'Invalid v3 backup: chunk (${chunk.length.encrypted} bytes) checksum mismatch at index $chunkIndex\n'
+ throw InvalidBackupException('Invalid v3 backup: chunk (${chunk.length.encrypted} bytes) checksum mismatch at index $chunkIndex\n'
'expected: ${chunk.sha512sum.encrypted}\n'
'got: $chunkChecksum');
}
@@ -290,7 +284,7 @@ class BackupServiceV3 extends $BackupService {
final sha512sum = (await sha512.bind(decryptedData.openRead()).first).toString();
if (sha512sum.toString() != metadata.sha512sum) {
- throw Exception('Invalid v3 backup: SHA512 checksum mismatch\n'
+ throw InvalidBackupException('Invalid v3 backup: SHA512 checksum mismatch\n'
'expected: ${metadata.sha512sum}\n'
'got: $sha512sum');
}
### lib/core/wallet_creation_service.dart
@@ -1,5 +1,6 @@
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/store/settings_store.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_info.dart';
import 'package:cake_wallet/entities/preferences_key.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -10,6 +11,7 @@ import 'package:cw_core/wallet_credentials.dart';
import 'package:cw_core/wallet_service.dart';
import 'package:cw_core/wallet_type.dart';
+
class WalletCreationService {
WalletCreationService(
{required WalletType initialType,
@@ -45,7 +47,7 @@ class WalletCreationService {
Future<void> checkIfExists(String name) async {
if (await exists(name)) {
- throw Exception('Wallet with name ${name} already exists!');
+ throw WalletCreationException('Wallet with name ${name} already exists!');
}
}
### lib/core/wallet_loading_service.dart
@@ -11,6 +11,7 @@ import 'package:cake_wallet/src/widgets/alert_with_two_actions.dart';
import 'package:cake_wallet/utils/exception_handler.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cw_core/exceptions.dart' show WalletDeprecationException;
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_info.dart';
@@ -155,7 +156,7 @@ class WalletLoadingService {
throw msg;
}
if (wallet == null) {
- throw Exception("Wallet is null");
+ throw WalletOpenException("Wallet is null");
}
return wallet;
}
### lib/di.dart
@@ -271,6 +271,7 @@ import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/zcash/zcash.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/nano_account.dart';
import 'package:cw_core/node.dart';
import 'package:cw_core/payjoin_session.dart';
@@ -389,9 +390,7 @@ Future<void> setup({
case HardwareWalletType.coldcard:
case HardwareWalletType.seedsigner:
case HardwareWalletType.keystone:
- throw Exception(
- "This should not have happened, because airgapped Wallets don't need View Models",
- );
+ throw ArgumentError("This should not have happened, because airgapped Wallets don't need View Models");
}
});
@@ -887,8 +886,8 @@ Future<void> setup({
if (wallet.type == WalletType.nano || wallet.type == WalletType.banano) {
return NanoAccountListViewModel(wallet);
}
- throw Exception(
- 'Unexpected wallet type: ${wallet.type} for generate Nano/Banano AccountListViewModel');
+ throw BadWalletTypeException(
+ 'Unexpected wallet type: ${wallet.type} for generate Nano/Banano AccountListViewModel',wallet.type);
});
getIt.registerFactory<MoneroAccountListViewModel>(() {
@@ -898,8 +897,8 @@ Future<void> setup({
wallet.type == WalletType.haven) {
return MoneroAccountListViewModel(wallet);
}
- throw Exception(
- 'Unexpected wallet type: ${wallet.type} for generate Monero AccountListViewModel');
+ throw BadWalletTypeException(
+ 'Unexpected wallet type: ${wallet.type} for generate Monero AccountListViewModel',wallet.type);
});
getIt.registerFactory<BitcoinAccountListViewModel>(() {
@@ -1279,7 +1278,7 @@ Future<void> setup({
case WalletType.zcash:
return zcash!.createZcashWalletService(SettingsStoreBase.walletPasswordDirectInput);
case WalletType.none:
- throw Exception('Unexpected token: ${param1.toString()} for generating of WalletService');
+ throw BadWalletTypeException('Unexpected token: ${param1.toString()} for generating of WalletService',param1);
}
});
### lib/entities/balance_display_mode.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:flutter/foundation.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cw_core/enumerable_item.dart';
@@ -26,7 +27,7 @@ class BalanceDisplayMode extends EnumerableItem<int> with Serializable<int> {
case 3:
return displayableBalance;
default:
- throw Exception('Unexpected token: $raw for BalanceDisplayMode deserialize');
+ throw DeserializeException('Unexpected token: $raw for BalanceDisplayMode deserialize');
}
}
### lib/entities/bitcoin_amount_display_mode.dart
@@ -1,4 +1,5 @@
import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
class BitcoinAmountDisplayMode extends EnumerableItem<int> with Serializable<int> {
const BitcoinAmountDisplayMode({required String title, required int raw})
@@ -22,7 +23,7 @@ class BitcoinAmountDisplayMode extends EnumerableItem<int> with Serializable<int
case 2:
return satoshi;
default:
- throw Exception('Unexpected token: $raw for BalanceDisplayMode deserialize');
+ throw DeserializeException('Unexpected token: $raw for BalanceDisplayMode deserialize');
}
}
### lib/entities/cake_2fa_preset_options.dart
@@ -1,4 +1,5 @@
import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
class Cake2FAPresetsOptions extends EnumerableItem<int> with Serializable<int> {
const Cake2FAPresetsOptions({required String super.title, required int super.raw});
@@ -19,7 +20,7 @@ class Cake2FAPresetsOptions extends EnumerableItem<int> with Serializable<int> {
case 3:
return Cake2FAPresetsOptions.none;
default:
- throw Exception(
+ throw DeserializeException(
'Incorrect Cake 2FA Preset $raw for Cake2FAPresetOptions deserialize',
);
}
### lib/entities/encrypt.dart
@@ -22,7 +22,7 @@ String decrypt({required String source, required String key}) {
String hash({required String source}) {
// FIX-ME: Uninplemented
- throw Exception('Unimplemented');
+ throw UnimplementedError();
// final algorithm = PBKDF2();
// final hash = Password.hash(source, algorithm);
### lib/entities/exchange_api_mode.dart
@@ -1,5 +1,6 @@
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
class ExchangeApiMode extends EnumerableItem<int> with Serializable<int> {
const ExchangeApiMode({required String title, required int raw}) : super(title: title, raw: raw);
@@ -19,7 +20,7 @@ class ExchangeApiMode extends EnumerableItem<int> with Serializable<int> {
case 2:
return disabled;
default:
- throw Exception('Unexpected token: $raw for ExchangeApiMode deserialize');
+ throw DeserializeException('Unexpected token: $raw for ExchangeApiMode deserialize');
}
}
### lib/entities/fiat_api_mode.dart
@@ -1,5 +1,6 @@
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
class FiatApiMode extends EnumerableItem<int> with Serializable<int> {
const FiatApiMode({required String title, required int raw}) : super(title: title, raw: raw);
@@ -19,7 +20,7 @@ class FiatApiMode extends EnumerableItem<int> with Serializable<int> {
case 2:
return disabled;
default:
- throw Exception('Unexpected token: $raw for FiatApiMode deserialize');
+ throw DeserializeException('Unexpected token: $raw for FiatApiMode deserialize');
}
}
### lib/entities/hardware_wallet/require_hardware_wallet_connection.dart
@@ -1,6 +1,7 @@
import 'package:cake_wallet/core/wallet_loading_service.dart';
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/entities/preferences_key.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_type.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -13,7 +14,7 @@ Future<bool> requireHardwareWalletConnection() async {
}
if (name == null) {
- throw Exception('Incorrect current wallet name: $name');
+ throw WalletOpenException('Incorrect current wallet name: $name');
}
final type = deserializeFromInt(typeRaw);
### lib/entities/list_order_mode.dart
@@ -1,5 +1,6 @@
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:flutter/foundation.dart';
class ListOrderMode extends EnumerableItem<int> with Serializable<int> {
@@ -18,7 +19,7 @@ class ListOrderMode extends EnumerableItem<int> with Serializable<int> {
return descending;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for ListOrderMode deserialize');
+ throw DeserializeException('Unexpected token: $raw for ListOrderMode deserialize');
}
return descending;
}
### lib/entities/load_current_wallet.dart
@@ -1,4 +1,5 @@
import 'package:cake_wallet/di.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/entities/preferences_key.dart';
@@ -11,7 +12,7 @@ Future<void> loadCurrentWallet({String? password}) async {
final typeRaw = getIt.get<SharedPreferences>().getInt(PreferencesKey.currentWalletType) ?? 0;
if (name == null) {
- throw Exception('Incorrect current wallet name: $name');
+ throw WalletOpenException('Incorrect current wallet name: $name');
}
final type = deserializeFromInt(typeRaw);
### lib/entities/seed_type.dart
@@ -1,4 +1,5 @@
import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_info.dart';
class MoneroSeedType extends EnumerableItem<int> with Serializable<int> {
@@ -28,7 +29,7 @@ class MoneroSeedType extends EnumerableItem<int> with Serializable<int> {
case 3:
return bip39;
default:
- throw Exception('Unexpected token: $raw for SeedType deserialize');
+ throw DeserializeException('Unexpected token: $raw for SeedType deserialize');
}
}
@@ -56,7 +57,7 @@ class BitcoinSeedType extends EnumerableItem<int> with Serializable<int> {
case 1:
return bip39;
default:
- throw Exception('Unexpected token: $raw for SeedType deserialize');
+ throw DeserializeException('Unexpected token: $raw for SeedType deserialize');
}
}
}
@@ -81,7 +82,7 @@ class NanoSeedType extends EnumerableItem<int> with Serializable<int> {
case 1:
return bip39;
default:
- throw Exception('Unexpected token: $raw for SeedType deserialize');
+ throw DeserializeException('Unexpected token: $raw for SeedType deserialize');
}
}
}
### lib/exchange/exchange_exceptions.dart
@@ -0,0 +1,46 @@
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cw_core/currency.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class ExchangeProviderResponseException extends ServerResponseException {
+ const ExchangeProviderResponseException(super.message);
+}
+
+
+
+class ExchangeProviderResponseCodeException extends ExchangeProviderResponseException with ResponseCodeException {
+ ExchangeProviderResponseCodeException(super.message, this.code);
+
+ @override
+ final int code;
+}
+
+class RateNotFoundException extends ExchangeProviderResponseException {
+ const RateNotFoundException(this.from, this.to, {required this.provider, this.description = ''}) : super("");
+
+ final Currency from;
+ final Currency to;
+ final ExchangeProviderDescription provider;
+ final String description;
+
+ @override
+ String get message => 'no rate ${from.symbol} -> ${to.symbol} at $provider, $description';
+
+}
+
+class TradeNotFoundException extends ExchangeProviderResponseException {
+ const TradeNotFoundException(this.tradeId, {required this.provider, this.description = ''}) : super("");
+
+ final String tradeId;
+ final ExchangeProviderDescription provider;
+ final String description;
+
+ @override
+ String get message => '${S.current.trade_id_not_found(tradeId, provider.title)} $description';
+}
+
+
+class TradeExecutionException extends ExchangeProviderResponseException {
+ const TradeExecutionException(super.message);
+}
\ No newline at end of file
### lib/exchange/exchange_provider_description.dart
@@ -1,4 +1,5 @@
import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
class ExchangeProviderDescription extends EnumerableItem<int> with Serializable<int> {
const ExchangeProviderDescription(
@@ -133,7 +134,7 @@ class ExchangeProviderDescription extends EnumerableItem<int> with Serializable<
case 16:
return jupiter;
default:
- throw Exception('Unexpected token: $raw for ExchangeProviderDescription deserialize');
+ throw DeserializeException('Unexpected token: $raw for ExchangeProviderDescription deserialize');
}
}
}
### lib/exchange/provider/chainflip_exchange_provider.dart
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:math';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
@@ -68,8 +69,9 @@ class ChainflipExchangeProvider extends ExchangeProvider {
required CryptoCurrency to,
required bool isFixedRateMode}) async {
try {
- if (!_supported.contains(from) || !_supported.contains(to)) {
- throw Exception('No rates found for $from to $to');
+
+ if(!_supported.contains(from) || !_supported.contains(to)) {
+ throw RateNotFoundException(from, to, provider: description);
}
final assetId = _normalizeCurrency(from);
@@ -81,12 +83,14 @@ class ChainflipExchangeProvider extends ExchangeProvider {
orElse: () => null)?['minimalAmountNative'] ??
'0';
- if (minAmount == '0') throw Exception('No rates found for $from to $to');
+ if (minAmount == '0') throw RateNotFoundException(from, to, provider: description);
return Limits(min: _amountFromNative(minAmount.toString(), from));
+ } on ExchangeProviderResponseException {
+ rethrow;
} catch (e) {
printV(e.toString());
- throw Exception('Chainflip failed to fetch limits');
+ throw ExchangeProviderResponseException('Chainflip failed to fetch limits');
}
}
@@ -276,7 +280,8 @@ class ChainflipExchangeProvider extends ExchangeProvider {
final statusResponse = await _getStatus(statusParams);
- if (statusResponse == null) throw Exception('Trade not found for id: $id');
+ if (statusResponse == null)
+ throw TradeNotFoundException(id, provider: description);
final status = statusResponse['status'];
final currentState = _determineState(status['state'].toString());
@@ -376,8 +381,7 @@ class ChainflipExchangeProvider extends ExchangeProvider {
final response = await ProxyWrapper().get(clearnetUri: uri);
if ((response.statusCode != 200) || (response.body.contains('error'))) {
- throw Exception(
- 'Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}');
+ throw ExchangeProviderResponseException('Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}');
}
return json.decode(response.body) as Map<String, dynamic>;
@@ -389,8 +393,7 @@ class ChainflipExchangeProvider extends ExchangeProvider {
final response = await ProxyWrapper().get(clearnetUri: uri);
if ((response.statusCode != 200) || (response.body.contains('error'))) {
- throw Exception(
- 'Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}');
+ throw ExchangeProviderResponseCodeException('Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}', response.statusCode);
}
final List<dynamic> jsonList = json.decode(response.body) as List<dynamic>;
@@ -415,8 +418,7 @@ class ChainflipExchangeProvider extends ExchangeProvider {
if (response.statusCode == 404) return null;
if ((response.statusCode != 200) || (response.body.contains('error'))) {
- throw Exception(
- 'Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}');
+ throw ExchangeProviderResponseCodeException('Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}', response.statusCode);
}
return json.decode(response.body) as Map<String, dynamic>;
### lib/exchange/provider/changenow_exchange_provider.dart
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:io';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
@@ -72,11 +73,11 @@ class ChangeNowExchangeProvider extends ExchangeProvider {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error'] as String;
final message = responseJSON['message'] as String;
- throw Exception('${error}\n$message');
+ throw ExchangeProviderResponseCodeException('${error}\n$message', response.statusCode);
}
if (response.statusCode != 200)
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final min = double.tryParse(responseJSON['minAmount']?.toString() ?? '');
@@ -220,11 +221,11 @@ class ChangeNowExchangeProvider extends ExchangeProvider {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error'] as String;
final message = responseJSON['message'] as String;
- throw Exception('${error}\n$message');
+ throw ExchangeProviderResponseCodeException('${error}\n$message', response.statusCode);
}
if (response.statusCode != 200)
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final id = responseJSON['id'] as String;
@@ -270,7 +271,7 @@ class ChangeNowExchangeProvider extends ExchangeProvider {
}
if (response.statusCode != 200)
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
### lib/exchange/provider/exolix_exchange_provider.dart
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/core/lightning_invoice_service.dart';
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
@@ -81,13 +82,13 @@ class ExolixExchangeProvider extends ExchangeProvider {
params['amount'] = errorResponse['minAmount'].toString();
continue;
}
- throw Exception('Error 422: ${errorResponse['message'] ?? 'Unknown error'}');
+ throw ExchangeProviderResponseCodeException('Error 422: ${errorResponse['message'] ?? 'Unknown error'}', response.statusCode);
} else {
- throw Exception('Unexpected HTTP status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected HTTP status: ${response.statusCode}', response.statusCode);
}
}
- throw Exception('Failed to fetch limits after retrying.');
+ throw ExchangeProviderResponseException('Failed to fetch limits after retrying.');
}
@override
@@ -137,8 +138,8 @@ class ExolixExchangeProvider extends ExchangeProvider {
'url': uri.toString(),
},
);
-
- throw Exception(message);
+
+ throw ExchangeProviderResponseCodeException(message??"", response.statusCode);
}
final rate = double.tryParse(responseJSON['rate']?.toString() ?? '') ?? 0.0;
@@ -238,8 +239,8 @@ class ExolixExchangeProvider extends ExchangeProvider {
'url': uri.toString(),
},
);
-
- throw Exception(errorMessage);
+
+ throw ExchangeProviderResponseCodeException(errorMessage??"", response.statusCode);
}
if (response.statusCode != 200 && response.statusCode != 201) {
@@ -261,7 +262,7 @@ class ExolixExchangeProvider extends ExchangeProvider {
'url': uri.toString(),
},
);
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
@@ -336,7 +337,7 @@ class ExolixExchangeProvider extends ExchangeProvider {
}
if (response.statusCode != 200)
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
### lib/exchange/provider/jupiter_exchange_provider.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
@@ -12,6 +13,7 @@ import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/utils/exchange_provider_logger.dart';
import 'package:cw_core/amount_converter.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
@@ -56,7 +58,7 @@ class JupiterExchangeProvider extends ExchangeProvider {
// Check if currency tag is SOL (indicating it's a Solana token)
if (currency.tag != 'SOL') {
- throw Exception('Unsupported currency: ${currency.title} (not a Solana token)');
+ throw BadCurrencyException('Unsupported currency: ${currency.title} (not a Solana token)', currency);
}
// Use solana proxy to get token address
@@ -67,11 +69,11 @@ class JupiterExchangeProvider extends ExchangeProvider {
return solana!.getTokenAddress(currency);
} catch (e) {
printV('Error getting token address: $e');
- throw Exception('Unsupported currency: ${currency.title} (mint address not found: $e)');
+ throw BadCurrencyException('Unsupported currency: ${currency.title} (mint address not found: $e)', currency);
}
}
- throw Exception('Unsupported currency: ${currency.title} (Solana proxy not available)');
+ throw BadCurrencyException('Unsupported currency: ${currency.title} (Solana proxy not available)', currency);
}
@override
@@ -90,7 +92,7 @@ class JupiterExchangeProvider extends ExchangeProvider {
if (_isSolanaCurrency(from) && _isSolanaCurrency(to)) {
return Limits(min: null, max: null);
} else {
- throw Exception('not supported');
+ throw BadCurrencyPairException('not supported', from, to);
}
}
@@ -330,11 +332,11 @@ class JupiterExchangeProvider extends ExchangeProvider {
final totalFeeInSol = networkFeeInSol + integratorFeeInSol;
if (transaction == null || transaction.isEmpty) {
- throw Exception('No transaction returned from Jupiter order endpoint');
+ throw TradeNotCreatedException( description, description: 'No transaction returned from Jupiter order endpoint', );
}
if (requestId == null || requestId.isEmpty) {
- throw Exception('No requestId returned from Jupiter order endpoint');
+ throw TradeNotCreatedException( description,description: 'No requestId returned from Jupiter order endpoint');
}
final receiveAmount = AmountConverter.fromBaseUnits(outAmount, request.toCurrency.decimals);
@@ -395,7 +397,8 @@ class JupiterExchangeProvider extends ExchangeProvider {
},
);
printV('createTrade error: $e');
- throw TradeNotCreatedException(description);
+ if(e is! ExchangeProviderResponseException) throw TradeNotCreatedException(description, description: e.toString());
+ rethrow;
}
}
@@ -425,14 +428,14 @@ class JupiterExchangeProvider extends ExchangeProvider {
ExchangeProviderLogger.logError(
provider: description,
function: 'executeSwap',
- error: Exception('Failed to execute swap: ${response.statusCode} $errorBody'),
+ error: TradeExecutionException('Failed to execute swap: ${response.statusCode} $errorBody'),
stackTrace: StackTrace.current,
requestData: {
'requestId': requestId,
'hasSignedTransaction': signedTransaction.isNotEmpty,
},
);
- throw Exception('Failed to execute swap: ${response.statusCode} $errorBody');
+ throw TradeExecutionException('Failed to execute swap: ${response.statusCode} $errorBody');
}
final executeData = json.decode(response.body) as Map<String, dynamic>;
@@ -459,6 +462,7 @@ class JupiterExchangeProvider extends ExchangeProvider {
'hasSignedTransaction': signedTransaction.isNotEmpty,
},
);
+ if(e is! ExchangeProviderResponseException) throw TradeExecutionException(e.toString());
rethrow;
}
}
@@ -481,7 +485,7 @@ class JupiterExchangeProvider extends ExchangeProvider {
// - Poll /ultra/v1/execute with both signedTransaction and requestId
//
// For now, throw exception to indicate status must be checked on-chain
- throw Exception(
+ throw ExchangeProviderResponseException(
'Jupiter trade status must be checked on-chain using transaction signature (txId). '
'After transaction is sent, txId will contain the signature for status checking.');
}
### lib/exchange/provider/letsexchange_exchange_provider.dart
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:developer';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
@@ -70,7 +71,7 @@ class LetsExchangeExchangeProvider extends ExchangeProvider {
return Limits(min: min, max: max);
} catch (e) {
log(e.toString());
- throw Exception('Failed to fetch limits');
+ throw ExchangeProviderResponseException('Failed to fetch limits');
}
}
@@ -218,7 +219,7 @@ class LetsExchangeExchangeProvider extends ExchangeProvider {
'url': uri.toString(),
},
);
- throw Exception('LetsExchange create trade failed: ${response.body}');
+ throw TradeNotCreatedException(description, description: 'LetsExchange create trade failed: ${response.body}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final id = responseJSON['transaction_id'] as String;
@@ -340,7 +341,7 @@ class LetsExchangeExchangeProvider extends ExchangeProvider {
final response = await ProxyWrapper().get(clearnetUri: url, headers: headers);
if (response.statusCode != 200) {
- throw Exception('LetsExchange fetch trade failed: ${response.body}');
+ throw ExchangeProviderResponseCodeException('LetsExchange fetch trade failed: ${response.body}', response.statusCode);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
@@ -399,11 +400,11 @@ class LetsExchangeExchangeProvider extends ExchangeProvider {
);
if (response.statusCode != 200) {
- throw Exception('LetsExchange fetch info failed: ${response.body}');
+ throw ExchangeProviderResponseCodeException('LetsExchange fetch info failed: ${response.body}', response.statusCode);
}
return json.decode(response.body) as Map<String, dynamic>;
} catch (e) {
- throw Exception('LetsExchange failed to fetch info ${e.toString()}');
+ throw ExchangeProviderResponseException('LetsExchange failed to fetch info ${e.toString()}');
}
}
### lib/exchange/provider/near_Intents_exchange_provider.dart
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/core/utilities.dart';
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
@@ -10,6 +11,7 @@ import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cw_core/amount_converter.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
@@ -108,8 +110,8 @@ class NearIntentsExchangeProvider extends ExchangeProvider {
final destinationToken = currencyToNearAssetId(to, tokens);
if (originToken == null || destinationToken == null) {
- throw Exception(
- 'fetchLimits: unsupported currency pair: ${from.title} ${from.tag ?? ''} to ${to.title} ${to.tag ?? ''}');
+ throw BadCurrencyPairException(
+ 'fetchLimits: unsupported currency pair: ${from.title} ${from.tag ?? ''} to ${to.title} ${to.tag ?? ''}', from, to);
}
return Limits(min: null, max: null);
@@ -129,7 +131,7 @@ class NearIntentsExchangeProvider extends ExchangeProvider {
try {
if (originToken == null || destinationToken == null) {
- throw Exception('fetchRate: Unsupported currency pair');
+ throw BadCurrencyPairException('fetchRate: Unsupported currency pair', from, to);
}
final formattedAmount = AmountConverter.toBaseUnits(
@@ -152,7 +154,7 @@ class NearIntentsExchangeProvider extends ExchangeProvider {
);
if (quote == null) {
- throw Exception('fetchRate: Quote returned null');
+ throw ExchangeProviderResponseException('fetchRate: Quote returned null');
}
final q = quote['quote'] as Map<String, dynamic>;
@@ -215,7 +217,7 @@ class NearIntentsExchangeProvider extends ExchangeProvider {
final destinationToken = currencyToNearAssetId(request.toCurrency, tokens);
if (originToken == null || destinationToken == null) {
- throw Exception('Unsupported currency pair');
+ throw BadCurrencyPairException('Unsupported currency pair', request.fromCurrency, request.toCurrency);
}
final rawAmountStr = isFixedRateMode ? request.toAmount : request.fromAmount;
@@ -240,7 +242,7 @@ class NearIntentsExchangeProvider extends ExchangeProvider {
);
if (quote == null) {
- throw Exception('Quote request failed');
+ throw ExchangeProviderResponseException('Quote request failed');
}
final quoteObj = quote['quote'] as Map<String, dynamic>;
@@ -249,7 +251,7 @@ class NearIntentsExchangeProvider extends ExchangeProvider {
final depositAmount = quoteObj['amountInFormatted'] as String?;
if (depositAmount == null) {
- throw Exception('Deposit amount is null in quote response');
+ throw ExchangeProviderResponseException('Deposit amount is null in quote response');
}
final quoteRequest = quote['quoteRequest'] as Map<String, dynamic>;
@@ -258,12 +260,12 @@ class NearIntentsExchangeProvider extends ExchangeProvider {
final fromCurrency = _nearAssetIdToCurrency(fromAssetId, tokens);
if (fromCurrency == null) {
- throw Exception('Failed to parse from currency from assetId: $fromAssetId');
+ throw CurrencyParseException('Failed to parse from currency from assetId: $fromAssetId');
}
final toCurrency = _nearAssetIdToCurrency(toAssetId, tokens);
if (toCurrency == null) {
- throw Exception('Failed to parse to currency from assetId: $toAssetId');
+ throw CurrencyParseException('Failed to parse to currency from assetId: $toAssetId');
}
final from =
@@ -341,8 +343,8 @@ class NearIntentsExchangeProvider extends ExchangeProvider {
final response = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (response.statusCode != 200) {
- throw Exception(
- 'Near Intents fetch trade failed: ${response.statusCode} ${response.body}',
+ throw ExchangeProviderResponseCodeException(
+ 'Near Intents fetch trade failed: ${response.statusCode} ${response.body}', response.statusCode
);
}
@@ -610,7 +612,7 @@ class Token {
factory Token.fromJson(Map<String, dynamic> json) {
final decimals = json['decimals'] as int?;
if (decimals == null) {
- throw Exception('Token decimals is null for assetId: ${json['assetId']}');
+ throw ExchangeProviderResponseException('Token decimals is null for assetId: ${json['assetId']}');
}
return Token(
assetId: json['assetId'] as String,
### lib/exchange/provider/sideshift_exchange_provider.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
@@ -49,7 +50,7 @@ class SideShiftExchangeProvider extends ExchangeProvider {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error']['message'] as String;
- throw Exception('$error');
+ throw ExchangeProviderResponseCodeException('$error', response.statusCode);
}
if (response.statusCode != 200) return false;
@@ -79,11 +80,11 @@ class SideShiftExchangeProvider extends ExchangeProvider {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error']['message'] as String;
- throw Exception('$error');
+ throw ExchangeProviderResponseCodeException('$error', response.statusCode);
}
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
@@ -143,7 +144,7 @@ class SideShiftExchangeProvider extends ExchangeProvider {
},
);
- throw Exception('SideShift Internal Server Error: $error');
+ throw ExchangeProviderResponseCodeException('SideShift Internal Server Error: $error', response.statusCode);
}
if (response.statusCode != 200) {
@@ -162,7 +163,7 @@ class SideShiftExchangeProvider extends ExchangeProvider {
},
);
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
}
final rate = double.parse(responseJSON['rate'] as String);
@@ -352,11 +353,11 @@ class SideShiftExchangeProvider extends ExchangeProvider {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error']['message'] as String;
- throw TradeNotFoundException(id, provider: description, description: error);
+ throw ExchangeProviderResponseCodeException(error, response.statusCode);
}
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
### lib/exchange/provider/simpleswap_exchange_provider.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
@@ -67,11 +68,11 @@ class SimpleSwapExchangeProvider extends ExchangeProvider {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['message'] as String;
- throw Exception('$error');
+ throw ExchangeProviderResponseCodeException('$error', response.statusCode);
}
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
@@ -303,11 +304,11 @@ class SimpleSwapExchangeProvider extends ExchangeProvider {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['message'] as String;
- throw TradeNotFoundException(id, provider: description, description: error);
+ throw ExchangeProviderResponseCodeException(error, response.statusCode);
}
if (response.statusCode != 200) {
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
### lib/exchange/provider/stealth_ex_exchange_provider.dart
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:developer';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
@@ -68,15 +69,15 @@ class StealthExExchangeProvider extends ExchangeProvider {
);
if (response.statusCode != 200) {
- throw Exception('StealthEx fetch limits failed: ${response.body}');
+ throw ExchangeProviderResponseCodeException('StealthEx fetch limits failed: ${response.body}', response.statusCode);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final min = _toDouble(responseJSON['min_amount']);
final max = _toDouble(responseJSON['max_amount']);
return Limits(min: min, max: max);
} catch (e) {
log(e.toString());
- throw Exception('StealthEx failed to fetch limits');
+ throw ExchangeProviderResponseException('StealthEx failed to fetch limits');
}
}
@@ -216,7 +217,7 @@ class StealthExExchangeProvider extends ExchangeProvider {
'rateId': rateId,
},
);
- throw Exception('StealthEx create trade failed: ${response.body}');
+ throw ExchangeProviderResponseCodeException('StealthEx create trade failed: ${response.body}', response.statusCode);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final deposit = responseJSON['deposit'] as Map<String, dynamic>;
@@ -332,7 +333,7 @@ class StealthExExchangeProvider extends ExchangeProvider {
final response = await ProxyWrapper().get(clearnetUri: uri, headers: headers);
if (response.statusCode != 200) {
- throw Exception('StealthEx fetch trade failed: ${response.body}');
+ throw ExchangeProviderResponseCodeException('StealthEx fetch trade failed: ${response.body}', response.statusCode);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final deposit = responseJSON['deposit'] as Map<String, dynamic>;
### lib/exchange/provider/swapsxyz_exchange_provider.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
@@ -9,6 +10,7 @@ import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cw_core/amount_converter.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/crypto_currency.dart';
@@ -71,7 +73,7 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
}) async {
try {
final chains = await _geSupportedChain();
- if (chains.isEmpty) throw Exception('Failed to fetch supported chains');
+ if (chains.isEmpty) throw ExchangeProviderResponseException('Failed to fetch supported chains');
final fromToUse = isFixedRateMode ? to : from;
final toToUse = isFixedRateMode ? from : to;
@@ -95,14 +97,14 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
final uri = Uri.https(_baseUrl, _getPaths, params);
final res = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (res.statusCode != 200) {
- throw Exception('Unexpected http status: ${res.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${res.statusCode}', res.statusCode);
}
final body = json.decode(res.body) as Map<String, dynamic>;
final paths = (body['paths'] as List? ?? const []).cast<Map<String, dynamic>>();
if (paths.isEmpty) {
- throw Exception('No paths for ${fromToUse.title} -> ${toToUse.title}');
+ throw ExchangeProviderResponseException('No paths for ${fromToUse.title} -> ${toToUse.title}');
}
final int requestedDstId = dstChain.chainId;
@@ -123,10 +125,12 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
final supportsExactAmountOut = path['supportsExactAmountOut'] as bool? ?? false;
if (isFixedRateMode && !supportsExactAmountOut) {
- throw Exception('This route does not support fixed receive (exact-amount-out)');
+ throw ExchangeProviderResponseException(
+ 'This route does not support fixed receive (exact-amount-out)');
}
if (!isFixedRateMode && !supportsExactAmountIn) {
- throw Exception('This route does not support exact send (exact-amount-in)');
+ throw ExchangeProviderResponseException(
+ 'This route does not support exact send (exact-amount-in)');
}
Map<String, dynamic>? useLimits;
@@ -167,7 +171,7 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
return Limits(min: min, max: max);
} catch (e) {
printV('fetchLimits error: $e');
- throw Exception('Error fetching limits: $e');
+ throw ExchangeProviderResponseException('Error fetching limits: $e');
}
}
@@ -275,11 +279,12 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
final sender = request.refundAddress.trim();
final recipient = request.toAddress.trim();
if (sender.isEmpty || recipient.isEmpty) {
- throw Exception('Sender (refundAddress) or recipient (toAddress) is empty');
+ throw ArgumentError(
+ 'Sender (refundAddress) or recipient (toAddress) is empty');
}
final chains = await _geSupportedChain();
- if (chains.isEmpty) throw Exception('Failed to fetch supported chains');
+ if (chains.isEmpty) throw ExchangeProviderResponseException('Failed to fetch supported chains');
final srcChain = _findChainByCurrency(request.fromCurrency, chains);
final dstChain = _findChainByCurrency(request.toCurrency, chains);
@@ -295,7 +300,7 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
final amountStr = isFixedRateMode ? request.toAmount : request.fromAmount;
final rawAmount = double.tryParse(amountStr) ?? 0.0;
- if (rawAmount <= 0) throw Exception('Invalid amount');
+ if (rawAmount <= 0) throw ArgumentError('Invalid amount');
final formattedAmount = AmountConverter.toBaseUnits(
amountStr,
@@ -319,7 +324,7 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
final res = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (res.statusCode != 200) {
- throw Exception('getAction failed: ${res.statusCode} ${res.body}');
+ throw ExchangeProviderResponseException('getAction failed: ${res.statusCode} ${res.body}');
}
final data = json.decode(res.body) as Map<String, dynamic>;
@@ -344,13 +349,13 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
_decodeMethodSelector(routerData) == _swapAndExecuteSig;
if (!isAllowed) {
- throw Exception('Does not support that method selector');
+ throw ExchangeProviderResponseException('Does not support that method selector');
}
final txValue = txObj['value']?.toString() ?? '0';
final bridgeIds = (data['bridgeIds'] as List?) ?? const [];
- if (txId.isEmpty) throw Exception('No txId returned by getAction');
+ if (txId.isEmpty) throw ExchangeProviderResponseException('No txId returned by getAction');
final amtIn = (data['amountIn'] as Map?) ?? const {};
final amtInMax = (data['amountInMax'] as Map?) ?? const {};
@@ -442,14 +447,14 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
@override
Future<Trade> findTradeById({required String id}) async {
if (id.isEmpty) {
- throw Exception('Trade id is empty');
+ throw ArgumentError('Trade id is empty');
}
final uri = Uri.https(_baseUrl, _getStatus, {'txId': id});
final resp = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (resp.statusCode != 200) {
- throw Exception('getStatus failed: ${resp.statusCode} ${resp.body}');
+ throw ExchangeProviderResponseCodeException('getStatus failed: ${resp.statusCode} ${resp.body}', resp.statusCode);
}
final data = json.decode(resp.body) as Map<String, dynamic>;
@@ -459,7 +464,8 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
final error = data['error'] as Map<String, dynamic>?;
if (error != null) {
final code = error['code']?.toString() ?? 'unknown';
- throw Exception('SwapXyzExchangeProvider findTradeById error: ($id) $code');
+ throw ExchangeProviderResponseException(
+ 'SwapXyzExchangeProvider findTradeById error: ($id) $code');
}
}
@@ -742,7 +748,7 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
(c) {
return c.name.toUpperCase() == network;
},
- orElse: () => throw Exception('Unsupported chain for ${cur.title}'),
+ orElse: () => throw BadCurrencyException('Unsupported chain for ${cur.title}', cur),
);
}
### lib/exchange/provider/swaptrade_exchange_provider.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
@@ -65,7 +66,7 @@ class SwapTradeExchangeProvider extends ExchangeProvider {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode != 200)
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
final coinsInfoRaw = responseJSON['data'];
final coinsInfo = coinsInfoRaw is List<dynamic> ? coinsInfoRaw : <dynamic>[];
@@ -127,7 +128,7 @@ class SwapTradeExchangeProvider extends ExchangeProvider {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
- error: Exception('Unexpected http status: ${response.statusCode}'),
+ error: ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode),
stackTrace: StackTrace.current,
requestData: {
'from': from.title,
@@ -139,7 +140,7 @@ class SwapTradeExchangeProvider extends ExchangeProvider {
'url': uri.toString(),
},
);
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
}
final data = responseBody['data'] as Map<String, dynamic>;
@@ -277,7 +278,7 @@ class SwapTradeExchangeProvider extends ExchangeProvider {
'url': uri.toString(),
},
);
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
}
final responseData = responseBody['data'] as Map<String, dynamic>;
@@ -365,7 +366,7 @@ class SwapTradeExchangeProvider extends ExchangeProvider {
}
if (response.statusCode != 200)
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
final responseData = responseBody['data'] as Map<String, dynamic>;
final fromCurrency = responseData['coin_send'] as String;
### lib/exchange/provider/thorchain_exchange.provider.dart
@@ -1,9 +1,11 @@
import 'dart:convert';
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
import 'package:cake_wallet/exchange/trade.dart';
+import "package:cake_wallet/exchange/trade_not_created_exception.dart";
import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
@@ -197,23 +199,23 @@ class ThorChainExchangeProvider extends ExchangeProvider {
@override
Future<Trade> findTradeById({required String id}) async {
- if (id.isEmpty) throw Exception('Trade id is empty');
+ if (id.isEmpty) throw ArgumentError('Trade id is empty');
final formattedId = id.startsWith('0x') ? id.substring(2) : id;
final uri = Uri.https(_baseNodeURL, '$_txInfoPath$formattedId');
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 404) {
- throw Exception('Trade not found for id: $formattedId');
+ throw TradeNotFoundException(id, description:'Trade not found for id: $formattedId', provider: description);
} else if (response.statusCode != 200) {
- throw Exception('Unexpected HTTP status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected HTTP status: ${response.statusCode}', response.statusCode);
}
final responseJSON = json.decode(response.body);
final Map<String, dynamic> stagesJson = responseJSON['stages'] as Map<String, dynamic>;
final inboundObservedStarted = stagesJson['inbound_observed']?['started'] as bool? ?? true;
if (!inboundObservedStarted) {
- throw Exception('Trade has not started for id: $formattedId');
+ throw TradeNotCreatedException(description, description: 'Trade has not started for id: $formattedId');
}
final currentState = _updateStateBasedOnStages(stagesJson) ?? TradeState.notFound;
@@ -292,28 +294,28 @@ class ThorChainExchangeProvider extends ExchangeProvider {
ExchangeProviderLogger.logError(
provider: description,
function: '_getSwapQuote',
- error: Exception('Unexpected HTTP status: ${response.statusCode}'),
+ error: ExchangeProviderResponseCodeException('Unexpected HTTP status: ${response.statusCode}', response.statusCode),
stackTrace: StackTrace.current,
requestData: {
'params': params,
'url': uri.toString(),
},
);
- throw Exception('Unexpected HTTP status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected HTTP status: ${response.statusCode}', response.statusCode);
}
if (response.body.contains('error')) {
ExchangeProviderLogger.logError(
provider: description,
function: '_getSwapQuote',
- error: Exception('Unexpected response: ${response.body}'),
+ error: ExchangeProviderResponseException('Unexpected response: ${response.body}'),
stackTrace: StackTrace.current,
requestData: {
'params': params,
'url': uri.toString(),
},
);
- throw Exception('Unexpected response: ${response.body}');
+ throw ExchangeProviderResponseException('Unexpected response: ${response.body}');
}
return json.decode(response.body) as Map<String, dynamic>;
### lib/exchange/provider/trocador_exchange_provider.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
@@ -94,11 +95,11 @@ class TrocadorExchangeProvider extends ExchangeProvider {
final response = await ProxyWrapper().get(clearnetUri: uri, headers: {'API-Key': apiKey});
if (response.statusCode != 200)
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
final responseJSON = json.decode(response.body) as List<dynamic>;
- if (responseJSON.isEmpty) throw Exception('No data');
+ if (responseJSON.isEmpty) throw ExchangeProviderResponseException('No data');
final coinJson = responseJSON.first as Map<String, dynamic>;
@@ -167,7 +168,7 @@ class TrocadorExchangeProvider extends ExchangeProvider {
'url': uri.toString(),
},
);
- throw Exception('No enabled providers found for the selected trade.');
+ throw ExchangeProviderResponseException('No enabled providers found for the selected trade.');
}
if (rateId.isNotEmpty) _lastUsedRateId = rateId;
@@ -268,7 +269,7 @@ class TrocadorExchangeProvider extends ExchangeProvider {
'params': params,
},
);
- throw Exception('No available provider is enabled');
+ throw ExchangeProviderResponseException('No available provider is enabled');
}
params['provider'] = _provider.first.toString();
@@ -300,7 +301,7 @@ class TrocadorExchangeProvider extends ExchangeProvider {
},
);
- throw Exception('${error}\n$message');
+ throw ExchangeProviderResponseException('${error}\n$message');
}
if (response.statusCode != 200) {
@@ -322,7 +323,7 @@ class TrocadorExchangeProvider extends ExchangeProvider {
'url': uri.toString(),
},
);
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
@@ -402,7 +403,7 @@ class TrocadorExchangeProvider extends ExchangeProvider {
return ProxyWrapper()
.get(clearnetUri: uri, headers: {'API-Key': apiKey}).then((response) async {
if (response.statusCode != 200)
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
final responseListJson = json.decode(response.body) as List;
final responseJSON = responseListJson.first as Map<String, dynamic>;
@@ -464,7 +465,7 @@ class TrocadorExchangeProvider extends ExchangeProvider {
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode != 200)
- throw Exception('Unexpected http status: ${response.statusCode}');
+ throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
### lib/exchange/provider/xoswap_exchange_provider.dart
@@ -1,5 +1,6 @@
import 'dart:convert';
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
@@ -9,6 +10,7 @@ import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cake_wallet/utils/package_info.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cake_wallet/utils/exchange_provider_logger.dart';
@@ -122,7 +124,7 @@ class XOSwapExchangeProvider extends ExchangeProvider {
final response = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (response.statusCode != 200) {
- throw Exception('Failed to fetch assets for ${currency.title} on ${currency.tag}');
+ throw ExchangeProviderResponseCodeException('Failed to fetch assets for ${currency.title} on ${currency.tag}', response.statusCode);
}
final decoded = jsonDecode(response.body);
@@ -171,7 +173,7 @@ class XOSwapExchangeProvider extends ExchangeProvider {
}) async {
try {
final rates = await getRatesForPair(from: from, to: to);
- if (rates.isEmpty) throw Exception('No rates found for $from to $to');
+ if (rates.isEmpty) throw BadCurrencyPairException('No rates found for $from to $to', from, to);
double minLimit = double.infinity;
double maxLimit = 0;
@@ -185,7 +187,7 @@ class XOSwapExchangeProvider extends ExchangeProvider {
return Limits(min: minLimit, max: maxLimit);
} catch (e) {
printV(e.toString());
- throw Exception('StealthEx failed to fetch limits');
+ throw ExchangeProviderResponseException('StealthEx failed to fetch limits');
}
}
@@ -359,8 +361,8 @@ class XOSwapExchangeProvider extends ExchangeProvider {
'url': uri.toString(),
},
);
-
- throw Exception('$error\n$message');
+
+ throw ExchangeProviderResponseException('$error\n$message');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
@@ -376,7 +378,7 @@ class XOSwapExchangeProvider extends ExchangeProvider {
final parsedAmount = double.tryParse(depositAmountStr);
if (parsedAmount == null || parsedAmount <= 0) {
- throw Exception('Invalid deposit amount received from API');
+ throw ExchangeProviderResponseException('Invalid deposit amount received from API');
}
final receiveAmount = toAmount['value'] as String;
@@ -463,11 +465,11 @@ class XOSwapExchangeProvider extends ExchangeProvider {
if (response.statusCode != 200) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
if (responseJSON.containsKey('code') && responseJSON['code'] == 'NOT_FOUND') {
- throw Exception('Trade not found');
+ throw TradeNotFoundException(id, description: 'Trade not found', provider: description);
}
final error = responseJSON['error'] ?? 'Unknown error';
final message = responseJSON['message'] ?? responseJSON['details'] ?? '';
- throw Exception('$error\n$message');
+ throw ExchangeProviderResponseException('$error\n$message');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
@@ -522,7 +524,7 @@ class XOSwapExchangeProvider extends ExchangeProvider {
final parsedAmount = double.tryParse(depositAmountStr);
if (parsedAmount == null || parsedAmount <= 0) {
- throw Exception('Invalid deposit amount received from API');
+ throw ExchangeProviderResponseException('Invalid deposit amount received from API');
}
final receiveAmount = toAmount['value'] as String;
### lib/exchange/trade_not_found_exception.dart
@@ -1,13 +0,0 @@
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/generated/i18n.dart';
-
-class TradeNotFoundException implements Exception {
- TradeNotFoundException(this.tradeId, {required this.provider, this.description = ''});
-
- String tradeId;
- ExchangeProviderDescription provider;
- String description;
-
- @override
- String toString() => '${S.current.trade_id_not_found(tradeId, provider.title)} $description';
-}
### lib/monero/cw_monero.dart
@@ -134,7 +134,7 @@ class CWMoneroWalletDetails extends MoneroWalletDetails {
@computed
@override
MoneroBalance get balance {
- throw Exception('Unimplemented');
+ throw UnimplementedError();
// return MoneroBalance();
//return MoneroBalance(
// fullBalance: balance.fullBalance,
### lib/nano/cw_nano.dart
@@ -113,7 +113,7 @@ class CWNano extends Nano {
String? passphrase,
}) {
if (mnemonic.split(" ").length == 12 && derivationType != DerivationType.bip39) {
- throw Exception("Invalid mnemonic for derivation type!");
+ throw BadMnemonicException("Invalid mnemonic for derivation type!");
}
return NanoRestoreWalletFromSeedCredentials(
@@ -133,7 +133,7 @@ class CWNano extends Nano {
required DerivationType derivationType,
}) {
if (seedKey.length == 128 && derivationType != DerivationType.bip39) {
- throw Exception("Invalid seed key length for derivation type!");
+ throw BadKeysException("Invalid seed key length for derivation type!");
}
return NanoRestoreWalletFromKeysCredentials(
@@ -164,7 +164,7 @@ class CWNano extends Nano {
@override
Future<void> changeRep(Object wallet, String address) async {
if ((wallet as NanoWallet).transactionHistory.transactions.isEmpty) {
- throw Exception("Can't change representative without an existing transaction history");
+ throw NanoChangeRepException("Can't change representative without an existing transaction history");
}
return wallet.changeRep(address);
}
@@ -232,7 +232,7 @@ class CWNanoUtil extends NanoUtil {
String? publicAddress;
if (seedKey == null && mnemonic == null) {
- throw Exception("One of seed key OR mnemonic must be provided!");
+ throw ArgumentError("One of seed key OR mnemonic must be provided!");
}
try {
### lib/new-ui/model/charts/price_data.dart
@@ -21,7 +21,7 @@ Currency currencyFromApiString(String key) {
case "sol":
throw UnimplementedError();
}
- throw Exception("unknown api string");
+ throw ArgumentError("unknown api string");
}
class PriceData implements Comparable<PriceData> {
### lib/new-ui/viewmodels/charts/charts_bloc.dart
@@ -89,7 +89,7 @@ class ChartsBloc extends Bloc<ChartsEvent, ChartsState> {
),
);
} else {
- throw Exception("attempted price load without currency data");
+ throw StateError("attempted price load without currency data");
}
}
@@ -132,7 +132,7 @@ class ChartsBloc extends Bloc<ChartsEvent, ChartsState> {
final newCurrencies = s.currencies..remove(event.currency);
if (newCurrencies.isEmpty) {
- throw Exception(
+ throw StateError(
"removed the last currency ${kDebugMode ? "- your ui should block this! what did you do?" : ""}",
);
}
### lib/new-ui/widgets/receive_page/receive_top_bar.dart
@@ -20,10 +20,10 @@ class ModalTopBar extends StatelessWidget {
this.leadingSemanticLabel,
this.trailingSemanticLabel}) {
if (leadingIcon != null && leadingWidget != null) {
- throw Exception("Cannot have both leadingIcon and leadingWidget");
+ throw ArgumentError("Cannot have both leadingIcon and leadingWidget");
}
if (trailingIcon != null && trailingWidget != null) {
- throw Exception("Cannot have both trailingIcon and trailingWidget");
+ throw ArgumentError("Cannot have both trailingIcon and trailingWidget");
}
}
### lib/order/order_provider_description.dart
@@ -1,4 +1,5 @@
import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
class OrderProviderDescription extends EnumerableItem<int> with Serializable<int> {
const OrderProviderDescription({
@@ -17,7 +18,7 @@ class OrderProviderDescription extends EnumerableItem<int> with Serializable<int
case 0:
return cakePay;
default:
- throw Exception('Invalid OrderProviderDescription $raw');
+ throw DeserializeException('Invalid OrderProviderDescription $raw');
}
}
}
### lib/order/order_source_description.dart
@@ -1,4 +1,6 @@
import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
+
class OrderSourceDescription extends EnumerableItem<int> with Serializable<int> {
const OrderSourceDescription({required String title, required int raw})
@@ -14,7 +16,7 @@ class OrderSourceDescription extends EnumerableItem<int> with Serializable<int>
case 1:
return order;
default:
- throw Exception('Invalid OrderSourceDescription raw value: $raw');
+ throw DeserializeException('Invalid OrderSourceDescription raw value: $raw');
}
}
}
### lib/solana/cw_solana.dart
@@ -207,7 +207,7 @@ class CWSolana extends Solana {
final solanaProvider = solanaWallet.solanaProvider;
if (solanaProvider == null) {
- throw Exception('Solana provider not available');
+ throw TransactionGenerationException('Solana provider not available');
}
final unsignedTransactionBytes = base64.decode(base64Transaction);
@@ -222,11 +222,11 @@ class CWSolana extends Solana {
Future<String> sendTx() async {
try {
if (signedTransactionBase64.isEmpty) {
- throw Exception('Invalid transaction: transaction is empty');
+ throw TransactionSendingException('Invalid transaction: transaction is empty');
}
if (requestId.isEmpty) {
- throw Exception('Invalid requestId: requestId is empty');
+ throw TransactionSendingException('Invalid requestId: requestId is empty');
}
final jupiterProvider = JupiterExchangeProvider();
@@ -247,7 +247,7 @@ class CWSolana extends Solana {
if (signature == null ||
signature.isEmpty ||
signature == '1111111111111111111111111111111111111111111111111111111111111111') {
- throw Exception(
+ throw ExchangeProviderResponseException(
'Invalid transaction signature received from Jupiter. '
'Status: $status',
);
@@ -264,22 +264,22 @@ class CWSolana extends Solana {
errorMessage: errorMessage,
);
} else {
- throw Exception(userFriendlyError);
+ throw ExchangeProviderResponseException(userFriendlyError);
}
case 'Pending':
case 'Processing':
- throw Exception(
+ throw ExchangeProviderResponseException(
'Jupiter swap is still processing. Please wait and try checking the transaction status.',
);
default:
- throw Exception(
+ throw ExchangeProviderResponseException(
'Jupiter swap returned unknown status: $status. Error: $errorMessage. Code: $errorCode',
);
}
} on JupiterSwapFailedException {
rethrow;
} catch (e) {
- throw Exception('Failed to execute Jupiter swap: $e');
+ throw TradeNotCreatedException(ExchangeProviderDescription.jupiter, description: 'Failed to execute Jupiter swap: $e');
}
}
### lib/src/screens/dashboard/widgets/menu_widget.dart
@@ -1,6 +1,7 @@
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/src/widgets/setting_action_button.dart';
import 'package:cake_wallet/src/widgets/setting_actions.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:flutter/material.dart';
import "package:flutter_svg/svg.dart";
import 'package:cake_wallet/view_model/dashboard/dashboard_view_model.dart';
@@ -279,7 +280,7 @@ class MenuWidgetState extends State<MenuWidget> {
case WalletType.zcash:
return zcashIcon;
default:
- throw Exception('No icon for ${type.toString()}');
+ throw BadWalletTypeException('No icon for ${type.toString()}',type);
}
}
}
### lib/src/screens/dev/moneroc_cache_debug.dart
@@ -5,6 +5,7 @@ import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/utils/share_util.dart';
import 'package:cake_wallet/view_model/dashboard/dashboard_view_model.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/root_dir.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/material.dart';
@@ -37,7 +38,7 @@ class _MoneroCacheDebugState extends State<MoneroCacheDebug> {
late DebuggableWallets wallet = switch (dashboardViewModel.wallet.type) {
WalletType.monero => DebuggableWallets.monero,
- _ => throw Exception("Unknown wallet type"),
+ _ => throw BadWalletTypeException("Unknown wallet type",dashboardViewModel.wallet.type),
};
late Map<String, dynamic> walletCache = switch (wallet) {
### lib/src/screens/dev/moneroc_call_profiler.dart
@@ -8,6 +8,7 @@ import 'package:cake_wallet/src/widgets/primary_button.dart';
import 'package:cake_wallet/view_model/dashboard/dashboard_view_model.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zano/zano.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/material.dart';
import 'package:cake_wallet/src/screens/base_page.dart';
@@ -46,7 +47,7 @@ class _PerformanceDebugState extends State<PerformanceDebug> {
WalletType.monero => ProfilableWallet.monero,
WalletType.wownero => ProfilableWallet.wownero,
WalletType.zano => ProfilableWallet.zano,
- _ => throw Exception("Unknown wallet type"),
+ _ => throw BadWalletTypeException("Unknown wallet type",dashboardViewModel.wallet.type),
};
final precalc = 1700298;
### lib/src/screens/setup_2fa/setup_2fa_enter_code_page.dart
@@ -79,7 +79,7 @@ class TotpAuthCodePageState extends State<TotpAuthCodePage> {
Future<void> close({String? route, dynamic arguments}) async {
if (_key.currentContext == null) {
- throw Exception('Key context is null. Should be not happened');
+ throw ArgumentError('Key context is null. Should be not happened');
}
await Future<void>.delayed(Duration(milliseconds: 50));
if (route != null) {
### lib/src/screens/wallet_unlock/wallet_unlock_page.dart
@@ -130,7 +130,7 @@ class WalletUnlockPageState extends AuthPageState<WalletUnlockPage> {
@override
Future<void> close({String? route, arguments}) async {
if (_key.currentContext == null) {
- throw Exception('Key context is null. Should be not happened');
+ throw ArgumentError('Key context is null. Should be not happened');
}
/// not the best scenario, but WidgetsBinding is not behaving correctly on Android
### lib/src/widgets/blockchain_height_widget.dart
@@ -4,6 +4,7 @@ import 'package:cake_wallet/utils/date_picker.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/zcash/zcash.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
@@ -204,7 +205,7 @@ class BlockchainHeightState extends State<BlockchainHeightWidget> {
} else if (widget.walletType == WalletType.zano) {
height = zano!.getHeightByDate(date: date);
} else {
- throw Exception("unknown currency in BlockchainHeightWidget");
+ throw BadWalletTypeException("unknown currency in BlockchainHeightWidget",widget.walletType);
}
}
if (mounted) {
### lib/src/widgets/standard_list.dart
@@ -219,7 +219,7 @@ class SectionStandardList extends StatelessWidget {
Widget buildTitle(List<Widget> items, int sectionIndex) {
if (sectionTitleBuilder == null) {
- throw Exception('Cannot to build title. sectionTitleBuilder is null');
+ throw ArgumentError('Cannot to build title. sectionTitleBuilder is null');
}
return sectionTitleBuilder!.call(sectionIndex);
### lib/store/settings_store.dart
@@ -33,6 +33,7 @@ import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/zcash/zcash.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:cake_wallet/exchange/provider/trocador_exchange_provider.dart';
import 'package:cake_wallet/monero/monero.dart';
@@ -1134,15 +1135,15 @@ abstract class SettingsStoreBase with Store {
}
}
- throw Exception('No node found for EVM wallet type with chainId: $chainId');
+ throw NodeLookupException('No node found for EVM wallet type with chainId: $chainId');
}
final node = nodes[walletType];
if (node == null) {
- throw Exception('No node found for wallet type: ${walletType.toString()}');
+ throw NodeLookupException('No node found for wallet type: ${walletType.toString()}');
}
if (node.type != walletType) {
- throw Exception("Node is not valid for $walletType (found: ${node.type}");
+ throw NodeLookupException("Node is not valid for $walletType (found: ${node.type}");
}
return node;
@@ -1172,7 +1173,7 @@ abstract class SettingsStoreBase with Store {
final node = powNodes[walletType];
if (node == null) {
- throw Exception('No pow node found for wallet type: ${walletType.toString()}');
+ throw NodeLookupException('No pow node found for wallet type: ${walletType.toString()}');
}
return node;
### lib/view_model/auth_view_model.dart
@@ -105,15 +105,11 @@ abstract class AuthViewModelBase with Store {
@action
Future<void> biometricAuth() async {
- try {
if (await _biometricAuth.canCheckBiometrics() && await _biometricAuth.isAuthenticated()) {
state = ExecutedSuccessfullyState();
} else {
- throw Exception('Biometric authentication failed');
+ state = FailureState("Biometric authentication failed");
}
- } catch (e) {
- state = FailureState(e.toString());
- }
}
void _saveLastAuthTime(ExecutionState state) {
### lib/view_model/cake_pay/cake_pay_buy_card_view_model.dart
@@ -200,7 +200,7 @@ abstract class CakePayBuyCardViewModelBase with Store {
method: selectedPaymentMethod,
order: order); // TODO should hande other currencies if added
if (paymentData == null || order == null)
- throw Exception('Payment data or order is not available.');
+ throw CakePayNoDataException('Payment data or order is not available.');
await confirmSending(paymentData);
expirationTime = order!.paymentData.expirationTime;
@@ -247,7 +247,7 @@ abstract class CakePayBuyCardViewModelBase with Store {
@action
Future<void> simulatePayment() async {
if (order == null) {
- throw Exception('Order is not created yet.');
+ throw CakePayNoDataException('Order is not created yet.');
}
try {
### lib/view_model/dashboard/balance_view_model.dart
@@ -14,6 +14,7 @@ import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/view_model/wallet_account_list/account_list_item.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_amount_format.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cake_wallet/store/app_store.dart';
@@ -509,7 +510,7 @@ abstract class BalanceViewModelBase with Store {
Balance _currencyBalance(CryptoCurrency cryptoCurrency) {
final balance = wallet.balance[cryptoCurrency];
- if (balance == null) throw Exception('No balance for ${wallet.currency}');
+ if (balance == null) throw BadCurrencyException('No balance for ${wallet.currency}', wallet.currency);
return balance;
}
### lib/view_model/dashboard/dashboard_view_model.dart
@@ -10,6 +10,7 @@ import 'package:cake_wallet/view_model/wallet_account_list/account_list_item.dar
import 'package:cw_core/account.dart';
import 'package:cake_wallet/view_model/dashboard/date_section_item.dart';
import "package:cw_core/balance_card_layout.dart";
+import "package:cake_wallet/view_model/viewmodel_exceptions.dart";
import "package:cw_core/balance_card_style_settings.dart";
import 'package:cake_wallet/core/trade_monitor.dart';
import 'package:cake_wallet/entities/auto_generate_subaddress_status.dart';
@@ -1029,7 +1030,8 @@ abstract class DashboardViewModelBase with Store {
if (permissionStatus != PermissionStatus.granted) {
final resp = await Permission.notification.request();
if (resp == PermissionStatus.denied) {
- throw Exception("Notification permission denied");
+ throw const SystemPermissionException(
+ Permission.notification, "Notification permission denied");
}
}
backgroundSyncNotificationsEnabled = value;
### lib/view_model/dashboard/nft_view_model.dart
@@ -10,6 +10,7 @@ import 'package:cake_wallet/src/screens/wallet_connect/services/bottom_sheet_ser
import 'package:cake_wallet/src/screens/wallet_connect/widgets/bottom_sheet/bottom_sheet_message_display_widget.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/utils/debounce.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import "package:cw_core/utils/ipfs_url.dart";
import "package:cw_core/utils/print_verbose.dart";
import "package:cw_core/wallet_base.dart";
@@ -23,6 +24,17 @@ import 'package:cake_wallet/store/app_store.dart';
part 'nft_view_model.g.dart';
+class NFTResponseException extends ServerResponseException with ResponseCodeException {
+ const NFTResponseException(super.message, this.code);
+
+ @override
+ final int code;
+}
+
+class NFTMetadataException extends CakeException {
+ NFTMetadataException(super.message);
+}
+
class NFTViewModel = NFTViewModelBase with _$NFTViewModel;
abstract class NFTViewModelBase with Store {
@@ -268,7 +280,7 @@ abstract class NFTViewModelBase with Store {
.timeout(_requestTimeout);
if (response.statusCode < 200 || response.statusCode >= 300) {
- throw Exception("Failed to fetch wallet NFTs (${response.statusCode})");
+ throw NFTResponseException("Failed to fetch wallet NFTs (${response.statusCode})", response.statusCode);
}
return (jsonDecode(response.body) as List<dynamic>)
@@ -380,7 +392,7 @@ abstract class NFTViewModelBase with Store {
}
if (onChainData == null) {
- throw Exception("Could not load NFT metadata for $address");
+ throw NFTMetadataException("Could not load NFT metadata for $address");
}
return SolanaNFTAssetModel(
@@ -406,7 +418,7 @@ abstract class NFTViewModelBase with Store {
.timeout(_requestTimeout);
if (response.statusCode < 200 || response.statusCode >= 300) {
- throw Exception("Failed to fetch NFT metadata (${response.statusCode})");
+ throw NFTResponseException("Failed to fetch NFT metadata (${response.statusCode})", response.statusCode);
}
return SolanaNFTAssetModel.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
### lib/view_model/dev/shared_preferences.dart
@@ -1,8 +1,13 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
part 'shared_preferences.g.dart';
+class SharedPreferencesException extends CakeException{
+ const SharedPreferencesException(super.message);
+}
+
class DevSharedPreferences = DevSharedPreferencesBase with _$DevSharedPreferences;
enum PreferenceType { unknown, string, int, double, bool, listString }
@@ -55,8 +60,8 @@ abstract class DevSharedPreferencesBase with Store {
case PreferenceType.listString:
await sharedPreferences!.setStringList(key, List<String>.from(value as Iterable<dynamic>));
break;
- default:
- throw Exception("Unknown preference type: $type");
+ case PreferenceType.unknown:
+ throw SharedPreferencesException("Unknown preference type: $type");
}
}
### lib/view_model/exchange/exchange_view_model.dart
@@ -44,6 +44,7 @@ import 'package:cake_wallet/utils/exchange_provider_logger.dart';
import 'package:cw_core/amount/amount_sanitizer.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/amount/money_double.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import "package:cw_core/wallet_info.dart";
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
import 'package:cake_wallet/store/dashboard/trades_store.dart';
@@ -536,7 +537,7 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
if (priority == null) {
- throw Exception('Unexpected type ${wallet.type.toString()}');
+ throw BadWalletTypeException('Unexpected type ${wallet.type.toString()}', wallet.type);
}
return priority;
### lib/view_model/hardware_wallet/bitbox_view_model.dart
@@ -7,6 +7,7 @@ import "package:cake_wallet/entities/hardware_wallet/hardware_wallet_device.dart
import "package:cake_wallet/evm/evm.dart";
import "package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_model.dart";
import "package:cake_wallet/wallet_type_utils.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
import "package:cw_core/hardware/hardware_wallet_service.dart";
import "package:cw_core/root_dir.dart";
import "package:cw_core/utils/print_verbose.dart";
@@ -132,7 +133,7 @@ abstract class BitboxViewModelBase extends HardwareWalletViewModel with Store {
case WalletType.polygon:
return evm!.setHardwareWalletService(wallet, getHardwareWalletService(wallet.type));
default:
- throw Exception("Unexpected wallet type: ${wallet.type} for bitbox");
+ throw BadWalletTypeException('Unexpected wallet type: ${wallet.type} for bitbox', wallet.type);
}
}
}
### lib/view_model/hardware_wallet/ledger_view_model.dart
@@ -9,9 +9,9 @@ import "package:cake_wallet/main.dart";
import "package:cake_wallet/monero/monero.dart";
import "package:cake_wallet/routes.dart";
import "package:cake_wallet/src/screens/connect_device/connect_device_page.dart";
-import "package:cake_wallet/store/app_store.dart";
import "package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_model.dart";
import "package:cake_wallet/wallet_type_utils.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
import "package:cw_core/hardware/device_connection_type.dart";
import "package:cw_core/hardware/hardware_wallet_service.dart";
import "package:cw_core/utils/print_verbose.dart";
@@ -22,6 +22,7 @@ import "package:flutter/widgets.dart";
import "package:ledger_flutter_plus/ledger_flutter_plus.dart" as sdk;
import "package:mobx/mobx.dart";
import "package:permission_handler/permission_handler.dart";
+import "package:cake_wallet/store/app_store.dart";
part "ledger_view_model.g.dart";
@@ -226,7 +227,7 @@ abstract class LedgerViewModelBase extends HardwareWalletViewModel with Store {
case WalletType.polygon:
return evm!.setHardwareWalletService(wallet, getHardwareWalletService(wallet.type));
default:
- throw Exception("Unexpected wallet type: ${wallet.type} for ledger");
+ throw BadWalletTypeException("Unexpected wallet type: ${wallet.type} for ledger", wallet.type);
}
}
### lib/view_model/hardware_wallet/trezor_connect_view_model.dart
@@ -26,6 +26,8 @@ import "package:mobx/mobx.dart";
import "package:permission_handler/permission_handler.dart";
import "package:trezor_connect/trezor_connect.dart" as connect_sdk;
import "package:trezor_flutter/trezor_flutter.dart" as sdk;
+import "package:cw_core/exceptions/cake_exception.dart";
+
part "trezor_connect_view_model.g.dart";
@@ -250,10 +252,7 @@ abstract class TrezorConnectViewModelBase extends HardwareWalletViewModel with S
final res = await _pinCompleter!.future;
paringState = TrezorParingState.verifyingPin;
- if (res == null) {
- throw Exception();
- }
- return res;
+ return res!;
}
final deviceInfo = await _deviceName;
@@ -378,7 +377,7 @@ abstract class TrezorConnectViewModelBase extends HardwareWalletViewModel with S
case WalletType.polygon:
return evm!.setHardwareWalletService(wallet, getHardwareWalletService(wallet.type));
default:
- throw Exception("Unexpected wallet type: ${wallet.type} for trezor");
+ throw BadWalletTypeException('Unexpected wallet type: ${wallet.type} for trezor', wallet.type);
}
}
@@ -419,7 +418,7 @@ abstract class TrezorConnectViewModelBase extends HardwareWalletViewModel with S
_state = state;
return state;
} catch (_) {
- throw Exception("Unable to save Trezor State");
+ rethrow;
}
}
### lib/view_model/integrations/deuro_view_model.dart
@@ -11,13 +11,18 @@ import 'package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_mode
import 'package:cake_wallet/view_model/send/send_view_model_state.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/parse_fixed.dart';
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:mobx/mobx.dart';
part 'deuro_view_model.g.dart';
+class DeuroException extends CakeException {
+ const DeuroException(super.message);
+}
+
class DEuroViewModel = DEuroViewModelBase with _$DEuroViewModel;
abstract class DEuroViewModelBase with Store {
@@ -160,7 +165,7 @@ abstract class DEuroViewModelBase with Store {
state = TransactionCommitting();
final priority = _appStore.settingsStore.getPriority(wallet.type, chainId: wallet.chainId)!;
final approval = await evm!.enableDEuroSaving(_appStore.wallet!, priority);
- if (approval == null) throw Exception("DEuro saving not available");
+ if (approval == null) throw DeuroException("DEuro saving not available");
approvalTransaction = approval;
state = InitialExecutionState();
@@ -175,21 +180,21 @@ abstract class DEuroViewModelBase with Store {
state = TransactionCommitting();
if (amountRaw.isEmpty || amountRaw.trim().isEmpty) {
- throw Exception("Invalid amount: amount cannot be empty");
+ throw ArgumentError("Invalid amount: amount cannot be empty");
}
final amount = tryParseFixed(amountRaw, 18);
if (amount == BigInt.zero || amount == null) {
- throw Exception("Invalid amount: amount cannot be zero");
+ throw ArgumentError("Invalid amount: amount cannot be zero");
}
final priority = _appStore.settingsStore.getPriority(wallet.type, chainId: wallet.chainId)!;
actionType = isAdding ? DEuroActionType.deposit : DEuroActionType.withdraw;
final tx = await (isAdding
? evm!.addDEuroSaving(_appStore.wallet!, amount, priority)
: evm!.removeDEuroSaving(_appStore.wallet!, amount, priority));
- if (tx == null) throw Exception("DEuro saving not available");
+ if (tx == null) throw DeuroException("DEuro saving not available");
transaction = tx;
state = InitialExecutionState();
@@ -205,7 +210,7 @@ abstract class DEuroViewModelBase with Store {
actionType = DEuroActionType.withdraw;
final priority = _appStore.settingsStore.getPriority(wallet.type, chainId: wallet.chainId)!;
final tx = await evm!.withdrawDEuroSavingV1(_appStore.wallet!, priority);
- if (tx == null) throw Exception("DEuro saving not available");
+ if (tx == null) throw DeuroException("DEuro saving not available");
transaction = tx;
state = InitialExecutionState();
@@ -235,7 +240,7 @@ abstract class DEuroViewModelBase with Store {
actionType = DEuroActionType.reinvest;
final priority = _appStore.settingsStore.getPriority(wallet.type, chainId: wallet.chainId)!;
final tx = await evm!.reinvestDEuroInterest(_appStore.wallet!, priority);
- if (tx == null) throw Exception("DEuro saving not available");
+ if (tx == null) throw DeuroException("DEuro saving not available");
transaction = tx;
state = InitialExecutionState();
### lib/view_model/node_list/node_create_or_edit_view_model.dart
@@ -3,6 +3,7 @@ import 'package:cake_wallet/entities/new_ui_entities/list_item/list_item.dart';
import 'package:cake_wallet/entities/qr_scanner.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/utils/permission_handler.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/wallet_type.dart';
@@ -307,18 +308,18 @@ abstract class NodeCreateOrEditViewModelBase with Store {
await PermissionHandler.checkPermission(Permission.camera, context);
if (!isCameraPermissionGranted) return;
String? code = await presentQRScanner(context);
- if (code == null) throw Exception("Unexpected QR code value: aborted");
+ if (code == null) throw ScanValueException("Unexpected QR code value: aborted");
if (code.isEmpty) {
- throw Exception('Unexpected scan QR code value: value is empty');
+ throw ScanValueException('Unexpected scan QR code value: value is empty');
}
if (code.startsWith("monero_node:")) code = code.replaceFirst("monero_node:", "tcp://");
if (!code.contains('://')) code = 'tcp://$code';
final uri = Uri.tryParse(code);
if (uri == null || uri.host.isEmpty) {
- throw Exception('Invalid QR code: Unable to parse or missing host.');
+ throw ScanValueException('Invalid QR code: Unable to parse or missing host.');
}
final queryParams = uri.queryParameters;
### lib/view_model/node_list/node_list_view_model.dart
@@ -2,6 +2,7 @@ import 'dart:math';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/store/app_store.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node_list.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
@@ -78,7 +79,7 @@ abstract class NodeListViewModelBase with Store {
final node = isPow ? settingsStore.powNodes[walletType] : settingsStore.nodes[walletType];
if (node == null) {
- throw Exception('No node for wallet type: $walletType');
+ throw NodeLookupException('No node for wallet type: $walletType');
}
return node;
}
@@ -165,11 +166,11 @@ abstract class NodeListViewModelBase with Store {
if (nodeWalletType != null) {
node = (await Node.getDefaultForWalletType(nodeWalletType))!;
} else {
- throw Exception(
+ throw BadChainIdException(
'Cannot reset node for EVM wallet: wallet type not found for chainId: $chainId');
}
} else {
- throw Exception('Cannot reset node for EVM wallet: chainId is null');
+ throw BadChainIdException('Cannot reset node for EVM wallet: chainId is null');
}
} else {
node = (await Node.getDefaultForWalletType(_appStore.wallet!.type))!;
@@ -195,7 +196,7 @@ abstract class NodeListViewModelBase with Store {
return;
}
}
- throw Exception('Cannot set node for EVM wallet: chainId or wallet type not found');
+ throw BadChainIdException('Cannot set node for EVM wallet: chainId or wallet type not found');
}
// For non-EVM wallets, use the wallet type directly
### lib/view_model/restore/wallet_restore_from_qr_code.dart
@@ -10,6 +10,7 @@ import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cake_wallet/view_model/restore/restore_mode.dart';
import 'package:cake_wallet/view_model/restore/restore_wallet.dart';
import 'package:cw_core/currency_for_wallet_type.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_type.dart';
import 'package:bip39/bip39.dart' as bip39;
import 'package:flutter/cupertino.dart';
@@ -117,8 +118,8 @@ class WalletRestoreFromQRCode {
static Future<RestoredWallet> scanQRCodeForRestoring(BuildContext context) async {
String? code = await presentQRScanner(context);
- if (code == null) throw Exception("QR scan is cancelled");
- if (code.isEmpty) throw Exception('Unexpected scan QR code value: value is empty');
+ if (code == null) throw ScanValueException("QR scan is cancelled");
+ if (code.isEmpty) throw ScanValueException('Unexpected scan QR code value: value is empty');
if (code.startsWith("[")) code = code.substring(code.indexOf("]") + 1);
@@ -133,15 +134,15 @@ class WalletRestoreFromQRCode {
await _specifyWalletAssets(context, "Can't determine wallet type, please pick it manually");
walletType =
await Navigator.pushNamed(context, Routes.restoreWalletTypeFromQR) as WalletType?;
- if (walletType == null) throw Exception("Failed to determine wallet type.");
+ if (walletType == null) throw ScanValueException("Failed to determine wallet type.");
final seedPhrase = _extractSeedPhraseFromUrl(code, walletType);
formattedUri = seedPhrase != null
? '$walletType:?seed=$seedPhrase'
: code.startsWith(prefix)
- ? '$walletType:?$prefix=$code'
- : throw Exception('Failed to determine valid seed phrase');
+ ? '$walletType:?$prefix=$code'
+ : throw BadMnemonicException('Failed to determine valid seed phrase');
} else {
final index = code.indexOf(':');
final query = code.substring(index + 1).replaceAll('?', '&');
@@ -170,7 +171,7 @@ class WalletRestoreFromQRCode {
case WalletRestoreMode.keys:
return RestoredWallet.fromKey(credentials);
default:
- throw Exception('Unexpected restore mode: ${credentials['mode']}');
+ throw ScanValueException('Unexpected restore mode: ${credentials['mode']}');
}
}
@@ -179,7 +180,7 @@ class WalletRestoreFromQRCode {
if (credentials.containsKey('tx_payment_id')) {
final txIdValue = credentials['tx_payment_id'] as String? ?? '';
if (txIdValue.isNotEmpty) return WalletRestoreMode.txids;
- throw Exception('Unexpected restore mode: tx_payment_id is invalid');
+ throw ScanValueException('Unexpected restore mode: tx_payment_id is invalid');
}
if (credentials.containsKey("xpub") || credentials.containsKey("zpub")) {
@@ -201,13 +202,12 @@ class WalletRestoreFromQRCode {
seedValue.split(' ').forEach((element) {
if (!words.contains(element)) {
- throw Exception(
- "Unexpected restore mode: mnemonic_seed is invalid or doesn't match wallet type",
- );
+ throw ScanValueException(
+ "Unexpected restore mode: mnemonic_seed is invalid or doesn't match wallet type");
}
});
if (isEVMCompatibleChain(type) && !bip39.validateMnemonic(seedValue)) {
- throw Exception(
+ throw BadMnemonicException(
'EVM mnemonic has an invalid checksum. Please check the seed phrase for typos.',
);
}
@@ -220,13 +220,13 @@ class WalletRestoreFromQRCode {
return spendKeyValue.isNotEmpty || viewKeyValue.isNotEmpty
? WalletRestoreMode.keys
- : throw Exception('Unexpected restore mode: spend_key or view_key is invalid');
+ : throw ScanValueException('Unexpected restore mode: spend_key or view_key is invalid');
}
if (isEVMCompatibleChain(type) && credentials.containsKey('private_key')) {
final privateKey = credentials['private_key'] as String;
if (privateKey.isEmpty) {
- throw Exception('Unexpected restore mode: private_key');
+ throw ScanValueException('Unexpected restore mode: private_key');
}
return WalletRestoreMode.keys;
}
@@ -235,23 +235,23 @@ class WalletRestoreFromQRCode {
credentials.containsKey('hexSeed')) {
final hexSeed = credentials['hexSeed'] as String;
if (hexSeed.isEmpty) {
- throw Exception('Unexpected restore mode: hexSeed');
+ throw ScanValueException('Unexpected restore mode: hexSeed');
}
return WalletRestoreMode.seed;
}
if (type == WalletType.solana && credentials.containsKey('private_key')) {
final privateKey = credentials['private_key'] as String;
if (privateKey.isEmpty) {
- throw Exception('Unexpected restore mode: private_key');
+ throw ScanValueException('Unexpected restore mode: private_key');
}
return WalletRestoreMode.keys;
}
if (type == WalletType.tron && credentials.containsKey('private_key')) {
final privateKey = credentials['private_key'] as String;
if (privateKey.isEmpty) {
- throw Exception('Unexpected restore mode: private_key');
+ throw ScanValueException('Unexpected restore mode: private_key');
}
return WalletRestoreMode.keys;
}
@@ -268,7 +268,7 @@ class WalletRestoreFromQRCode {
return WalletRestoreMode.keys;
}
- throw Exception('Unexpected restore mode: restore params are invalid');
+ throw ScanValueException('Unexpected restore mode: restore params are invalid');
}
}
### lib/view_model/restore_from_backup_view_model.dart
@@ -1,4 +1,5 @@
import 'dart:io';
+import "package:cake_wallet/core/backup_service.dart";
import 'package:cake_wallet/core/backup_service_v3.dart';
import 'package:cake_wallet/core/execution_state.dart';
import 'package:cake_wallet/utils/exception_handler.dart';
@@ -47,13 +48,11 @@ abstract class RestoreFromBackupViewModelBase with Store {
await backupService.importBackupFile(file, password, checkBackupApp: checkBackupApp);
} on IncompatibleBackupAppException {
rethrow;
+ } on UnknownBackupVersionException {
+ state = FailureState(
+ 'This is not a valid backup file, please make sure you have selected the correct one');
} catch (e, s) {
- if (e.toString().contains("unknown_backup_version")) {
- state = FailureState(
- 'This is not a valid backup file, please make sure you have selected the correct one');
- } else {
- state = FailureState(e.toString() + "\n" + s.toString());
- }
+ state = FailureState(e.toString() + "\n" + s.toString());
}
try {
### lib/view_model/send/fees_view_model.dart
@@ -10,6 +10,7 @@ import 'package:cake_wallet/zcash/zcash.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/view_model/dashboard/balance_view_model.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:mobx/mobx.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
@@ -56,7 +57,7 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
if (priority == null && hasFeesPriority) {
- throw Exception('Unexpected type ${wallet.type}');
+ throw BadWalletTypeException('Unexpected type ${wallet.type}', wallet.type);
}
return priority!;
### lib/view_model/send/send_view_model.dart
@@ -59,6 +59,7 @@ import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/currency_for_wallet_type.dart';
import 'package:cw_core/erc20_token.dart';
import 'package:cw_core/exceptions.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/lnurl.dart';
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_core/sync_status.dart';
@@ -943,7 +944,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
return pendingTransaction;
} catch (e, s) {
printV('Jupiter swap error: $e\n$s');
- throw Exception('Failed to process Jupiter swap: $e');
+ throw TransactionGenerationException('Failed to process Jupiter swap: $e');
}
}
}
@@ -956,7 +957,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
final estimateTxAmount = outputs.fold<BigInt>(
BigInt.zero, (acc, output) => acc + output.cryptoAmountMoney.amount);
if (estimateTxAmount <= BigInt.zero) {
- throw Exception('Amount must be greater than 0');
+ throw TransactionGenerationException('Amount must be greater than 0');
}
}
@@ -976,14 +977,14 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
strictParsing: false,
);
if (tradeAmountMoney == null || tradeAmountMoney.sign <= 0) {
- throw Exception('Trade amount must be greater than 0');
+ throw TransactionGenerationException('Trade amount must be greater than 0');
}
final tradeAmountDouble = double.tryParse(tradeAmountMoney.toString()) ?? 0.0;
if (trade.isSendAll == true) {
if (provider is NearIntentsExchangeProvider) {
if (txAmountDouble != tradeAmountDouble) {
- throw Exception(
+ throw TransactionGenerationException(
'Transaction amount $txAmountDouble does not match expected trade amount $tradeAmountDouble');
}
}
@@ -992,11 +993,11 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
if (provider is ThorChainExchangeProvider) {
final outputCount = pendingTransaction?.outputCount ?? 0;
if (outputCount > 10) {
- throw Exception("THORChain does not support more than 10 outputs");
+ throw TransactionGenerationException("THORChain does not support more than 10 outputs");
}
if (_hasTaprootInput(pendingTransaction)) {
- throw Exception("THORChain does not support Taproot addresses");
+ throw TransactionGenerationException("THORChain does not support Taproot addresses");
}
}
}
@@ -1088,7 +1089,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
@action
Future<void> commitTransaction(BuildContext context) async {
if (pendingTransaction == null) {
- throw Exception("Pending transaction doesn't exist. It should not be happened.");
+ throw TransactionGenerationException("Pending transaction doesn't exist. It should not be happened.");
}
try {
@@ -1328,7 +1329,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
WalletType.robinhood,
WalletType.zcash,
].contains(wallet.type)) {
- throw Exception('Priority is null for wallet type: ${wallet.type}');
+ throw BadWalletTypeException('Priority is null for wallet type: ${wallet.type}', wallet.type);
}
switch (wallet.type) {
@@ -1393,7 +1394,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
// priority: priority,
);
default:
- throw Exception('Unexpected wallet type: ${wallet.type} for send');
+ throw BadWalletTypeException('Unexpected wallet type: ${wallet.type} for send', wallet.type);
}
}
### lib/view_model/settings/other_settings_view_model.dart
@@ -8,6 +8,7 @@ import 'package:cake_wallet/utils/package_info.dart';
import 'package:cake_wallet/view_model/send/send_view_model.dart';
import 'package:collection/collection.dart';
import 'package:cw_core/balance.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/transaction_info.dart';
@@ -54,7 +55,7 @@ abstract class OtherSettingsViewModelBase with Store {
final priority = _settingsStore.getPriority(walletType, chainId: chainId);
if (priority == null) {
- throw Exception('Unexpected type ${walletType.toString()}');
+ throw BadWalletTypeException('Unexpected type ${walletType.toString()}', walletType);
}
return priority;
### lib/view_model/setup_pin_code_view_model.dart
@@ -53,7 +53,7 @@ class SetupPinCodeViewModel {
if (pin == realPin) {
reset();
- throw Exception('Duress PIN cannot be the same as regular PIN');
+ throw ArgumentError('Duress PIN cannot be the same as regular PIN');
}
}
}
### lib/view_model/viewmodel_exceptions.dart
@@ -0,0 +1,10 @@
+
+
+import "package:cw_core/exceptions/cake_exception.dart";
+import "package:permission_handler/permission_handler.dart";
+
+class SystemPermissionException extends CakeException {
+
+ const SystemPermissionException(this.permission, super.message);
+ final Permission permission;
+}
\ No newline at end of file
### lib/view_model/wallet_account_list/nano_account_list/nano_account_list_view_model.dart
@@ -1,5 +1,6 @@
import 'package:cake_wallet/nano/nano.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_type.dart';
import 'package:cw_core/nano_account.dart';
import 'package:mobx/mobx.dart';
@@ -36,7 +37,7 @@ abstract class NanoAccountListViewModelBase with Store {
.toList();
}
- throw Exception('Unexpected wallet type: ${_wallet.type} for nano');
+ throw BadWalletTypeException('Unexpected wallet type: ${_wallet.type} for nano', _wallet.type);
}
final WalletBase _wallet;
### lib/view_model/wallet_creation_vm.dart
@@ -2,6 +2,7 @@ import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/execution_state.dart';
import 'package:cake_wallet/core/wallet_creation_service.dart';
import 'package:cake_wallet/di.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/generate_name.dart';
import 'package:cake_wallet/entities/hash_wallet_identifier.dart';
import 'package:cake_wallet/generated/i18n.dart';
@@ -91,11 +92,11 @@ abstract class WalletCreationVMBase with Store {
}
if (hasWalletPassword && (walletPassword?.isEmpty ?? true)) {
- throw Exception(S.current.wallet_password_is_empty);
+ throw WalletCreationException(S.current.wallet_password_is_empty);
}
if (hasWalletPassword && walletPassword != repeatedWalletPassword) {
- throw Exception(S.current.repeated_password_is_incorrect);
+ throw WalletCreationException(S.current.repeated_password_is_incorrect);
}
await walletCreationService.checkIfExists(name);
### lib/view_model/wallet_hardware_restore_view_model.dart
@@ -9,6 +9,7 @@ import 'package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_mode
import 'package:cake_wallet/view_model/hardware_wallet/trezor_connect_view_model.dart';
import 'package:cake_wallet/view_model/seed_settings_view_model.dart';
import 'package:cake_wallet/view_model/wallet_creation_vm.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/hardware/hardware_account_data.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
@@ -93,7 +94,7 @@ abstract class WalletHardwareRestoreViewModelBase extends WalletCreationVM with
passphrase: _options['passphrase'] as String?,
);
default:
- throw Exception('Unexpected type: ${type.toString()}');
+ throw BadWalletTypeException('Unexpected type: ${type.toString()}', type);
}
credentials.hardwareWalletType = hardwareWalletVM.hardwareWalletType;
### lib/view_model/wallet_keys_view_model.dart
@@ -6,6 +6,7 @@ import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/zcash/zcash.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_direction.dart';
import 'package:cw_core/transaction_info.dart';
import 'package:cw_core/wallet_base.dart';
@@ -339,7 +340,7 @@ abstract class WalletKeysViewModelBase with Store {
case WalletType.zcash:
return 'zcash-wallet';
case WalletType.none:
- throw Exception('Unexpected wallet type: ${_wallet.type.toString()} for wallet keys');
+ throw BadWalletTypeException('Unexpected wallet type: ${_wallet.type.toString()} for wallet keys', _wallet.type);
}
}
### lib/view_model/wallet_new_vm.dart
@@ -7,6 +7,7 @@ import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/tron/tron.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zcash/zcash.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:mobx/mobx.dart';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/wallet_creation_service.dart';
@@ -158,7 +159,7 @@ abstract class WalletNewVMBase extends WalletCreationVM with Store {
mnemonic: newWalletArguments!.mnemonic);
case WalletType.none:
case WalletType.haven:
- throw Exception('Unexpected type: ${type.toString()}');
+ throw BadWalletTypeException('Unexpected type: ${type.toString()}', type);
}
}
### lib/view_model/wallet_restore_view_model.dart
@@ -20,6 +20,7 @@ import 'package:cake_wallet/view_model/wallet_creation_vm.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/zcash/zcash.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_credentials.dart';
import 'package:cw_core/wallet_info.dart';
@@ -336,7 +337,7 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
}
}
- throw Exception('Unexpected type: ${type.toString()}');
+ throw BadWalletTypeException('Unexpected type: ${type.toString()}', type);
}
Future<List<DerivationInfo>> getDerivationInfo(dynamic credentials) async {
### tool/configure.dart
@@ -790,6 +790,7 @@ import 'package:cw_core/wallet_credentials.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/transaction_info.dart';
import 'package:cw_core/transaction_history.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_service.dart';
import 'package:cw_core/output_info.dart';
import 'package:cw_core/nano_account_info_response.dart';
@@ -802,6 +803,7 @@ import 'package:cake_wallet/view_model/send/output.dart';
const nanoCWHeaders = """
import 'package:cw_nano/nano_client.dart';
import 'package:cw_nano/nano_mnemonic.dart';
+import "package:cw_nano/nano_exceptions.dart";
import 'package:cw_nano/nano_wallet.dart';
import 'package:cw_nano/nano_wallet_service.dart';
import 'package:cw_nano/nano_transaction_info.dart';
@@ -927,6 +929,10 @@ import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/output_info.dart';
import 'package:cw_core/pending_transaction.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/trade_not_created_exception.dart";
import 'package:cw_core/transaction_info.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_credentials.dart';Why this scored 31/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.