Reformat the whole codebase with 100 line width (#3403)

This commit is contained in:
Omar Hatem
2026-07-15 01:20:33 +03:00
committed by GitHub
parent 1241b28bec
commit 16ddc0837a
801 changed files with 17517 additions and 17091 deletions
+2 -2
View File
@@ -78,7 +78,7 @@ class AnonPayApi {
clearnetUri: Uri.https(clearNetAuthority, anonPayPath, body),
onionUri: Uri.https(onionApiAuthority, anonPayPath, body),
);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final id = responseJSON['ID'] as String;
final url = responseJSON['url'] as String;
@@ -156,7 +156,7 @@ class AnonPayApi {
clearnetUri: Uri.https(clearNetAuthority, coinPath, params),
onionUri: Uri.https(onionApiAuthority, coinPath, params),
);
final responseJSON = json.decode(response.body) as List<dynamic>;
if (response.statusCode != 200) {
throw Exception('Unexpected http status: ${response.statusCode}');
+3 -3
View File
@@ -1,13 +1,13 @@
import 'package:cake_wallet/anonpay/anonpay_info_base.dart';
class AnonpayDonationLinkInfo implements AnonpayInfoBase{
class AnonpayDonationLinkInfo implements AnonpayInfoBase {
final String clearnetUrl;
final String onionUrl;
final String address;
AnonpayDonationLinkInfo({
required this.clearnetUrl,
required this.onionUrl,
required this.address,
});
}
}
+1 -1
View File
@@ -2,4 +2,4 @@ abstract class AnonpayInfoBase {
String get clearnetUrl;
String get onionUrl;
String get address;
}
}
+4 -4
View File
@@ -1,5 +1,5 @@
class AnyPayChain {
static const xmr = 'XMR';
static const btc = 'BTC';
static const ltc = 'LTC';
}
static const xmr = 'XMR';
static const btc = 'BTC';
static const ltc = 'LTC';
}
+55 -53
View File
@@ -4,60 +4,62 @@ import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/monero/monero.dart';
class AnyPayPayment {
AnyPayPayment({
required this.time,
required this.expires,
required this.memo,
required this.paymentUrl,
required this.paymentId,
required this.chain,
required this.network,
required this.instructions});
AnyPayPayment(
{required this.time,
required this.expires,
required this.memo,
required this.paymentUrl,
required this.paymentId,
required this.chain,
required this.network,
required this.instructions});
factory AnyPayPayment.fromMap(Map<String, dynamic> obj) {
final instructions = (obj['instructions'] as List<dynamic>)
.map((dynamic instruction) => AnyPayPaymentInstruction.fromMap(instruction as Map<String, dynamic>))
.toList();
return AnyPayPayment(
time: DateTime.parse(obj['time'] as String),
expires: DateTime.parse(obj['expires'] as String),
memo: obj['memo'] as String,
paymentUrl: obj['paymentUrl'] as String,
paymentId: obj['paymentId'] as String,
chain: obj['chain'] as String,
network: obj['network'] as String,
instructions: instructions);
}
factory AnyPayPayment.fromMap(Map<String, dynamic> obj) {
final instructions = (obj['instructions'] as List<dynamic>)
.map((dynamic instruction) =>
AnyPayPaymentInstruction.fromMap(instruction as Map<String, dynamic>))
.toList();
return AnyPayPayment(
time: DateTime.parse(obj['time'] as String),
expires: DateTime.parse(obj['expires'] as String),
memo: obj['memo'] as String,
paymentUrl: obj['paymentUrl'] as String,
paymentId: obj['paymentId'] as String,
chain: obj['chain'] as String,
network: obj['network'] as String,
instructions: instructions);
}
final DateTime time;
final DateTime expires;
final String memo;
final String paymentUrl;
final String paymentId;
final String chain;
final String network;
final List<AnyPayPaymentInstruction> instructions;
final DateTime time;
final DateTime expires;
final String memo;
final String paymentUrl;
final String paymentId;
final String chain;
final String network;
final List<AnyPayPaymentInstruction> instructions;
String get totalAmount {
final total = instructions
.fold<int>(0, (int acc, instruction) => acc + instruction.outputs
.fold<int>(0, (int outAcc, out) => outAcc + out.amount));
switch (chain) {
case AnyPayChain.xmr:
return monero!.formatterMoneroAmountToString(amount: total);
case AnyPayChain.btc:
return bitcoin!.formatterBitcoinAmountToString(amount: total);
case AnyPayChain.ltc:
return bitcoin!.formatterBitcoinAmountToString(amount: total);
default:
return '';
}
}
String get totalAmount {
final total = instructions.fold<int>(
0,
(int acc, instruction) =>
acc + instruction.outputs.fold<int>(0, (int outAcc, out) => outAcc + out.amount));
switch (chain) {
case AnyPayChain.xmr:
return monero!.formatterMoneroAmountToString(amount: total);
case AnyPayChain.btc:
return bitcoin!.formatterBitcoinAmountToString(amount: total);
case AnyPayChain.ltc:
return bitcoin!.formatterBitcoinAmountToString(amount: total);
default:
return '';
}
}
List<String> get outAddresses {
return instructions
.map((instruction) => instruction.outputs.map((out) => out.address))
.expand((e) => e)
.toList();
}
}
List<String> get outAddresses {
return instructions
.map((instruction) => instruction.outputs.map((out) => out.address))
.expand((e) => e)
.toList();
}
}
+12 -12
View File
@@ -1,16 +1,16 @@
import 'package:cake_wallet/anypay/any_pay_trasnaction.dart';
class AnyPayPaymentCommittedInfo {
const AnyPayPaymentCommittedInfo({
required this.uri,
required this.currency,
required this.chain,
required this.transactions,
required this.memo});
const AnyPayPaymentCommittedInfo(
{required this.uri,
required this.currency,
required this.chain,
required this.transactions,
required this.memo});
final String uri;
final String currency;
final String chain;
final List<AnyPayTransaction> transactions;
final String memo;
}
final String uri;
final String currency;
final String chain;
final List<AnyPayTransaction> transactions;
final String memo;
}
+24 -25
View File
@@ -1,31 +1,30 @@
import 'package:cake_wallet/anypay/any_pay_payment_instruction_output.dart';
class AnyPayPaymentInstruction {
AnyPayPaymentInstruction({
required this.type,
required this.requiredFeeRate,
required this.txKey,
required this.txHash,
required this.outputs});
AnyPayPaymentInstruction(
{required this.type,
required this.requiredFeeRate,
required this.txKey,
required this.txHash,
required this.outputs});
factory AnyPayPaymentInstruction.fromMap(Map<String, dynamic> obj) {
final outputs = (obj['outputs'] as List<dynamic>)
.map((dynamic out) =>
AnyPayPaymentInstructionOutput.fromMap(out as Map<String, dynamic>))
.toList();
return AnyPayPaymentInstruction(
type: obj['type'] as String,
requiredFeeRate: obj['requiredFeeRate'] as int,
txKey: obj['tx_key'] as bool? ?? false,
txHash: obj['tx_hash'] as bool? ?? false,
outputs: outputs);
}
factory AnyPayPaymentInstruction.fromMap(Map<String, dynamic> obj) {
final outputs = (obj['outputs'] as List<dynamic>)
.map((dynamic out) => AnyPayPaymentInstructionOutput.fromMap(out as Map<String, dynamic>))
.toList();
return AnyPayPaymentInstruction(
type: obj['type'] as String,
requiredFeeRate: obj['requiredFeeRate'] as int,
txKey: obj['tx_key'] as bool? ?? false,
txHash: obj['tx_hash'] as bool? ?? false,
outputs: outputs);
}
static const transactionType = 'transaction';
static const transactionType = 'transaction';
final String type;
final int requiredFeeRate;
final bool txKey;
final bool txHash;
final List<AnyPayPaymentInstructionOutput> outputs;
}
final String type;
final int requiredFeeRate;
final bool txKey;
final bool txHash;
final List<AnyPayPaymentInstructionOutput> outputs;
}
@@ -1,10 +1,10 @@
class AnyPayPaymentInstructionOutput {
const AnyPayPaymentInstructionOutput(this.address, this.amount);
const AnyPayPaymentInstructionOutput(this.address, this.amount);
factory AnyPayPaymentInstructionOutput.fromMap(Map<String, dynamic> obj) {
return AnyPayPaymentInstructionOutput(obj['address'] as String, obj['amount'] as int);
}
factory AnyPayPaymentInstructionOutput.fromMap(Map<String, dynamic> obj) {
return AnyPayPaymentInstructionOutput(obj['address'] as String, obj['amount'] as int);
}
final String address;
final int amount;
}
final String address;
final int amount;
}
+5 -5
View File
@@ -1,7 +1,7 @@
class AnyPayTransaction {
const AnyPayTransaction(this.tx, {required this.id, required this.key});
const AnyPayTransaction(this.tx, {required this.id, required this.key});
final String tx;
final String id;
final String? key;
}
final String tx;
final String id;
final String? key;
}
+83 -79
View File
@@ -9,101 +9,105 @@ import 'package:cake_wallet/anypay/any_pay_trasnaction.dart';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
class AnyPayApi {
static const contentTypePaymentRequest = 'application/payment-request';
static const contentTypePayment = 'application/payment';
static const xPayproVersion = '2';
static const anypayToken = secrets.anypayToken;
static const contentTypePaymentRequest = 'application/payment-request';
static const contentTypePayment = 'application/payment';
static const xPayproVersion = '2';
static const anypayToken = secrets.anypayToken;
static String chainByScheme(String scheme) {
switch (scheme.toLowerCase()) {
case 'monero':
return CryptoCurrency.xmr.title;
case 'bitcoin':
return CryptoCurrency.btc.title;
case 'litecoin':
return CryptoCurrency.ltc.title;
default:
return '';
}
}
static String chainByScheme(String scheme) {
switch (scheme.toLowerCase()) {
case 'monero':
return CryptoCurrency.xmr.title;
case 'bitcoin':
return CryptoCurrency.btc.title;
case 'litecoin':
return CryptoCurrency.ltc.title;
default:
return '';
}
}
static CryptoCurrency currencyByScheme(String scheme) {
switch (scheme.toLowerCase()) {
case 'monero':
return CryptoCurrency.xmr;
case 'bitcoin':
return CryptoCurrency.btc;
case 'litecoin':
return CryptoCurrency.ltc;
default:
throw Exception('Unexpected scheme: ${scheme}');
}
}
static CryptoCurrency currencyByScheme(String scheme) {
switch (scheme.toLowerCase()) {
case 'monero':
return CryptoCurrency.xmr;
case 'bitcoin':
return CryptoCurrency.btc;
case 'litecoin':
return CryptoCurrency.ltc;
default:
throw Exception('Unexpected scheme: ${scheme}');
}
}
Future<AnyPayPayment> paymentRequest(String uri) async {
final fragments = uri.split(':?r=');
final scheme = fragments.first;
final url = Uri.parse(fragments[1]);
final headers = <String, String>{
'Content-Type': contentTypePaymentRequest,
'X-Paypro-Version': xPayproVersion,
'Accept': '*/*',
'x-wallet': 'cake',
'x-wallet-token': anypayToken,};
final body = <String, dynamic>{
'chain': chainByScheme(scheme),
'currency': currencyByScheme(scheme).title};
final response = await ProxyWrapper().post(
Future<AnyPayPayment> paymentRequest(String uri) async {
final fragments = uri.split(':?r=');
final scheme = fragments.first;
final url = Uri.parse(fragments[1]);
final headers = <String, String>{
'Content-Type': contentTypePaymentRequest,
'X-Paypro-Version': xPayproVersion,
'Accept': '*/*',
'x-wallet': 'cake',
'x-wallet-token': anypayToken,
};
final body = <String, dynamic>{
'chain': chainByScheme(scheme),
'currency': currencyByScheme(scheme).title
};
final response = await ProxyWrapper().post(
clearnetUri: url,
headers: headers,
body: json.encode(body),
);
if (response.statusCode != 200) {
await ExceptionHandler.onError(FlutterErrorDetails(exception: response));
await ExceptionHandler.onError(FlutterErrorDetails(exception: response));
throw Exception('Unexpected response http code: ${response.statusCode}');
}
}
final decodedBody = json.decode(response.body) as Map<String, dynamic>;
return AnyPayPayment.fromMap(decodedBody);
}
}
Future<AnyPayPaymentCommittedInfo> payment(
String uri,
{required String chain,
required String currency,
required List<AnyPayTransaction> transactions}) async {
final headers = <String, String>{
'Content-Type': contentTypePayment,
'X-Paypro-Version': xPayproVersion,
'Accept': '*/*',
'x-wallet': 'cake',
'x-wallet-token': anypayToken,};
final body = <String, dynamic>{
'chain': chain,
'currency': currency,
'transactions': transactions.map((tx) => {'tx': tx.tx, 'tx_hash': tx.id, 'tx_key': tx.key}).toList()};
final response = await ProxyWrapper().post(
Future<AnyPayPaymentCommittedInfo> payment(String uri,
{required String chain,
required String currency,
required List<AnyPayTransaction> transactions}) async {
final headers = <String, String>{
'Content-Type': contentTypePayment,
'X-Paypro-Version': xPayproVersion,
'Accept': '*/*',
'x-wallet': 'cake',
'x-wallet-token': anypayToken,
};
final body = <String, dynamic>{
'chain': chain,
'currency': currency,
'transactions':
transactions.map((tx) => {'tx': tx.tx, 'tx_hash': tx.id, 'tx_key': tx.key}).toList()
};
final response = await ProxyWrapper().post(
clearnetUri: Uri.parse(uri),
headers: headers,
body: json.encode(body),
);
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');
}
if (response.statusCode != 200) {
throw Exception('Unexpected response');
}
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');
}
final decodedBody = json.decode(response.body) as Map<String, dynamic>;
return AnyPayPaymentCommittedInfo(
uri: uri,
currency: currency,
chain: chain,
transactions: transactions,
memo: decodedBody['memo'] as String);
}
}
if (response.statusCode != 200) {
throw Exception('Unexpected response');
}
final decodedBody = json.decode(response.body) as Map<String, dynamic>;
return AnyPayPaymentCommittedInfo(
uri: uri,
currency: currency,
chain: chain,
transactions: transactions,
memo: decodedBody['memo'] as String);
}
}
+19 -19
View File
@@ -185,7 +185,7 @@ class CWBitcoin extends Bitcoin {
balance: addr.balance,
isChange: addr.isHidden,
isLegacyDerivation: addr.isLegacyDerivation,
derivationPath: addr.derivationPath))
derivationPath: addr.derivationPath))
.toList();
}
@@ -206,10 +206,8 @@ class CWBitcoin extends Bitcoin {
return estimatedTx.amount;
}
if (wallet.type == WalletType.dogecoin) {
final dogeAddr =
sk.getPublic().toP2pkhAddress();
final dogeAddr = sk.getPublic().toP2pkhAddress();
final estimatedTx = await electrumWallet.estimateSendAllTx(
[BitcoinOutput(address: dogeAddr, value: BigInt.zero)],
getFeeRate(wallet, priority as BitcoinTransactionPriority),
@@ -276,14 +274,13 @@ class CWBitcoin extends Bitcoin {
await bitcoinWallet.updateAllUnspents();
}
WalletService createBitcoinWalletService(
Box<UnspentCoinsInfo> unspentCoinSource,
Box<PayjoinSession> payjoinSessionSource,
bool isDirect) {
WalletService createBitcoinWalletService(Box<UnspentCoinsInfo> unspentCoinSource,
Box<PayjoinSession> payjoinSessionSource, bool isDirect) {
return BitcoinWalletService(unspentCoinSource, payjoinSessionSource, isDirect);
}
WalletService createLitecoinWalletService(Box<UnspentCoinsInfo> unspentCoinSource, bool isDirect) {
WalletService createLitecoinWalletService(
Box<UnspentCoinsInfo> unspentCoinSource, bool isDirect) {
return LitecoinWalletService(unspentCoinSource, isDirect);
}
@@ -340,7 +337,8 @@ class CWBitcoin extends Bitcoin {
}
@override
BitcoinReceivePageOption getBitcoinLightningReceivePageOption() => BitcoinReceivePageOption.lightning;
BitcoinReceivePageOption getBitcoinLightningReceivePageOption() =>
BitcoinReceivePageOption.lightning;
@override
BitcoinReceivePageOption getBitcoinSegwitPageOption() => BitcoinReceivePageOption.p2wpkh;
@override
@@ -839,9 +837,11 @@ class CWBitcoin extends Bitcoin {
final addresses = <String>[];
if (bitcoinTx.unspents == null || bitcoinTx.unspents!.isEmpty) {
if(bitcoinTx.outputAddresses == null) return null;
for(final addr in bitcoinTx.outputAddresses!) {
if(bitcoinWallet.walletAddresses.allAddresses.firstWhereOrNull((item)=>item.address==addr) != null) {
if (bitcoinTx.outputAddresses == null) return null;
for (final addr in bitcoinTx.outputAddresses!) {
if (bitcoinWallet.walletAddresses.allAddresses
.firstWhereOrNull((item) => item.address == addr) !=
null) {
addresses.add(addr);
}
}
@@ -850,12 +850,12 @@ class CWBitcoin extends Bitcoin {
final labels = <String>[];
try {
bitcoinTx.unspents!.forEach((unspent) {
addresses.add(bitcoinWallet.walletAddresses.silentAddresses
.firstWhere((address) => address.silentPaymentTweak == unspent.silentPaymentLabel)
.address);
});
} catch (e) {}
bitcoinTx.unspents!.forEach((unspent) {
addresses.add(bitcoinWallet.walletAddresses.silentAddresses
.firstWhere((address) => address.silentPaymentTweak == unspent.silentPaymentLabel)
.address);
});
} catch (e) {}
return addresses;
}
+6 -2
View File
@@ -5,7 +5,8 @@ class CWBitcoinCash extends BitcoinCash {
String getCashAddrFormat(String address) => AddressUtils.getCashAddrFormat(address);
@override
WalletService createBitcoinCashWalletService(Box<UnspentCoinsInfo> unspentCoinSource, bool isDirect) {
WalletService createBitcoinCashWalletService(
Box<UnspentCoinsInfo> unspentCoinSource, bool isDirect) {
return BitcoinCashWalletService(unspentCoinSource, isDirect);
}
@@ -27,7 +28,10 @@ class CWBitcoinCash extends BitcoinCash {
@override
WalletCredentials createBitcoinCashRestoreWalletFromSeedCredentials(
{required String name, required String mnemonic, required String password, String? passphrase}) =>
{required String name,
required String mnemonic,
required String password,
String? passphrase}) =>
BitcoinCashRestoreWalletFromSeedCredentials(
name: name, mnemonic: mnemonic, password: password, passphrase: passphrase);
+6 -7
View File
@@ -1,13 +1,12 @@
class BuyAmount {
BuyAmount({
required this.sourceAmount,
required this.destAmount,
this.achSourceAmount,
this.minAmount = 0});
BuyAmount(
{required this.sourceAmount,
required this.destAmount,
this.achSourceAmount,
this.minAmount = 0});
final double sourceAmount;
final double destAmount;
final double? achSourceAmount;
final int minAmount;
}
}
+1 -2
View File
@@ -1,4 +1,3 @@
class BuyException implements Exception {
BuyException({required this.title, required this.content});
@@ -7,4 +6,4 @@ class BuyException implements Exception {
@override
String toString() => '$title: $content';
}
}
+8 -9
View File
@@ -10,13 +10,12 @@ import 'package:cw_core/wallet_base.dart';
import 'package:flutter/material.dart';
abstract class BuyProvider {
BuyProvider({
required this.wallet,
required this.isTestEnvironment,
required this.hardwareWalletVM,
required this.supportedCryptoList,
required this.supportedFiatList
});
BuyProvider(
{required this.wallet,
required this.isTestEnvironment,
required this.hardwareWalletVM,
required this.supportedCryptoList,
required this.supportedFiatList});
final WalletBase wallet;
final bool isTestEnvironment;
@@ -54,7 +53,7 @@ abstract class BuyProvider {
throw UnimplementedError();
Future<List<PaymentMethod>> getAvailablePaymentTypes(
String fiatCurrency, CryptoCurrency cryptoCurrency, bool isBuyAction) async =>
String fiatCurrency, CryptoCurrency cryptoCurrency, bool isBuyAction) async =>
[];
Future<List<Quote>?> fetchQuote(
@@ -64,7 +63,7 @@ abstract class BuyProvider {
required bool isBuyAction,
required String walletAddress,
PaymentType? paymentType,
String? customPaymentMethodType,
String? customPaymentMethodType,
String? countryCode}) async =>
null;
}
+8 -9
View File
@@ -56,7 +56,7 @@ class DFXBuyProvider extends BuyProvider {
static final List<FiatCurrency> _supportedFiat = [FiatCurrency.chf, FiatCurrency.eur];
static final List<FiatCurrency> _notSupportedFiat =
FiatCurrency.all.where((fiat) => !_supportedFiat.contains(fiat)).toList();
FiatCurrency.all.where((fiat) => !_supportedFiat.contains(fiat)).toList();
@override
String get title => 'DFX.swiss';
@@ -84,7 +84,6 @@ class DFXBuyProvider extends BuyProvider {
}
}
Future<String> getSignMessage(String walletAddress) async =>
"By_signing_this_message,_you_confirm_that_you_are_the_sole_owner_of_the_provided_Blockchain_address._Your_ID:_$walletAddress";
@@ -156,10 +155,9 @@ class DFXBuyProvider extends BuyProvider {
final url = Uri.https(_baseUrl, '/v1/fiat');
try {
final response = await ProxyWrapper().get(
clearnetUri: url,
headers: {'accept': 'application/json'});
final response =
await ProxyWrapper().get(clearnetUri: url, headers: {'accept': 'application/json'});
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as List<dynamic>;
for (final item in data) {
@@ -181,8 +179,9 @@ class DFXBuyProvider extends BuyProvider {
final url = Uri.https(_baseUrl, '/v1/asset', {'blockchains': blockchain});
try {
final response = await ProxyWrapper().get(clearnetUri: url, headers: {'accept': 'application/json'});
final response =
await ProxyWrapper().get(clearnetUri: url, headers: {'accept': 'application/json'});
if (response.statusCode == 200) {
final responseData = jsonDecode(response.body);
@@ -300,7 +299,7 @@ class DFXBuyProvider extends BuyProvider {
headers: headers,
body: body,
);
final responseData = jsonDecode(response.body);
if (response.statusCode == 200) {
+4 -7
View File
@@ -2,13 +2,10 @@ import 'package:flutter/material.dart';
import 'package:cake_wallet/buy/buy_provider_description.dart';
Image? getBuyProviderIcon(BuyProviderDescription providerDescription,
{Color iconColor = Colors.black}) {
final _wyreIcon =
Image.asset('assets/images/wyre-icon.png', width: 36, height: 36);
{Color iconColor = Colors.black}) {
final _wyreIcon = Image.asset('assets/images/wyre-icon.png', width: 36, height: 36);
final _moonPayIcon =
Image.asset('assets/images/moonpay-icon.png', color: iconColor,
width: 36, height: 34);
Image.asset('assets/images/moonpay-icon.png', color: iconColor, width: 36, height: 34);
switch (providerDescription) {
case BuyProviderDescription.wyre:
@@ -18,4 +15,4 @@ Image? getBuyProviderIcon(BuyProviderDescription providerDescription,
default:
return null;
}
}
}
+9 -10
View File
@@ -18,13 +18,13 @@ import 'package:url_launcher/url_launcher.dart';
class KryptonimBuyProvider extends BuyProvider {
KryptonimBuyProvider({required WalletBase wallet, bool isTestEnvironment = false})
: super(
wallet: wallet,
isTestEnvironment: isTestEnvironment,
hardwareWalletVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
wallet: wallet,
isTestEnvironment: isTestEnvironment,
hardwareWalletVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
static const _isProduction = true;
@@ -81,7 +81,6 @@ class KryptonimBuyProvider extends BuyProvider {
);
if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 401) {
return jsonDecode(response.body) as Map<String, dynamic>;
} else {
return {};
@@ -94,7 +93,6 @@ class KryptonimBuyProvider extends BuyProvider {
@override
Future<List<PaymentMethod>> getAvailablePaymentTypes(
String fiatCurrency, CryptoCurrency cryptoCurrency, bool isBuyAction) async {
final data = await getExchangeRates(
cryptoCurrency: cryptoCurrency,
fiatCurrency: fiatCurrency,
@@ -155,7 +153,8 @@ class KryptonimBuyProvider extends BuyProvider {
final selectedPaymentType =
PaymentMethod.getPaymentTypeId(selectedPaymentMethod['payment_method'] as String?);
final quote = Quote.fromKryptonimJson(selectedPaymentMethod, isBuyAction, selectedPaymentType ?? PaymentType.unknown);
final quote = Quote.fromKryptonimJson(
selectedPaymentMethod, isBuyAction, selectedPaymentType ?? PaymentType.unknown);
quote.setFiatCurrency = fiatCurrency;
quote.setCryptoCurrency = cryptoCurrency;
+15 -17
View File
@@ -20,13 +20,13 @@ import 'package:url_launcher/url_launcher.dart';
class MeldBuyProvider extends BuyProvider {
MeldBuyProvider({required WalletBase wallet, bool isTestEnvironment = false})
: super(
wallet: wallet,
isTestEnvironment: isTestEnvironment,
hardwareWalletVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
wallet: wallet,
isTestEnvironment: isTestEnvironment,
hardwareWalletVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
static const _isProduction = false;
@@ -45,7 +45,7 @@ class MeldBuyProvider extends BuyProvider {
static const List<CryptoCurrency> _notSupportedCrypto = [];
static const List<FiatCurrency> _notSupportedFiat = [];
static String get _testPublicKey => '' ; //secrets.meldTestPublicKey;
static String get _testPublicKey => ''; //secrets.meldTestPublicKey;
@override
String get title => 'Meld';
@@ -80,7 +80,6 @@ class MeldBuyProvider extends BuyProvider {
'content-type': 'application/json',
},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as List<dynamic>;
@@ -100,13 +99,13 @@ class MeldBuyProvider extends BuyProvider {
@override
Future<List<Quote>?> fetchQuote(
{required CryptoCurrency cryptoCurrency,
required FiatCurrency fiatCurrency,
required double amount,
required bool isBuyAction,
required String walletAddress,
PaymentType? paymentType,
String? customPaymentMethodType,
String? countryCode}) async {
required FiatCurrency fiatCurrency,
required double amount,
required bool isBuyAction,
required String walletAddress,
PaymentType? paymentType,
String? customPaymentMethodType,
String? countryCode}) async {
String? paymentMethod;
if (paymentType != null && paymentType != PaymentType.all) {
paymentMethod = normalizePaymentMethod(paymentType);
@@ -136,7 +135,6 @@ class MeldBuyProvider extends BuyProvider {
headers: headers,
body: body,
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as Map<String, dynamic>;
+11 -12
View File
@@ -34,13 +34,13 @@ class MoonPayProvider extends BuyProvider {
baseBuyUrl = isTestEnvironment ? _baseBuyTestUrl : _baseBuyProductUrl,
this._appStore = appStore,
super(
wallet: wallet,
isTestEnvironment: isTestEnvironment,
hardwareWalletVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
wallet: wallet,
isTestEnvironment: isTestEnvironment,
hardwareWalletVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
final AppStore _appStore;
@@ -81,7 +81,8 @@ class MoonPayProvider extends BuyProvider {
String get _apiKey => isTestEnvironment ? secrets.moonPaySandboxApiKey : secrets.moonPayApiKey;
String get currencyCode => walletTypeToCryptoCurrency(wallet.type, chainId: wallet.chainId).title.toLowerCase();
String get currencyCode =>
walletTypeToCryptoCurrency(wallet.type, chainId: wallet.chainId).title.toLowerCase();
String get trackUrl => baseBuyUrl + '/transaction_receipt?transactionId=';
@@ -105,7 +106,6 @@ class MoonPayProvider extends BuyProvider {
headers: {'Content-Type': 'application/json', 'x-api-key': _exchangeHelperApiKey},
body: json.encode({'query': query}),
);
if (response.statusCode == 200) {
printV((jsonDecode(response.body) as Map<String, dynamic>));
@@ -130,7 +130,7 @@ class MoonPayProvider extends BuyProvider {
clearnetUri: url,
headers: {'accept': 'application/json'},
);
if (response.statusCode == 200) {
return jsonDecode(response.body) as Map<String, dynamic>;
} else {
@@ -202,7 +202,7 @@ class MoonPayProvider extends BuyProvider {
final url = Uri.https(_baseUrl, path, params);
try {
final response = await ProxyWrapper().get(clearnetUri: url);
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as Map<String, dynamic>;
@@ -312,7 +312,6 @@ class MoonPayProvider extends BuyProvider {
final url = _apiUrl + _transactionsSuffix + '/$id' + '?apiKey=' + _apiKey;
final uri = Uri.parse(url);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode != 200) {
throw BuyException(title: providerDescription, content: 'Transaction $id is not found!');
+35 -37
View File
@@ -16,15 +16,15 @@ import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
class OnRamperBuyProvider extends BuyProvider {
OnRamperBuyProvider(
{required WalletBase wallet, bool isTestEnvironment = false})
: super(wallet: wallet,
isTestEnvironment: isTestEnvironment,
hardwareWalletVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
OnRamperBuyProvider({required WalletBase wallet, bool isTestEnvironment = false})
: super(
wallet: wallet,
isTestEnvironment: isTestEnvironment,
hardwareWalletVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
static const _baseUrl = 'buy.onramper.com';
static const _baseApiUrl = 'api.onramper.com';
@@ -68,7 +68,6 @@ class OnRamperBuyProvider extends BuyProvider {
body: json.encode({'query': query}),
);
if (response.statusCode == 200) {
return (jsonDecode(response.body) as Map<String, dynamic>)['signature'] as String;
} else {
@@ -78,7 +77,6 @@ class OnRamperBuyProvider extends BuyProvider {
}
Future<String?> getRecommendedPaymentType(bool isBuyAction) async {
final params = {'type': isBuyAction ? 'buy' : 'sell'};
final url = Uri.https(_baseApiUrl, '$supported$defaultsAll', params);
@@ -95,10 +93,9 @@ class OnRamperBuyProvider extends BuyProvider {
final recommendedPaymentType = recommended['paymentMethod'] as String?;
return recommendedPaymentType ;
return recommendedPaymentType;
} else {
final responseBody =
jsonDecode(response.body) as Map<String, dynamic>;
final responseBody = jsonDecode(response.body) as Map<String, dynamic>;
printV('Failed to fetch available payment types: ${responseBody['message']}');
}
} catch (e) {
@@ -109,21 +106,20 @@ class OnRamperBuyProvider extends BuyProvider {
Future<List<PaymentMethod>> getAvailablePaymentTypes(
String fiatCurrency, CryptoCurrency cryptoCurrency, bool isBuyAction) async {
final normalizedCryptoCurrency =
cryptoCurrency.title + _getNormalizeNetwork(cryptoCurrency);
final normalizedCryptoCurrency = cryptoCurrency.title + _getNormalizeNetwork(cryptoCurrency);
final sourceCurrency = (isBuyAction ? fiatCurrency : normalizedCryptoCurrency).toLowerCase();
final destinationCurrency = (isBuyAction ? normalizedCryptoCurrency : fiatCurrency).toLowerCase();
final destinationCurrency =
(isBuyAction ? normalizedCryptoCurrency : fiatCurrency).toLowerCase();
final params = {'type': isBuyAction ? 'buy' : 'sell', 'destination' : destinationCurrency};
final params = {'type': isBuyAction ? 'buy' : 'sell', 'destination': destinationCurrency};
final url = Uri.https(_baseApiUrl, '$supported$paymentTypes/$sourceCurrency', params);
try {
final response =
await ProxyWrapper().get(clearnetUri: url, headers: {'Authorization': _apiKey, 'accept': 'application/json'});
final response = await ProxyWrapper()
.get(clearnetUri: url, headers: {'Authorization': _apiKey, 'accept': 'application/json'});
if (response.statusCode == 200) {
final Map<String, dynamic> data = jsonDecode(response.body) as Map<String, dynamic>;
final List<dynamic> message = data['message'] as List<dynamic>;
@@ -136,8 +132,7 @@ class OnRamperBuyProvider extends BuyProvider {
return allAvailablePaymentMethods;
} else {
final responseBody =
jsonDecode(response.body) as Map<String, dynamic>;
final responseBody = jsonDecode(response.body) as Map<String, dynamic>;
printV('Failed to fetch available payment types: ${responseBody['message']}');
return [];
}
@@ -151,9 +146,8 @@ class OnRamperBuyProvider extends BuyProvider {
final url = Uri.https(_baseApiUrl, '$supported/onramps/all');
try {
final response =
await ProxyWrapper().get(clearnetUri: url, headers: {'Authorization': _apiKey, 'accept': 'application/json'});
final response = await ProxyWrapper()
.get(clearnetUri: url, headers: {'Authorization': _apiKey, 'accept': 'application/json'});
if (response.statusCode == 200) {
final Map<String, dynamic> data = jsonDecode(response.body) as Map<String, dynamic>;
@@ -191,8 +185,10 @@ class OnRamperBuyProvider extends BuyProvider {
String? countryCode}) async {
String? paymentMethod;
if (paymentType == PaymentType.all ) paymentMethod = null;
else if (paymentType == PaymentType.unknown) paymentMethod = customPaymentMethodType;
if (paymentType == PaymentType.all)
paymentMethod = null;
else if (paymentType == PaymentType.unknown)
paymentMethod = customPaymentMethodType;
else if (paymentType != null) paymentMethod = normalizePaymentMethod(paymentType);
final actionType = isBuyAction ? 'buy' : 'sell';
@@ -217,7 +213,7 @@ class OnRamperBuyProvider extends BuyProvider {
try {
final response = await ProxyWrapper().get(clearnetUri: url, headers: headers);
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as List<dynamic>;
if (data.isEmpty) return null;
@@ -227,7 +223,6 @@ class OnRamperBuyProvider extends BuyProvider {
if (_onrampMetadata.isEmpty) _onrampMetadata = await getOnrampMetadata();
for (var item in data) {
if (item['errors'] != null) continue;
final paymentMethod = (item as Map<String, dynamic>)['paymentMethod'] as String;
@@ -237,8 +232,8 @@ class OnRamperBuyProvider extends BuyProvider {
if (rampMetaData == null) continue;
final quote = Quote.fromOnramperJson(
item, isBuyAction, _onrampMetadata, _getPaymentTypeByString(paymentMethod), customPaymentMethodType);
final quote = Quote.fromOnramperJson(item, isBuyAction, _onrampMetadata,
_getPaymentTypeByString(paymentMethod), customPaymentMethodType);
quote.setFiatCurrency = fiatCurrency;
quote.setCryptoCurrency = cryptoCurrency;
validQuotes.add(quote);
@@ -266,18 +261,21 @@ class OnRamperBuyProvider extends BuyProvider {
String? countryCode}) async {
final actionType = isBuyAction ? 'buy' : 'sell';
final primaryColor = getColorStr(Theme.of(context).colorScheme.primary,);
final primaryColor = getColorStr(
Theme.of(context).colorScheme.primary,
);
final secondaryColor = getColorStr(Theme.of(context).colorScheme.surface);
final primaryTextColor = getColorStr(Theme.of(context).colorScheme.onSurface);
final secondaryTextColor =
getColorStr(Theme.of(context).colorScheme.onSurfaceVariant);
final secondaryTextColor = getColorStr(Theme.of(context).colorScheme.onSurfaceVariant);
final containerColor = getColorStr(Theme.of(context).colorScheme.surface);
var cardColor = getColorStr(Theme.of(context).colorScheme.surfaceContainer);
final defaultCrypto =
quote.cryptoCurrency.title + _getNormalizeNetwork(quote.cryptoCurrency).toLowerCase();
final paymentMethod = quote.paymentType == PaymentType.unknown ? quote.customPaymentMethodType : normalizePaymentMethod(quote.paymentType);
final paymentMethod = quote.paymentType == PaymentType.unknown
? quote.customPaymentMethodType
: normalizePaymentMethod(quote.paymentType);
final networkWallets =
'${_tagToNetwork(quote.cryptoCurrency.tag ?? quote.cryptoCurrency.title).toLowerCase()}:$cryptoCurrencyAddress';
@@ -237,8 +237,9 @@ class RobinhoodBuyProvider extends BuyProvider {
Uri.https('api.robinhood.com', '/catpay/v1/${cryptoCurrency.title}/quote/', queryParams);
try {
final response = await ProxyWrapper().get(clearnetUri: uri, headers: {'accept': 'application/json'});
final response =
await ProxyWrapper().get(clearnetUri: uri, headers: {'accept': 'application/json'});
final responseData = jsonDecode(response.body) as Map<String, dynamic>;
if (response.statusCode == 200) {
+1 -2
View File
@@ -8,7 +8,6 @@ class PaymentMethodLoaded extends PaymentMethodLoadingState {}
class PaymentMethodFailed extends PaymentMethodLoadingState {}
abstract class BuySellQuotLoadingState {}
class InitialBuySellQuotState extends BuySellQuotLoadingState {}
@@ -21,4 +20,4 @@ class BuySellQuotFailed extends BuySellQuotLoadingState {
final String? errorMessage;
BuySellQuotFailed({this.errorMessage});
}
}
+7 -9
View File
@@ -19,13 +19,13 @@ class WyreBuyProvider extends BuyProvider {
WyreBuyProvider({required WalletBase wallet, bool isTestEnvironment = false})
: baseApiUrl = isTestEnvironment ? _baseTestApiUrl : _baseProductApiUrl,
super(
wallet: wallet,
isTestEnvironment: isTestEnvironment,
hardwareWalletVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
wallet: wallet,
isTestEnvironment: isTestEnvironment,
hardwareWalletVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
static const _baseTestApiUrl = 'https://api.testwyre.com';
static const _baseProductApiUrl = 'https://api.sendwyre.com';
@@ -89,7 +89,6 @@ class WyreBuyProvider extends BuyProvider {
throw BuyException(title: providerDescription, content: 'Url $url is not found!');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final urlFromResponse = responseJSON['url'] as String;
return urlFromResponse;
@@ -120,7 +119,6 @@ class WyreBuyProvider extends BuyProvider {
throw BuyException(title: providerDescription, content: 'Quote is not found!');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final sourceAmount = responseJSON['sourceAmount'] as double;
final destAmount = responseJSON['destAmount'] as double;
@@ -25,8 +25,7 @@ class CakePayAccountPage extends BasePage {
label: S.of(context).seed_alert_back,
child: TextButton(
style: ButtonStyle(
overlayColor: WidgetStateColor.resolveWith(
(states) => Colors.transparent),
overlayColor: WidgetStateColor.resolveWith((states) => Colors.transparent),
),
onPressed: () => Navigator.pop(context),
child: backButton(context),
@@ -41,10 +40,10 @@ class CakePayAccountPage extends BasePage {
Widget middle(BuildContext context) {
return Text(
S.current.account,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.w600,
),
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.w600,
),
);
}
@@ -66,9 +65,7 @@ class CakePayAccountPage extends BasePage {
),
),
child: CakePayTile(
title: S.of(context).email_address,
subTitle: cakePayAccountViewModel.email
),
title: S.of(context).email_address, subTitle: cakePayAccountViewModel.email),
),
),
],
@@ -146,9 +146,7 @@ class CakePayVerifyOtpPage extends BasePage {
});
}
void _onOtpSuccessful(BuildContext context) =>
Navigator.pop(context, true);
void _onOtpSuccessful(BuildContext context) => Navigator.pop(context, true);
void _verify() async => await _authViewModel.verifyEmail(_codeController.text);
}
-1
View File
@@ -58,7 +58,6 @@ class UserCakePayCardsStateFailure extends UserCakePayCardsState {
class UserCakePayCardsStateSuccess extends UserCakePayCardsState {}
abstract class CakePayVendorState {}
class InitialCakePayVendorLoadingState extends CakePayVendorState {}
@@ -360,7 +360,8 @@ class CakePayBuyCardPage extends BasePage {
},
text: S.of(context).purchase_gift_card,
isDisabled: !cakePayBuyCardViewModel.isAmountSufficient ||
cakePayBuyCardViewModel.isPurchasing || _sendViewModel.state is ExecutedSuccessfullyState,
cakePayBuyCardViewModel.isPurchasing ||
_sendViewModel.state is ExecutedSuccessfullyState,
isLoading: _sendViewModel.state is IsExecutingState ||
cakePayBuyCardViewModel.isPurchasing,
color: Theme.of(context).colorScheme.primary,
@@ -585,8 +586,7 @@ class CakePayBuyCardPage extends BasePage {
.map((o) => o.OutputCopyWithParsedAddress(
parsedAddress: ParsedAddress(
parsedAddressByCurrencyMap: {
cakePayBuyCardViewModel.sendViewModel.selectedCryptoCurrency:
o.address,
cakePayBuyCardViewModel.sendViewModel.selectedCryptoCurrency: o.address,
},
handle: 'Cake Pay',
profileName: order?.cards.first.cardName ?? 'Cake Pay',
@@ -613,13 +613,13 @@ class CakePayBuyCardPage extends BasePage {
titleIconPath: _sendViewModel.selectedCryptoCurrency.iconPath,
currency: _sendViewModel.selectedCryptoCurrency,
amount: S.of(bottomSheetContext).send_amount,
amountValue: _sendViewModel.amountParsingProxy.asDisplayStringWithSymbol(
_sendViewModel.pendingTransaction!.amount),
amountValue: _sendViewModel.amountParsingProxy
.asDisplayStringWithSymbol(_sendViewModel.pendingTransaction!.amount),
quantity: 'QTY: ${cakePayBuyCardViewModel.quantity}',
fiatAmountValue: _sendViewModel.pendingTransactionFiatAmountFormatted,
fee: S.of(bottomSheetContext).send_fee,
feeValue: _sendViewModel.amountParsingProxy.asDisplayStringWithSymbol(
_sendViewModel.pendingTransaction!.fee),
feeValue: _sendViewModel.amountParsingProxy
.asDisplayStringWithSymbol(_sendViewModel.pendingTransaction!.fee),
feeFiatAmount: _sendViewModel.pendingTransactionFeeFiatAmountFormatted,
outputs: displayingOutputs,
footerType: FooterType.slideActionButton,
@@ -657,8 +657,7 @@ class CakePayBuyCardPage extends BasePage {
.map((o) => o.OutputCopyWithParsedAddress(
parsedAddress: ParsedAddress(
parsedAddressByCurrencyMap: {
cakePayBuyCardViewModel.sendViewModel.selectedCryptoCurrency:
o.address,
cakePayBuyCardViewModel.sendViewModel.selectedCryptoCurrency: o.address,
},
handle: 'Cake Pay',
profileName: order?.cards.first.cardName ?? 'Cake Pay',
@@ -92,7 +92,9 @@ class CakePayCardsPage extends BasePage {
@override
Widget body(BuildContext context) {
return KeyboardHideOverlay(child:CakePayCardsPageBody(cardsListViewModel: _cardsListViewModel, titleColor: titleColor));
return KeyboardHideOverlay(
child:
CakePayCardsPageBody(cardsListViewModel: _cardsListViewModel, titleColor: titleColor));
}
}
+6 -1
View File
@@ -45,7 +45,11 @@ class CakePayCard {
final parsedMinValueLocal = _toDouble(json['min_value']);
final parsedMinValueUsd = _toDouble(json['min_value_usd']);
if (parsedMinValueLocal != null && parsedMinValueLocal > 0 && parsedMinValueUsd != null && parsedMinValueUsd > 0 && parsedMinValueUsd < 10.0) {
if (parsedMinValueLocal != null &&
parsedMinValueLocal > 0 &&
parsedMinValueUsd != null &&
parsedMinValueUsd > 0 &&
parsedMinValueUsd < 10.0) {
final rate = parsedMinValueLocal / parsedMinValueUsd;
final minLocalValueLimit = 10.0 * rate;
minValue = minLocalValueLimit.toStringAsFixed(2);
@@ -80,6 +84,7 @@ class CakePayCard {
static String stripHtmlIfNeeded(String text) {
return text.replaceAll(RegExp(r'<[^>]*>|&[^;]+;'), ' ');
}
static double? _toDouble(dynamic v) {
if (v == null) return null;
if (v is num) return v.toDouble();
+19 -12
View File
@@ -37,15 +37,12 @@ class CakePayOrder {
});
factory CakePayOrder.fromMap(Map<String, dynamic> map) {
final cards = map['cards'] as List<dynamic>;
final firstCard = cards.isNotEmpty ? cards.first as Map<String, dynamic> : {};
return CakePayOrder(
orderId: map['order_id'] as String,
cards: cards
.map((x) => OrderCard.fromMap(x as Map<String, dynamic>))
.toList(),
cards: cards.map((x) => OrderCard.fromMap(x as Map<String, dynamic>)).toList(),
externalId: map['external_id'] as String?,
amountUsd: map['amount_usd'] as double,
totalReceiveAmount: firstCard['subtotal'] as String? ?? '',
@@ -56,7 +53,7 @@ class CakePayOrder {
paymentData: PaymentData.fromMap(map['payment_data'] as Map<String, dynamic>));
}
static CryptoPaymentData? getPaymentDataFor({CakePayPaymentMethod? method,CakePayOrder? order}) {
static CryptoPaymentData? getPaymentDataFor({CakePayPaymentMethod? method, CakePayOrder? order}) {
if (order == null || method == null) return null;
final data = switch (method) {
@@ -76,7 +73,8 @@ class CakePayOrder {
final addr = uri.path;
final price = uri.queryParameters['amount'] ?? data.price;
return CryptoPaymentData(price: price, address: addr, amount: data.amount, paymentUrls: data.paymentUrls);
return CryptoPaymentData(
price: price, address: addr, amount: data.amount, paymentUrls: data.paymentUrls);
}
return data;
@@ -151,12 +149,21 @@ class PaymentData {
factory PaymentData.fromMap(Map<String, dynamic> map) {
return PaymentData(
btc: map['BTC'] != null ? CryptoPaymentData.fromMap(map['BTC'] as Map<String, dynamic>) : null,
btc_ln: map['BTC_LN'] != null ? CryptoPaymentData.fromMap(map['BTC_LN'] as Map<String, dynamic>) : null,
xmr: map['XMR'] != null ? CryptoPaymentData.fromMap(map['XMR'] as Map<String, dynamic>) : null,
ltc: map['LTC'] != null ? CryptoPaymentData.fromMap(map['LTC'] as Map<String, dynamic>) : null,
ltc_mweb: map['LTC_MWEB'] != null ? CryptoPaymentData.fromMap(map['LTC_MWEB'] as Map<String, dynamic>) : null,
zec: map['ZEC_CHAIN'] != null ? CryptoPaymentData.fromMap(map['ZEC_CHAIN'] as Map<String, dynamic>) : null,
btc:
map['BTC'] != null ? CryptoPaymentData.fromMap(map['BTC'] as Map<String, dynamic>) : null,
btc_ln: map['BTC_LN'] != null
? CryptoPaymentData.fromMap(map['BTC_LN'] as Map<String, dynamic>)
: null,
xmr:
map['XMR'] != null ? CryptoPaymentData.fromMap(map['XMR'] as Map<String, dynamic>) : null,
ltc:
map['LTC'] != null ? CryptoPaymentData.fromMap(map['LTC'] as Map<String, dynamic>) : null,
ltc_mweb: map['LTC_MWEB'] != null
? CryptoPaymentData.fromMap(map['LTC_MWEB'] as Map<String, dynamic>)
: null,
zec: map['ZEC_CHAIN'] != null
? CryptoPaymentData.fromMap(map['ZEC_CHAIN'] as Map<String, dynamic>)
: null,
invoiceTime: DateTime.fromMillisecondsSinceEpoch(map['invoice_time'] as int),
expirationTime: DateTime.fromMillisecondsSinceEpoch(map['expiration_time'] as int),
commission: map['commission'] as int?,
@@ -1,6 +1,6 @@
class CakePayUserCredentials {
const CakePayUserCredentials(this.username, this.token);
const CakePayUserCredentials(this.username, this.token);
final String username;
final String token;
}
final String username;
final String token;
}
+6 -6
View File
@@ -15,7 +15,7 @@ class CakePayTile extends StatelessWidget {
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return GestureDetector(
onTap: onTap,
child: Row(
@@ -27,16 +27,16 @@ class CakePayTile extends StatelessWidget {
Text(
title,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
color: colorScheme.onSurfaceVariant,
),
),
SizedBox(height: 8),
Text(
subTitle,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: colorScheme.onSurface,
fontWeight: FontWeight.w600,
),
color: colorScheme.onSurface,
fontWeight: FontWeight.w600,
),
),
],
)
@@ -65,18 +65,18 @@ class _DenominationsAmountWidgetState extends State<DenominationsAmountWidget> {
mainAxisSize: MainAxisSize.min,
children: [
DropdownFilterList(
items: widget.denominations
.map((e) => e.value.toString())
.toList(),
items: widget.denominations.map((e) => e.value.toString()).toList(),
itemPrefix: widget.fiatCurrency,
selectedItem: _selected.$1,
onItemSelected: (value) {
setState(() => _selected = (value, widget.denominations
.firstWhere((e) => e.value.toString() == value)
.cardId));
setState(() => _selected = (
value,
widget.denominations.firstWhere((e) => e.value.toString() == value).cardId
));
widget.amountController.text = value;
widget.onAmountChanged(value);
widget.cakePayBuyCardViewModel.selectedDenomination = (_selected.$1, _selected.$2);
widget.cakePayBuyCardViewModel.selectedDenomination =
(_selected.$1, _selected.$2);
},
),
const SizedBox(height: 4),
@@ -59,12 +59,11 @@ class EnterAmountWidget extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
Text('QTY ', style: Theme.of(context).textTheme.titleMedium!),
Text(
'1',
style: Theme.of(context).textTheme
.titleMedium!
.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant)
),
Text('1',
style: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant)),
],
),
),
@@ -87,12 +86,12 @@ class EnterAmountWidget extends StatelessWidget {
children: [
Text(S.of(context).min_amount(minValue) + ' $fiatCurrency',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
)),
color: Theme.of(context).colorScheme.onSurfaceVariant,
)),
Text(S.of(context).max_amount(maxValue) + ' $fiatCurrency',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
)),
color: Theme.of(context).colorScheme.onSurfaceVariant,
)),
],
),
Spacer(flex: 1),
@@ -21,7 +21,7 @@ class FlipCard extends StatefulWidget {
class FlipCardState extends State<FlipCard> with SingleTickerProviderStateMixin {
late final AnimationController _ctrl =
AnimationController(vsync: this, duration: widget.duration);
AnimationController(vsync: this, duration: widget.duration);
bool _isFront = true;
void toggleCard() {
@@ -45,18 +45,17 @@ class FlipCardState extends State<FlipCard> with SingleTickerProviderStateMixin
transform: Matrix4.identity()
..setEntry(3, 2, 0.001)
..rotateY(angle),
child: isFront ? widget.front
child: isFront
? widget.front
: Transform(
alignment: Alignment.center,
transform: Matrix4.rotationY(math.pi),
child: widget.back,
),
alignment: Alignment.center,
transform: Matrix4.rotationY(math.pi),
child: widget.back,
),
);
},
);
return widget.flipOnTouch
? GestureDetector(onTap: toggleCard, child: content)
: content;
return widget.flipOnTouch ? GestureDetector(onTap: toggleCard, child: content) : content;
}
}
+1 -1
View File
@@ -31,7 +31,7 @@ class ClickableLinksText extends StatelessWidget {
text: url,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.primary,
fontSize: 18,
fontSize: 18,
),
recognizer: TapGestureRecognizer()
..onTap = () async {
@@ -14,16 +14,15 @@ class RoundedOverlayCards extends StatelessWidget {
final screenHeight = MediaQuery.of(context).size.height;
return ClipRRect(
borderRadius:
BorderRadius.only(bottomLeft: Radius.circular(25.0), bottomRight: Radius.circular(25.0)),
BorderRadius.only(bottomLeft: Radius.circular(25.0), bottomRight: Radius.circular(25.0)),
child: Container(
height: screenHeight * 0.50,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(24),
bottomRight: Radius.circular(24),
),
color: Theme.of(context).colorScheme.surfaceContainer
),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(24),
bottomRight: Radius.circular(24),
),
color: Theme.of(context).colorScheme.surfaceContainer),
child: Column(
children: [
ClipRRect(
@@ -44,4 +43,4 @@ class RoundedOverlayCards extends StatelessWidget {
),
);
}
}
}
@@ -48,8 +48,8 @@ class ThreeCheckboxAlert extends BaseAlertDialog {
@override
VoidCallback get actionRight => () {
actionRightButton(checkbox1, checkbox2, checkbox3);
};
actionRightButton(checkbox1, checkbox2, checkbox3);
};
@override
bool get barrierDismissible => alertBarrierDismissible;
@@ -87,13 +87,13 @@ class ThreeCheckboxAlertContent extends StatefulWidget {
@override
_ThreeCheckboxAlertContentState createState() => _ThreeCheckboxAlertContentState(
checkbox1: checkbox1,
toggleCheckbox1: toggleCheckbox1,
checkbox2: checkbox2,
toggleCheckbox2: toggleCheckbox2,
checkbox3: checkbox3,
toggleCheckbox3: toggleCheckbox3,
);
checkbox1: checkbox1,
toggleCheckbox1: toggleCheckbox1,
checkbox2: checkbox2,
toggleCheckbox2: toggleCheckbox2,
checkbox3: checkbox3,
toggleCheckbox3: toggleCheckbox3,
);
static _ThreeCheckboxAlertContentState? of(BuildContext context) {
return context.findAncestorStateOfType<_ThreeCheckboxAlertContentState>();
+2 -7
View File
@@ -2,12 +2,7 @@ import 'package:flutter/material.dart';
import 'image_placeholder.dart';
class UserCardItem extends StatelessWidget {
UserCardItem({
required this.title,
required this.subTitle,
this.onTap,
this.logoUrl
});
UserCardItem({required this.title, required this.subTitle, this.onTap, this.logoUrl});
final VoidCallback? onTap;
final String title;
@@ -80,4 +75,4 @@ class UserCardItem extends StatelessWidget {
),
);
}
}
}
@@ -5,7 +5,6 @@ import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/wallet_base.dart';
abstract class AddressLookupProvider {
AddressSource get source;
List<CryptoCurrency> get supportedCurrencies;
@@ -104,7 +104,8 @@ class AddressResolverService {
if (results.isNotEmpty) {
final parsedAddress = results.first.parsedAddressByCurrencyMap[currency];
final parsedAddressStr = parsedAddress == null || parsedAddress.isEmpty ? 'N/A' : parsedAddress;
final parsedAddressStr =
parsedAddress == null || parsedAddress.isEmpty ? 'N/A' : parsedAddress;
printV('[address resolver service] resolved $src - $cur - $parsedAddressStr');
return [results.first];
}
@@ -14,7 +14,8 @@ class AddressResolverUtils {
final result = <CryptoCurrency, String>{};
for (final currency in currencies) {
final address = await UnstoppableAddressProvider.fetchUnstoppableDomainAddress(domain, currency.title);
final address =
await UnstoppableAddressProvider.fetchUnstoppableDomainAddress(domain, currency.title);
if (address.isNotEmpty) {
result[currency] = address;
}
@@ -54,15 +54,17 @@ class Bip353AddressProvider extends AddressLookupProvider {
printV('Bip353Record.fetchDnsProof error: $e');
}
return [ParsedAddress(
parsedAddressByCurrencyMap: result,
addressSource: AddressSource.bip353,
handle: query,
bip353DnsProof: dnsProof ?? '',
)];
return [
ParsedAddress(
parsedAddressByCurrencyMap: result,
addressSource: AddressSource.bip353,
handle: query,
bip353DnsProof: dnsProof ?? '',
)
];
} catch (e) {
printV('[address resolver] Error resolving BIP353 address: $e');
return [];
}
}
}
}
@@ -99,5 +99,4 @@ class Bip353Record {
return result;
}
}
}
}
+12 -12
View File
@@ -9,10 +9,10 @@ import 'package:web3dart/web3dart.dart';
class EnsRecord {
static Future<String> fetchEnsAddress(
String name,
CryptoCurrency cur, {
WalletBase? wallet,
}) async {
String name,
CryptoCurrency cur, {
WalletBase? wallet,
}) async {
Web3Client? _client;
if (wallet?.type == WalletType.ethereum || wallet?.type == WalletType.polygon) {
@@ -45,11 +45,11 @@ class EnsRecord {
}
static CoinType? getEnsCoinType(CryptoCurrency cur) => switch (cur) {
CryptoCurrency.xmr => CoinType.XMR,
CryptoCurrency.btc => CoinType.BTC,
CryptoCurrency.ltc => CoinType.LTC,
CryptoCurrency.eth => CoinType.ETH,
CryptoCurrency.matic => CoinType.MATIC,
_ => null,
};
}
CryptoCurrency.xmr => CoinType.XMR,
CryptoCurrency.btc => CoinType.BTC,
CryptoCurrency.ltc => CoinType.LTC,
CryptoCurrency.eth => CoinType.ETH,
CryptoCurrency.matic => CoinType.MATIC,
_ => null,
};
}
@@ -34,23 +34,23 @@ class FioAddressProvider extends AddressLookupProvider {
}) async {
final Map<CryptoCurrency, String> result = {};
try {
final bool isFioRegistered = await FioAddressProvider.checkAvail(query);
if (!isFioRegistered) return [];
final bool isFioRegistered = await FioAddressProvider.checkAvail(query);
if (!isFioRegistered) return [];
for (final cur in currencies) {
final address = await FioAddressProvider.getPubAddress(query, cur.title);
if (address != null && address.isNotEmpty) {
result[cur] = address;
for (final cur in currencies) {
final address = await FioAddressProvider.getPubAddress(query, cur.title);
if (address != null && address.isNotEmpty) {
result[cur] = address;
}
}
}
if (result.isNotEmpty) {
return [
ParsedAddress(
parsedAddressByCurrencyMap: result, addressSource: AddressSource.fio, handle: query)
];
}
return [];
if (result.isNotEmpty) {
return [
ParsedAddress(
parsedAddressByCurrencyMap: result, addressSource: AddressSource.fio, handle: query)
];
}
return [];
} catch (e) {
printV('FioAddressProvider.resolve error: $e');
return [];
@@ -16,7 +16,8 @@ class LNUrlPayAddressProvider extends AddressLookupProvider {
List<CryptoCurrency> get supportedCurrencies => [CryptoCurrency.btcln];
@override
bool canHandle(String q) => q.contains('.') && q.contains('@'); // LNURL-pay handle example: user@domain.com
bool canHandle(String q) =>
q.contains('.') && q.contains('@'); // LNURL-pay handle example: user@domain.com
@override
bool isEnabled(SettingsStore settingsStore) => settingsStore.lookupsLNUrl;
@@ -63,4 +64,4 @@ class LNUrlPayAddressProvider extends AddressLookupProvider {
return [];
}
}
}
}
@@ -13,7 +13,7 @@ class LNUrlPayRecord {
final String address;
static Future<String?> checkWellKnownUsername(String username, CryptoCurrency currency,
{bool allowRethrow = false}) async {
{bool allowRethrow = false}) async {
if (![CryptoCurrency.btc, CryptoCurrency.btcln].contains(currency)) return null;
// split the string by the @ symbol:
@@ -21,7 +21,6 @@ class MastodonAPI {
);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode != 200) return null;
@@ -49,7 +48,6 @@ class MastodonAPI {
);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode != 200) {
throw Exception('Unexpected HTTP status: ${response.statusCode}');
@@ -15,12 +15,11 @@ class MastodonUser {
factory MastodonUser.fromJson(Map<String, dynamic> json) {
return MastodonUser(
id: json['id'] as String,
username: json['username'] as String? ?? '',
acct: json['acct'] as String,
note: json['note'] as String,
profileImageUrl: json['avatar'] as String? ?? ''
);
id: json['id'] as String,
username: json['username'] as String? ?? '',
acct: json['acct'] as String,
note: json['note'] as String,
profileImageUrl: json['avatar'] as String? ?? '');
}
}
@@ -21,9 +21,9 @@ class NostrProfileHandler {
}
static Future<UserMetadata?> processRelays(
ProfilePointer profile,
String nip05Address,
) async {
ProfilePointer profile,
String nip05Address,
) async {
final userDomain = _extractDomain(nip05Address);
const int metaKind = 0;
@@ -124,4 +124,4 @@ class NostrProfileHandler {
return '';
}
}
}
}
@@ -1,4 +1,3 @@
class UserMetadata {
final String name;
final String lnurl;
@@ -32,4 +31,4 @@ class UserMetadata {
website: json['website'] as String? ?? '',
);
}
}
}
@@ -66,4 +66,4 @@ class OpenaliasRecord {
return OpenaliasRecord(address: address, name: name, description: note);
}
}
}
@@ -19,4 +19,4 @@ class ParsedAddress {
final String profileName;
final String description;
final String? bip353DnsProof;
}
}
@@ -11,7 +11,6 @@ import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
class TwitterAddressProvider extends AddressLookupProvider {
@override
AddressSource get source => AddressSource.twitter;
@@ -23,14 +23,14 @@ class TwitterApi {
path: userPath + userName,
queryParameters: queryParams);
final response = await ProxyWrapper().get(clearnetUri: uri, headers: headers).catchError((error) {
final response =
await ProxyWrapper().get(clearnetUri: uri, headers: headers).catchError((error) {
throw Exception('HTTP request failed: $error');
});
if (response.statusCode != 200) {
throw Exception('Unexpected http status: ${response.statusCode}');
}
final Map<String, dynamic> responseJSON = jsonDecode(response.body) as Map<String, dynamic>;
if (responseJSON['errors'] != null &&
@@ -211,13 +211,15 @@ class UnstoppableAddressProvider extends AddressLookupProvider {
var address = '';
try {
final uri = Uri.parse("https://api.unstoppabledomains.com/profile/public/${Uri.encodeQueryComponent(domain)}?fields=records");
final uri = Uri.parse(
"https://api.unstoppabledomains.com/profile/public/${Uri.encodeQueryComponent(domain)}?fields=records");
final response = await ProxyWrapper().get(clearnetUri: uri);
final jsonParsed = json.decode(response.body) as Map<String, dynamic>;
if (jsonParsed["records"] == null) {
throw Exception(".records response from $uri is empty");
};
}
;
final records = jsonParsed["records"] as Map<String, dynamic>;
final key = "crypto.${ticker.toUpperCase()}.address";
if (records[key] == null) {
@@ -20,9 +20,9 @@ class WellKnownRecord {
static const _jsonLocation = {CryptoCurrency.nano: 'nano-currency'};
static Future<WellKnownRecord?> fetch(
String username,
CryptoCurrency currency,
) async {
String username,
CryptoCurrency currency,
) async {
final location = _jsonLocation[currency];
if (location == null) {
printV('well-known: unsupported coin $currency');
@@ -75,4 +75,4 @@ class WellKnownRecord {
}
return null;
}
}
}
@@ -16,4 +16,4 @@ class YatRecord {
@override
String toString() => 'YatRecord(tag: $tag, address: $address)';
}
}
@@ -11,8 +11,7 @@ class YatService {
static const apiReleaseUrl = "https://a.y.at";
static const apiDevUrl = 'https://a.yat.fyi';
static String lookupEmojiUrl(String emojiId) =>
"$apiUrl/emoji_id/$emojiId/payment";
static String lookupEmojiUrl(String emojiId) => "$apiUrl/emoji_id/$emojiId/payment";
static const String MONERO_SUB_ADDRESS = '0x1002';
static const String MONERO_STD_ADDRESS = '0x1001';
@@ -23,9 +22,9 @@ class YatService {
};
static Future<List<YatRecord>> fetchYatAddress(
String emojiId,
String ticker,
) async {
String emojiId,
String ticker,
) async {
final tagQuery = tags[ticker.toUpperCase()];
if (tagQuery == null) return const [];
@@ -48,9 +47,7 @@ class YatService {
records.add(YatRecord.fromJson(data, tag.toString()));
}
});
}
else if (res is List) {
} else if (res is List) {
for (final item in res) {
if (item is Map<String, dynamic>) {
final tag = item['tag']?.toString() ?? '';
@@ -64,4 +61,4 @@ class YatService {
return const [];
}
}
}
}
+30 -34
View File
@@ -25,29 +25,28 @@ class YatLink {
static const requestReleaseUrl = ''; //'https://a.y.at/emoji_id/';
static const startFlowUrl = ''; // 'https://www.y03btrk.com/4RQSJ/6JHXF/';
static const isDevMode = true;
static const tags = <String, List<String>>{"XMR" : ['0x1001', '0x1002'],
"BTC" : ['0x1003'], "LTC" : ['0x1019']};
static const tags = <String, List<String>>{
"XMR": ['0x1001', '0x1002'],
"BTC": ['0x1003'],
"LTC": ['0x1019']
};
static String get apiUrl => YatLink.isDevMode
? YatLink.apiDevUrl
: YatLink.apiReleaseUrl;
static String get apiUrl => YatLink.isDevMode ? YatLink.apiDevUrl : YatLink.apiReleaseUrl;
static String get emojiIdUrl => apiUrl + '/emoji_id/';
static String get baseUrl => YatLink.isDevMode
? YatLink.baseDevUrl
: YatLink.baseReleaseUrl;
static String get baseUrl => YatLink.isDevMode ? YatLink.baseDevUrl : YatLink.baseReleaseUrl;
}
Future<List<String>> fetchYatAddress(String emojiId, String ticker) async {
throw Exception();
//final url = YatLink.emojiIdUrl + emojiId + '/payment';
//final response = await get(url);
//if (response.statusCode != 200) {
// throw YatException(text: response.body.toString());
//}
//final addresses = <String>[];
//final currency = ticker.toUpperCase();
//final responseJSON = json.decode(response.body) as Map<String, dynamic>;
@@ -55,7 +54,7 @@ Future<List<String>> fetchYatAddress(String emojiId, String ticker) async {
//result.forEach((dynamic key, dynamic value) {
// final tag = key as String ?? '';
// final record = value as Map<String, dynamic>;
// if (YatLink.tags[currency]?.contains(tag) ?? false) {
// final address = record['address'] as String;
// if (address?.isNotEmpty ?? false) {
@@ -80,11 +79,11 @@ Future<String> fetchYatAccessToken(String refreshToken) async {
// 'Accept': '*/*'
// },
// body: bodyJson);
// if (response.statusCode != 200) {
// throw YatException(text: response.body.toString());
// }
// final responseJSON = json.decode(response.body) as Map<String, dynamic>;
// return responseJSON['access_token'] as String;
//}catch(_) {
@@ -110,7 +109,7 @@ Future<String> fetchYatApiKey(String accessKey) async {
// if (response.statusCode != 200) {
// throw YatException(text: response.body.toString());
// }
// final responseJSON = json.decode(response.body) as Map<String, dynamic>;
// return responseJSON['api_key'] as String;
//}catch(_) {
@@ -119,7 +118,8 @@ Future<String> fetchYatApiKey(String accessKey) async {
return '';
}
Future<void> updateEmojiIdAddress(String emojiId, String address, String apiKey, WalletType type) async {
Future<void> updateEmojiIdAddress(
String emojiId, String address, String apiKey, WalletType type) async {
throw Exception();
//final url = YatLink.emojiIdUrl + emojiId;
//final cur = walletTypeToCryptoCurrency(type);
@@ -166,15 +166,13 @@ Future<String> visualisationForEmojiId(String emojiId) async {
class YatStore = YatStoreBase with _$YatStore;
abstract class YatStoreBase with Store {
YatStoreBase({
required this.appStore,
required this.secureStorage})
: _wallet = appStore.wallet,
emoji = appStore.wallet?.walletInfo?.yatEmojiId ?? '',
refreshToken = '',
accessToken = '',
apiKey = '',
emojiIncommingSC = StreamController<String>.broadcast() {
YatStoreBase({required this.appStore, required this.secureStorage})
: _wallet = appStore.wallet,
emoji = appStore.wallet?.walletInfo?.yatEmojiId ?? '',
refreshToken = '',
accessToken = '',
apiKey = '',
emojiIncommingSC = StreamController<String>.broadcast() {
//reaction((_) => appStore.wallet, _onWalletChange);
//reaction((_) => emoji, (String _) => _onEmojiChange());
//reaction((_) => refreshToken, (String _) => _onRefreshTokenChange());
@@ -209,24 +207,22 @@ abstract class YatStoreBase with Store {
Stream<String> get emojiIncommingStream => emojiIncommingSC.stream;
@observable
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo>?
_wallet;
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo>? _wallet;
Future<void> init() async {
if (_wallet == null) {
return;
}
refreshToken = await secureStorage.read(key: yatRefreshTokenKey(_wallet!.walletInfo.name)) ?? '';
refreshToken =
await secureStorage.read(key: yatRefreshTokenKey(_wallet!.walletInfo.name)) ?? '';
accessToken = await secureStorage.read(key: yatAccessTokenKey(_wallet!.walletInfo.name)) ?? '';
apiKey = await secureStorage.read(key: yatApiKey(_wallet!.walletInfo.name)) ?? '';
}
@action
void _onWalletChange(
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>,
TransactionInfo>
wallet) {
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo> wallet) {
this._wallet = wallet;
emoji = wallet?.walletInfo?.yatEmojiId ?? '';
init();
@@ -252,7 +248,7 @@ abstract class YatStoreBase with Store {
@action
Future<void> _onRefreshTokenChange() async {
throw Exception();
//try {
// await secureStorage.write(key: yatRefreshTokenKey(_wallet.walletInfo.name), value: refreshToken);
// accessToken = await fetchYatAccessToken(refreshToken);
@@ -269,7 +265,7 @@ abstract class YatStoreBase with Store {
//final result = <String, String>{};
//final tags = YatLink.tags[_wallet.currency.toString().toUpperCase()];
//String tag = tags.first;
//if (_wallet.type == WalletType.monero
// && _wallet.walletAddresses.address.startsWith('4')) {
// tag = tags.last;
@@ -277,7 +273,7 @@ abstract class YatStoreBase with Store {
//result[tag] = '${_wallet.walletAddresses.address}|${_wallet.name}';
//final addressJson = json.encode([result]);
//final addressJsonBytes = utf8.encode(addressJson);
//return base64.encode(addressJsonBytes);
return '';
}
@@ -10,7 +10,6 @@ import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/wallet_base.dart';
class ZanoAliasAddressProvider extends AddressLookupProvider {
@override
AddressSource get source => AddressSource.zanoAlias;
@@ -67,8 +67,7 @@ class ZcashNamesRecord {
}
static bool _isValidZcashAddress(String address) {
final pattern =
AddressValidator.getAddressFromStringPattern(CryptoCurrency.zec);
final pattern = AddressValidator.getAddressFromStringPattern(CryptoCurrency.zec);
if (pattern == null) return false;
return RegExp('^(?:$pattern)\$').hasMatch(address);
}
+28 -29
View File
@@ -12,29 +12,29 @@ const AFTER_REGEX = '(\$|\\s)';
class AddressValidator extends TextValidator {
AddressValidator({required CryptoCurrency type, bool isTestnet = false})
: super(
errorMessage: S.current.error_text_address,
useAdditionalValidation: [CryptoCurrency.btc, CryptoCurrency.ltc].contains(type)
? (String txt) {
final RegExp lightningInvoiceRegex = RegExp(
r'^(lightning:)?(lnbc|lntb|lnbs|lnbcrt|lnurl)[a-z0-9]+$',
caseSensitive: false);
if (lightningInvoiceRegex.hasMatch(txt)) return true;
errorMessage: S.current.error_text_address,
useAdditionalValidation: [CryptoCurrency.btc, CryptoCurrency.ltc].contains(type)
? (String txt) {
final RegExp lightningInvoiceRegex = RegExp(
r'^(lightning:)?(lnbc|lntb|lnbs|lnbcrt|lnurl)[a-z0-9]+$',
caseSensitive: false);
if (lightningInvoiceRegex.hasMatch(txt)) return true;
return BitcoinAddressUtils.validateAddress(
address: txt,
network: type == CryptoCurrency.btc
? isTestnet
? BitcoinNetwork.testnet
: BitcoinNetwork.mainnet
: LitecoinNetwork.mainnet,
);
}
: type == CryptoCurrency.zano
? zano?.validateAddress
: null,
pattern: getPattern(type, isTestnet: isTestnet),
length: getLength(type),
);
return BitcoinAddressUtils.validateAddress(
address: txt,
network: type == CryptoCurrency.btc
? isTestnet
? BitcoinNetwork.testnet
: BitcoinNetwork.mainnet
: LitecoinNetwork.mainnet,
);
}
: type == CryptoCurrency.zano
? zano?.validateAddress
: null,
pattern: getPattern(type, isTestnet: isTestnet),
length: getLength(type),
);
static const List<CryptoCurrency> reliableValidateCurrencies = [
CryptoCurrency.xmr,
@@ -170,8 +170,7 @@ class AddressValidator extends TextValidator {
case CryptoCurrency.hbar:
pattern = '[0-9a-zA-Z.]+';
case CryptoCurrency.zec:
pattern =
'(?:'
pattern = '(?:'
't1[0-9A-Za-z]{33}'
'|t3[0-9A-Za-z]{33}'
'|zs[a-z0-9]{76}'
@@ -195,7 +194,8 @@ class AddressValidator extends TextValidator {
case CryptoCurrency.pivx:
pattern = 'D([1-9a-km-zA-HJ-NP-Z]){33}';
case CryptoCurrency.btcln:
pattern = r'(lightning:)?(lnbc|lntb|lnbs|lnbcrt|lnurl|LNBC|LNTB|LNBS|LNBCRT|LNURL)[a-zA-Z0-9]+';
pattern =
r'(lightning:)?(lnbc|lntb|lnbs|lnbcrt|lnurl|LNBC|LNTB|LNBS|LNBCRT|LNURL)[a-zA-Z0-9]+';
case CryptoCurrency.zano:
pattern = r'([1-9A-HJ-NP-Za-km-z]{90,200})|(@[\w\d.-]+)';
case CryptoCurrency.doge:
@@ -369,7 +369,7 @@ class AddressValidator extends TextValidator {
'|([0-9a-zA-Z]{106})';
case CryptoCurrency.btc:
pattern =
'${P2pkhAddress.regex.pattern}|${P2shAddress.regex.pattern}|${P2wpkhAddress.regex.pattern}|${P2trAddress.regex.pattern}|${P2wshAddress.regex.pattern}|${SilentPaymentAddress.regex.pattern}';
'${P2pkhAddress.regex.pattern}|${P2shAddress.regex.pattern}|${P2wpkhAddress.regex.pattern}|${P2trAddress.regex.pattern}|${P2wshAddress.regex.pattern}|${SilentPaymentAddress.regex.pattern}';
case CryptoCurrency.ltc:
pattern = '([^0-9a-zA-Z]|^)^L[a-zA-Z0-9]{26,33}([^0-9a-zA-Z]|\$)'
'|([^0-9a-zA-Z]|^)[LM][a-km-zA-HJ-NP-Z1-9]{26,33}([^0-9a-zA-Z]|\$)'
@@ -394,8 +394,7 @@ class AddressValidator extends TextValidator {
case CryptoCurrency.zano:
pattern = '([1-9A-HJ-NP-Za-km-z]{90,200})|(@[\w\d.-]+)';
case CryptoCurrency.zec:
pattern =
'(?:'
pattern = '(?:'
't1[0-9A-Za-z]{33}'
'|t3[0-9A-Za-z]{33}'
'|zs[a-z0-9]{76}'
@@ -419,4 +418,4 @@ class AddressValidator extends TextValidator {
return pattern != null ? "($pattern)" : null;
}
}
}
+3 -3
View File
@@ -12,9 +12,9 @@ class AmountValidator extends TextValidator {
String? minValue,
String? maxValue,
}) {
symbolsAmountValidator =
SymbolsAmountValidator(isAutovalidate: isAutovalidate);
decimalAmountValidator = DecimalAmountValidator(currency: currency,isAutovalidate: isAutovalidate);
symbolsAmountValidator = SymbolsAmountValidator(isAutovalidate: isAutovalidate);
decimalAmountValidator =
DecimalAmountValidator(currency: currency, isAutovalidate: isAutovalidate);
amountMinValidator = AmountMinValidator(
minValue: minValue,
-1
View File
@@ -17,4 +17,3 @@ class AuthenticationBanned extends AuthState {
final String error;
}
+26 -21
View File
@@ -25,8 +25,8 @@ import 'package:cake_wallet/wallet_types.g.dart';
import 'package:cake_backup/backup.dart' as cake_backup;
class $BackupService {
$BackupService(this._secureStorage, this.transactionDescriptionBox,
this.keyService, this.sharedPreferences)
$BackupService(
this._secureStorage, this.transactionDescriptionBox, this.keyService, this.sharedPreferences)
: cipher = Cryptography.instance.chacha20Poly1305Aead(),
correctWallets = <WalletInfo>[];
@@ -42,7 +42,6 @@ class $BackupService {
final KeyService keyService;
List<WalletInfo> correctWallets;
Future<void> importBackupV1(Uint8List data, String password, {required String nonce}) async {
final appDir = await getAppDir();
final decryptedData = await _decryptV1(data, password, nonce);
@@ -59,7 +58,8 @@ class $BackupService {
} else {
Directory('${appDir.path}/' + filename)..create(recursive: true);
}
};
}
;
await verifyWallets();
await _importKeychainDumpV1(password, nonce: nonce);
@@ -101,7 +101,8 @@ class $BackupService {
dir.createSync(recursive: true);
}
}
};
}
;
await verifyWallets();
await importKeychainDumpV2(password);
@@ -112,7 +113,9 @@ class $BackupService {
Future<void> verifyWallets() async {
await performHiveMigration(); // for backups made before sqlite migration
await performTradeHiveMigration(_secureStorage);
correctWallets = (await WalletInfo.getAll()).where((info) => availableWalletTypes.contains(info.type)).toList();
correctWallets = (await WalletInfo.getAll())
.where((info) => availableWalletTypes.contains(info.type))
.toList();
if (correctWallets.isEmpty) {
printV('Correct wallets not detected');
@@ -133,12 +136,11 @@ class $BackupService {
MapEntry(key, TransactionDescription.fromJson(value as Map<String, dynamic>)));
var box = transactionDescriptionBox;
if (!box.isOpen) {
final transactionDescriptionsBoxKey =
await getEncryptionKey(secureStorage: _secureStorage, forKey: TransactionDescription.boxKey);
box = await CakeHive.openBox<TransactionDescription>(
TransactionDescription.boxName,
encryptionKey: transactionDescriptionsBoxKey);
}
final transactionDescriptionsBoxKey = await getEncryptionKey(
secureStorage: _secureStorage, forKey: TransactionDescription.boxKey);
box = await CakeHive.openBox<TransactionDescription>(TransactionDescription.boxName,
encryptionKey: transactionDescriptionsBoxKey);
}
await box.putAll(descriptionsMap);
}
@@ -152,7 +154,8 @@ class $BackupService {
final data = json.decode(preferencesFile.readAsStringSync()) as Map<String, dynamic>;
try { // shouldn't throw an error but just in case, so it doesn't stop the backup restore
try {
// shouldn't throw an error but just in case, so it doesn't stop the backup restore
for (var entry in data.entries) {
String key = entry.key;
dynamic value = entry.value;
@@ -170,7 +173,8 @@ class $BackupService {
await sharedPreferences.setStringList(key, value);
} else {
if (kDebugMode) {
printV('Skipping individual save for key "$key": Unsupported type (${value.runtimeType}). Value: $value');
printV(
'Skipping individual save for key "$key": Unsupported type (${value.runtimeType}). Value: $value');
}
}
}
@@ -187,9 +191,7 @@ class $BackupService {
currentWalletName = correctWallets.first.name;
currentWalletType = serializeToInt(correctWallets.first.type);
}
} catch (e) {
}
} catch (e) {}
if (DeviceInfo.instance.isDesktop) {
await sharedPreferences.setInt(PreferencesKey.currentTheme, ThemeList.darkTheme.raw);
@@ -247,8 +249,8 @@ class $BackupService {
for (var key in (keychainJSON['_all'] as Map<String, dynamic>).keys) {
try {
if (!key.startsWith('MONERO_WALLET_')) continue;
final decodedPassword = decodeWalletPassword(
password: keychainJSON['_all'][key].toString());
final decodedPassword =
decodeWalletPassword(password: keychainJSON['_all'][key].toString());
final walletName = key.split('_WALLET_')[1];
final walletType = key.split('_WALLET_')[0].toLowerCase();
await importWalletKeychainInfo({
@@ -294,8 +296,11 @@ class $BackupService {
}));
final backupPasswordKey = generateStoreKeyFor(key: SecretStoreKey.backupPassword);
final backupPassword = await _secureStorage.read(key: backupPasswordKey);
final data = utf8.encode(
json.encode({'wallets': wallets, backupPasswordKey: backupPassword, '_all': await _secureStorage.readAll()}));
final data = utf8.encode(json.encode({
'wallets': wallets,
backupPasswordKey: backupPassword,
'_all': await _secureStorage.readAll()
}));
final encrypted = await _encryptV2(Uint8List.fromList(data), '$keychainSalt$password');
return encrypted;
+33 -30
View File
@@ -73,6 +73,7 @@ class ChunkLength {
'plain': plain,
};
}
@override
String toString() {
return 'ChunkLength(encrypted: $encrypted, plain: $plain)';
@@ -124,7 +125,9 @@ class BackupMetadata {
return BackupMetadata(
version: BackupVersion.values[json['version'] as int],
sha512sum: json['sha512sum'] as String,
chunks: (json['chunks'] as List<dynamic>).map((chunk) => ChunkDetails.fromJson(chunk as Map<String, dynamic>)).toList(),
chunks: (json['chunks'] as List<dynamic>)
.map((chunk) => ChunkDetails.fromJson(chunk as Map<String, dynamic>))
.toList(),
cakeVersion: json['cakeVersion'] as String,
);
}
@@ -160,7 +163,8 @@ class IncompatibleBackupAppException implements Exception {
}
class BackupServiceV3 extends $BackupService {
BackupServiceV3(super.secureStorage, super.transactionDescriptionBox, super.keyService, super.sharedPreferences);
BackupServiceV3(super.secureStorage, super.transactionDescriptionBox, super.keyService,
super.sharedPreferences);
static BackupVersion get currentVersion => BackupVersion.v3;
@@ -170,12 +174,12 @@ class BackupServiceV3 extends $BackupService {
BackupVersion getVersionFile(File data) {
final raf = data.openSync(mode: FileMode.read);
try {
// Read first 4 bytes to check both version and zip signature
final buffer = Uint8List(1);
final bytesRead = raf.readIntoSync(buffer);
if (bytesRead == 0) {
throw Exception('Invalid backup file: empty file');
}
@@ -231,7 +235,7 @@ class BackupServiceV3 extends $BackupService {
}
Future<void> importBackupFileV3(File file, String password,
{String nonce = secrets.backupSalt,bool checkBackupApp = true}) async{
{String nonce = secrets.backupSalt, bool checkBackupApp = true}) async {
// Overall design of v3 backup is the following:
// 1. backup.zip - plaintext zip file that user can open with any archive manager
// 2. backup.zip/README.txt - text file to let user know what is inside of this file
@@ -259,14 +263,14 @@ class BackupServiceV3 extends $BackupService {
throw Exception('Invalid v3 backup: missing data.bin');
}
final dataStream = dataFile.rawContent!.getStream();
final decryptedData = File('${file.path}_decrypted'); // decrypted zip file
if (decryptedData.existsSync()) {
decryptedData.deleteSync();
}
decryptedData.createSync(recursive: true);
decryptedData.writeAsBytesSync(Uint8List(0), mode: FileMode.write, flush: true);
int chunkIndex = 0;
for (var chunk in metadata.chunks) {
chunkIndex++;
@@ -275,7 +279,8 @@ 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 Exception(
'Invalid v3 backup: chunk (${chunk.length.encrypted} bytes) checksum mismatch at index $chunkIndex\n'
'expected: ${chunk.sha512sum.encrypted}\n'
'got: $chunkChecksum');
}
@@ -283,7 +288,6 @@ class BackupServiceV3 extends $BackupService {
decryptedData.writeAsBytesSync(decryptedChunk, mode: FileMode.append, flush: true);
}
final sha512sum = (await sha512.bind(decryptedData.openRead()).first).toString();
if (sha512sum.toString() != metadata.sha512sum) {
throw Exception('Invalid v3 backup: SHA512 checksum mismatch\n'
@@ -301,7 +305,6 @@ class BackupServiceV3 extends $BackupService {
final decryptedDataStream = InputFileStream(decryptedData.path);
final backupArchive = zip.decodeStream(decryptedDataStream);
final appDir = await getAppDir();
outer:
@@ -315,8 +318,7 @@ class BackupServiceV3 extends $BackupService {
}
printV("restoring: $filename");
if (file.isFile) {
final output = File('${appDir.path}/' + filename)
..createSync(recursive: true);
final output = File('${appDir.path}/' + filename)..createSync(recursive: true);
final outputStream = OutputFileStream(output.path);
file.writeContent(outputStream);
outputStream.flush();
@@ -326,7 +328,8 @@ class BackupServiceV3 extends $BackupService {
dir.createSync(recursive: true);
}
}
};
}
;
// Continue importing the backup the old way
await super.verifyWallets();
@@ -344,10 +347,10 @@ class BackupServiceV3 extends $BackupService {
{String keychainSalt = secrets.backupKeychainSalt}) async {
final appDir = await getAppDir();
final keychainDumpFile = File('${appDir.path}/~_keychain_dump');
final decryptedKeychainDumpFileData = await decryptV2(
keychainDumpFile.readAsBytesSync(), '$keychainSalt$password');
final keychainJSON = json.decode(utf8.decode(decryptedKeychainDumpFileData))
as Map<String, dynamic>;
final decryptedKeychainDumpFileData =
await decryptV2(keychainDumpFile.readAsBytesSync(), '$keychainSalt$password');
final keychainJSON =
json.decode(utf8.decode(decryptedKeychainDumpFileData)) as Map<String, dynamic>;
final keychainWalletsInfo = keychainJSON['wallets'] as List;
final expectedHardwareWallets = keychainWalletsInfo
@@ -358,10 +361,10 @@ class BackupServiceV3 extends $BackupService {
for (final expectedHardwareWallet in expectedHardwareWallets) {
final info = expectedHardwareWallet as Map<String, dynamic>;
final actualWalletInfo = await WalletInfo.get(info['name'] as String, WalletType.values.firstWhere((e) => e.toString() == info['type'] as String));
final actualWalletInfo = await WalletInfo.get(info['name'] as String,
WalletType.values.firstWhere((e) => e.toString() == info['type'] as String));
if (actualWalletInfo != null &&
info["hardwareWalletType"] !=
actualWalletInfo.hardwareWalletType?.index) {
info["hardwareWalletType"] != actualWalletInfo.hardwareWalletType?.index) {
actualWalletInfo.hardwareWalletType =
HardwareWalletType.values[info["hardwareWalletType"] as int];
await actualWalletInfo.save();
@@ -390,7 +393,8 @@ class BackupServiceV3 extends $BackupService {
final transactionDescriptionDumpFile =
File('${tmpDir.path}/~_transaction_descriptions_dump_TMP');
final transactionDescriptionData = super.transactionDescriptionBox
final transactionDescriptionData = super
.transactionDescriptionBox
.toMap()
.map((key, value) => MapEntry(key.toString(), value.toJson()));
final transactionDescriptionDump = jsonEncode(transactionDescriptionData);
@@ -443,15 +447,14 @@ class BackupServiceV3 extends $BackupService {
int chunkIndex = 0;
final stopwatch = Stopwatch()..start();
printV("Starting backup encryption...");
metadata.sha512sum = (await sha512.bind(dataBinUnencrypted.openRead()).first).toString();
final raf = await dataBinUnencrypted.open();
while (true) {
printV("Reading chunk ${chunkIndex++}");
stopwatch.reset();
final chunk = await raf.read(chunkSize);
printV("Chunk read completed in ${stopwatch.elapsed}");
@@ -459,13 +462,14 @@ class BackupServiceV3 extends $BackupService {
if (chunk.length == 0) {
break;
}
stopwatch.reset();
final encryptedChunk = await cake_backup.encrypt(password, chunk);
printV("Encryption completed in ${stopwatch.elapsed}");
stopwatch.reset();
final sha512sumEncryptedChunk = await sha512.bind(Stream.fromIterable([encryptedChunk])).first;
final sha512sumEncryptedChunk =
await sha512.bind(Stream.fromIterable([encryptedChunk])).first;
final sha512sumUnencryptedChunk = await sha512.bind(Stream.fromIterable([chunk])).first;
printV("Hashing completed in ${stopwatch.elapsed}");
@@ -481,7 +485,7 @@ class BackupServiceV3 extends $BackupService {
plain: chunk.length,
),
));
await dataBinWriter.flush();
printV("Writing completed in ${stopwatch.elapsed}");
}
@@ -495,7 +499,8 @@ class BackupServiceV3 extends $BackupService {
metadataFile.writeAsStringSync(JsonEncoder.withIndent(' ').convert(metadata.toJson()));
final readmeFile = File('${tmpDir.path}/README.txt');
readmeFile.writeAsStringSync('''This is a ${packageInfo.appName} backup. Do not modify this archive.
readmeFile
.writeAsStringSync('''This is a ${packageInfo.appName} backup. Do not modify this archive.
App version: ${packageInfo.version}
@@ -524,11 +529,9 @@ This backup was created on ${DateTime.now().toIso8601String()}
final sourceAppName = _extractBackupAppName(readmeString);
if (sourceAppName == null) return;
final currentAppName = (await PackageInfo.fromPlatform()).appName;
if (sourceAppName == currentAppName) return;
throw IncompatibleBackupAppException(
sourceAppName: sourceAppName,
currentAppName: currentAppName,
+4 -7
View File
@@ -73,12 +73,8 @@ class CsvExportService {
// Prefer tx.to/tx.from; fall back to address lists for chains that don't populate them.
final address = tx.direction == TransactionDirection.incoming
? (tx.from?.isNotEmpty == true
? tx.from!
: (tx.inputAddresses?.firstOrNull ?? ''))
: (tx.to?.isNotEmpty == true
? tx.to!
: (tx.outputAddresses?.firstOrNull ?? ''));
? (tx.from?.isNotEmpty == true ? tx.from! : (tx.inputAddresses?.firstOrNull ?? ''))
: (tx.to?.isNotEmpty == true ? tx.to! : (tx.outputAddresses?.firstOrNull ?? ''));
final fee = tx.fee != null && !tx.fee!.isZero ? tx.fee.toString() : '';
@@ -213,7 +209,8 @@ class CsvExportService {
String _isoDate(DateTime dt) => dt.toUtc().toIso8601String();
Future<void> exportToCsv(List<ActionListItem> items, BuildContext context) async {
final dataItems = items.whereType<ActionListItem>().where((e) => e is! DateSectionItem).toList();
final dataItems =
items.whereType<ActionListItem>().where((e) => e is! DateSectionItem).toList();
if (dataItems.isEmpty) {
await showBar<void>(context, S.current.csv_nothing_to_export);
+1 -2
View File
@@ -5,7 +5,6 @@ class EmailValidator extends TextValidator {
EmailValidator()
: super(
errorMessage: 'Invalid email address',
pattern:
'^[^@]+@[^@]+\.[^@]+',
pattern: '^[^@]+@[^@]+\.[^@]+',
);
}
+1 -1
View File
@@ -25,4 +25,4 @@ class AwaitingConfirmationState extends ExecutionState {
final String? message;
final Function()? onConfirm;
final Function()? onCancel;
}
}
+6 -12
View File
@@ -10,7 +10,6 @@ const _fiatApiOnionAuthority = '46wisoe2uwipcj2j4og6smiq7hbmj34fkkrquwlzbbsqtgat
const _fiatApiPath = '/v2/rates';
Future<double> _fetchPrice(String crypto, String fiat, bool torOnly) async {
final Map<String, String> queryParams = {
'interval_count': '1',
'base': crypto.split(".").first,
@@ -23,14 +22,10 @@ Future<double> _fetchPrice(String crypto, String fiat, bool torOnly) async {
final onionUri = Uri.http(_fiatApiOnionAuthority, _fiatApiPath, queryParams);
final clearnetUri = Uri.https(_fiatApiClearNetAuthority, _fiatApiPath, queryParams);
final response = await ProxyWrapper().get(
onionUri: onionUri,
clearnetUri: torOnly ? onionUri : clearnetUri,
headers: {
"x-api-key": secrets.fiatApiKey,
}
);
final response = await ProxyWrapper()
.get(onionUri: onionUri, clearnetUri: torOnly ? onionUri : clearnetUri, headers: {
"x-api-key": secrets.fiatApiKey,
});
if (response.statusCode != 200) {
return 0.0;
@@ -52,9 +47,8 @@ Future<double> _fetchPrice(String crypto, String fiat, bool torOnly) async {
/// Override specific [CryptoCurrency] to fix its price to the price of another
/// e.g. nDEPS should have the same price as DEPS, but only DEPS is tracked
CryptoCurrency _overrideCryptoCurrency(CryptoCurrency crypto) {
if (crypto.title == CryptoCurrency.ndeps.title)
return CryptoCurrency.deps;
return crypto;
if (crypto.title == CryptoCurrency.ndeps.title) return CryptoCurrency.deps;
return crypto;
}
class FiatConversionService {
+1 -1
View File
@@ -14,4 +14,4 @@ int mnemonicLength(WalletType type) {
default:
return 0;
}
}
}
+4 -4
View File
@@ -4,8 +4,8 @@ import 'package:cake_wallet/core/validator.dart';
class MoneroLabelValidator extends TextValidator {
MoneroLabelValidator()
: super(
errorMessage: S.current.error_text_account_name,
pattern: '^[a-zA-Z0-9_ ]{1,15}\$',
minLength: 1,
maxLength: 15);
errorMessage: S.current.error_text_account_name,
pattern: '^[a-zA-Z0-9_ ]{1,15}\$',
minLength: 1,
maxLength: 15);
}
@@ -9,8 +9,7 @@ import 'package:cw_core/utils/proxy_wrapper.dart';
class OpenCryptoPayService {
static bool isOpenCryptoPayQR(String value) =>
value.toLowerCase().contains("lightning=lnurl") ||
value.toLowerCase().startsWith("lnurl");
value.toLowerCase().contains("lightning=lnurl") || value.toLowerCase().startsWith("lnurl");
static bool requiresClientCommit(CryptoCurrency currency) =>
[CryptoCurrency.xmr, CryptoCurrency.zano, CryptoCurrency.sol].contains(currency) ||
@@ -71,8 +70,8 @@ class OpenCryptoPayService {
);
}
Future<(_OpenCryptoPayQuote, Map<String, List<OpenCryptoPayQuoteAsset>>)>
_getOpenCryptoPayParams(Uri uri) async {
Future<(_OpenCryptoPayQuote, Map<String, List<OpenCryptoPayQuoteAsset>>)> _getOpenCryptoPayParams(
Uri uri) async {
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 200) {
@@ -90,18 +89,15 @@ class OpenCryptoPayService {
final method = transferAmount['method'] as String;
methods[method] = [];
for (final assetJson in transferAmount['assets'] as List) {
final asset = OpenCryptoPayQuoteAsset.fromJson(
assetJson as Map<String, dynamic>);
final asset = OpenCryptoPayQuoteAsset.fromJson(assetJson as Map<String, dynamic>);
methods[method]?.add(asset);
}
}
log(responseBody.toString());
final quote = _OpenCryptoPayQuote.fromJson(
responseBody['callback'] as String,
responseBody['displayName'] as String?,
responseBody['quote'] as Map<String, dynamic>);
final quote = _OpenCryptoPayQuote.fromJson(responseBody['callback'] as String,
responseBody['displayName'] as String?, responseBody['quote'] as Map<String, dynamic>);
return (quote, methods);
} else {
@@ -110,8 +106,7 @@ class OpenCryptoPayService {
}
}
Future<Uri> getOpenCryptoPayAddress(
OpenCryptoPayRequest request, CryptoCurrency asset) async {
Future<Uri> getOpenCryptoPayAddress(OpenCryptoPayRequest request, CryptoCurrency asset) async {
final uri = Uri.parse(request.callbackUrl);
final queryParams = Map.of(uri.queryParameters);
@@ -135,8 +130,7 @@ class OpenCryptoPayService {
if (result.queryParameters['amount'] != null) return result;
final newQueryParameters =
Map<String, dynamic>.from(result.queryParameters);
final newQueryParameters = Map<String, dynamic>.from(result.queryParameters);
newQueryParameters['amount'] = _getAmountByAsset(request, asset);
return Uri(
+2 -3
View File
@@ -22,8 +22,7 @@ class SeedValidator extends Validator<MnemonicItem> {
final String language;
final List<String> _words;
static List<String> getWordList(
{required WalletType type, required String language}) {
static List<String> getWordList({required WalletType type, required String language}) {
switch (type) {
case WalletType.bitcoin:
return getBitcoinWordList(language);
@@ -49,7 +48,7 @@ class SeedValidator extends Validator<MnemonicItem> {
case WalletType.tron:
return tron!.getTronWordList(language);
case WalletType.wownero:
return wownero!.getWowneroWordList(language);
return wownero!.getWowneroWordList(language);
case WalletType.zano:
return zano!.getWordList(language);
case WalletType.decred:
-3
View File
@@ -5,7 +5,6 @@ abstract class SelectableItem {
class OptionTitle extends SelectableItem {
OptionTitle({required String title}) : super(title: title);
}
abstract class SelectableOption extends SelectableItem {
@@ -43,5 +42,3 @@ abstract class SelectableOption extends SelectableItem {
set isOptionSelected(bool isSelected) => false;
}
@@ -4,7 +4,6 @@ import 'package:cake_wallet/generated/i18n.dart';
class SocksProxyNodeAddressValidator extends TextValidator {
SocksProxyNodeAddressValidator()
: super(
errorMessage: S.current.error_text_node_proxy_address,
pattern:
'^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]+\$');
errorMessage: S.current.error_text_node_proxy_address,
pattern: '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]+\$');
}
+5 -6
View File
@@ -4,9 +4,8 @@ import 'package:cake_wallet/generated/i18n.dart';
class TemplateValidator extends TextValidator {
TemplateValidator()
: super(
minLength: 0,
maxLength: 0,
pattern: '''^[^`,'"]{1,20}\$''',
errorMessage: S.current.error_text_template
);
}
minLength: 0,
maxLength: 0,
pattern: '''^[^`,'"]{1,20}\$''',
errorMessage: S.current.error_text_template);
}
+1 -1
View File
@@ -132,7 +132,7 @@ class UniversalAddressDetector {
pattern: RegExp(r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'),
currency: CryptoCurrency.btcln,
),
// Lightning Address (LNURL format)
_DetectionPattern(
pattern: RegExp(r'^(lightning:)?(lnurl)[a-z0-9]+$', caseSensitive: false),
+1 -2
View File
@@ -8,8 +8,7 @@ extension EnhancedList<T> on Iterable<T> {
}
}
String middleTruncate(String s, int head, int tail) {
if (s.length <= head + tail + 3) return s;
return s.substring(0, head) + '...' + s.substring(s.length - tail);
}
}
+3 -7
View File
@@ -18,9 +18,7 @@ class TextValidator extends Validator<String> {
String errorMessage = '',
this.length,
this.isAutovalidate = false,
}) : super(
errorMessage: errorMessage,
useAdditionalValidation: useAdditionalValidation);
}) : super(errorMessage: errorMessage, useAdditionalValidation: useAdditionalValidation);
final int? minLength;
final int? maxLength;
@@ -40,8 +38,7 @@ class TextValidator extends Validator<String> {
final lengthMatched = length?.contains(value.length) ?? true;
if (!lengthMatched) return false;
final lowerThanMaxLength =
(maxLength ?? 0) > 0 ? (value.length <= maxLength!) : true;
final lowerThanMaxLength = (maxLength ?? 0) > 0 ? (value.length <= maxLength!) : true;
if (!lowerThanMaxLength) return false;
if (pattern == null) return true;
@@ -54,6 +51,5 @@ class TextValidator extends Validator<String> {
return valueValidated;
}
bool match(String value) =>
pattern != null ? RegExp(pattern!).hasMatch(value) : false;
bool match(String value) => pattern != null ? RegExp(pattern!).hasMatch(value) : false;
}
+2 -1
View File
@@ -35,7 +35,8 @@ class WalletCreationService {
Future<bool> exists(String name) async {
final walletName = name.toLowerCase();
return (await WalletInfo.getAll()).any((walletInfo) => walletInfo.name.toLowerCase() == walletName);
return (await WalletInfo.getAll())
.any((walletInfo) => walletInfo.name.toLowerCase() == walletName);
}
Future<bool> typeExists(WalletType type) async {
+1 -1
View File
@@ -10,4 +10,4 @@ class WalletCreationFailure extends WalletCreationState {
WalletCreationFailure({required this.error});
final String error;
}
}
+43 -38
View File
@@ -58,10 +58,12 @@ class WalletLoadingService {
}
}
Future<WalletBase> load(WalletType type, String name, {String? password, bool isBackground = false}) async {
Future<WalletBase> load(WalletType type, String name,
{String? password, bool isBackground = false}) async {
try {
if (!isBackground) {
await sharedPreferences.setString(PreferencesKey.backgroundSyncLastTrigger(name), DateTime.now().toIso8601String());
await sharedPreferences.setString(
PreferencesKey.backgroundSyncLastTrigger(name), DateTime.now().toIso8601String());
}
final walletService = walletServiceFactory.call(type);
final walletPassword = password ?? (await keyService.getWalletPassword(walletName: name));
@@ -75,10 +77,14 @@ class WalletLoadingService {
} catch (error, stack) {
String corruptedWalletsSeeds = "Corrupted wallets seeds (if retrievable, empty otherwise):";
if(error is WalletDeprecationException) {
if(navigatorKey.currentContext != null) {
if (error is WalletDeprecationException) {
if (navigatorKey.currentContext != null) {
showModalBottomSheet(
context: navigatorKey.currentContext!, builder: (context)=>WalletDeprecationPopup(type: type, seed: error.seed,));
context: navigatorKey.currentContext!,
builder: (context) => WalletDeprecationPopup(
type: type,
seed: error.seed,
));
}
} else {
await ExceptionHandler.resetLastPopupDate();
@@ -106,8 +112,7 @@ class WalletLoadingService {
await updateMoneroWalletPassword(wallet);
}
await sharedPreferences.setString(
PreferencesKey.currentWalletName, wallet.name);
await sharedPreferences.setString(PreferencesKey.currentWalletName, wallet.name);
await sharedPreferences.setInt(
PreferencesKey.currentWalletType, serializeToInt(wallet.type));
@@ -130,22 +135,22 @@ class WalletLoadingService {
// if all user's wallets are corrupted throw exception
final msg = error.toString() + "\n" + corruptedWalletsSeeds;
if (navigatorKey.currentContext != null) {
await showPopUp<void>(
context: navigatorKey.currentContext!,
builder: (BuildContext context) {
return AlertWithTwoActions(
alertTitle: "Corrupted seeds",
alertContent: S.of(context).corrupted_seed_notice,
leftButtonText: S.of(context).cancel,
rightButtonText: S.of(context).show_seed,
actionLeftButton: () {
if (context.mounted && Navigator.of(context).canPop()) {
Navigator.of(context).pop();
}
},
actionRightButton: () => showSeedsPopup(context, msg),
);
});
await showPopUp<void>(
context: navigatorKey.currentContext!,
builder: (BuildContext context) {
return AlertWithTwoActions(
alertTitle: "Corrupted seeds",
alertContent: S.of(context).corrupted_seed_notice,
leftButtonText: S.of(context).cancel,
rightButtonText: S.of(context).show_seed,
actionLeftButton: () {
if (context.mounted && Navigator.of(context).canPop()) {
Navigator.of(context).pop();
}
},
actionRightButton: () => showSeedsPopup(context, msg),
);
});
} else {
throw msg;
}
@@ -159,21 +164,21 @@ class WalletLoadingService {
Future<void> showSeedsPopup(BuildContext context, String message) async {
Navigator.of(context).pop();
await showPopUp<void>(
context: context,
builder: (BuildContext context) {
return AlertWithTwoActions(
alertTitle: "Corrupted seeds",
alertContent: message,
leftButtonText: S.of(context).copy,
rightButtonText: S.of(context).ok,
actionLeftButton: () async {
await Clipboard.setData(ClipboardData(text: message));
},
actionRightButton: () async {
Navigator.of(context).pop();
},
);
});
context: context,
builder: (BuildContext context) {
return AlertWithTwoActions(
alertTitle: "Corrupted seeds",
alertContent: message,
leftButtonText: S.of(context).copy,
rightButtonText: S.of(context).ok,
actionLeftButton: () async {
await Clipboard.setData(ClipboardData(text: message));
},
actionRightButton: () async {
Navigator.of(context).pop();
},
);
});
}
Future<void> updateMoneroWalletPassword(WalletBase wallet) async {
+224 -246
View File
@@ -379,7 +379,6 @@ Future<void> setup({
return;
}
getIt.registerSingleton(AuthenticationStore());
getIt.registerSingleton<WalletListStore>(WalletListStore());
// getIt.registerSingleton(NodeListStoreBase.instance);
@@ -390,13 +389,12 @@ Future<void> setup({
settingsStore: getIt.get<SettingsStore>(),
// nodeListStore: getIt.get<NodeListStore>(),
themeStore: getIt.get<ThemeStore>()));
getIt.registerSingleton<TradesStore>(
TradesStore(appStore: getIt.get<AppStore>()));
getIt.registerSingleton<TradesStore>(TradesStore(appStore: getIt.get<AppStore>()));
getIt.registerSingleton<OrdersStore>(
OrdersStore(ordersSource: _ordersSource, settingsStore: getIt.get<SettingsStore>()));
getIt.registerSingleton<BridgeTransfersStore>(BridgeTransfersStore());
getIt.registerFactory(() =>
PayjoinTransactionsStore(payjoinSessionSource: _payjoinSessionSource));
getIt
.registerFactory(() => PayjoinTransactionsStore(payjoinSessionSource: _payjoinSessionSource));
getIt.registerSingleton<TradeFilterStore>(TradeFilterStore());
getIt.registerSingleton<OrderFilterStore>(OrderFilterStore());
getIt.registerSingleton<TransactionFilterStore>(TransactionFilterStore(getIt.get<AppStore>()));
@@ -411,15 +409,19 @@ Future<void> setup({
getIt.registerSingleton<SeedSettingsStore>(SeedSettingsStore());
getIt.registerFactoryParam<HardwareWalletViewModel, HardwareWalletType, void>((type, _) {
switch(type) {
case HardwareWalletType.bitbox: return getIt<BitboxViewModel>();
case HardwareWalletType.ledger: return getIt<LedgerViewModel>();
case HardwareWalletType.trezor: return getIt<TrezorConnectViewModel>();
switch (type) {
case HardwareWalletType.bitbox:
return getIt<BitboxViewModel>();
case HardwareWalletType.ledger:
return getIt<LedgerViewModel>();
case HardwareWalletType.trezor:
return getIt<TrezorConnectViewModel>();
case HardwareWalletType.cupcake:
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 Exception(
"This should not have happened, because airgapped Wallets don't need View Models");
}
});
@@ -427,20 +429,19 @@ Future<void> setup({
getIt.registerLazySingleton(() => BitboxViewModel());
getIt.registerLazySingleton(() => TrezorConnect("cakewallet://trezor_connect",
appName: "Cake Wallet"));
getIt.registerLazySingleton(
() => TrezorConnect("cakewallet://trezor_connect", appName: "Cake Wallet"));
getIt.registerLazySingleton(() => TrezorConnectViewModel(getIt<TrezorConnect>()));
getIt.registerFactory<KeyService>(() => KeyService(getIt.get<SecureStorage>()));
getIt.registerFactoryParam<WalletCreationService, WalletType, void>((type, _) =>
WalletCreationService(
initialType: type,
keyService: getIt.get<KeyService>(),
sharedPreferences: getIt.get<SharedPreferences>(),
settingsStore: getIt.get<SettingsStore>(),
));
getIt.registerFactoryParam<WalletCreationService, WalletType, void>(
(type, _) => WalletCreationService(
initialType: type,
keyService: getIt.get<KeyService>(),
sharedPreferences: getIt.get<SharedPreferences>(),
settingsStore: getIt.get<SettingsStore>(),
));
getIt.registerFactoryParam<AdvancedPrivacySettingsViewModel, WalletType, void>(
(type, _) => AdvancedPrivacySettingsViewModel(type, getIt.get<SettingsStore>()));
@@ -451,14 +452,13 @@ Future<void> setup({
(WalletType type) => getIt.get<WalletService>(param1: type)));
getIt.registerFactoryParam<WalletNewVM, NewWalletArguments, void>(
(newWalletArgs, _) => WalletNewVM(
getIt.get<AppStore>(),
getIt.get<WalletCreationService>(param1:newWalletArgs.type),
getIt.get<AdvancedPrivacySettingsViewModel>(param1: newWalletArgs.type),
getIt.get<SeedSettingsViewModel>(),
newWalletArguments: newWalletArgs,
));
(newWalletArgs, _) => WalletNewVM(
getIt.get<AppStore>(),
getIt.get<WalletCreationService>(param1: newWalletArgs.type),
getIt.get<AdvancedPrivacySettingsViewModel>(param1: newWalletArgs.type),
getIt.get<SeedSettingsViewModel>(),
newWalletArguments: newWalletArgs,
));
final walletList = await WalletInfo.getAll();
@@ -479,62 +479,52 @@ Future<void> setup({
);
getIt.registerFactoryParam<WalletUnlockPage, WalletUnlockArguments, bool>((args, closable) {
return WalletUnlockPage(
getIt.get<WalletUnlockLoadableViewModel>(param1: args),
args.callback,
args.authPasswordHandler,
closable: closable);
return WalletUnlockPage(getIt.get<WalletUnlockLoadableViewModel>(param1: args), args.callback,
args.authPasswordHandler,
closable: closable);
}, instanceName: 'wallet_unlock_loadable');
getIt.registerFactory<WalletUnlockPage>(
() => getIt.get<WalletUnlockPage>(
param1: WalletUnlockArguments(
callback: (bool successful, _) {
if (successful) {
final authStore = getIt.get<AuthenticationStore>();
authStore.allowed();
}}),
param2: false,
instanceName: 'wallet_unlock_loadable'),
instanceName: 'wallet_password_login');
() => getIt.get<WalletUnlockPage>(
param1: WalletUnlockArguments(callback: (bool successful, _) {
if (successful) {
final authStore = getIt.get<AuthenticationStore>();
authStore.allowed();
}
}),
param2: false,
instanceName: 'wallet_unlock_loadable'),
instanceName: 'wallet_password_login');
getIt.registerFactoryParam<WalletUnlockPage, WalletUnlockArguments, bool>((args, closable) {
return WalletUnlockPage(
getIt.get<WalletUnlockVerifiableViewModel>(param1: args),
args.callback,
args.authPasswordHandler,
closable: closable);
return WalletUnlockPage(getIt.get<WalletUnlockVerifiableViewModel>(param1: args), args.callback,
args.authPasswordHandler,
closable: closable);
}, instanceName: 'wallet_unlock_verifiable');
getIt.registerFactoryParam<WalletUnlockLoadableViewModel, WalletUnlockArguments, void>((args, _) {
final currentWalletName = getIt
.get<SharedPreferences>()
.getString(PreferencesKey.currentWalletName) ?? '';
final currentWalletName =
getIt.get<SharedPreferences>().getString(PreferencesKey.currentWalletName) ?? '';
final currentWalletTypeRaw =
getIt.get<SharedPreferences>()
.getInt(PreferencesKey.currentWalletType) ?? 0;
getIt.get<SharedPreferences>().getInt(PreferencesKey.currentWalletType) ?? 0;
final currentWalletType = deserializeFromInt(currentWalletTypeRaw);
return WalletUnlockLoadableViewModel(
getIt.get<AppStore>(),
getIt.get<WalletLoadingService>(),
walletName: args.walletName ?? currentWalletName,
walletType: args.walletType ?? currentWalletType);
return WalletUnlockLoadableViewModel(getIt.get<AppStore>(), getIt.get<WalletLoadingService>(),
walletName: args.walletName ?? currentWalletName,
walletType: args.walletType ?? currentWalletType);
});
getIt.registerFactoryParam<WalletUnlockVerifiableViewModel, WalletUnlockArguments, void>((args, _) {
final currentWalletName = getIt
.get<SharedPreferences>()
.getString(PreferencesKey.currentWalletName) ?? '';
getIt.registerFactoryParam<WalletUnlockVerifiableViewModel, WalletUnlockArguments, void>(
(args, _) {
final currentWalletName =
getIt.get<SharedPreferences>().getString(PreferencesKey.currentWalletName) ?? '';
final currentWalletTypeRaw =
getIt.get<SharedPreferences>()
.getInt(PreferencesKey.currentWalletType) ?? 0;
getIt.get<SharedPreferences>().getInt(PreferencesKey.currentWalletType) ?? 0;
final currentWalletType = deserializeFromInt(currentWalletTypeRaw);
return WalletUnlockVerifiableViewModel(
getIt.get<AppStore>(),
walletName: args.walletName ?? currentWalletName,
walletType: args.walletType ?? currentWalletType);
return WalletUnlockVerifiableViewModel(getIt.get<AppStore>(),
walletName: args.walletName ?? currentWalletName,
walletType: args.walletType ?? currentWalletType);
});
getIt.registerFactoryParam<WalletHardwareRestoreViewModel, WalletType, HardwareWalletViewModel>(
@@ -577,29 +567,30 @@ Future<void> setup({
);
getIt.registerFactory(() => DashboardViewModel(
tradeMonitor: getIt.get<TradeMonitor>(),
balanceViewModel: getIt.get<BalanceViewModel>(),
appStore: getIt.get<AppStore>(),
tradesStore: getIt.get<TradesStore>(),
ordersStore: getIt.get<OrdersStore>(),
tradeFilterStore: getIt.get<TradeFilterStore>(),
orderFilterStore: getIt.get<OrderFilterStore>(),
transactionFilterStore: getIt.get<TransactionFilterStore>(),
settingsStore: settingsStore,
yatStore: getIt.get<YatStore>(),
anonpayTransactionsStore: getIt.get<AnonpayTransactionsStore>(),
payjoinTransactionsStore: getIt.get<PayjoinTransactionsStore>(),
sharedPreferences: getIt.get<SharedPreferences>(),
keyService: getIt.get<KeyService>()));
tradeMonitor: getIt.get<TradeMonitor>(),
balanceViewModel: getIt.get<BalanceViewModel>(),
appStore: getIt.get<AppStore>(),
tradesStore: getIt.get<TradesStore>(),
ordersStore: getIt.get<OrdersStore>(),
tradeFilterStore: getIt.get<TradeFilterStore>(),
orderFilterStore: getIt.get<OrderFilterStore>(),
transactionFilterStore: getIt.get<TransactionFilterStore>(),
settingsStore: settingsStore,
yatStore: getIt.get<YatStore>(),
anonpayTransactionsStore: getIt.get<AnonpayTransactionsStore>(),
payjoinTransactionsStore: getIt.get<PayjoinTransactionsStore>(),
sharedPreferences: getIt.get<SharedPreferences>(),
keyService: getIt.get<KeyService>()));
getIt.registerFactoryParam<CardCustomizerBloc, bool, BitcoinAmountDisplayMode?>(
(lightningMode, displayMode) {
final wallet = getIt.get<AppStore>().wallet!;
return CardCustomizerBloc(wallet,
lightningMode: lightningMode,
displaySats: wallet.type == WalletType.bitcoin && (displayMode == BitcoinAmountDisplayMode.satoshi ||
(displayMode == BitcoinAmountDisplayMode.satoshiForLightning && lightningMode)));
});
final wallet = getIt.get<AppStore>().wallet!;
return CardCustomizerBloc(wallet,
lightningMode: lightningMode,
displaySats: wallet.type == WalletType.bitcoin &&
(displayMode == BitcoinAmountDisplayMode.satoshi ||
(displayMode == BitcoinAmountDisplayMode.satoshiForLightning && lightningMode)));
});
getIt.registerFactory<AccountCreationModal>(() => AccountCreationModal(
accountEditOrCreateViewModel: getIt.get<MoneroAccountEditOrCreateViewModel>()));
@@ -608,7 +599,7 @@ Future<void> setup({
() => LightningUsernameBloc(getIt.get<AppStore>().wallet!));
getIt.registerFactory<AuthService>(
() => AuthService(
() => AuthService(
secureStorage: getIt.get<SecureStorage>(),
sharedPreferences: getIt.get<SharedPreferences>(),
settingsStore: getIt.get<SettingsStore>(),
@@ -781,11 +772,14 @@ Future<void> setup({
));
getIt.registerFactory<NewDashboard>(() => NewDashboard(
dashboardViewModel: getIt.get<DashboardViewModel>(),
bottomSheetService: getIt.get<BottomSheetService>(),
));
dashboardViewModel: getIt.get<DashboardViewModel>(),
bottomSheetService: getIt.get<BottomSheetService>(),
));
getIt.registerFactory<NewHomePage>(()=>NewHomePage(dashboardViewModel: getIt.get<DashboardViewModel>(),nftViewModel: getIt.get<NFTViewModel>(),));
getIt.registerFactory<NewHomePage>(() => NewHomePage(
dashboardViewModel: getIt.get<DashboardViewModel>(),
nftViewModel: getIt.get<NFTViewModel>(),
));
getIt.registerFactory<DesktopSidebarWrapper>(() {
final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();
@@ -878,9 +872,8 @@ Future<void> setup({
walletAddressEditOrCreateViewModel:
getIt.get<WalletAddressEditOrCreateViewModel>(param1: item)));
getIt.registerFactoryParam<AddressInfoPopup, dynamic, void>((dynamic item, _) =>
AddressInfoPopup(
walletAddressEditOrCreateViewModel:
getIt.registerFactoryParam<AddressInfoPopup, dynamic, void>((dynamic item, _) => AddressInfoPopup(
walletAddressEditOrCreateViewModel:
getIt.get<WalletAddressEditOrCreateViewModel>(param1: item)));
getIt.registerFactoryParam<ReceiveLabelModal, dynamic, void>((dynamic item, _) =>
@@ -896,21 +889,20 @@ Future<void> setup({
getIt.registerFactoryParam<SendViewModel, UnspentCoinType?, void>(
(coinTypeToSpendFrom, _) => SendViewModel(
getIt.get<AppStore>(),
getIt.get<SendTemplateViewModel>(),
getIt.get<FiatConversionStore>(),
getIt.get<AddressResolverService>(),
getIt.get<BalanceViewModel>(),
getIt.get<ContactListViewModel>(),
_transactionDescriptionBox,
getIt.get<AppStore>().wallet!.isHardwareWallet
? getIt<HardwareWalletViewModel>(
param1: getIt.get<AppStore>().wallet!.hardwareWalletType!)
: null,
coinTypeToSpendFrom: coinTypeToSpendFrom ?? UnspentCoinType.nonMweb,
getIt.get<UnspentCoinsListViewModel>(param1: coinTypeToSpendFrom),
getIt.get<FeesViewModel>()
),
getIt.get<AppStore>(),
getIt.get<SendTemplateViewModel>(),
getIt.get<FiatConversionStore>(),
getIt.get<AddressResolverService>(),
getIt.get<BalanceViewModel>(),
getIt.get<ContactListViewModel>(),
_transactionDescriptionBox,
getIt.get<AppStore>().wallet!.isHardwareWallet
? getIt<HardwareWalletViewModel>(
param1: getIt.get<AppStore>().wallet!.hardwareWalletType!)
: null,
coinTypeToSpendFrom: coinTypeToSpendFrom ?? UnspentCoinType.nonMweb,
getIt.get<UnspentCoinsListViewModel>(param1: coinTypeToSpendFrom),
getIt.get<FeesViewModel>()),
);
getIt.registerFactoryParam<SendPage, PaymentRequest?, UnspentCoinType?>(
@@ -973,7 +965,6 @@ Future<void> setup({
);
getIt.registerFactoryParam<WalletEditPage, WalletEditPageArguments, void>((arguments, _) {
return WalletEditPage(
pageArguments: WalletEditPageArguments(
walletEditViewModel: getIt.get<WalletEditViewModel>(param1: arguments.walletListViewModel),
@@ -1003,7 +994,7 @@ Future<void> setup({
if (wallet.type == WalletType.monero ||
wallet.type == WalletType.wownero ||
wallet.type == WalletType.haven) {
return MoneroAccountListViewModel(wallet,getIt.get<SettingsStore>());
return MoneroAccountListViewModel(wallet, getIt.get<SettingsStore>());
}
throw Exception(
'Unexpected wallet type: ${wallet.type} for generate Monero AccountListViewModel');
@@ -1054,8 +1045,8 @@ Future<void> setup({
nanoAccountCreationViewModel:
getIt.get<NanoAccountEditOrCreateViewModel>(param1: account)));
getIt.registerFactory(() =>
DisplaySettingsViewModel(getIt.get<AppStore>(), getIt.get<ThemeStore>()));
getIt.registerFactory(
() => DisplaySettingsViewModel(getIt.get<AppStore>(), getIt.get<ThemeStore>()));
getIt.registerFactory(() =>
SilentPaymentsSettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!));
@@ -1063,24 +1054,24 @@ Future<void> setup({
getIt.registerFactory(
() => MwebSettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!));
getIt.registerFactory(() =>
PrivacySettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!));
getIt.registerFactory(
() => PrivacySettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!));
getIt.registerFactory(() => TrocadorExchangeProvider());
getIt.registerFactory(() => TrocadorProvidersViewModel(
getIt.get<SettingsStore>(), getIt.get<TrocadorExchangeProvider>()));
getIt.registerFactory(() =>
OtherSettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!,
getIt.get<SendViewModel>()));
getIt.registerFactory(() => OtherSettingsViewModel(
getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!, getIt.get<SendViewModel>()));
getIt.registerFactory(() =>
SecuritySettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AuthService>()));
getIt.registerFactory(
() => SecuritySettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AuthService>()));
getIt.registerFactory(() => WalletSeedViewModel(getIt.get<AppStore>().wallet!));
getIt.registerFactory<SeedSettingsViewModel>(() => SeedSettingsViewModel(getIt.get<AppStore>(), getIt.get<SeedSettingsStore>()));
getIt.registerFactory<SeedSettingsViewModel>(
() => SeedSettingsViewModel(getIt.get<AppStore>(), getIt.get<SeedSettingsStore>()));
getIt.registerFactory(() => DevMoneroBackgroundSync(getIt.get<AppStore>().wallet!));
@@ -1097,13 +1088,11 @@ Future<void> setup({
getIt.registerFactory(() => AnimatedURModel(getIt.get<AppStore>()));
getIt.registerFactoryParam<AnimatedURPage, Map<String, String>, void>((Map<String, String> urQr, _) =>
AnimatedURPage(getIt.get<AnimatedURModel>(), urQr: urQr));
getIt.registerFactoryParam<AnimatedURPage, Map<String, String>, void>(
(Map<String, String> urQr, _) => AnimatedURPage(getIt.get<AnimatedURModel>(), urQr: urQr));
getIt.registerFactoryParam<ContactViewModel, ContactRecord?, void>(
(ContactRecord? contact, _) => ContactViewModel(_contactSource,
getIt.get<AppStore>(),
getIt.get<AddressResolverService>(),
getIt.registerFactoryParam<ContactViewModel, ContactRecord?, void>((ContactRecord? contact, _) =>
ContactViewModel(_contactSource, getIt.get<AppStore>(), getIt.get<AddressResolverService>(),
contact: contact));
getIt.registerFactoryParam<ContactListViewModel, CryptoCurrency?, void>(
@@ -1128,14 +1117,15 @@ Future<void> setup({
});
getIt.registerFactoryParam<NewAddressesPage, bool, void>(
(showHidden, _) => NewAddressesPage(
(showHidden, _) => NewAddressesPage(
showHidden: showHidden,
addressListViewModel: getIt<WalletAddressListViewModel>(),
dashboardViewModel: getIt<DashboardViewModel>(),
),
);
getIt.registerFactory(() => ConnectionSyncViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!));
getIt.registerFactory(
() => ConnectionSyncViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!));
getIt.registerFactory(() => ConnectionSyncPage(getIt.get<ConnectionSyncViewModel>()));
@@ -1163,7 +1153,7 @@ Future<void> setup({
getIt.registerFactory(() => OtherSettingsPage(getIt.get<OtherSettingsViewModel>()));
getIt.registerFactory(()=> AboutPage(appVersion: getIt.get<SettingsStore>().appVersion));
getIt.registerFactory(() => AboutPage(appVersion: getIt.get<SettingsStore>().appVersion));
getIt.registerFactory(() => NanoChangeRepPage(
settingsStore: getIt.get<AppStore>().settingsStore,
@@ -1172,31 +1162,28 @@ Future<void> setup({
getIt.registerFactoryParam<NodeCreateOrEditViewModel, Map<String, dynamic>, void>(
(Map<String, dynamic> args, _) {
final WalletType type = args['type'] as WalletType? ?? getIt.get<AppStore>().wallet!.type;
final bool isPow = args['isPow'] as bool? ?? false;
final Node? editingNode = args['editingNode'] as Node?;
return NodeCreateOrEditViewModel(
isPow,
type,
getIt.get<SettingsStore>(),
editingNode: editingNode
);
}
);
final WalletType type = args['type'] as WalletType? ?? getIt.get<AppStore>().wallet!.type;
final bool isPow = args['isPow'] as bool? ?? false;
final Node? editingNode = args['editingNode'] as Node?;
return NodeCreateOrEditViewModel(isPow, type, getIt.get<SettingsStore>(),
editingNode: editingNode);
});
getIt.registerFactoryParam<NodeCreateOrEditPage, Node?, bool?>(
(Node? editingNode, bool? isSelected) {
final vm = getIt.get<NodeCreateOrEditViewModel>(param1: {'isPow' : false,'editingNode': editingNode});
return NodeCreateOrEditPage(
nodeCreateOrEditViewModel: vm,
editingNode: editingNode,
isSelected: isSelected,
type: getIt.get<AppStore>().wallet!.type);
});
final vm =
getIt.get<NodeCreateOrEditViewModel>(param1: {'isPow': false, 'editingNode': editingNode});
return NodeCreateOrEditPage(
nodeCreateOrEditViewModel: vm,
editingNode: editingNode,
isSelected: isSelected,
type: getIt.get<AppStore>().wallet!.type);
});
getIt.registerFactoryParam<PowNodeCreateOrEditPage, Node?, bool?>(
(Node? editingNode, bool? isSelected) => PowNodeCreateOrEditPage(
nodeCreateOrEditViewModel: getIt.get<NodeCreateOrEditViewModel>(param1: {'isPow' : true, 'editingNode': editingNode}),
nodeCreateOrEditViewModel: getIt
.get<NodeCreateOrEditViewModel>(param1: {'isPow': true, 'editingNode': editingNode}),
editingNode: editingNode,
isSelected: isSelected));
@@ -1225,12 +1212,12 @@ Future<void> setup({
));
getIt.registerFactory<MeldBuyProvider>(() => MeldBuyProvider(
wallet: getIt.get<AppStore>().wallet!,
));
wallet: getIt.get<AppStore>().wallet!,
));
getIt.registerFactory<KryptonimBuyProvider>(() => KryptonimBuyProvider(
wallet: getIt.get<AppStore>().wallet!,
));
wallet: getIt.get<AppStore>().wallet!,
));
getIt.registerFactoryParam<WebViewPage, String, Uri>((title, uri) => WebViewPage(title, uri));
@@ -1253,10 +1240,8 @@ Future<void> setup({
getIt.registerFactoryParam<ExchangePage, PaymentRequest?, void>(
(PaymentRequest? paymentRequest, __) {
return ExchangePage(getIt.get<ExchangeViewModel>(),
getIt.get<AuthService>(),
getIt.get<AddressResolverService>(),
paymentRequest);
return ExchangePage(getIt.get<ExchangeViewModel>(), getIt.get<AuthService>(),
getIt.get<AddressResolverService>(), paymentRequest);
});
getIt.registerFactoryParam<NewSwapPage, PaymentRequest?, CryptoCurrency?>(
@@ -1276,8 +1261,8 @@ Future<void> setup({
getIt.registerFactory(
() => ExchangeTradePage(exchangeTradeViewModel: getIt.get<ExchangeTradeViewModel>()));
getIt.registerFactory(
() => ExchangeTradeExternalSendPage(exchangeTradeViewModel: getIt.get<ExchangeTradeViewModel>()));
getIt.registerFactory(() =>
ExchangeTradeExternalSendPage(exchangeTradeViewModel: getIt.get<ExchangeTradeViewModel>()));
getIt.registerFactory(() => BackgroundSyncPage(getIt.get<DashboardViewModel>()));
@@ -1298,13 +1283,13 @@ Future<void> setup({
);
getIt.registerFactory(() => PaymentViewModel(
appStore: getIt.get<AppStore>(),
));
appStore: getIt.get<AppStore>(),
));
getIt.registerFactory(() => WalletSwitcherViewModel(
appStore: getIt.get<AppStore>(),
walletLoadingService: getIt.get<WalletLoadingService>(),
));
appStore: getIt.get<AppStore>(),
walletLoadingService: getIt.get<WalletLoadingService>(),
));
getIt.registerFactoryParam<WalletService, WalletType, void>((WalletType param1, __) {
switch (param1) {
@@ -1328,9 +1313,11 @@ Future<void> setup({
case WalletType.bsc:
return evm!.createEVMWalletService(param1, SettingsStoreBase.walletPasswordDirectInput);
case WalletType.bitcoinCash:
return bitcoinCash!.createBitcoinCashWalletService(_unspentCoinsInfoSource, SettingsStoreBase.walletPasswordDirectInput);
return bitcoinCash!.createBitcoinCashWalletService(
_unspentCoinsInfoSource, SettingsStoreBase.walletPasswordDirectInput);
case WalletType.dogecoin:
return dogecoin!.createDogeCoinWalletService(_unspentCoinsInfoSource, SettingsStoreBase.walletPasswordDirectInput);
return dogecoin!.createDogeCoinWalletService(
_unspentCoinsInfoSource, SettingsStoreBase.walletPasswordDirectInput);
case WalletType.nano:
case WalletType.banano:
return nano!.createNanoWalletService(SettingsStoreBase.walletPasswordDirectInput);
@@ -1354,19 +1341,16 @@ Future<void> setup({
});
getIt.registerFactoryParam<SetupPinCodeViewModel, bool?, void>(
(isDuressPin, _) => SetupPinCodeViewModel(
(isDuressPin, _) => SetupPinCodeViewModel(
getIt.get<AuthService>(),
getIt.get<SettingsStore>(),
isDuressPin: isDuressPin ?? false,
),
);
getIt.registerFactoryParam<
SetupPinCodePage,
void Function(PinCodeState<PinCodeWidget>, String),
getIt.registerFactoryParam<SetupPinCodePage, void Function(PinCodeState<PinCodeWidget>, String),
bool?>(
(onSuccessfulPinSetup, isDuressPin) => SetupPinCodePage(
(onSuccessfulPinSetup, isDuressPin) => SetupPinCodePage(
getIt.get<SetupPinCodeViewModel>(param1: isDuressPin),
onSuccessfulPinSetup: onSuccessfulPinSetup,
isDuressPin: isDuressPin ?? false,
@@ -1386,17 +1370,14 @@ Future<void> setup({
final restoredWallet = additionalParams?['restoredWallet'] as RestoredWallet?;
final hardwareWalletType = additionalParams?['hardwareWalletType'] as HardwareWalletType?;
return WalletRestoreViewModel(
getIt.get<AppStore>(),
getIt.get<WalletCreationService>(param1: type),
getIt.get<SeedSettingsViewModel>(),
type: type,
restoredWallet: restoredWallet,
hardwareWalletType: hardwareWalletType);
return WalletRestoreViewModel(getIt.get<AppStore>(),
getIt.get<WalletCreationService>(param1: type), getIt.get<SeedSettingsViewModel>(),
type: type, restoredWallet: restoredWallet, hardwareWalletType: hardwareWalletType);
});
getIt.registerFactoryParam<WalletRestorePage, WalletType, Map<String, dynamic>?>((type, additionalParams) =>
WalletRestorePage(getIt.get<WalletRestoreViewModel>(param1: type, param2: additionalParams),
getIt.registerFactoryParam<WalletRestorePage, WalletType, Map<String, dynamic>?>(
(type, additionalParams) => WalletRestorePage(
getIt.get<WalletRestoreViewModel>(param1: type, param2: additionalParams),
getIt.get<SeedSettingsViewModel>()));
getIt.registerFactoryParam<WalletRestoreChooseDerivationViewModel, List<DerivationInfo>, void>(
@@ -1408,22 +1389,20 @@ Future<void> setup({
param1: derivations,
)));
getIt.registerFactoryParam<TransactionDetailsViewModel, List<dynamic>, void>(
(params, _) {
final transactionInfo = params[0] as TransactionInfo;
final canReplaceByFee = params[1] as bool? ?? false;
final wallet = getIt.get<AppStore>().wallet!;
getIt.registerFactoryParam<TransactionDetailsViewModel, List<dynamic>, void>((params, _) {
final transactionInfo = params[0] as TransactionInfo;
final canReplaceByFee = params[1] as bool? ?? false;
final wallet = getIt.get<AppStore>().wallet!;
return TransactionDetailsViewModel(
transactionInfo: transactionInfo,
transactionDescriptionBox: _transactionDescriptionBox,
wallet: wallet,
appStore: getIt.get<AppStore>(),
sendViewModel: getIt.get<SendViewModel>(),
canReplaceByFee: canReplaceByFee,
);
}
);
return TransactionDetailsViewModel(
transactionInfo: transactionInfo,
transactionDescriptionBox: _transactionDescriptionBox,
wallet: wallet,
appStore: getIt.get<AppStore>(),
sendViewModel: getIt.get<SendViewModel>(),
canReplaceByFee: canReplaceByFee,
);
});
getIt.registerFactoryParam<TransactionDetailsModal, TransactionInfo, bool?>(
(transactionInfo, highlightNoteField) => TransactionDetailsModal(
@@ -1433,22 +1412,20 @@ Future<void> setup({
));
getIt.registerFactoryParam<TransactionDetailsPage, TransactionInfo, void>(
(TransactionInfo transactionInfo, _) => TransactionDetailsPage(
transactionDetailsViewModel: getIt.get<TransactionDetailsViewModel>(
param1: [transactionInfo, false])));
(TransactionInfo transactionInfo, _) => TransactionDetailsPage(
transactionDetailsViewModel:
getIt.get<TransactionDetailsViewModel>(param1: [transactionInfo, false])));
getIt.registerFactoryParam<RBFDetailsPage, List<dynamic>, void>(
(params, _) {
final transactionInfo = params[0] as TransactionInfo;
final txHex = params[1] as String;
return RBFDetailsPage(
transactionDetailsViewModel: getIt.get<TransactionDetailsViewModel>(
param1: [transactionInfo, true],
),
rawTransaction: txHex,
);
}
);
getIt.registerFactoryParam<RBFDetailsPage, List<dynamic>, void>((params, _) {
final transactionInfo = params[0] as TransactionInfo;
final txHex = params[1] as String;
return RBFDetailsPage(
transactionDetailsViewModel: getIt.get<TransactionDetailsViewModel>(
param1: [transactionInfo, true],
),
rawTransaction: txHex,
);
});
getIt.registerFactoryParam<NewWalletTypePage, NewWalletTypeArguments, void>(
(newWalletTypeArguments, _) {
@@ -1460,22 +1437,19 @@ Future<void> setup({
getIt.registerFactory<PreSeedPage>(() => PreSeedPage());
getIt.registerFactoryParam<TransactionSuccessPage, String, void>(
(content, _) => TransactionSuccessPage(content: content));
(content, _) => TransactionSuccessPage(content: content));
getIt.registerFactoryParam<TradeDetailsViewModel, Trade, void>(
(trade, _) => TradeDetailsViewModel(tradeForDetails: trade, appStore: getIt.get<AppStore>()));
getIt.registerFactory(() => CakeFeaturesViewModel(getIt.get<CakePayService>()));
getIt.registerFactory(() => CakeFeaturesPage(
dashboardViewModel: getIt.get<DashboardViewModel>(),
cakeFeaturesViewModel: getIt.get<CakeFeaturesViewModel>()));
getIt.registerFactory(() => BackupServiceV3(getIt.get<SecureStorage>(),
_transactionDescriptionBox,
getIt.get<KeyService>(), getIt.get<SharedPreferences>()));
_transactionDescriptionBox, getIt.get<KeyService>(), getIt.get<SharedPreferences>()));
getIt.registerFactory(() => BackupPage(getIt.get<BackupViewModel>()));
@@ -1483,8 +1457,8 @@ Future<void> setup({
() => EditBackupPasswordViewModel(getIt.get<SecureStorage>()),
);
getIt.registerFactory(() => BackupViewModel(
getIt.get<SecureStorage>(),getIt.get<BackupServiceV3>(), getIt.get<EditBackupPasswordViewModel>()));
getIt.registerFactory(() => BackupViewModel(getIt.get<SecureStorage>(),
getIt.get<BackupServiceV3>(), getIt.get<EditBackupPasswordViewModel>()));
getIt.registerFactory(() => EditBackupPasswordPage(getIt.get<EditBackupPasswordViewModel>()));
@@ -1502,22 +1476,22 @@ Future<void> setup({
getIt.registerFactory(() => BuySellViewModel(getIt.get<AppStore>()));
getIt.registerFactory(() => BuySellPage(getIt.get<BuySellViewModel>(), getIt.get<AddressResolverService>()));
getIt.registerFactory(
() => BuySellPage(getIt.get<BuySellViewModel>(), getIt.get<AddressResolverService>()));
getIt.registerFactoryParam<BuyOptionsPage, List<dynamic>, void>((List<dynamic> args, _) {
final items = args.first as List<SelectableItem>;
final pickAnOption = args[1] as void Function(SelectableOption option)?;
final confirmOption = args[2] as void Function(BuildContext contex)?;
return BuyOptionsPage(
items: items, pickAnOption: pickAnOption, confirmOption: confirmOption);
return BuyOptionsPage(items: items, pickAnOption: pickAnOption, confirmOption: confirmOption);
});
getIt.registerFactoryParam<PaymentMethodOptionsPage, List<dynamic>, void>((List<dynamic> args, _) {
getIt
.registerFactoryParam<PaymentMethodOptionsPage, List<dynamic>, void>((List<dynamic> args, _) {
final items = args.first as List<SelectableOption>;
final pickAnOption = args[1] as void Function(SelectableOption option)?;
return PaymentMethodOptionsPage(
items: items, pickAnOption: pickAnOption);
return PaymentMethodOptionsPage(items: items, pickAnOption: pickAnOption);
});
getIt.registerFactory(() {
@@ -1578,11 +1552,11 @@ Future<void> setup({
getIt.get<UnspentCoinsListViewModel>(param1: coinTypeToSpendFrom)));
getIt.registerFactoryParam<NewCoinControlPage, UnspentCoinType?, bool?>(
(coinTypeToSpendFrom, canEdit) => NewCoinControlPage(
unspentCoinsListViewModel:
getIt.get<UnspentCoinsListViewModel>(param1: coinTypeToSpendFrom), canEdit: canEdit ?? true,)
);
(coinTypeToSpendFrom, canEdit) => NewCoinControlPage(
unspentCoinsListViewModel:
getIt.get<UnspentCoinsListViewModel>(param1: coinTypeToSpendFrom),
canEdit: canEdit ?? true,
));
getIt.registerFactoryParam<UnspentCoinsDetailsViewModel, UnspentCoinsItem,
UnspentCoinsListViewModel>(
@@ -1601,7 +1575,7 @@ Future<void> setup({
getIt.registerFactory(() => YatService());
getIt.registerFactory<AddressResolverService>(
() => AddressResolverService(settingsStore: getIt.get<SettingsStore>()),
() => AddressResolverService(settingsStore: getIt.get<SettingsStore>()),
);
getIt.registerFactoryParam<FullscreenQRPage, QrViewData, void>(
@@ -1614,15 +1588,15 @@ Future<void> setup({
getIt.registerFactory<CakePayService>(
() => CakePayService(getIt.get<SecureStorage>(), getIt.get<CakePayApi>()));
getIt.registerFactory(
() => CakePayCardsListViewModel(cakePayService: getIt.get<CakePayService>(),
settingsStore: getIt.get<SettingsStore>()));
getIt.registerFactory(() => CakePayCardsListViewModel(
cakePayService: getIt.get<CakePayService>(), settingsStore: getIt.get<SettingsStore>()));
getIt.registerFactory(() => CakePayAuthViewModel(cakePayService: getIt.get<CakePayService>()));
getIt.registerFactoryParam<CakePayBuyCardViewModel, CakePayVendor, void>(
(CakePayVendor vendor, _) {
return CakePayBuyCardViewModel(vendor: vendor,
return CakePayBuyCardViewModel(
vendor: vendor,
cakePayService: getIt.get<CakePayService>(),
sendViewModel: getIt.get<SendViewModel>(),
orders: _ordersSource);
@@ -1666,8 +1640,7 @@ Future<void> setup({
));
getIt.registerFactoryParam<PayjoinDetailsViewModel, String, TransactionInfo?>(
(String sessionId, TransactionInfo? transactionInfo) =>
PayjoinDetailsViewModel(
(String sessionId, TransactionInfo? transactionInfo) => PayjoinDetailsViewModel(
sessionId,
transactionInfo,
payjoinSessionSource: _payjoinSessionSource,
@@ -1684,8 +1657,8 @@ Future<void> setup({
getIt.registerFactoryParam<PayjoinDetailsPage, String, TransactionInfo?>(
(String sessionId, TransactionInfo? transactionInfo) => PayjoinDetailsPage(
payjoinDetailsViewModel: getIt.get<PayjoinDetailsViewModel>(
param1: sessionId, param2: transactionInfo)));
payjoinDetailsViewModel:
getIt.get<PayjoinDetailsViewModel>(param1: sessionId, param2: transactionInfo)));
getIt.registerFactoryParam<HomeSettingsPage, BalanceViewModel, void>((balanceViewModel, _) =>
HomeSettingsPage(getIt.get<HomeSettingsViewModel>(param1: balanceViewModel)));
@@ -1702,7 +1675,9 @@ Future<void> setup({
);
getIt.registerFactoryParam<ManageNodesPage, bool, void>((bool isPow, _) {
return ManageNodesPage(isPow, nodeListViewModel: getIt.get<NodeListViewModel>(param1: isPow), dashboardViewModel: getIt.get<DashboardViewModel>());
return ManageNodesPage(isPow,
nodeListViewModel: getIt.get<NodeListViewModel>(param1: isPow),
dashboardViewModel: getIt.get<DashboardViewModel>());
});
getIt.registerFactory(
@@ -1738,9 +1713,12 @@ Future<void> setup({
getIt.registerFactory(() => DevQRToolsPage());
getIt.registerFactory(() => ExchangeProviderLogsViewModel());
getIt.registerFactory(() => DevExchangeProviderLogsPage(getIt.get<ExchangeProviderLogsViewModel>()));
getIt.registerFactory(
() => DevExchangeProviderLogsPage(getIt.get<ExchangeProviderLogsViewModel>()));
getIt.registerFactory(() => StartTorPage(StartTorViewModel(),));
getIt.registerFactory(() => StartTorPage(
StartTorViewModel(),
));
getIt.registerFactory(() => DEuroViewModel(
getIt<AppStore>(),
@@ -1782,9 +1760,9 @@ Future<void> setup({
));
getIt.registerLazySingleton(() => NodeSwitchingService(
appStore: getIt.get<AppStore>(),
settingsStore: getIt.get<SettingsStore>(),
));
appStore: getIt.get<AppStore>(),
settingsStore: getIt.get<SettingsStore>(),
));
getIt.registerFactoryParam<BridgeAmountPage, CryptoCurrency, void>(
(CryptoCurrency initialToken, _) => BridgeAmountPage(
+2 -3
View File
@@ -1,10 +1,9 @@
part of 'dogecoin.dart';
class CWDogeCoin extends DogeCoin {
@override
WalletService createDogeCoinWalletService(Box<UnspentCoinsInfo> unspentCoinSource, bool isDirect) {
WalletService createDogeCoinWalletService(
Box<UnspentCoinsInfo> unspentCoinSource, bool isDirect) {
return DogeCoinWalletService(unspentCoinSource, isDirect);
}
@@ -1,13 +1,11 @@
enum AutoGenerateSubaddressStatus {
initialized(1),
enabled(2),
enum AutoGenerateSubaddressStatus {
initialized(1),
enabled(2),
disabled(3);
const AutoGenerateSubaddressStatus(this.value);
final int value;
static AutoGenerateSubaddressStatus deserialize({required int raw}) =>
static AutoGenerateSubaddressStatus deserialize({required int raw}) =>
AutoGenerateSubaddressStatus.values.firstWhere((e) => e.value == raw);
}
}
+3 -6
View File
@@ -11,12 +11,9 @@ class BalanceDisplayMode extends EnumerableItem<int> with Serializable<int> {
BalanceDisplayMode.displayableBalance,
];
static const fullBalance = BalanceDisplayMode(raw: 0, title: 'Full Balance');
static const availableBalance =
BalanceDisplayMode(raw: 1, title: 'Available Balance');
static const hiddenBalance =
BalanceDisplayMode(raw: 2, title: 'Hidden Balance');
static const displayableBalance =
BalanceDisplayMode(raw: 3, title: 'Displayable Balance');
static const availableBalance = BalanceDisplayMode(raw: 1, title: 'Available Balance');
static const hiddenBalance = BalanceDisplayMode(raw: 2, title: 'Hidden Balance');
static const displayableBalance = BalanceDisplayMode(raw: 3, title: 'Displayable Balance');
static BalanceDisplayMode deserialize({required int raw}) {
switch (raw) {
+1 -1
View File
@@ -27,4 +27,4 @@ class BiometricAuth {
return canAuthenticate;
}
}
}
@@ -9,8 +9,7 @@ class BitcoinAmountDisplayMode extends EnumerableItem<int> with Serializable<int
BitcoinAmountDisplayMode.satoshiForLightning,
BitcoinAmountDisplayMode.bitcoin,
];
static const satoshiForLightning =
BitcoinAmountDisplayMode(raw: 0, title: 'sats (LN)');
static const satoshiForLightning = BitcoinAmountDisplayMode(raw: 0, title: 'sats (LN)');
static const bitcoin = BitcoinAmountDisplayMode(raw: 1, title: 'BTC');
static const satoshi = BitcoinAmountDisplayMode(raw: 2, title: 'sats');
+2 -2
View File
@@ -16,7 +16,7 @@ String calculateFiatAmount({double? price, String? cryptoAmount, bool raw = fals
return '0.00';
}
if(raw) {
if (raw) {
return result.toStringAsFixed(2);
}
@@ -48,7 +48,7 @@ String formatWithCommas(String? number) {
(Match match) => ',',
);
if(decimalPart.length == 1) {
if (decimalPart.length == 1) {
decimalPart = "${decimalPart}0";
}
+1 -1
View File
@@ -12,4 +12,4 @@ String calculateFiatAmountRaw({required double cryptoAmount, double? price}) {
}
return result > 0.01 ? formatWithCommas(result.toStringAsFixed(2)) : '< 0.01';
}
}
+6 -1
View File
@@ -7,7 +7,12 @@ part 'contact.part.dart';
// @HiveType(typeId: Contact.typeId)
class Contact extends HiveObject with Keyable {
Contact({required this.name, required this.address, CryptoCurrency? type, DateTime? lastChange, this.displayName = ""})
Contact(
{required this.name,
required this.address,
CryptoCurrency? type,
DateTime? lastChange,
this.displayName = ""})
: lastChange = lastChange ?? DateTime.now() {
if (type != null) {
raw = type.raw;
+1 -3
View File
@@ -46,7 +46,5 @@ class ContactAdapter extends TypeAdapter<Contact> {
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ContactAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
other is ContactAdapter && runtimeType == other.runtimeType && typeId == other.typeId;
}
+1 -1
View File
@@ -10,4 +10,4 @@ abstract class ContactBase {
String displayName;
CryptoCurrency type;
}
}
+4 -3
View File
@@ -11,7 +11,8 @@ class Country extends EnumerableItem<String> with Serializable<String> {
static List<Country> get all => _all.values.toList();
static List<Country> get allForCakePay => _all.values
.where((element) => element.countryCode != 'EU' && element.countryCode != 'AQ').toList();
.where((element) => element.countryCode != 'EU' && element.countryCode != 'AQ')
.toList();
static const afghanistan = Country(code: 'afg', countryCode: 'AF', fullName: "Afghanistan");
static const andorra = Country(code: 'and', countryCode: 'AD', fullName: "Andorra");
@@ -366,9 +367,9 @@ class Country extends EnumerableItem<String> with Serializable<String> {
return _all.values.firstWhereOrNull((element) => element.raw == countryCode.toLowerCase());
}
static Country? fromCountryCode(String countryCode) {
return _all.values.firstWhereOrNull((element) => element.countryCode == countryCode.toUpperCase());
return _all.values
.firstWhereOrNull((element) => element.countryCode == countryCode.toUpperCase());
}
@override
+15 -18
View File
@@ -283,7 +283,7 @@ Future<void> defaultSettingsMigration(
// await insecureStorageMigration(secureStorage: secureStorage, sharedPreferences: sharedPreferences);
break;
case 27:
await addWalletNodeList( type: WalletType.solana);
await addWalletNodeList(type: WalletType.solana);
await _changeDefaultNode(
sharedPreferences: sharedPreferences,
type: WalletType.solana,
@@ -516,7 +516,7 @@ Future<void> defaultSettingsMigration(
currentNodePreferenceKey: PreferencesKey.currentBaseNodeIdKey,
);
break;
case 53:
case 53:
await addWalletNodeList(type: WalletType.arbitrum);
await _changeDefaultNode(
sharedPreferences: sharedPreferences,
@@ -662,13 +662,13 @@ Future<void> _changeDefaultNode({
shouldReplace = true;
} else {
final currentNode = nodes.firstWhereOrNull((node) => node.id == currentNodeId);
shouldReplace = currentNode == null || (oldUri?.any((e) => currentNode!.uriRaw.contains(e)) ?? true);
shouldReplace =
currentNode == null || (oldUri?.any((e) => currentNode!.uriRaw.contains(e)) ?? true);
}
if (shouldReplace) {
newDefaultUri ??= (await getDefaultNodeFromFiles(type)).uriRaw;
var newNodeId =
nodes.firstWhereOrNull((element) => element.uriRaw == newDefaultUri)?.id;
var newNodeId = nodes.firstWhereOrNull((element) => element.uriRaw == newDefaultUri)?.id;
// new node doesn't exist, then add it
if (newNodeId == null) {
@@ -734,8 +734,7 @@ Future<void> updateNanoNodeList() async {
}
// update the nautilus node:
final nautilusNode =
nodes.firstWhereOrNull((element) => element.uriRaw == "node.perish.co");
final nautilusNode = nodes.firstWhereOrNull((element) => element.uriRaw == "node.perish.co");
if (nautilusNode != null) {
nautilusNode.uriRaw = "node.nautilus.io";
nautilusNode.path = "/api";
@@ -855,9 +854,9 @@ Future<void> validateBitcoinSavedTransactionPriority(SharedPreferences sharedPre
Future<void> replaceNodesMigration() async {
final replaceNodes = <String, Node>{
'eu-node.cakewallet.io:18081':
Node(uri: 'xmr-node-eu.cakewallet.com:18081', type: WalletType.monero),
Node(uri: 'xmr-node-eu.cakewallet.com:18081', type: WalletType.monero),
'node.cakewallet.io:18081':
Node(uri: 'xmr-node-usa-east.cakewallet.com:18081', type: WalletType.monero),
Node(uri: 'xmr-node-usa-east.cakewallet.com:18081', type: WalletType.monero),
'node.xmr.ru:13666': Node(uri: 'node.monero.net:18081', type: WalletType.monero)
};
@@ -874,11 +873,10 @@ Future<void> replaceNodesMigration() async {
});
}
Future<Node?> getBitcoinTestnetDefaultElectrumServer()async {
Future<Node?> getBitcoinTestnetDefaultElectrumServer() async {
final nodes = await Node.getAll();
return nodes
.firstWhereOrNull((Node node) => node.uriRaw == publicBitcoinTestnetElectrumUri) ??
return nodes.firstWhereOrNull((Node node) => node.uriRaw == publicBitcoinTestnetElectrumUri) ??
nodes.firstWhereOrNull((node) => node.type == WalletType.bitcoin);
}
@@ -1086,8 +1084,8 @@ Future<void> resetBitcoinElectrumServer(SharedPreferences sharedPreferences) asy
sharedPreferences.getInt(PreferencesKey.currentBitcoinElectrumSererIdKey);
final oldElectrumServer = nodeSource
.firstWhereOrNull((node) => node.uri.toString().contains('electrumx.cakewallet.com'));
var cakeWalletNode = nodeSource
.firstWhereOrNull((node) => node.uriRaw.toString() == cakeWalletBitcoinElectrumUri);
var cakeWalletNode =
nodeSource.firstWhereOrNull((node) => node.uriRaw.toString() == cakeWalletBitcoinElectrumUri);
if (cakeWalletNode == null) {
cakeWalletNode = Node(
@@ -1147,8 +1145,7 @@ Future<void> addWalletNodeList({required WalletType type}) async {
}
}
Future<void> removeMoneroWorld(
{required SharedPreferences sharedPreferences}) async {
Future<void> removeMoneroWorld({required SharedPreferences sharedPreferences}) async {
final nodes = await Node.getAll();
const cakeWalletMoneroNodeUriPattern = '.moneroworld.com';
final currentMoneroNodeId = sharedPreferences.getInt(PreferencesKey.currentNodeIdKey);
@@ -1218,14 +1215,13 @@ Future<void> migrateExistingNodesToUseAutoSwitching() async {
final powNodes = await Node.getAllPow();
for(var node in powNodes) {
for (var node in powNodes) {
if (listOfDefaultNodesWithAutoSwitching.contains(node.uriRaw)) {
node.isEnabledForAutoSwitching = true;
node.isPow = true;
await node.save();
}
}
}
Future<void> _addXautTokenToExistingEthereumWallets() async {
@@ -1264,6 +1260,7 @@ Future<void> _addXautTokenToExistingEthereumWallets() async {
printV('Error in XAUT migration: $e');
}
}
Future<void> _addXaut0TokenToExistingSolanaWallets() async {
try {
final xaut0Token = SPLToken(
+4 -4
View File
@@ -16,11 +16,11 @@ extension Emoji on String {
bool _hasOnlyEmojis() {
final parsedText = this.replaceAll(' ', '');
if(parsedText.isEmpty) return false;
for (final c in Characters(parsedText))
if (!REGEX_EMOJI.hasMatch(c)) return false;
if (parsedText.isEmpty) return false;
for (final c in Characters(parsedText)) if (!REGEX_EMOJI.hasMatch(c)) return false;
return true;
}
/// Returns true if the given text contains only emojis.
/// Returns true if the given text contains only emojis.
bool get hasOnlyEmojis => _hasOnlyEmojis();
}

Some files were not shown because too many files have changed in this diff Show More