cake_wallet/lib/view_model/wallet_creation_vm.dart

391 lines
12 KiB
Dart
Raw Normal View History

2023-06-09 07:37:02 +00:00
import 'dart:async';
import 'package:cake_wallet/core/wallet_creation_service.dart';
2023-07-04 22:04:34 +00:00
import 'package:cake_wallet/entities/load_current_wallet.dart';
import 'package:cake_wallet/entities/transaction_description.dart';
2023-06-09 07:37:02 +00:00
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
2023-06-13 09:03:17 +00:00
import 'package:cake_wallet/view_model/restore/restore_mode.dart';
import 'package:cake_wallet/view_model/restore/restore_wallet.dart';
2023-06-09 07:37:02 +00:00
import 'package:cake_wallet/view_model/send/output.dart';
import 'package:cw_core/balance.dart';
2023-06-09 07:37:02 +00:00
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_core/sync_status.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/transaction_info.dart';
2020-07-06 20:09:03 +00:00
import 'package:hive/hive.dart';
2020-06-20 07:10:00 +00:00
import 'package:mobx/mobx.dart';
2020-09-21 11:50:26 +00:00
import 'package:cake_wallet/core/execution_state.dart';
2021-12-24 12:37:24 +00:00
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_credentials.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_type.dart';
2020-09-21 11:50:26 +00:00
import 'package:cake_wallet/store/app_store.dart';
2020-10-22 18:24:24 +00:00
import 'package:cake_wallet/entities/generate_name.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/haven/haven.dart';
2020-06-20 07:10:00 +00:00
part 'wallet_creation_vm.g.dart';
class WalletCreationVM = WalletCreationVMBase with _$WalletCreationVM;
abstract class WalletCreationVMBase with Store {
WalletCreationVMBase(
this._appStore,
this._walletInfoSource,
this.walletCreationService,
this._fiatConversationStore,
this.transactionDescriptionBox,
{required this.type,
required this.isRecovery})
2022-10-12 17:09:57 +00:00
: state = InitialExecutionState(),
outputs = ObservableList(),
2022-10-12 17:09:57 +00:00
name = '';
2020-06-20 07:10:00 +00:00
@observable
String name;
@observable
2020-09-21 11:50:26 +00:00
ExecutionState state;
2020-06-20 07:10:00 +00:00
2023-06-09 07:37:02 +00:00
@observable
PendingTransaction? pendingTransaction;
@observable
ObservableList<Output> outputs;
WalletType type;
2020-07-06 20:09:03 +00:00
final bool isRecovery;
final WalletCreationService walletCreationService;
2020-09-10 14:51:59 +00:00
final Box<WalletInfo> _walletInfoSource;
2020-09-21 11:50:26 +00:00
final AppStore _appStore;
2023-06-13 09:03:17 +00:00
final FiatConversionStore _fiatConversationStore;
final Box<TransactionDescription> transactionDescriptionBox;
2023-06-09 07:37:02 +00:00
bool nameExists(String name) => walletCreationService.exists(name);
bool typeExists(WalletType type) => walletCreationService.typeExists(type);
Future<void> create({dynamic options, RestoredWallet? restoreWallet}) async {
// if (restoreWallet != null &&
// restoreWallet.restoreMode == WalletRestoreMode.txids) {
await _createFlowForSweepAll(options, restoreWallet);
// }
// await _createTransactionFlowNormally(options, restoreWallet);
}
Future<void> _createTransactionFlowNormally(
dynamic options,
RestoredWallet? restoreWallet,
) async {
2020-06-20 07:10:00 +00:00
try {
final restoredWallet = await _createNewWalletWithoutSwitching(
options: options,
restoreWallet: restoreWallet,
regenerateName: true,
);
2023-06-13 09:03:17 +00:00
print(
'Restored Wallet Address ' + restoredWallet.walletAddresses.address,
);
await _walletInfoSource.add(restoredWallet.walletInfo);
_appStore.changeCurrentWallet(restoredWallet);
_appStore.authenticationStore.allowed();
state = ExecutedSuccessfullyState();
} catch (e) {
print('Error occurred while creating a new wallet from Scan QR normally');
state = FailureState(e.toString());
}
}
Future<void> _createFlowForSweepAll(
dynamic options,
RestoredWallet? restoreWallet,
) async {
final type = restoreWallet?.type ?? this.type;
try {
final newWallet =
await _createNewWalletWithoutSwitching(options: options);
final newWalletAddress = newWallet.walletAddresses.address;
print('New Wallet Address ' + newWalletAddress);
final restoredWallet = await _createNewWalletWithoutSwitching(
options: options,
restoreWallet: restoreWallet,
regenerateName: true,
);
print(
'Restored Wallet Address ' + restoredWallet.walletAddresses.address,
);
2023-07-04 22:04:34 +00:00
//* Switch to the restoredWallet in order to activate the node connection
await _walletInfoSource.add(restoredWallet.walletInfo);
//* Connect to Node to get the ConnectedSyncStatus
await _connectToNode(restoredWallet);
//* Switch to the restoredWallet for good measure
_appStore.changeCurrentWallet(restoredWallet);
//* Load the wallet to simulate a real wallet interaction environment
2023-07-04 22:04:34 +00:00
await loadCurrentWallet();
//*Synchronize
await restoredWallet.startSync();
2023-07-04 22:04:34 +00:00
await syncCompleter.future;
2023-07-04 22:04:34 +00:00
// * Sweep all funds from restoredWallet to newWallet
await _sweepAllFundsToNewWallet(
2023-07-04 22:04:34 +00:00
restoredWallet,
2023-07-06 16:11:50 +00:00
newWallet,
2023-07-04 22:04:34 +00:00
type,
restoreWallet?.txId ?? '',
);
2020-06-20 07:10:00 +00:00
} catch (e) {
print(
'Error occurred while creating a new wallet from Scan QR using sweep all',
);
2020-09-21 11:50:26 +00:00
state = FailureState(e.toString());
2020-06-20 07:10:00 +00:00
}
}
Future<void> _connectToNode(
2023-07-04 22:04:34 +00:00
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>,
TransactionInfo>
wallet) async {
final node = _appStore.settingsStore.getCurrentNode(wallet.type);
await wallet.connectToNode(node: node);
}
2023-06-13 09:03:17 +00:00
Future<
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>,
TransactionInfo>> _createNewWalletWithoutSwitching(
2023-06-13 09:03:17 +00:00
{dynamic options,
RestoredWallet? restoreWallet,
bool regenerateName = false}) async {
state = IsExecutingState();
if (name.isEmpty) {
name = await generateName();
}
if (regenerateName) {
name = await generateName();
}
walletCreationService.checkIfExists(name);
final dirPath = await pathForWalletDir(name: name, type: type);
final path = await pathForWallet(name: name, type: type);
final credentials = restoreWallet != null
? getCredentialsFromRestoredWallet(options, restoreWallet)
: getCredentials(options);
final walletInfo = WalletInfo.external(
id: WalletBase.idFor(name, type),
name: name,
type: type,
//TODO(David): Ask Omar about this, was previous isRecovery
isRecovery: restoreWallet != null ? true : false,
restoreHeight: credentials.height ?? 0,
date: DateTime.now(),
path: path,
dirPath: dirPath,
address: '',
2023-06-13 09:03:17 +00:00
showIntroCakePayCard: (!walletCreationService.typeExists(type)) &&
type != WalletType.haven);
credentials.walletInfo = walletInfo;
final wallet = restoreWallet != null
? await processFromRestoredWallet(credentials, restoreWallet)
: await process(credentials);
walletInfo.address = wallet.walletAddresses.address;
2023-06-13 09:03:17 +00:00
return wallet;
}
Future<void> _sweepAllFundsToNewWallet(
2023-06-13 09:03:17 +00:00
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>,
TransactionInfo>
wallet,
2023-07-06 16:11:50 +00:00
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>,
TransactionInfo>
newWallet,
2023-06-13 09:03:17 +00:00
WalletType type,
String paymentId,
) async {
2023-06-13 09:03:17 +00:00
final output = Output(wallet, _appStore.settingsStore,
_fiatConversationStore,
() => wallet.currency,
);
outputs.add(output);
output.address = newWallet.walletAddresses.address;
2023-06-13 09:03:17 +00:00
output.sendAll = true;
output.note = 'testing the sweep all function';
2023-06-13 09:03:17 +00:00
final credentials = _credentials(type, wallet.currency.title, output);
print('About to enter create function');
2023-06-13 09:03:17 +00:00
try {
//* Simulating a send all transaction
await _createTransaction(wallet, credentials);
2023-06-13 09:03:17 +00:00
await _commitTransaction();
2023-06-13 09:03:17 +00:00
//* Add the new Wallet info to the walletInfoSource
2023-07-06 16:11:50 +00:00
await _walletInfoSource.add(newWallet.walletInfo);
2023-06-13 09:03:17 +00:00
//* Switch to the new wallet
_appStore.changeCurrentWallet(newWallet);
//* Load the wallet to simulate a real wallet interaction environment
await loadCurrentWallet();
2023-06-13 09:03:17 +00:00
//* Approve authentication as successful
_appStore.authenticationStore.allowed();
2023-06-13 09:03:17 +00:00
print('Successfully done inisde sweep all');
state = ExecutedSuccessfullyState();
} catch (e) {
state = FailureState(e.toString());
}
2023-06-09 07:37:02 +00:00
}
2023-06-13 09:03:17 +00:00
Object _credentials(
WalletType type, String cryptoCurrencyTitle, Output output) {
2023-06-09 07:37:02 +00:00
switch (type) {
case WalletType.bitcoin:
final priority = _appStore.settingsStore.priority[type];
if (priority == null) {
throw Exception('Priority is null for wallet type: ${type}');
}
2023-06-13 09:03:17 +00:00
return bitcoin!
.createBitcoinTransactionCredentials([output], priority: priority);
2023-06-09 07:37:02 +00:00
case WalletType.litecoin:
final priority = _appStore.settingsStore.priority[type];
if (priority == null) {
throw Exception('Priority is null for wallet type: ${type}');
}
2023-06-13 09:03:17 +00:00
return bitcoin!
.createBitcoinTransactionCredentials([output], priority: priority);
2023-06-09 07:37:02 +00:00
case WalletType.monero:
final priority = _appStore.settingsStore.priority[type];
if (priority == null) {
throw Exception('Priority is null for wallet type: ${type}');
}
return monero!.createMoneroTransactionCreationCredentials(
2023-06-13 09:03:17 +00:00
outputs: [output], priority: priority);
2023-06-09 07:37:02 +00:00
case WalletType.haven:
final priority = _appStore.settingsStore.priority[type];
if (priority == null) {
throw Exception('Priority is null for wallet type: ${type}');
}
2023-06-13 09:03:17 +00:00
2023-06-09 07:37:02 +00:00
return haven!.createHavenTransactionCreationCredentials(
2023-06-13 09:03:17 +00:00
outputs: [output],
priority: priority,
assetType: cryptoCurrencyTitle);
2023-06-09 07:37:02 +00:00
default:
throw Exception('Unexpected wallet type: ${type}');
}
}
Future<void> _createTransaction(WalletBase wallet, Object credentials) async {
2023-06-09 07:37:02 +00:00
try {
2023-06-13 09:03:17 +00:00
print('in here');
2023-06-09 07:37:02 +00:00
state = IsExecutingState();
print('about to enter wallet create transaction function');
pendingTransaction = await wallet.createTransaction(credentials);
state = ExecutedSuccessfullyState();
} catch (e) {
state = FailureState(e.toString());
}
}
Future<void> _commitTransaction() async {
if (pendingTransaction == null) {
throw Exception(
"Pending transaction doesn't exist. It should not be happened.");
}
String address = outputs.fold('', (acc, value) {
return value.isParsedAddress
? acc + value.address + '\n' + value.extractedAddress + '\n\n'
: acc + value.address + '\n\n';
});
address = address.trim();
String note = outputs.fold('', (acc, value) {
return acc + value.note + '\n';
});
note = note.trim();
try {
await pendingTransaction!.commit();
if (pendingTransaction!.id.isNotEmpty) {
_appStore.settingsStore.shouldSaveRecipientAddress
? await transactionDescriptionBox.add(TransactionDescription(
id: pendingTransaction!.id,
recipientAddress: address,
transactionNote: note))
: await transactionDescriptionBox.add(TransactionDescription(
id: pendingTransaction!.id, transactionNote: note));
}
} catch (e) {
state = FailureState(e.toString());
}
}
WalletCredentials getCredentials(dynamic options) {
switch (type) {
case WalletType.monero:
2023-06-13 09:03:17 +00:00
return monero!.createMoneroNewWalletCredentials(
name: name, language: options as String? ?? '');
case WalletType.bitcoin:
return bitcoin!.createBitcoinNewWalletCredentials(name: name);
case WalletType.litecoin:
return bitcoin!.createBitcoinNewWalletCredentials(name: name);
case WalletType.haven:
2023-06-13 09:03:17 +00:00
return haven!.createHavenNewWalletCredentials(
name: name, language: options as String? ?? '');
default:
throw Exception('Unexpected type: ${type.toString()}');
}
}
Future<WalletBase> process(WalletCredentials credentials) {
walletCreationService.changeWalletType(type: type);
return walletCreationService.create(credentials);
}
WalletCredentials getCredentialsFromRestoredWallet(
dynamic options, RestoredWallet restoreWallet) =>
throw UnimplementedError();
Future<WalletBase> processFromRestoredWallet(
WalletCredentials credentials, RestoredWallet restoreWallet) =>
throw UnimplementedError();
2020-06-20 07:10:00 +00:00
}