mirror of
https://github.com/cake-tech/cake_wallet.git
synced 2025-01-03 17:40:43 +00:00
added multibalance/asset support for zano (ui)
This commit is contained in:
parent
ce952294af
commit
5699230ba1
12 changed files with 447 additions and 252 deletions
|
@ -15,3 +15,4 @@ const NANO_ACCOUNT_TYPE_ID = 13;
|
|||
const POW_NODE_TYPE_ID = 14;
|
||||
const DERIVATION_TYPE_TYPE_ID = 15;
|
||||
const SPL_TOKEN_TYPE_ID = 16;
|
||||
const ZANO_ASSET_TYPE_ID = 17;
|
||||
|
|
|
@ -184,8 +184,6 @@ CryptoCurrency walletTypeToCryptoCurrency(WalletType type) {
|
|||
return CryptoCurrency.ltc;
|
||||
case WalletType.haven:
|
||||
return CryptoCurrency.xhv;
|
||||
case WalletType.zano:
|
||||
return CryptoCurrency.zano;
|
||||
case WalletType.ethereum:
|
||||
return CryptoCurrency.eth;
|
||||
case WalletType.bitcoinCash:
|
||||
|
@ -198,6 +196,8 @@ CryptoCurrency walletTypeToCryptoCurrency(WalletType type) {
|
|||
return CryptoCurrency.maticpoly;
|
||||
case WalletType.solana:
|
||||
return CryptoCurrency.sol;
|
||||
case WalletType.zano:
|
||||
return CryptoCurrency.zano;
|
||||
default:
|
||||
throw Exception(
|
||||
'Unexpected wallet type: ${type.toString()} for CryptoCurrency walletTypeToCryptoCurrency');
|
||||
|
|
29
cw_zano/lib/default_zano_assets.dart
Normal file
29
cw_zano/lib/default_zano_assets.dart
Normal file
|
@ -0,0 +1,29 @@
|
|||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_zano/zano_asset.dart';
|
||||
|
||||
class DefaultZanoAssets {
|
||||
final List<ZanoAsset> _defaultAssets = [
|
||||
ZanoAsset(
|
||||
assetId: 'd6329b5b1f7c0805b5c345f4957554002a2f557845f64d7645dae0e051a6498a',
|
||||
decimal: 12,
|
||||
name: 'Zano',
|
||||
symbol: 'ZANO',
|
||||
),
|
||||
ZanoAsset(
|
||||
assetId: '123',
|
||||
decimal: 12,
|
||||
name: 'Test Coin',
|
||||
symbol: 'TC',
|
||||
),
|
||||
];
|
||||
|
||||
List<ZanoAsset> get initialZanoAssets => _defaultAssets.map(
|
||||
(token) {
|
||||
String? iconPath;
|
||||
if (CryptoCurrency.all.any((element) => element.title.toUpperCase() == token.symbol.toUpperCase())) {
|
||||
iconPath = CryptoCurrency.all.singleWhere((element) => element.title.toUpperCase() == token.symbol.toUpperCase()).iconPath;
|
||||
}
|
||||
return ZanoAsset.copyWith(token, iconPath, 'ZANO');
|
||||
},
|
||||
).toList();
|
||||
}
|
64
cw_zano/lib/zano_asset.dart
Normal file
64
cw_zano/lib/zano_asset.dart
Normal file
|
@ -0,0 +1,64 @@
|
|||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_core/hive_type_ids.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
|
||||
part 'zano_asset.g.dart';
|
||||
|
||||
@HiveType(typeId: ZanoAsset.typeId)
|
||||
class ZanoAsset extends CryptoCurrency with HiveObjectMixin {
|
||||
@HiveField(0)
|
||||
final String name;
|
||||
@HiveField(1)
|
||||
final String symbol;
|
||||
@HiveField(2)
|
||||
final String assetId;
|
||||
@HiveField(3)
|
||||
final int decimal;
|
||||
@HiveField(4, defaultValue: true)
|
||||
bool _enabled;
|
||||
@HiveField(5)
|
||||
final String? iconPath;
|
||||
@HiveField(6)
|
||||
final String? tag;
|
||||
|
||||
bool get enabled => _enabled;
|
||||
|
||||
set enabled(bool value) => _enabled = value;
|
||||
|
||||
ZanoAsset({
|
||||
required this.name,
|
||||
required this.symbol,
|
||||
required this.assetId,
|
||||
required this.decimal,
|
||||
bool enabled = true,
|
||||
this.iconPath,
|
||||
this.tag,
|
||||
}) : _enabled = enabled,
|
||||
super(
|
||||
name: symbol.toLowerCase(),
|
||||
title: symbol.toUpperCase(),
|
||||
fullName: name,
|
||||
tag: tag,
|
||||
iconPath: iconPath,
|
||||
decimals: decimal);
|
||||
|
||||
ZanoAsset.copyWith(ZanoAsset other, String? icon, String? tag)
|
||||
: this.name = other.name,
|
||||
this.symbol = other.symbol,
|
||||
this.assetId = other.assetId,
|
||||
this.decimal = other.decimal,
|
||||
this._enabled = other.enabled,
|
||||
this.tag = tag,
|
||||
this.iconPath = icon,
|
||||
super(
|
||||
name: other.name,
|
||||
title: other.symbol.toUpperCase(),
|
||||
fullName: other.name,
|
||||
tag: tag,
|
||||
iconPath: icon,
|
||||
decimals: other.decimal,
|
||||
);
|
||||
|
||||
static const typeId = ZANO_ASSET_TYPE_ID;
|
||||
static const zanoAssetsBoxName = 'zanoAssets';
|
||||
}
|
|
@ -4,6 +4,7 @@ import 'dart:ffi';
|
|||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:cw_core/cake_hive.dart';
|
||||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_core/monero_amount_format.dart';
|
||||
import 'package:cw_core/monero_wallet_utils.dart';
|
||||
|
@ -25,6 +26,7 @@ import 'package:cw_zano/api/model/zano_wallet_keys.dart';
|
|||
import 'package:cw_zano/api/zano_api.dart';
|
||||
import 'package:cw_zano/exceptions/zano_transaction_creation_exception.dart';
|
||||
import 'package:cw_zano/pending_zano_transaction.dart';
|
||||
import 'package:cw_zano/zano_asset.dart';
|
||||
import 'package:cw_zano/zano_balance.dart';
|
||||
import 'package:cw_zano/zano_transaction_credentials.dart';
|
||||
import 'package:cw_zano/zano_transaction_history.dart';
|
||||
|
@ -32,49 +34,30 @@ import 'package:cw_zano/zano_transaction_info.dart';
|
|||
import 'package:cw_zano/zano_wallet_addresses.dart';
|
||||
import 'package:ffi/ffi.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
import 'package:mobx/mobx.dart';
|
||||
|
||||
import 'default_zano_assets.dart';
|
||||
|
||||
part 'zano_wallet.g.dart';
|
||||
|
||||
const moneroBlockSize = 1000;
|
||||
|
||||
class ZanoWallet = ZanoWalletBase with _$ZanoWallet;
|
||||
|
||||
typedef _load_wallet = Pointer<Utf8> Function(
|
||||
Pointer<Utf8>, Pointer<Utf8>, Int8);
|
||||
typedef _LoadWallet = Pointer<Utf8> Function(Pointer<Utf8>, Pointer<Utf8>, int);
|
||||
|
||||
const int zanoMixin = 10;
|
||||
|
||||
abstract class ZanoWalletBase
|
||||
extends WalletBase<ZanoBalance, ZanoTransactionHistory, ZanoTransactionInfo>
|
||||
with Store {
|
||||
ZanoWalletBase(WalletInfo walletInfo)
|
||||
: balance = ObservableMap.of(
|
||||
{CryptoCurrency.zano: ZanoBalance(total: 0, unlocked: 0)}),
|
||||
_isTransactionUpdating = false,
|
||||
_hasSyncAfterStartup = false,
|
||||
walletAddresses = ZanoWalletAddresses(walletInfo),
|
||||
syncStatus = NotConnectedSyncStatus(),
|
||||
super(walletInfo) {
|
||||
transactionHistory = ZanoTransactionHistory();
|
||||
// _onAccountChangeReaction =
|
||||
// reaction((_) => walletAddresses.account, (Account? account) {
|
||||
// if (account == null) {
|
||||
// return;
|
||||
// }
|
||||
// balance.addAll(getZanoBalance(accountIndex: account.id));
|
||||
// /**walletAddresses.updateSubaddressList(accountIndex: account.id);*/
|
||||
// });
|
||||
}
|
||||
typedef _load_wallet = Pointer<Utf8> Function(Pointer<Utf8>, Pointer<Utf8>, Int8);
|
||||
typedef _LoadWallet = Pointer<Utf8> Function(Pointer<Utf8>, Pointer<Utf8>, int);
|
||||
|
||||
List<History> history = [];
|
||||
String defaultAsssetId = '';
|
||||
class ZanoWallet = ZanoWalletBase with _$ZanoWallet;
|
||||
|
||||
abstract class ZanoWalletBase extends WalletBase<ZanoBalance, ZanoTransactionHistory, ZanoTransactionInfo> with Store {
|
||||
static const int _autoSaveInterval = 30;
|
||||
|
||||
static const _statusDelivered = 'delivered';
|
||||
static const _maxAttempts = 10;
|
||||
|
||||
List<History> history = [];
|
||||
String defaultAsssetId = '';
|
||||
@override
|
||||
ZanoWalletAddresses walletAddresses;
|
||||
|
||||
|
@ -90,44 +73,59 @@ abstract class ZanoWalletBase
|
|||
String seed = '';
|
||||
|
||||
@override
|
||||
ZanoWalletKeys keys = ZanoWalletKeys(
|
||||
privateSpendKey: '',
|
||||
privateViewKey: '',
|
||||
publicSpendKey: '',
|
||||
publicViewKey: '');
|
||||
ZanoWalletKeys keys = ZanoWalletKeys(privateSpendKey: '', privateViewKey: '', publicSpendKey: '', publicViewKey: '');
|
||||
|
||||
late final Box<ZanoAsset> zanoAssetsBox;
|
||||
List<ZanoAsset> get zanoAssets => zanoAssetsBox.values.toList();
|
||||
|
||||
//zano_wallet.SyncListener? _listener;
|
||||
// ReactionDisposer? _onAccountChangeReaction;
|
||||
Timer? _updateSyncInfoTimer;
|
||||
|
||||
int _cachedBlockchainHeight = 0;
|
||||
int _lastKnownBlockHeight = 0;
|
||||
int _initialSyncHeight = 0;
|
||||
bool _isTransactionUpdating;
|
||||
bool _hasSyncAfterStartup;
|
||||
Timer? _autoSaveTimer;
|
||||
|
||||
int _hWallet = 0;
|
||||
|
||||
ZanoWalletBase(WalletInfo walletInfo)
|
||||
: balance = ObservableMap.of({CryptoCurrency.zano: ZanoBalance(total: 0, unlocked: 0)}),
|
||||
_isTransactionUpdating = false,
|
||||
_hasSyncAfterStartup = false,
|
||||
walletAddresses = ZanoWalletAddresses(walletInfo),
|
||||
syncStatus = NotConnectedSyncStatus(),
|
||||
super(walletInfo) {
|
||||
transactionHistory = ZanoTransactionHistory();
|
||||
if (!CakeHive.isAdapterRegistered(ZanoAsset.typeId)) {
|
||||
CakeHive.registerAdapter(ZanoAssetAdapter());
|
||||
}
|
||||
// _onAccountChangeReaction =
|
||||
// reaction((_) => walletAddresses.account, (Account? account) {
|
||||
// if (account == null) {
|
||||
// return;
|
||||
// }
|
||||
// balance.addAll(getZanoBalance(accountIndex: account.id));
|
||||
// /**walletAddresses.updateSubaddressList(accountIndex: account.id);*/
|
||||
// });
|
||||
}
|
||||
|
||||
int get hWallet => _hWallet;
|
||||
|
||||
set hWallet(int value) {
|
||||
_hWallet = value;
|
||||
}
|
||||
|
||||
Future<void> init(String address) async {
|
||||
await walletAddresses.init();
|
||||
await walletAddresses.updateAddress(address);
|
||||
|
||||
///balance.addAll(getZanoBalance(/**accountIndex: walletAddresses.account?.id ?? 0*/));
|
||||
//_setListeners();
|
||||
await updateTransactions();
|
||||
|
||||
_autoSaveTimer = Timer.periodic(
|
||||
Duration(seconds: _autoSaveInterval), (_) async => await save());
|
||||
@override
|
||||
int calculateEstimatedFee(TransactionPriority priority, [int? amount = null]) {
|
||||
return ApiCalls.getCurrentTxFee(priority: priority.raw);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void>? updateBalance() => null;
|
||||
Future<void> changePassword(String password) async {
|
||||
ApiCalls.setPassword(hWallet: hWallet, password: password);
|
||||
}
|
||||
|
||||
@override
|
||||
void close() {
|
||||
|
@ -159,72 +157,6 @@ abstract class ZanoWalletBase
|
|||
}
|
||||
}
|
||||
|
||||
void _updateSyncProgress(GetWalletStatusResult walletStatus) {
|
||||
final syncHeight = walletStatus.currentWalletHeight;
|
||||
if (_initialSyncHeight <= 0) {
|
||||
_initialSyncHeight = syncHeight;
|
||||
}
|
||||
final bchHeight = walletStatus.currentDaemonHeight;
|
||||
|
||||
if (_lastKnownBlockHeight == syncHeight) {
|
||||
return;
|
||||
}
|
||||
|
||||
_lastKnownBlockHeight = syncHeight;
|
||||
final track = bchHeight - _initialSyncHeight;
|
||||
final diff = track - (bchHeight - syncHeight);
|
||||
final ptc = diff <= 0 ? 0.0 : diff / track;
|
||||
final left = bchHeight - syncHeight;
|
||||
|
||||
if (syncHeight < 0 || left < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Actual new height; 2. Blocks left to finish; 3. Progress in percents;
|
||||
_onNewBlock.call(syncHeight, left, ptc);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> startSync() async {
|
||||
try {
|
||||
syncStatus = AttemptingSyncStatus();
|
||||
_cachedBlockchainHeight = 0;
|
||||
_lastKnownBlockHeight = 0;
|
||||
_initialSyncHeight = 0;
|
||||
_updateSyncInfoTimer ??=
|
||||
Timer.periodic(Duration(milliseconds: 1200), (_) async {
|
||||
/**if (isNewTransactionExist()) {
|
||||
onNewTransaction?.call();
|
||||
}*/
|
||||
|
||||
final walletStatus = getWalletStatus();
|
||||
_updateSyncProgress(walletStatus);
|
||||
// You can call getWalletInfo ONLY if getWalletStatus returns NOT is in long refresh and wallet state is 2 (ready)
|
||||
if (!walletStatus.isInLongRefresh && walletStatus.walletState == 2) {
|
||||
final walletInfo = getWalletInfo();
|
||||
seed = walletInfo.wiExtended.seed;
|
||||
keys = ZanoWalletKeys(
|
||||
privateSpendKey: walletInfo.wiExtended.spendPrivateKey,
|
||||
privateViewKey: walletInfo.wiExtended.viewPrivateKey,
|
||||
publicSpendKey: walletInfo.wiExtended.spendPublicKey,
|
||||
publicViewKey: walletInfo.wiExtended.viewPublicKey,
|
||||
);
|
||||
|
||||
final _balance = walletInfo.wi.balances.first;
|
||||
defaultAsssetId = _balance.assetInfo.assetId;
|
||||
balance = ObservableMap.of({
|
||||
CryptoCurrency.zano:
|
||||
ZanoBalance(total: _balance.total, unlocked: _balance.unlocked)
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
syncStatus = FailedSyncStatus();
|
||||
print(e);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<PendingTransaction> createTransaction(Object credentials) async {
|
||||
final creds = credentials as ZanoTransactionCredentials;
|
||||
|
@ -234,12 +166,10 @@ abstract class ZanoWalletBase
|
|||
final fee = calculateEstimatedFee(creds.priority);
|
||||
late List<Destination> destinations;
|
||||
if (hasMultiDestination) {
|
||||
if (outputs.any((output) =>
|
||||
output.sendAll || (output.formattedCryptoAmount ?? 0) <= 0)) {
|
||||
if (outputs.any((output) => output.sendAll || (output.formattedCryptoAmount ?? 0) <= 0)) {
|
||||
throw ZanoTransactionCreationException("You don't have enough coins.");
|
||||
}
|
||||
final int totalAmount = outputs.fold(
|
||||
0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0));
|
||||
final int totalAmount = outputs.fold(0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0));
|
||||
if (totalAmount + fee > unlockedBalance) {
|
||||
throw ZanoTransactionCreationException(
|
||||
"You don't have enough coins (required: ${moneroAmountToString(amount: totalAmount + fee)}, unlocked ${moneroAmountToString(amount: unlockedBalance)}).");
|
||||
|
@ -247,9 +177,7 @@ abstract class ZanoWalletBase
|
|||
destinations = outputs
|
||||
.map((output) => Destination(
|
||||
amount: output.formattedCryptoAmount ?? 0,
|
||||
address: output.isParsedAddress
|
||||
? output.extractedAddress!
|
||||
: output.address,
|
||||
address: output.isParsedAddress ? output.extractedAddress! : output.address,
|
||||
assetId: defaultAsssetId,
|
||||
))
|
||||
.toList();
|
||||
|
@ -268,16 +196,13 @@ abstract class ZanoWalletBase
|
|||
destinations = [
|
||||
Destination(
|
||||
amount: amount,
|
||||
address: output.isParsedAddress
|
||||
? output.extractedAddress!
|
||||
: output.address,
|
||||
address: output.isParsedAddress ? output.extractedAddress! : output.address,
|
||||
assetId: defaultAsssetId,
|
||||
)
|
||||
];
|
||||
}
|
||||
destinations.forEach((destination) {
|
||||
debugPrint(
|
||||
'destination ${destination.address} ${destination.amount} ${destination.assetId}');
|
||||
debugPrint('destination ${destination.address} ${destination.amount} ${destination.assetId}');
|
||||
});
|
||||
return PendingZanoTransaction(
|
||||
zanoWallet: this,
|
||||
|
@ -288,34 +213,72 @@ abstract class ZanoWalletBase
|
|||
}
|
||||
|
||||
@override
|
||||
int calculateEstimatedFee(TransactionPriority priority,
|
||||
[int? amount = null]) {
|
||||
return ApiCalls.getCurrentTxFee(priority: priority.raw);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save() async {
|
||||
Future<Map<String, ZanoTransactionInfo>> fetchTransactions() async {
|
||||
try {
|
||||
await walletAddresses.updateAddressesInBox();
|
||||
await backupWalletFiles(name);
|
||||
await store();
|
||||
await _refreshTransactions();
|
||||
return history.map<ZanoTransactionInfo>((history) => ZanoTransactionInfo.fromHistory(history)).fold<Map<String, ZanoTransactionInfo>>(
|
||||
<String, ZanoTransactionInfo>{},
|
||||
(Map<String, ZanoTransactionInfo> acc, ZanoTransactionInfo tx) {
|
||||
acc[tx.id] = tx;
|
||||
return acc;
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
print('Error while saving Zano wallet file ${e.toString()}');
|
||||
print(e);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> store() async {
|
||||
try {
|
||||
final json = await invokeMethod('store', '{}');
|
||||
final map = jsonDecode(json) as Map<String, dynamic>;
|
||||
if (map['result'] == null || map['result']['result'] == null) {
|
||||
throw 'store empty response';
|
||||
GetWalletInfoResult getWalletInfo() {
|
||||
final json = ApiCalls.getWalletInfo(hWallet);
|
||||
print('wallet info $json'); // TODO: remove
|
||||
final result = GetWalletInfoResult.fromJson(jsonDecode(json) as Map<String, dynamic>);
|
||||
return result;
|
||||
}
|
||||
final _ =
|
||||
StoreResult.fromJson(map['result']['result'] as Map<String, dynamic>);
|
||||
} catch (e) {
|
||||
print(e.toString());
|
||||
|
||||
GetWalletStatusResult getWalletStatus() {
|
||||
final json = ApiCalls.getWalletStatus(hWallet: hWallet);
|
||||
print('wallet status $json'); // TODO: remove
|
||||
final status = GetWalletStatusResult.fromJson(jsonDecode(json) as Map<String, dynamic>);
|
||||
return status;
|
||||
}
|
||||
|
||||
Future<void> init(String address) async {
|
||||
_initZanoAssetsBox();
|
||||
await walletAddresses.init();
|
||||
await walletAddresses.updateAddress(address);
|
||||
|
||||
///balance.addAll(getZanoBalance(/**accountIndex: walletAddresses.account?.id ?? 0*/));
|
||||
//_setListeners();
|
||||
await updateTransactions();
|
||||
|
||||
_autoSaveTimer = Timer.periodic(Duration(seconds: _autoSaveInterval), (_) async => await save());
|
||||
}
|
||||
|
||||
Future<String> invokeMethod(String methodName, Object params) async {
|
||||
var invokeResult =
|
||||
ApiCalls.asyncCall(methodName: 'invoke', hWallet: hWallet, params: '{"method": "$methodName","params": ${jsonEncode(params)}}');
|
||||
var map = jsonDecode(invokeResult) as Map<String, dynamic>;
|
||||
int attempts = 0;
|
||||
if (map['job_id'] != null) {
|
||||
final jobId = map['job_id'] as int;
|
||||
do {
|
||||
await Future.delayed(Duration(milliseconds: attempts < 2 ? 100 : 500));
|
||||
final result = ApiCalls.tryPullResult(jobId);
|
||||
map = jsonDecode(result) as Map<String, dynamic>;
|
||||
if (map['status'] != null && map['status'] == _statusDelivered && map['result'] != null) {
|
||||
return result;
|
||||
}
|
||||
} while (++attempts < _maxAttempts);
|
||||
}
|
||||
return invokeResult;
|
||||
}
|
||||
|
||||
String loadWallet(String path, String password) {
|
||||
print('load_wallet path $path password $password');
|
||||
final result = ApiCalls.loadWallet(path: path, password: password);
|
||||
print('load_wallet result $result');
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
|
@ -342,16 +305,6 @@ abstract class ZanoWalletBase
|
|||
await Directory(currentWalletPath).delete(recursive: true);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> changePassword(String password) async {
|
||||
ApiCalls.setPassword(hWallet: hWallet, password: password);
|
||||
}
|
||||
|
||||
Future<void> setAsRecovered() async {
|
||||
walletInfo.isRecovery = false;
|
||||
await walletInfo.save();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> rescan({required int height}) async {
|
||||
walletInfo.restoreHeight = height;
|
||||
|
@ -366,67 +319,81 @@ abstract class ZanoWalletBase
|
|||
await walletInfo.save();
|
||||
}
|
||||
|
||||
Future<void> _refreshTransactions() async {
|
||||
@override
|
||||
Future<void> save() async {
|
||||
try {
|
||||
final result = await invokeMethod('get_recent_txs_and_info',
|
||||
GetRecentTxsAndInfoParams(offset: 0, count: 30));
|
||||
final map = jsonDecode(result) as Map<String, dynamic>?;
|
||||
if (map == null) {
|
||||
print('get_recent_txs_and_info empty response');
|
||||
return;
|
||||
await walletAddresses.updateAddressesInBox();
|
||||
await backupWalletFiles(name);
|
||||
await store();
|
||||
} catch (e) {
|
||||
print('Error while saving Zano wallet file ${e.toString()}');
|
||||
}
|
||||
}
|
||||
|
||||
final resultData = map['result'];
|
||||
if (resultData == null) {
|
||||
print('get_recent_txs_and_info empty response');
|
||||
return;
|
||||
Future<void> setAsRecovered() async {
|
||||
walletInfo.isRecovery = false;
|
||||
await walletInfo.save();
|
||||
}
|
||||
|
||||
if (resultData['error'] != null) {
|
||||
print('get_recent_txs_and_info error ${resultData['error']}');
|
||||
return;
|
||||
@override
|
||||
Future<void> startSync() async {
|
||||
try {
|
||||
syncStatus = AttemptingSyncStatus();
|
||||
_cachedBlockchainHeight = 0;
|
||||
_lastKnownBlockHeight = 0;
|
||||
_initialSyncHeight = 0;
|
||||
_updateSyncInfoTimer ??= Timer.periodic(Duration(milliseconds: 1200), (_) async {
|
||||
/*if (isNewTransactionExist()) {
|
||||
onNewTransaction?.call();
|
||||
}*/
|
||||
|
||||
final walletStatus = getWalletStatus();
|
||||
_updateSyncProgress(walletStatus);
|
||||
// You can call getWalletInfo ONLY if getWalletStatus returns NOT is in long refresh and wallet state is 2 (ready)
|
||||
if (!walletStatus.isInLongRefresh && walletStatus.walletState == 2) {
|
||||
final walletInfo = getWalletInfo();
|
||||
seed = walletInfo.wiExtended.seed;
|
||||
keys = ZanoWalletKeys(
|
||||
privateSpendKey: walletInfo.wiExtended.spendPrivateKey,
|
||||
privateViewKey: walletInfo.wiExtended.viewPrivateKey,
|
||||
publicSpendKey: walletInfo.wiExtended.spendPublicKey,
|
||||
publicViewKey: walletInfo.wiExtended.viewPublicKey,
|
||||
);
|
||||
|
||||
final _balance = walletInfo.wi.balances.first;
|
||||
defaultAsssetId = _balance.assetInfo.assetId;
|
||||
balance[CryptoCurrency.zano] = ZanoBalance(total: _balance.total, unlocked: _balance.unlocked);
|
||||
//balance = ObservableMap.of({CryptoCurrency.zano: ZanoBalance(total: _balance.total, unlocked: _balance.unlocked)});
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
syncStatus = FailedSyncStatus();
|
||||
print(e);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
final transfers = resultData['result']?['transfers'] as List<dynamic>?;
|
||||
if (transfers == null) {
|
||||
print('get_recent_txs_and_info empty transfers');
|
||||
return;
|
||||
Future<void> store() async {
|
||||
try {
|
||||
final json = await invokeMethod('store', '{}');
|
||||
final map = jsonDecode(json) as Map<String, dynamic>;
|
||||
if (map['result'] == null || map['result']['result'] == null) {
|
||||
throw 'store empty response';
|
||||
}
|
||||
|
||||
history = transfers
|
||||
.map((e) => History.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
final _ = StoreResult.fromJson(map['result']['result'] as Map<String, dynamic>);
|
||||
} catch (e) {
|
||||
print(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, ZanoTransactionInfo>> fetchTransactions() async {
|
||||
try {
|
||||
await _refreshTransactions();
|
||||
return history
|
||||
.map<ZanoTransactionInfo>(
|
||||
(history) => ZanoTransactionInfo.fromHistory(history))
|
||||
.fold<Map<String, ZanoTransactionInfo>>(
|
||||
<String, ZanoTransactionInfo>{},
|
||||
(Map<String, ZanoTransactionInfo> acc, ZanoTransactionInfo tx) {
|
||||
acc[tx.id] = tx;
|
||||
return acc;
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
print(e);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
Future<void>? updateBalance() => null;
|
||||
|
||||
Future<void> updateTransactions() async {
|
||||
try {
|
||||
if (_isTransactionUpdating) {
|
||||
return;
|
||||
}
|
||||
|
||||
_isTransactionUpdating = true;
|
||||
final transactions = await fetchTransactions();
|
||||
transactionHistory.addMany(transactions);
|
||||
|
@ -438,6 +405,65 @@ abstract class ZanoWalletBase
|
|||
}
|
||||
}
|
||||
|
||||
Future<void> _initZanoAssetsBox() async {
|
||||
final boxName = "${walletInfo.name.replaceAll(" ", "_")}_${ZanoAsset.zanoAssetsBoxName}";
|
||||
if (await CakeHive.boxExists(boxName)) {
|
||||
zanoAssetsBox = await CakeHive.openBox<ZanoAsset>(boxName);
|
||||
} else {
|
||||
zanoAssetsBox = await CakeHive.openBox<ZanoAsset>(boxName.replaceAll(" ", ""));
|
||||
}
|
||||
}
|
||||
|
||||
void addInitialAssets() {
|
||||
final initialZanoAssets = DefaultZanoAssets().initialZanoAssets;
|
||||
|
||||
for (var token in initialZanoAssets) {
|
||||
zanoAssetsBox.put(token.assetId, token);
|
||||
}
|
||||
}
|
||||
|
||||
ZanoAsset createNewZanoAssetObject(ZanoAsset asset, String? iconPath) {
|
||||
return ZanoAsset(
|
||||
name: asset.name,
|
||||
symbol: asset.symbol,
|
||||
assetId: asset.assetId,
|
||||
decimal: asset.decimal,
|
||||
enabled: asset.enabled,
|
||||
tag: asset.tag ?? "ZANO",
|
||||
iconPath: iconPath,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> addZanoAsset(ZanoAsset asset) async {
|
||||
String? iconPath;
|
||||
try {
|
||||
iconPath = CryptoCurrency.all
|
||||
.firstWhere((element) => element.title.toUpperCase() == asset.title.toUpperCase())
|
||||
.iconPath;
|
||||
} catch (_) {}
|
||||
|
||||
final newAsset = createNewZanoAssetObject(asset, iconPath);
|
||||
|
||||
await zanoAssetsBox.put(newAsset.assetId, newAsset);
|
||||
|
||||
if (asset.enabled) {
|
||||
balance[asset] = ZanoBalance(total: 0, unlocked: 0);
|
||||
} else {
|
||||
balance.remove(asset);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteZanoAsset(ZanoAsset token) async {
|
||||
await token.delete();
|
||||
|
||||
balance.remove(token);
|
||||
//_updateBalance();
|
||||
}
|
||||
|
||||
Future<ZanoAsset?> getZanoAsset(String assetId) async {
|
||||
return ZanoAsset(assetId: assetId, decimal: 12, name: 'Not implemented', symbol: 'NI');
|
||||
}
|
||||
|
||||
// List<ZanoTransactionInfo> _getAllTransactions(dynamic _) =>
|
||||
// zano_transaction_history
|
||||
// .getAllTransations()
|
||||
|
@ -450,12 +476,10 @@ abstract class ZanoWalletBase
|
|||
// }
|
||||
|
||||
void _askForUpdateBalance() {
|
||||
debugPrint(
|
||||
'askForUpdateBalance'); // TODO: remove, also remove this method completely
|
||||
debugPrint('askForUpdateBalance'); // TODO: remove, also remove this method completely
|
||||
}
|
||||
|
||||
Future<void> _askForUpdateTransactionHistory() async =>
|
||||
await updateTransactions();
|
||||
Future<void> _askForUpdateTransactionHistory() async => await updateTransactions();
|
||||
|
||||
void _onNewBlock(int height, int blocksLeft, double ptc) async {
|
||||
try {
|
||||
|
@ -497,49 +521,60 @@ abstract class ZanoWalletBase
|
|||
}
|
||||
}
|
||||
|
||||
String loadWallet(String path, String password) {
|
||||
print('load_wallet path $path password $password');
|
||||
final result = ApiCalls.loadWallet(path: path, password: password);
|
||||
print('load_wallet result $result');
|
||||
return result;
|
||||
Future<void> _refreshTransactions() async {
|
||||
try {
|
||||
final result = await invokeMethod('get_recent_txs_and_info', GetRecentTxsAndInfoParams(offset: 0, count: 30));
|
||||
final map = jsonDecode(result) as Map<String, dynamic>?;
|
||||
if (map == null) {
|
||||
print('get_recent_txs_and_info empty response');
|
||||
return;
|
||||
}
|
||||
|
||||
Future<String> invokeMethod(String methodName, Object params) async {
|
||||
var invokeResult = ApiCalls.asyncCall(
|
||||
methodName: 'invoke',
|
||||
hWallet: hWallet,
|
||||
params: '{"method": "$methodName","params": ${jsonEncode(params)}}');
|
||||
var map = jsonDecode(invokeResult) as Map<String, dynamic>;
|
||||
int attempts = 0;
|
||||
if (map['job_id'] != null) {
|
||||
final jobId = map['job_id'] as int;
|
||||
do {
|
||||
await Future.delayed(Duration(milliseconds: attempts < 2 ? 100 : 500));
|
||||
final result = ApiCalls.tryPullResult(jobId);
|
||||
map = jsonDecode(result) as Map<String, dynamic>;
|
||||
if (map['status'] != null &&
|
||||
map['status'] == _statusDelivered &&
|
||||
map['result'] != null) {
|
||||
return result;
|
||||
}
|
||||
} while (++attempts < _maxAttempts);
|
||||
}
|
||||
return invokeResult;
|
||||
final resultData = map['result'];
|
||||
if (resultData == null) {
|
||||
print('get_recent_txs_and_info empty response');
|
||||
return;
|
||||
}
|
||||
|
||||
GetWalletInfoResult getWalletInfo() {
|
||||
final json = ApiCalls.getWalletInfo(hWallet);
|
||||
print('wallet info $json'); // TODO: remove
|
||||
final result =
|
||||
GetWalletInfoResult.fromJson(jsonDecode(json) as Map<String, dynamic>);
|
||||
return result;
|
||||
if (resultData['error'] != null) {
|
||||
print('get_recent_txs_and_info error ${resultData['error']}');
|
||||
return;
|
||||
}
|
||||
|
||||
GetWalletStatusResult getWalletStatus() {
|
||||
final json = ApiCalls.getWalletStatus(hWallet: hWallet);
|
||||
print('wallet status $json'); // TODO: remove
|
||||
final status = GetWalletStatusResult.fromJson(
|
||||
jsonDecode(json) as Map<String, dynamic>);
|
||||
return status;
|
||||
final transfers = resultData['result']?['transfers'] as List<dynamic>?;
|
||||
if (transfers == null) {
|
||||
print('get_recent_txs_and_info empty transfers');
|
||||
return;
|
||||
}
|
||||
|
||||
history = transfers.map((e) => History.fromJson(e as Map<String, dynamic>)).toList();
|
||||
} catch (e) {
|
||||
print(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
void _updateSyncProgress(GetWalletStatusResult walletStatus) {
|
||||
final syncHeight = walletStatus.currentWalletHeight;
|
||||
if (_initialSyncHeight <= 0) {
|
||||
_initialSyncHeight = syncHeight;
|
||||
}
|
||||
final bchHeight = walletStatus.currentDaemonHeight;
|
||||
|
||||
if (_lastKnownBlockHeight == syncHeight) {
|
||||
return;
|
||||
}
|
||||
|
||||
_lastKnownBlockHeight = syncHeight;
|
||||
final track = bchHeight - _initialSyncHeight;
|
||||
final diff = track - (bchHeight - syncHeight);
|
||||
final ptc = diff <= 0 ? 0.0 : diff / track;
|
||||
final left = bchHeight - syncHeight;
|
||||
|
||||
if (syncHeight < 0 || left < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Actual new height; 2. Blocks left to finish; 3. Progress in percents;
|
||||
_onNewBlock.call(syncHeight, left, ptc);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -71,6 +71,7 @@ class ZanoWalletService extends WalletService<ZanoNewWalletCredentials, ZanoRest
|
|||
_parseCreateWalletResult(createWalletResult, wallet);
|
||||
await wallet.store();
|
||||
await wallet.init(createWalletResult.wi.address);
|
||||
wallet.addInitialAssets();
|
||||
return wallet;
|
||||
} catch (e) {
|
||||
// TODO: Implement Exception for wallet list service.
|
||||
|
@ -188,6 +189,7 @@ class ZanoWalletService extends WalletService<ZanoNewWalletCredentials, ZanoRest
|
|||
_parseCreateWalletResult(createWalletResult, wallet);
|
||||
await wallet.store();
|
||||
await wallet.init(createWalletResult.wi.address);
|
||||
wallet.addInitialAssets();
|
||||
return wallet;
|
||||
} else if (map['error'] != null) {
|
||||
final code = map['error']['code'] as String;
|
||||
|
|
|
@ -10,6 +10,7 @@ import 'package:cake_wallet/themes/extensions/transaction_trade_theme.dart';
|
|||
import 'package:cake_wallet/view_model/dashboard/home_settings_view_model.dart';
|
||||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_core/erc20_token.dart';
|
||||
import 'package:cw_zano/zano_asset.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
|
@ -195,12 +196,19 @@ class _EditTokenPageBodyState extends State<EditTokenPageBody> {
|
|||
onPressed: () async {
|
||||
if (_formKey.currentState!.validate() &&
|
||||
(!_showDisclaimer || _disclaimerChecked)) {
|
||||
await widget.homeSettingsViewModel.addToken(Erc20Token(
|
||||
// TODO: fix it!!!
|
||||
await widget.homeSettingsViewModel.addToken(ZanoAsset(
|
||||
name: _tokenNameController.text,
|
||||
symbol: _tokenSymbolController.text,
|
||||
contractAddress: _contractAddressController.text,
|
||||
assetId: _contractAddressController.text,
|
||||
decimal: int.parse(_tokenDecimalController.text),
|
||||
));
|
||||
// await widget.homeSettingsViewModel.addToken(Erc20Token(
|
||||
// name: _tokenNameController.text,
|
||||
// symbol: _tokenSymbolController.text,
|
||||
// contractAddress: _contractAddressController.text,
|
||||
// decimal: int.parse(_tokenDecimalController.text),
|
||||
// ));
|
||||
if (context.mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
|
|
@ -80,7 +80,7 @@ abstract class BalanceViewModelBase with Store {
|
|||
|
||||
@computed
|
||||
bool get isHomeScreenSettingsEnabled =>
|
||||
isEVMCompatibleChain(wallet.type) || wallet.type == WalletType.solana;
|
||||
isEVMCompatibleChain(wallet.type) || wallet.type == WalletType.solana || wallet.type == WalletType.zano;
|
||||
|
||||
@computed
|
||||
bool get hasAccounts => wallet.type == WalletType.monero;
|
||||
|
|
|
@ -6,6 +6,7 @@ import 'package:cake_wallet/polygon/polygon.dart';
|
|||
import 'package:cake_wallet/solana/solana.dart';
|
||||
import 'package:cake_wallet/store/settings_store.dart';
|
||||
import 'package:cake_wallet/view_model/dashboard/balance_view_model.dart';
|
||||
import 'package:cake_wallet/zano/zano.dart';
|
||||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_core/erc20_token.dart';
|
||||
import 'package:cw_core/wallet_type.dart';
|
||||
|
@ -57,6 +58,10 @@ abstract class HomeSettingsViewModelBase with Store {
|
|||
await solana!.addSPLToken(_balanceViewModel.wallet, token);
|
||||
}
|
||||
|
||||
if (_balanceViewModel.wallet.type == WalletType.zano) {
|
||||
await zano!.addZanoAsset(_balanceViewModel.wallet, token);
|
||||
}
|
||||
|
||||
_updateTokensList();
|
||||
_updateFiatPrices(token);
|
||||
}
|
||||
|
@ -74,6 +79,10 @@ abstract class HomeSettingsViewModelBase with Store {
|
|||
await solana!.deleteSPLToken(_balanceViewModel.wallet, token);
|
||||
}
|
||||
|
||||
if (_balanceViewModel.wallet.type == WalletType.zano) {
|
||||
await zano!.deleteZanoAsset(_balanceViewModel.wallet, token);
|
||||
}
|
||||
|
||||
_updateTokensList();
|
||||
}
|
||||
|
||||
|
@ -90,6 +99,10 @@ abstract class HomeSettingsViewModelBase with Store {
|
|||
return await solana!.getSPLToken(_balanceViewModel.wallet, contractAddress);
|
||||
}
|
||||
|
||||
if (_balanceViewModel.wallet.type == WalletType.zano) {
|
||||
return await zano!.getZanoAsset(_balanceViewModel.wallet, contractAddress);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -120,6 +133,10 @@ abstract class HomeSettingsViewModelBase with Store {
|
|||
solana!.addSPLToken(_balanceViewModel.wallet, token);
|
||||
}
|
||||
|
||||
if (_balanceViewModel.wallet.type == WalletType.zano) {
|
||||
await zano!.addZanoAsset(_balanceViewModel.wallet, token);
|
||||
}
|
||||
|
||||
_refreshTokensList();
|
||||
}
|
||||
|
||||
|
@ -166,6 +183,13 @@ abstract class HomeSettingsViewModelBase with Store {
|
|||
.toList()
|
||||
..sort(_sortFunc));
|
||||
}
|
||||
|
||||
if (_balanceViewModel.wallet.type == WalletType.zano) {
|
||||
tokens.addAll(zano!.getZanoAssets(_balanceViewModel.wallet)
|
||||
.where((element) => _matchesSearchText(element))
|
||||
.toList()
|
||||
..sort(_sortFunc));
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
|
@ -206,6 +230,10 @@ abstract class HomeSettingsViewModelBase with Store {
|
|||
return polygon!.getTokenAddress(asset);
|
||||
}
|
||||
|
||||
if (_balanceViewModel.wallet.type == WalletType.zano) {
|
||||
return zano!.getZanoAssetAddress(asset);
|
||||
}
|
||||
|
||||
// We return null if it's neither Polygin, Ethereum or Solana wallet (which is actually impossible because we only display home settings for either of these three wallets).
|
||||
return null;
|
||||
}
|
||||
|
|
|
@ -135,10 +135,6 @@ abstract class OutputBase with Store {
|
|||
return haven!.formatterMoneroAmountToDouble(amount: fee);
|
||||
}
|
||||
|
||||
if (_wallet.type == WalletType.zano) {
|
||||
return zano!.formatterMoneroAmountToDouble(amount: fee);
|
||||
}
|
||||
|
||||
if (_wallet.type == WalletType.ethereum) {
|
||||
return ethereum!.formatterEthereumAmountToDouble(amount: BigInt.from(fee));
|
||||
}
|
||||
|
@ -146,6 +142,10 @@ abstract class OutputBase with Store {
|
|||
if (_wallet.type == WalletType.polygon) {
|
||||
return polygon!.formatterPolygonAmountToDouble(amount: BigInt.from(fee));
|
||||
}
|
||||
|
||||
if (_wallet.type == WalletType.zano) {
|
||||
return zano!.formatterMoneroAmountToDouble(amount: fee);
|
||||
}
|
||||
} catch (e) {
|
||||
print(e.toString());
|
||||
}
|
||||
|
|
|
@ -79,6 +79,25 @@ class CWZano extends Zano {
|
|||
return CWZanoAccountList(wallet);
|
||||
}*/
|
||||
|
||||
List<ZanoAsset> getZanoAssets(WalletBase wallet) {
|
||||
final zanoWallet = wallet as ZanoWallet;
|
||||
return zanoWallet.zanoAssets;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> addZanoAsset(WalletBase wallet, CryptoCurrency token) async =>
|
||||
await (wallet as ZanoWallet).addZanoAsset(token as ZanoAsset);
|
||||
|
||||
@override
|
||||
Future<void> deleteZanoAsset(WalletBase wallet, CryptoCurrency token) async =>
|
||||
await (wallet as ZanoWallet).deleteZanoAsset(token as ZanoAsset);
|
||||
|
||||
@override
|
||||
Future<ZanoAsset?> getZanoAsset(WalletBase wallet, String mintAddress) async {
|
||||
final zanoWallet = wallet as ZanoWallet;
|
||||
return await zanoWallet.getZanoAsset(mintAddress);
|
||||
}
|
||||
|
||||
@override
|
||||
TransactionHistoryBase getTransactionHistory(Object wallet) {
|
||||
final zanoWallet = wallet as ZanoWallet;
|
||||
|
@ -214,6 +233,8 @@ class CWZano extends Zano {
|
|||
return asset;
|
||||
}
|
||||
|
||||
String getZanoAssetAddress(CryptoCurrency asset) => (asset as ZanoAsset).assetId;
|
||||
|
||||
// @override
|
||||
// List<AssetRate> getAssetRate() =>
|
||||
// getRate().map((rate) => AssetRate(rate.getAssetType(), rate.getRate())).toList();
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
import 'package:cake_wallet/utils/language_list.dart';
|
||||
import 'package:cw_core/wallet_base.dart';
|
||||
import 'package:cw_zano/zano_asset.dart';
|
||||
import 'package:cw_zano/zano_transaction_credentials.dart';
|
||||
import 'package:mobx/mobx.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
@ -118,6 +120,11 @@ abstract class Zano {
|
|||
int getTransactionInfoAccountId(TransactionInfo tx);
|
||||
WalletService createZanoWalletService(Box<WalletInfo> walletInfoSource);
|
||||
CryptoCurrency assetOfTransaction(TransactionInfo tx);
|
||||
List<ZanoAsset> getZanoAssets(WalletBase wallet);
|
||||
String getZanoAssetAddress(CryptoCurrency asset);
|
||||
Future<void> addZanoAsset(WalletBase wallet, CryptoCurrency token);
|
||||
Future<void> deleteZanoAsset(WalletBase wallet, CryptoCurrency token);
|
||||
Future<CryptoCurrency?> getZanoAsset(WalletBase wallet, String contractAddress);
|
||||
// List<AssetRate> getAssetRate();
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue