WIP:Replace libepiccash calls with calls to abstract class, add error handling and return types other than strings

This commit is contained in:
likho 2023-09-27 17:53:10 +02:00
parent dc457e7266
commit 13a171f3ef
3 changed files with 63 additions and 84 deletions

View file

@ -48,14 +48,19 @@ import 'package:stackwallet/utilities/logger.dart';
import 'package:stackwallet/utilities/prefs.dart'; import 'package:stackwallet/utilities/prefs.dart';
import 'package:stackwallet/utilities/stack_file_system.dart'; import 'package:stackwallet/utilities/stack_file_system.dart';
import 'package:stackwallet/utilities/test_epic_box_connection.dart'; import 'package:stackwallet/utilities/test_epic_box_connection.dart';
import 'package:stackwallet/wallets/crypto_currency/coins/epiccash.dart';
import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
import 'package:tuple/tuple.dart'; import 'package:tuple/tuple.dart';
import 'package:websocket_universal/websocket_universal.dart'; import 'package:websocket_universal/websocket_universal.dart';
import 'package:stackwallet/wallets/example/libepiccash.dart';
const int MINIMUM_CONFIRMATIONS = 3; const int MINIMUM_CONFIRMATIONS = 3;
const String GENESIS_HASH_MAINNET = ""; const String GENESIS_HASH_MAINNET = "";
const String GENESIS_HASH_TESTNET = ""; const String GENESIS_HASH_TESTNET = "";
final epiccash = Epiccash(CryptoCurrencyNetwork.main);
class BadEpicHttpAddressException implements Exception { class BadEpicHttpAddressException implements Exception {
final String? message; final String? message;
@ -383,34 +388,12 @@ class EpicCashWallet extends CoinServiceAPI
return ""; return "";
} }
Future<String> allWalletBalances() async { Future<({double awaitingFinalization, double pending, double spendable, double total})> allWalletBalances() async {
final wallet = await _secureStore.read(key: '${_walletId}_wallet'); final wallet = await _secureStore.read(key: '${_walletId}_wallet');
const refreshFromNode = 0; const refreshFromNode = 0;
({String wallet, int refreshFromNode, }) data = (wallet: wallet!, refreshFromNode: refreshFromNode);
dynamic message; var balances = await epiccash.getWalletInfo(data);
await m.protect(() async { return balances;
ReceivePort receivePort = await getIsolate({
"function": "getWalletInfo",
"wallet": wallet!,
"refreshFromNode": refreshFromNode,
"minimumConfirmations": MINIMUM_CONFIRMATIONS,
}, name: walletName);
message = await receivePort.first;
if (message is String) {
Logging.instance
.log("this is a string $message", level: LogLevel.Error);
stop(receivePort);
throw Exception("getWalletInfo isolate failed");
}
stop(receivePort);
Logging.instance
.log('Closing getWalletInfo!\n $message', level: LogLevel.Info);
});
// return message;
final String walletBalances = message['result'] as String;
return walletBalances;
} }
Timer? timer; Timer? timer;
@ -777,17 +760,8 @@ class EpicCashWallet extends CoinServiceAPI
String name = _walletId; String name = _walletId;
await m.protect(() async { ({String config, String mnemonic, String password, String name,}) walletData = (config: stringConfig, mnemonic: mnemonicString, password: password, name: name);
await compute( await epiccash.createNewWallet(walletData);
_initWalletWrapper,
Tuple4(
stringConfig,
mnemonicString,
password,
name,
),
);
});
//Open wallet //Open wallet
final walletOpen = openWallet(stringConfig, password); final walletOpen = openWallet(stringConfig, password);
@ -1830,27 +1804,7 @@ class EpicCashWallet extends CoinServiceAPI
@override @override
bool validateAddress(String address) { bool validateAddress(String address) {
//Invalid address that contains HTTP and epicbox domain return epiccash.validateAddress(address);
if ((address.startsWith("http://") || address.startsWith("https://")) &&
address.contains("@")) {
return false;
}
if (address.startsWith("http://") || address.startsWith("https://")) {
if (Uri.tryParse(address) != null) {
return true;
}
}
String validate = validateSendAddress(address);
if (int.parse(validate) == 1) {
//Check if address contrains a domain
if (address.contains("@")) {
return true;
}
return false;
} else {
return false;
}
} }
@override @override
@ -1905,26 +1859,14 @@ class EpicCashWallet extends CoinServiceAPI
} }
Future<void> _refreshBalance() async { Future<void> _refreshBalance() async {
String walletBalances = await allWalletBalances(); var balances = await allWalletBalances();
var jsonBalances = json.decode(walletBalances);
final spendable =
(jsonBalances['amount_currently_spendable'] as double).toString();
final pending =
(jsonBalances['amount_awaiting_confirmation'] as double).toString();
final total = (jsonBalances['total'] as double).toString();
final awaiting =
(jsonBalances['amount_awaiting_finalization'] as double).toString();
_balance = Balance( _balance = Balance(
total: Amount.fromDecimal( total: Amount.fromDecimal(
Decimal.parse(total) + Decimal.parse(awaiting), Decimal.parse(balances.total.toString()) + Decimal.parse(balances.awaitingFinalization.toString()),
fractionDigits: coin.decimals, fractionDigits: coin.decimals,
), ),
spendable: Amount.fromDecimal( spendable: Amount.fromDecimal(
Decimal.parse(spendable), Decimal.parse(balances.spendable.toString()),
fractionDigits: coin.decimals, fractionDigits: coin.decimals,
), ),
blockedTotal: Amount( blockedTotal: Amount(
@ -1932,11 +1874,10 @@ class EpicCashWallet extends CoinServiceAPI
fractionDigits: coin.decimals, fractionDigits: coin.decimals,
), ),
pendingSpendable: Amount.fromDecimal( pendingSpendable: Amount.fromDecimal(
Decimal.parse(pending), Decimal.parse(balances.pending.toString()),
fractionDigits: coin.decimals, fractionDigits: coin.decimals,
), ),
); );
await updateCachedBalance(_balance!); await updateCachedBalance(_balance!);
} }

View file

@ -37,18 +37,36 @@ class Epiccash extends Bip39Currency {
return LibEpiccash.getMnemonic(); return LibEpiccash.getMnemonic();
} }
Future<void> createNewWallet( Future<String?> createNewWallet(
({ ({
String config, String config,
String mnemonic, String mnemonic,
String password, String password,
String name, String name,
})? data) async { })? data) async {
await LibEpiccash.initializeNewWallet( String result = await LibEpiccash.initializeNewWallet(
config: data!.config, config: data!.config,
mnemonic: data.mnemonic, mnemonic: data.mnemonic,
password: data.password, password: data.password,
name: data.name); name: data.name);
if(result.isNotEmpty) {
return result;
}
return null;
}
Future<({double awaitingFinalization, double pending, double spendable, double total})> getWalletInfo(
({
String wallet,
int refreshFromNode,
})? data
) async {
var result = await LibEpiccash.getWalletBalances(wallet: data!.wallet, refreshFromNode: data.refreshFromNode, minimumConfirmations: minConfirms);
return result;
} }
Future<void> scanOutputs( Future<void> scanOutputs(
@ -67,7 +85,6 @@ class Epiccash extends Bip39Currency {
String address, String address,
int secretKey, int secretKey,
String epicboxConfig, String epicboxConfig,
int minimumConfirmations,
String note, String note,
})? data) async { })? data) async {
await LibEpiccash.createTransaction( await LibEpiccash.createTransaction(
@ -76,7 +93,7 @@ class Epiccash extends Bip39Currency {
address: data.address, address: data.address,
secretKey: data.secretKey, secretKey: data.secretKey,
epicboxConfig: data.epicboxConfig, epicboxConfig: data.epicboxConfig,
minimumConfirmations: data.minimumConfirmations, minimumConfirmations: minConfirms,
note: data.note); note: data.note);
} }

View file

@ -1,3 +1,5 @@
import 'dart:convert';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter_libepiccash/epic_cash.dart' as lib_epiccash; import 'package:flutter_libepiccash/epic_cash.dart' as lib_epiccash;
import 'package:mutex/mutex.dart'; import 'package:mutex/mutex.dart';
@ -34,7 +36,11 @@ abstract class LibEpiccash {
// TODO: probably remove this as we don't use it in stack wallet. We store the mnemonic separately // TODO: probably remove this as we don't use it in stack wallet. We store the mnemonic separately
static String getMnemonic() { static String getMnemonic() {
try { try {
return lib_epiccash.walletMnemonic(); String mnemonic = lib_epiccash.walletMnemonic();
if (mnemonic.isEmpty) {
throw Exception("Error getting mnemonic, returned empty string");
}
return mnemonic;
} catch (e) { } catch (e) {
throw Exception(e.toString()); throw Exception(e.toString());
} }
@ -63,14 +69,14 @@ abstract class LibEpiccash {
/// ///
// TODO: Complete/modify the documentation comment above // TODO: Complete/modify the documentation comment above
// TODO: Should return a void future. On error this function should throw and exception // TODO: Should return a void future. On error this function should throw and exception
static Future<void> initializeNewWallet({ static Future<String> initializeNewWallet({
required String config, required String config,
required String mnemonic, required String mnemonic,
required String password, required String password,
required String name, required String name,
}) async { }) async {
try { try {
await compute( return await compute(
_initializeWalletWrapper, _initializeWalletWrapper,
( (
config: config, config: config,
@ -97,7 +103,7 @@ abstract class LibEpiccash {
/// ///
/// Get balance information for the currently open wallet /// Get balance information for the currently open wallet
/// ///
static Future<String> getWalletBalances( static Future<({double awaitingFinalization, double pending, double spendable, double total})> getWalletBalances(
{required String wallet, {required String wallet,
required int refreshFromNode, required int refreshFromNode,
required int minimumConfirmations}) async { required int minimumConfirmations}) async {
@ -107,7 +113,22 @@ abstract class LibEpiccash {
refreshFromNode: refreshFromNode, refreshFromNode: refreshFromNode,
minimumConfirmations: minimumConfirmations, minimumConfirmations: minimumConfirmations,
)); ));
return balances;
//If balances is valid json return, else return error
if (balances.toUpperCase().contains("ERROR")) {
throw Exception(balances);
}
var jsonBalances = json.decode(balances);
//Return balances as record
({
double spendable, double pending, double total, double awaitingFinalization
}) balancesRecord = (
spendable: jsonBalances['amount_currently_spendable'],
pending: jsonBalances['amount_awaiting_finalization'],
total: jsonBalances['total'],
awaitingFinalization: jsonBalances['amount_awaiting_finalization'],
);
return balancesRecord;
} catch (e) { } catch (e) {
throw ("Error getting wallet info : ${e.toString()}"); throw ("Error getting wallet info : ${e.toString()}");
} }