2023-07-19 17:08:46 +00:00
|
|
|
import 'dart:async';
|
2023-08-22 16:33:24 +00:00
|
|
|
import 'dart:convert';
|
2023-07-19 17:08:46 +00:00
|
|
|
|
2023-08-22 16:33:24 +00:00
|
|
|
import 'package:decimal/decimal.dart';
|
2023-07-19 17:08:46 +00:00
|
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import 'package:isar/isar.dart';
|
2023-07-27 14:11:20 +00:00
|
|
|
import 'package:stackwallet/db/isar/main_db.dart';
|
2023-07-19 17:08:46 +00:00
|
|
|
import 'package:stackwallet/models/balance.dart' as SWBalance;
|
2023-07-27 14:11:20 +00:00
|
|
|
import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'
|
|
|
|
as SWAddress;
|
|
|
|
import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'
|
|
|
|
as SWTransaction;
|
2023-07-19 17:08:46 +00:00
|
|
|
import 'package:stackwallet/models/isar/models/blockchain_data/utxo.dart';
|
2023-07-27 14:11:20 +00:00
|
|
|
import 'package:stackwallet/models/node_model.dart';
|
2023-07-19 17:08:46 +00:00
|
|
|
import 'package:stackwallet/models/paymint/fee_object_model.dart';
|
|
|
|
import 'package:stackwallet/services/coins/coin_service.dart';
|
2023-07-24 14:53:04 +00:00
|
|
|
import 'package:stackwallet/services/event_bus/events/global/node_connection_status_changed_event.dart';
|
|
|
|
import 'package:stackwallet/services/event_bus/events/global/updated_in_background_event.dart';
|
|
|
|
import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart';
|
|
|
|
import 'package:stackwallet/services/event_bus/global_event_bus.dart';
|
|
|
|
import 'package:stackwallet/services/mixins/wallet_cache.dart';
|
|
|
|
import 'package:stackwallet/services/mixins/wallet_db.dart';
|
|
|
|
import 'package:stackwallet/services/node_service.dart';
|
|
|
|
import 'package:stackwallet/services/transaction_notification_tracker.dart';
|
2023-07-27 14:11:20 +00:00
|
|
|
import 'package:stackwallet/utilities/amount/amount.dart';
|
|
|
|
import 'package:stackwallet/utilities/constants.dart';
|
|
|
|
import 'package:stackwallet/utilities/default_nodes.dart';
|
|
|
|
import 'package:stackwallet/utilities/enums/coin_enum.dart';
|
|
|
|
import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart';
|
|
|
|
import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart';
|
|
|
|
import 'package:stackwallet/utilities/logger.dart';
|
|
|
|
import 'package:stackwallet/utilities/prefs.dart';
|
2023-07-19 17:08:46 +00:00
|
|
|
import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart';
|
2023-07-27 14:11:20 +00:00
|
|
|
import 'package:tuple/tuple.dart';
|
2023-07-19 17:08:46 +00:00
|
|
|
|
|
|
|
const int MINIMUM_CONFIRMATIONS = 1;
|
|
|
|
|
2023-07-27 14:11:20 +00:00
|
|
|
class StellarWallet extends CoinServiceAPI with WalletCache, WalletDB {
|
2023-07-27 11:09:56 +00:00
|
|
|
late StellarSDK stellarSdk;
|
|
|
|
late Network stellarNetwork;
|
|
|
|
|
2023-08-22 16:33:24 +00:00
|
|
|
|
2023-07-19 17:08:46 +00:00
|
|
|
StellarWallet({
|
|
|
|
required String walletId,
|
|
|
|
required String walletName,
|
|
|
|
required Coin coin,
|
|
|
|
required TransactionNotificationTracker tracker,
|
|
|
|
required SecureStorageInterface secureStore,
|
|
|
|
MainDB? mockableOverride,
|
|
|
|
}) {
|
|
|
|
txTracker = tracker;
|
|
|
|
_walletId = walletId;
|
|
|
|
_walletName = walletName;
|
|
|
|
_coin = coin;
|
|
|
|
_secureStore = secureStore;
|
|
|
|
initCache(walletId, coin);
|
|
|
|
initWalletDB(mockableOverride: mockableOverride);
|
2023-07-27 11:09:56 +00:00
|
|
|
|
2023-08-22 16:33:24 +00:00
|
|
|
|
|
|
|
if (coin.isTestNet) {
|
2023-07-27 11:09:56 +00:00
|
|
|
stellarNetwork = Network.TESTNET;
|
|
|
|
} else {
|
|
|
|
stellarNetwork = Network.PUBLIC;
|
|
|
|
}
|
2023-08-22 16:33:24 +00:00
|
|
|
|
|
|
|
_updateNode();
|
|
|
|
}
|
|
|
|
|
|
|
|
void _updateNode() {
|
|
|
|
_xlmNode = NodeService(secureStorageInterface: _secureStore)
|
|
|
|
.getPrimaryNodeFor(coin: coin) ??
|
|
|
|
DefaultNodes.getNodeFor(coin);
|
|
|
|
stellarSdk = StellarSDK("${_xlmNode!.host}:${_xlmNode!.port}");
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
late final TransactionNotificationTracker txTracker;
|
|
|
|
late SecureStorageInterface _secureStore;
|
|
|
|
|
|
|
|
@override
|
|
|
|
bool get isFavorite => _isFavorite ??= getCachedIsFavorite();
|
|
|
|
bool? _isFavorite;
|
|
|
|
|
|
|
|
@override
|
|
|
|
set isFavorite(bool isFavorite) {
|
|
|
|
_isFavorite = isFavorite;
|
|
|
|
updateCachedIsFavorite(isFavorite);
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
bool get shouldAutoSync => _shouldAutoSync;
|
|
|
|
bool _shouldAutoSync = true;
|
|
|
|
|
|
|
|
Timer? timer;
|
|
|
|
|
|
|
|
final _prefs = Prefs.instance;
|
|
|
|
|
|
|
|
@override
|
|
|
|
set shouldAutoSync(bool shouldAutoSync) {
|
|
|
|
if (_shouldAutoSync != shouldAutoSync) {
|
|
|
|
_shouldAutoSync = shouldAutoSync;
|
|
|
|
if (!shouldAutoSync) {
|
|
|
|
timer?.cancel();
|
|
|
|
timer = null;
|
|
|
|
stopNetworkAlivePinging();
|
|
|
|
} else {
|
|
|
|
startNetworkAlivePinging();
|
|
|
|
refresh();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Timer? _networkAliveTimer;
|
|
|
|
|
|
|
|
void startNetworkAlivePinging() {
|
|
|
|
// call once on start right away
|
|
|
|
_periodicPingCheck();
|
|
|
|
|
|
|
|
// then periodically check
|
|
|
|
_networkAliveTimer = Timer.periodic(
|
|
|
|
Constants.networkAliveTimerDuration,
|
2023-07-27 14:11:20 +00:00
|
|
|
(_) async {
|
2023-07-19 17:08:46 +00:00
|
|
|
_periodicPingCheck();
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
void stopNetworkAlivePinging() {
|
|
|
|
_networkAliveTimer?.cancel();
|
|
|
|
_networkAliveTimer = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
void _periodicPingCheck() async {
|
|
|
|
bool hasNetwork = await testNetworkConnection();
|
|
|
|
|
|
|
|
if (_isConnected != hasNetwork) {
|
|
|
|
NodeConnectionStatus status = hasNetwork
|
|
|
|
? NodeConnectionStatus.connected
|
|
|
|
: NodeConnectionStatus.disconnected;
|
|
|
|
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
NodeConnectionStatusChangedEvent(
|
|
|
|
status,
|
|
|
|
walletId,
|
|
|
|
coin,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
_isConnected = hasNetwork;
|
|
|
|
if (hasNetwork) {
|
|
|
|
unawaited(refresh());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
String get walletName => _walletName;
|
|
|
|
late String _walletName;
|
|
|
|
|
|
|
|
@override
|
|
|
|
set walletName(String name) => _walletName = name;
|
|
|
|
|
|
|
|
@override
|
|
|
|
SWBalance.Balance get balance => _balance ??= getCachedBalance();
|
|
|
|
SWBalance.Balance? _balance;
|
|
|
|
|
|
|
|
@override
|
|
|
|
Coin get coin => _coin;
|
|
|
|
late Coin _coin;
|
|
|
|
|
2023-07-27 14:11:20 +00:00
|
|
|
Future<bool> _accountExists(String accountId) async {
|
2023-07-21 12:59:47 +00:00
|
|
|
bool exists = false;
|
|
|
|
|
|
|
|
try {
|
2023-07-27 14:11:20 +00:00
|
|
|
AccountResponse receiverAccount =
|
|
|
|
await stellarSdk.accounts.account(accountId);
|
2023-07-21 12:59:47 +00:00
|
|
|
if (receiverAccount.accountId != "") {
|
|
|
|
exists = true;
|
|
|
|
}
|
2023-07-27 14:11:20 +00:00
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"Error getting account ${e.toString()} - ${s.toString()}",
|
|
|
|
level: LogLevel.Error);
|
2023-07-21 12:59:47 +00:00
|
|
|
}
|
|
|
|
return exists;
|
|
|
|
}
|
2023-07-27 14:11:20 +00:00
|
|
|
|
2023-07-19 17:08:46 +00:00
|
|
|
@override
|
2023-07-20 15:40:49 +00:00
|
|
|
Future<String> confirmSend({required Map<String, dynamic> txData}) async {
|
2023-07-27 14:11:20 +00:00
|
|
|
final secretSeed = await _secureStore.read(key: '${_walletId}_secretSeed');
|
2023-07-20 15:40:49 +00:00
|
|
|
KeyPair senderKeyPair = KeyPair.fromSecretSeed(secretSeed!);
|
2023-07-27 14:11:20 +00:00
|
|
|
AccountResponse sender =
|
|
|
|
await stellarSdk.accounts.account(senderKeyPair.accountId);
|
2023-07-21 12:59:47 +00:00
|
|
|
final amountToSend = txData['recipientAmt'] as Amount;
|
|
|
|
|
|
|
|
//First check if account exists, can be skipped, but if the account does not exist,
|
|
|
|
// the transaction fee will be charged when the transaction fails.
|
2023-07-27 14:11:20 +00:00
|
|
|
bool validAccount = await _accountExists(txData['address'] as String);
|
2023-07-21 12:59:47 +00:00
|
|
|
Transaction transaction;
|
|
|
|
|
|
|
|
if (!validAccount) {
|
|
|
|
//Fund the account, user must ensure account is correct
|
|
|
|
CreateAccountOperationBuilder createAccBuilder =
|
2023-07-27 14:11:20 +00:00
|
|
|
CreateAccountOperationBuilder(
|
|
|
|
txData['address'] as String, amountToSend.decimal.toString());
|
2023-07-21 12:59:47 +00:00
|
|
|
transaction = TransactionBuilder(sender)
|
|
|
|
.addOperation(createAccBuilder.build())
|
|
|
|
.build();
|
|
|
|
} else {
|
|
|
|
transaction = TransactionBuilder(sender)
|
2023-07-27 14:11:20 +00:00
|
|
|
.addOperation(PaymentOperationBuilder(txData['address'] as String,
|
|
|
|
Asset.NATIVE, amountToSend.decimal.toString())
|
|
|
|
.build())
|
|
|
|
.build();
|
2023-07-21 12:59:47 +00:00
|
|
|
}
|
2023-07-27 11:09:56 +00:00
|
|
|
transaction.sign(senderKeyPair, stellarNetwork);
|
2023-07-21 12:59:47 +00:00
|
|
|
try {
|
2023-07-27 14:11:20 +00:00
|
|
|
SubmitTransactionResponse response =
|
2023-08-23 13:13:17 +00:00
|
|
|
await stellarSdk.submitTransaction(transaction).onError((error, stackTrace) => throw (error.toString()));
|
2023-07-21 12:59:47 +00:00
|
|
|
if (!response.success) {
|
2023-08-23 13:13:17 +00:00
|
|
|
throw (
|
|
|
|
"${response.extras?.resultCodes?.transactionResultCode}"
|
|
|
|
" ::: ${response.extras?.resultCodes?.operationsResultCodes}"
|
|
|
|
);
|
2023-07-21 12:59:47 +00:00
|
|
|
}
|
|
|
|
return response.hash!;
|
2023-07-27 14:11:20 +00:00
|
|
|
} catch (e, s) {
|
2023-07-21 12:59:47 +00:00
|
|
|
Logging.instance.log("Error sending TX $e - $s", level: LogLevel.Error);
|
|
|
|
rethrow;
|
2023-07-20 15:40:49 +00:00
|
|
|
}
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
|
2023-07-27 14:11:20 +00:00
|
|
|
Future<SWAddress.Address?> get _currentReceivingAddress => db
|
|
|
|
.getAddresses(walletId)
|
2023-07-19 17:08:46 +00:00
|
|
|
.filter()
|
|
|
|
.typeEqualTo(SWAddress.AddressType.unknown)
|
|
|
|
.and()
|
|
|
|
.subTypeEqualTo(SWAddress.AddressSubType.unknown)
|
|
|
|
.sortByDerivationIndexDesc()
|
|
|
|
.findFirst();
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<String> get currentReceivingAddress async =>
|
|
|
|
(await _currentReceivingAddress)?.value ?? await getAddressSW();
|
|
|
|
|
|
|
|
Future<int> getBaseFee() async {
|
2023-08-22 16:33:24 +00:00
|
|
|
var fees = await stellarSdk.feeStats.execute();
|
|
|
|
return int.parse(fees.lastLedgerBaseFee);
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<Amount> estimateFeeFor(Amount amount, int feeRate) async {
|
|
|
|
var baseFee = await getBaseFee();
|
2023-08-22 16:33:24 +00:00
|
|
|
return Amount(rawValue: BigInt.from(baseFee), fractionDigits: coin.decimals);
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2023-07-26 14:19:40 +00:00
|
|
|
Future<void> exit() async {
|
|
|
|
_hasCalledExit = true;
|
|
|
|
timer?.cancel();
|
|
|
|
timer = null;
|
|
|
|
stopNetworkAlivePinging();
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
NodeModel? _xlmNode;
|
|
|
|
|
|
|
|
NodeModel getCurrentNode() {
|
|
|
|
if (_xlmNode != null) {
|
|
|
|
return _xlmNode!;
|
2023-07-27 14:11:20 +00:00
|
|
|
} else if (NodeService(secureStorageInterface: _secureStore)
|
|
|
|
.getPrimaryNodeFor(coin: coin) !=
|
|
|
|
null) {
|
|
|
|
return NodeService(secureStorageInterface: _secureStore)
|
|
|
|
.getPrimaryNodeFor(coin: coin)!;
|
2023-07-19 17:08:46 +00:00
|
|
|
} else {
|
|
|
|
return DefaultNodes.getNodeFor(coin);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<FeeObject> get fees async {
|
2023-08-23 13:13:17 +00:00
|
|
|
|
|
|
|
int fee = await getBaseFee();
|
2023-07-19 17:08:46 +00:00
|
|
|
return FeeObject(
|
2023-08-22 16:33:24 +00:00
|
|
|
numberOfBlocksFast: 10,
|
|
|
|
numberOfBlocksAverage: 10,
|
|
|
|
numberOfBlocksSlow: 10,
|
2023-08-23 13:13:17 +00:00
|
|
|
fast: fee,
|
|
|
|
medium: fee,
|
|
|
|
slow: fee);
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2023-07-27 14:11:20 +00:00
|
|
|
Future<void> fullRescan(
|
|
|
|
int maxUnusedAddressGap, int maxNumberOfIndexesToCheck) async {
|
2023-07-19 17:08:46 +00:00
|
|
|
await _prefs.init();
|
|
|
|
await updateTransactions();
|
|
|
|
await updateChainHeight();
|
|
|
|
await updateBalance();
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<bool> generateNewAddress() {
|
|
|
|
// TODO: implement generateNewAddress
|
|
|
|
throw UnimplementedError();
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
bool get hasCalledExit => _hasCalledExit;
|
|
|
|
bool _hasCalledExit = false;
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<void> initializeExisting() async {
|
|
|
|
await _prefs.init();
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<void> initializeNew() async {
|
|
|
|
if ((await mnemonicString) != null || (await mnemonicPassphrase) != null) {
|
|
|
|
throw Exception(
|
|
|
|
"Attempted to overwrite mnemonic on generate new wallet!");
|
|
|
|
}
|
|
|
|
|
|
|
|
await _prefs.init();
|
|
|
|
|
|
|
|
String mnemonic = await Wallet.generate24WordsMnemonic();
|
2023-07-27 14:11:20 +00:00
|
|
|
await _secureStore.write(key: '${_walletId}_mnemonic', value: mnemonic);
|
|
|
|
await _secureStore.write(key: '${_walletId}_mnemonicPassphrase', value: "");
|
2023-07-19 17:08:46 +00:00
|
|
|
|
|
|
|
Wallet wallet = await Wallet.from(mnemonic);
|
|
|
|
KeyPair keyPair = await wallet.getKeyPair(index: 0);
|
|
|
|
String address = keyPair.accountId;
|
2023-07-27 14:11:20 +00:00
|
|
|
String secretSeed =
|
|
|
|
keyPair.secretSeed; //This will be required for sending a tx
|
2023-07-20 15:40:49 +00:00
|
|
|
|
2023-07-27 14:11:20 +00:00
|
|
|
await _secureStore.write(key: '${_walletId}_secretSeed', value: secretSeed);
|
2023-07-19 17:08:46 +00:00
|
|
|
|
|
|
|
final swAddress = SWAddress.Address(
|
|
|
|
walletId: walletId,
|
|
|
|
value: address,
|
|
|
|
publicKey: keyPair.publicKey,
|
|
|
|
derivationIndex: 0,
|
|
|
|
derivationPath: null,
|
|
|
|
type: SWAddress.AddressType.unknown, // TODO: set type
|
2023-07-27 14:11:20 +00:00
|
|
|
subType: SWAddress.AddressSubType.unknown);
|
|
|
|
|
2023-07-19 17:08:46 +00:00
|
|
|
await db.putAddress(swAddress);
|
2023-07-27 14:11:20 +00:00
|
|
|
|
|
|
|
await Future.wait(
|
|
|
|
[updateCachedId(walletId), updateCachedIsFavorite(false)]);
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Future<String> getAddressSW() async {
|
2023-07-27 14:11:20 +00:00
|
|
|
var mnemonic = await _secureStore.read(key: '${_walletId}_mnemonic');
|
2023-07-20 15:40:49 +00:00
|
|
|
|
|
|
|
Wallet wallet = await Wallet.from(mnemonic!);
|
|
|
|
KeyPair keyPair = await wallet.getKeyPair(index: 0);
|
|
|
|
|
2023-07-19 17:08:46 +00:00
|
|
|
return Future.value(keyPair.accountId);
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
bool get isConnected => _isConnected;
|
|
|
|
bool _isConnected = false;
|
|
|
|
|
|
|
|
@override
|
|
|
|
bool get isRefreshing => refreshMutex;
|
|
|
|
bool refreshMutex = false;
|
|
|
|
|
|
|
|
@override
|
|
|
|
// TODO: implement maxFee
|
|
|
|
Future<int> get maxFee => throw UnimplementedError();
|
|
|
|
|
|
|
|
@override
|
2023-07-27 14:11:20 +00:00
|
|
|
Future<List<String>> get mnemonic =>
|
|
|
|
mnemonicString.then((value) => value!.split(" "));
|
2023-07-19 17:08:46 +00:00
|
|
|
|
|
|
|
@override
|
2023-07-27 14:11:20 +00:00
|
|
|
Future<String?> get mnemonicPassphrase =>
|
|
|
|
_secureStore.read(key: '${_walletId}_mnemonicPassphrase');
|
2023-07-19 17:08:46 +00:00
|
|
|
|
|
|
|
@override
|
2023-07-27 14:11:20 +00:00
|
|
|
Future<String?> get mnemonicString =>
|
|
|
|
_secureStore.read(key: '${_walletId}_mnemonic');
|
2023-07-19 17:08:46 +00:00
|
|
|
|
|
|
|
@override
|
2023-07-27 14:11:20 +00:00
|
|
|
Future<Map<String, dynamic>> prepareSend(
|
|
|
|
{required String address,
|
|
|
|
required Amount amount,
|
|
|
|
Map<String, dynamic>? args}) async {
|
2023-08-22 16:33:24 +00:00
|
|
|
|
2023-07-19 17:08:46 +00:00
|
|
|
try {
|
|
|
|
final feeRate = args?["feeRate"];
|
|
|
|
var fee = 1000;
|
|
|
|
if (feeRate is FeeRateType) {
|
|
|
|
final theFees = await fees;
|
|
|
|
switch (feeRate) {
|
|
|
|
case FeeRateType.fast:
|
|
|
|
fee = theFees.fast;
|
|
|
|
case FeeRateType.slow:
|
|
|
|
fee = theFees.slow;
|
|
|
|
case FeeRateType.average:
|
|
|
|
default:
|
|
|
|
fee = theFees.medium;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Map<String, dynamic> txData = {
|
|
|
|
"fee": fee,
|
|
|
|
"address": address,
|
|
|
|
"recipientAmt": amount,
|
|
|
|
};
|
|
|
|
|
|
|
|
Logging.instance.log("prepare send: $txData", level: LogLevel.Info);
|
|
|
|
return txData;
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log("Error getting fees $e - $s", level: LogLevel.Error);
|
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2023-07-27 14:11:20 +00:00
|
|
|
Future<void> recoverFromMnemonic(
|
|
|
|
{required String mnemonic,
|
|
|
|
String? mnemonicPassphrase,
|
|
|
|
required int maxUnusedAddressGap,
|
|
|
|
required int maxNumberOfIndexesToCheck,
|
|
|
|
required int height}) async {
|
2023-07-19 17:08:46 +00:00
|
|
|
if ((await mnemonicString) != null ||
|
|
|
|
(await this.mnemonicPassphrase) != null) {
|
|
|
|
throw Exception("Attempted to overwrite mnemonic on restore!");
|
|
|
|
}
|
|
|
|
|
|
|
|
var wallet = await Wallet.from(mnemonic);
|
|
|
|
var keyPair = await wallet.getKeyPair(index: 0);
|
|
|
|
var address = keyPair.accountId;
|
2023-07-20 15:40:49 +00:00
|
|
|
var secretSeed = keyPair.secretSeed;
|
2023-07-19 17:08:46 +00:00
|
|
|
|
|
|
|
await _secureStore.write(
|
|
|
|
key: '${_walletId}_mnemonic', value: mnemonic.trim());
|
|
|
|
await _secureStore.write(
|
|
|
|
key: '${_walletId}_mnemonicPassphrase',
|
|
|
|
value: mnemonicPassphrase ?? "",
|
|
|
|
);
|
2023-07-27 14:11:20 +00:00
|
|
|
await _secureStore.write(key: '${_walletId}_secretSeed', value: secretSeed);
|
2023-07-19 17:08:46 +00:00
|
|
|
|
|
|
|
final swAddress = SWAddress.Address(
|
|
|
|
walletId: walletId,
|
|
|
|
value: address,
|
|
|
|
publicKey: keyPair.publicKey,
|
|
|
|
derivationIndex: 0,
|
|
|
|
derivationPath: null,
|
|
|
|
type: SWAddress.AddressType.unknown, // TODO: set type
|
2023-07-27 14:11:20 +00:00
|
|
|
subType: SWAddress.AddressSubType.unknown);
|
2023-07-19 17:08:46 +00:00
|
|
|
|
|
|
|
await db.putAddress(swAddress);
|
|
|
|
|
2023-07-27 14:11:20 +00:00
|
|
|
await Future.wait(
|
|
|
|
[updateCachedId(walletId), updateCachedIsFavorite(false)]);
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> updateChainHeight() async {
|
|
|
|
final height = await stellarSdk.ledgers
|
|
|
|
.order(RequestBuilderOrder.DESC)
|
|
|
|
.limit(1)
|
|
|
|
.execute()
|
2023-07-27 14:11:20 +00:00
|
|
|
.then((value) => value.records!.first.sequence)
|
|
|
|
.onError((error, stackTrace) => throw ("Error getting chain height"));
|
2023-07-19 17:08:46 +00:00
|
|
|
await updateCachedChainHeight(height);
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> updateTransactions() async {
|
2023-07-20 15:40:49 +00:00
|
|
|
try {
|
2023-07-27 14:11:20 +00:00
|
|
|
List<Tuple2<SWTransaction.Transaction, SWAddress.Address?>>
|
|
|
|
transactionList = [];
|
2023-07-20 15:40:49 +00:00
|
|
|
|
|
|
|
Page<OperationResponse> payments = await stellarSdk.payments
|
2023-07-27 14:11:20 +00:00
|
|
|
.forAccount(await getAddressSW())
|
|
|
|
.order(RequestBuilderOrder.DESC)
|
|
|
|
.execute()
|
|
|
|
.onError(
|
|
|
|
(error, stackTrace) => throw ("Could not fetch transactions"));
|
2023-07-25 13:58:29 +00:00
|
|
|
|
2023-07-20 15:40:49 +00:00
|
|
|
for (OperationResponse response in payments.records!) {
|
2023-07-24 14:53:04 +00:00
|
|
|
// PaymentOperationResponse por;
|
2023-07-20 15:40:49 +00:00
|
|
|
if (response is PaymentOperationResponse) {
|
2023-07-24 14:53:04 +00:00
|
|
|
PaymentOperationResponse por = response;
|
2023-07-21 12:59:47 +00:00
|
|
|
|
2023-07-20 15:40:49 +00:00
|
|
|
SWTransaction.TransactionType type;
|
|
|
|
if (por.sourceAccount == await getAddressSW()) {
|
|
|
|
type = SWTransaction.TransactionType.outgoing;
|
|
|
|
} else {
|
|
|
|
type = SWTransaction.TransactionType.incoming;
|
|
|
|
}
|
2023-07-25 13:58:29 +00:00
|
|
|
final amount = Amount(
|
2023-07-27 14:11:20 +00:00
|
|
|
rawValue: BigInt.parse(float
|
|
|
|
.parse(por.amount!)
|
|
|
|
.toStringAsFixed(coin.decimals)
|
|
|
|
.replaceAll(".", "")),
|
|
|
|
fractionDigits: coin.decimals,
|
|
|
|
);
|
2023-07-21 12:59:47 +00:00
|
|
|
int fee = 0;
|
|
|
|
int height = 0;
|
2023-07-24 14:53:04 +00:00
|
|
|
//Query the transaction linked to the payment,
|
|
|
|
// por.transaction returns a null sometimes
|
2023-07-27 14:11:20 +00:00
|
|
|
TransactionResponse tx =
|
|
|
|
await stellarSdk.transactions.transaction(por.transactionHash!);
|
2023-07-25 13:58:29 +00:00
|
|
|
|
|
|
|
if (tx.hash.isNotEmpty) {
|
2023-07-24 14:53:04 +00:00
|
|
|
fee = tx.feeCharged!;
|
|
|
|
height = tx.ledger;
|
2023-07-21 12:59:47 +00:00
|
|
|
}
|
|
|
|
var theTransaction = SWTransaction.Transaction(
|
|
|
|
walletId: walletId,
|
|
|
|
txid: por.transactionHash!,
|
2023-07-27 14:11:20 +00:00
|
|
|
timestamp:
|
|
|
|
DateTime.parse(por.createdAt!).millisecondsSinceEpoch ~/ 1000,
|
2023-07-21 12:59:47 +00:00
|
|
|
type: type,
|
|
|
|
subType: SWTransaction.TransactionSubType.none,
|
|
|
|
amount: 0,
|
|
|
|
amountString: amount.toJsonString(),
|
|
|
|
fee: fee,
|
|
|
|
height: height,
|
|
|
|
isCancelled: false,
|
|
|
|
isLelantus: false,
|
|
|
|
slateId: "",
|
|
|
|
otherData: "",
|
|
|
|
inputs: [],
|
|
|
|
outputs: [],
|
|
|
|
nonce: 0,
|
|
|
|
numberOfMessages: null,
|
|
|
|
);
|
|
|
|
SWAddress.Address? receivingAddress = await _currentReceivingAddress;
|
2023-07-27 14:11:20 +00:00
|
|
|
SWAddress.Address address =
|
|
|
|
type == SWTransaction.TransactionType.incoming
|
|
|
|
? receivingAddress!
|
|
|
|
: SWAddress.Address(
|
|
|
|
walletId: walletId,
|
|
|
|
value: por.sourceAccount!,
|
|
|
|
publicKey:
|
|
|
|
KeyPair.fromAccountId(por.sourceAccount!).publicKey,
|
|
|
|
derivationIndex: 0,
|
|
|
|
derivationPath: null,
|
|
|
|
type: SWAddress.AddressType.unknown, // TODO: set type
|
|
|
|
subType: SWAddress.AddressSubType.unknown);
|
|
|
|
Tuple2<SWTransaction.Transaction, SWAddress.Address> tuple =
|
|
|
|
Tuple2(theTransaction, address);
|
2023-07-21 12:59:47 +00:00
|
|
|
transactionList.add(tuple);
|
|
|
|
} else if (response is CreateAccountOperationResponse) {
|
2023-07-25 13:58:29 +00:00
|
|
|
CreateAccountOperationResponse caor = response;
|
2023-07-21 12:59:47 +00:00
|
|
|
SWTransaction.TransactionType type;
|
|
|
|
if (caor.sourceAccount == await getAddressSW()) {
|
|
|
|
type = SWTransaction.TransactionType.outgoing;
|
|
|
|
} else {
|
|
|
|
type = SWTransaction.TransactionType.incoming;
|
|
|
|
}
|
|
|
|
final amount = Amount(
|
2023-07-27 14:11:20 +00:00
|
|
|
rawValue: BigInt.parse(float
|
|
|
|
.parse(caor.startingBalance!)
|
|
|
|
.toStringAsFixed(coin.decimals)
|
|
|
|
.replaceAll(".", "")),
|
2023-07-20 15:40:49 +00:00
|
|
|
fractionDigits: coin.decimals,
|
|
|
|
);
|
|
|
|
int fee = 0;
|
|
|
|
int height = 0;
|
2023-07-27 14:11:20 +00:00
|
|
|
TransactionResponse tx =
|
|
|
|
await stellarSdk.transactions.transaction(caor.transactionHash!);
|
2023-07-25 13:58:29 +00:00
|
|
|
if (tx.hash.isNotEmpty) {
|
|
|
|
fee = tx.feeCharged!;
|
|
|
|
height = tx.ledger;
|
2023-07-20 15:40:49 +00:00
|
|
|
}
|
|
|
|
var theTransaction = SWTransaction.Transaction(
|
|
|
|
walletId: walletId,
|
|
|
|
txid: caor.transactionHash!,
|
2023-07-27 14:11:20 +00:00
|
|
|
timestamp:
|
|
|
|
DateTime.parse(caor.createdAt!).millisecondsSinceEpoch ~/ 1000,
|
2023-07-20 15:40:49 +00:00
|
|
|
type: type,
|
|
|
|
subType: SWTransaction.TransactionSubType.none,
|
|
|
|
amount: 0,
|
|
|
|
amountString: amount.toJsonString(),
|
|
|
|
fee: fee,
|
|
|
|
height: height,
|
|
|
|
isCancelled: false,
|
|
|
|
isLelantus: false,
|
|
|
|
slateId: "",
|
|
|
|
otherData: "",
|
|
|
|
inputs: [],
|
|
|
|
outputs: [],
|
|
|
|
nonce: 0,
|
|
|
|
numberOfMessages: null,
|
|
|
|
);
|
|
|
|
SWAddress.Address? receivingAddress = await _currentReceivingAddress;
|
2023-07-27 14:11:20 +00:00
|
|
|
SWAddress.Address address =
|
|
|
|
type == SWTransaction.TransactionType.incoming
|
|
|
|
? receivingAddress!
|
|
|
|
: SWAddress.Address(
|
|
|
|
walletId: walletId,
|
|
|
|
value: caor.sourceAccount!,
|
|
|
|
publicKey:
|
|
|
|
KeyPair.fromAccountId(caor.sourceAccount!).publicKey,
|
|
|
|
derivationIndex: 0,
|
|
|
|
derivationPath: null,
|
|
|
|
type: SWAddress.AddressType.unknown, // TODO: set type
|
|
|
|
subType: SWAddress.AddressSubType.unknown);
|
|
|
|
Tuple2<SWTransaction.Transaction, SWAddress.Address> tuple =
|
|
|
|
Tuple2(theTransaction, address);
|
2023-07-22 08:16:15 +00:00
|
|
|
transactionList.add(tuple);
|
2023-07-20 15:40:49 +00:00
|
|
|
}
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
2023-07-20 15:40:49 +00:00
|
|
|
await db.addNewTransactionData(transactionList, walletId);
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"Exception rethrown from updateTransactions(): $e\n$s",
|
|
|
|
level: LogLevel.Error);
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> updateBalance() async {
|
2023-07-21 12:59:47 +00:00
|
|
|
try {
|
2023-07-27 14:11:20 +00:00
|
|
|
AccountResponse accountResponse =
|
|
|
|
await stellarSdk.accounts.account(await getAddressSW());
|
2023-07-21 12:59:47 +00:00
|
|
|
for (Balance balance in accountResponse.balances) {
|
|
|
|
switch (balance.assetType) {
|
|
|
|
case Asset.TYPE_NATIVE:
|
|
|
|
_balance = SWBalance.Balance(
|
|
|
|
total: Amount(
|
2023-07-24 14:53:04 +00:00
|
|
|
rawValue: BigInt.from(float.parse(balance.balance) * 10000000),
|
2023-07-21 12:59:47 +00:00
|
|
|
fractionDigits: coin.decimals,
|
|
|
|
),
|
|
|
|
spendable: Amount(
|
2023-07-24 14:53:04 +00:00
|
|
|
rawValue: BigInt.from(float.parse(balance.balance) * 10000000),
|
2023-07-21 12:59:47 +00:00
|
|
|
fractionDigits: coin.decimals,
|
|
|
|
),
|
|
|
|
blockedTotal: Amount(
|
|
|
|
rawValue: BigInt.from(0),
|
|
|
|
fractionDigits: coin.decimals,
|
|
|
|
),
|
|
|
|
pendingSpendable: Amount(
|
|
|
|
rawValue: BigInt.from(0),
|
|
|
|
fractionDigits: coin.decimals,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
Logging.instance.log(_balance, level: LogLevel.Info);
|
|
|
|
await updateCachedBalance(_balance!);
|
|
|
|
}
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
2023-07-27 14:11:20 +00:00
|
|
|
} catch (e, s) {
|
2023-07-21 12:59:47 +00:00
|
|
|
Logging.instance.log(
|
2023-07-27 14:11:20 +00:00
|
|
|
"ERROR GETTING BALANCE $e\n$s",
|
2023-07-21 12:59:47 +00:00
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<void> refresh() async {
|
|
|
|
if (refreshMutex) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"$walletId $walletName refreshMutex denied",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
return;
|
|
|
|
} else {
|
|
|
|
refreshMutex = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
await _prefs.init();
|
|
|
|
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
WalletSyncStatusChangedEvent(
|
|
|
|
WalletSyncStatus.syncing,
|
|
|
|
walletId,
|
|
|
|
coin,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
await updateChainHeight();
|
|
|
|
await updateTransactions();
|
|
|
|
await updateBalance();
|
|
|
|
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
WalletSyncStatusChangedEvent(
|
|
|
|
WalletSyncStatus.synced,
|
|
|
|
walletId,
|
|
|
|
coin,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
if (shouldAutoSync) {
|
|
|
|
timer ??= Timer.periodic(const Duration(seconds: 30), (timer) async {
|
|
|
|
Logging.instance.log(
|
|
|
|
"Periodic refresh check for $walletId $walletName in object instance: $hashCode",
|
|
|
|
level: LogLevel.Info);
|
|
|
|
|
|
|
|
await refresh();
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
UpdatedInBackgroundEvent(
|
|
|
|
"New data found in $walletId $walletName in background!",
|
|
|
|
walletId,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"Failed to refresh stellar wallet $walletId: '$walletName': $e\n$s",
|
|
|
|
level: LogLevel.Warning,
|
|
|
|
);
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
WalletSyncStatusChangedEvent(
|
|
|
|
WalletSyncStatus.unableToSync,
|
|
|
|
walletId,
|
|
|
|
coin,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
refreshMutex = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
int get storedChainHeight => getCachedChainHeight();
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<bool> testNetworkConnection() {
|
|
|
|
// TODO: implement testNetworkConnection
|
|
|
|
throw UnimplementedError();
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2023-07-27 14:11:20 +00:00
|
|
|
Future<List<SWTransaction.Transaction>> get transactions =>
|
|
|
|
db.getTransactions(walletId).findAll();
|
2023-07-19 17:08:46 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
Future<void> updateNode(bool shouldRefresh) async {
|
2023-08-22 16:33:24 +00:00
|
|
|
_updateNode();
|
2023-07-19 17:08:46 +00:00
|
|
|
if (shouldRefresh) {
|
|
|
|
unawaited(refresh());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2023-07-21 12:59:47 +00:00
|
|
|
Future<void> updateSentCachedTxData(Map<String, dynamic> txData) async {
|
|
|
|
final transaction = SWTransaction.Transaction(
|
|
|
|
walletId: walletId,
|
|
|
|
txid: txData["txid"] as String,
|
|
|
|
timestamp: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
|
|
|
type: SWTransaction.TransactionType.outgoing,
|
|
|
|
subType: SWTransaction.TransactionSubType.none,
|
|
|
|
// precision may be lost here hence the following amountString
|
|
|
|
amount: (txData["recipientAmt"] as Amount).raw.toInt(),
|
|
|
|
amountString: (txData["recipientAmt"] as Amount).toJsonString(),
|
|
|
|
fee: txData["fee"] as int,
|
|
|
|
height: null,
|
|
|
|
isCancelled: false,
|
|
|
|
isLelantus: false,
|
|
|
|
otherData: null,
|
|
|
|
slateId: null,
|
|
|
|
nonce: null,
|
|
|
|
inputs: [],
|
|
|
|
outputs: [],
|
|
|
|
numberOfMessages: null,
|
|
|
|
);
|
|
|
|
|
|
|
|
final address = txData["address"] is String
|
2023-07-27 14:11:20 +00:00
|
|
|
? await db.getAddress(walletId, txData["address"] as String)
|
|
|
|
: null;
|
2023-07-21 12:59:47 +00:00
|
|
|
|
|
|
|
await db.addNewTransactionData(
|
2023-07-27 14:11:20 +00:00
|
|
|
[
|
|
|
|
Tuple2(transaction, address),
|
|
|
|
],
|
|
|
|
walletId,
|
2023-07-21 12:59:47 +00:00
|
|
|
);
|
2023-07-19 17:08:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
// TODO: implement utxos
|
|
|
|
Future<List<UTXO>> get utxos => throw UnimplementedError();
|
|
|
|
|
|
|
|
@override
|
|
|
|
bool validateAddress(String address) {
|
|
|
|
return RegExp(r"^[G][A-Z0-9]{55}$").hasMatch(address);
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
String get walletId => _walletId;
|
|
|
|
late String _walletId;
|
2023-07-27 14:11:20 +00:00
|
|
|
}
|