cake_wallet/cw_ethereum/lib/ethereum_wallet.dart

220 lines
6.2 KiB
Dart
Raw Normal View History

2023-01-04 14:51:23 +00:00
import 'dart:async';
2023-01-03 20:19:02 +00:00
import 'dart:convert';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/node.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_core/sync_status.dart';
import 'package:cw_core/transaction_priority.dart';
import 'package:cw_core/wallet_addresses.dart';
2022-12-28 15:02:04 +00:00
import 'package:cw_core/wallet_base.dart';
2023-01-03 20:19:02 +00:00
import 'package:cw_core/wallet_info.dart';
2022-12-28 15:02:04 +00:00
import 'package:cw_ethereum/ethereum_balance.dart';
2023-01-04 14:51:23 +00:00
import 'package:cw_ethereum/ethereum_client.dart';
2022-12-28 15:02:04 +00:00
import 'package:cw_ethereum/ethereum_transaction_history.dart';
import 'package:cw_ethereum/ethereum_transaction_info.dart';
import 'package:cw_ethereum/ethereum_transaction_priority.dart';
2023-01-03 20:19:02 +00:00
import 'package:cw_ethereum/ethereum_wallet_addresses.dart';
import 'package:cw_ethereum/file.dart';
2022-12-28 15:02:04 +00:00
import 'package:mobx/mobx.dart';
2023-01-04 14:51:23 +00:00
import 'package:web3dart/web3dart.dart';
2023-01-05 19:05:44 +00:00
import 'package:ed25519_hd_key/ed25519_hd_key.dart';
import 'package:bip39/bip39.dart' as bip39;
import 'package:hex/hex.dart';
2022-12-28 15:02:04 +00:00
part 'ethereum_wallet.g.dart';
class EthereumWallet = EthereumWalletBase with _$EthereumWallet;
abstract class EthereumWalletBase
extends WalletBase<EthereumBalance, EthereumTransactionHistory, EthereumTransactionInfo>
with Store {
2023-01-03 20:19:02 +00:00
EthereumWalletBase({
required WalletInfo walletInfo,
2023-01-05 19:05:44 +00:00
required String mnemonic,
2023-01-03 20:19:02 +00:00
required String password,
2023-01-04 14:51:23 +00:00
EthereumBalance? initialBalance,
2023-01-03 20:19:02 +00:00
}) : syncStatus = NotConnectedSyncStatus(),
_password = password,
2023-01-05 19:05:44 +00:00
_mnemonic = mnemonic,
_feeRates = [],
2023-01-03 20:19:02 +00:00
walletAddresses = EthereumWalletAddresses(walletInfo),
2023-01-04 14:51:23 +00:00
balance = ObservableMap<CryptoCurrency, EthereumBalance>.of(
2023-01-05 19:05:44 +00:00
{CryptoCurrency.eth: initialBalance ?? EthereumBalance(available: 0, additional: 0)}),
2023-01-03 20:19:02 +00:00
super(walletInfo) {
this.walletInfo = walletInfo;
}
2023-01-05 19:05:44 +00:00
final String _mnemonic;
2023-01-03 20:19:02 +00:00
final String _password;
2023-01-05 19:05:44 +00:00
late final String privateKey;
2023-01-04 14:51:23 +00:00
late EthereumClient _client;
List<int> _feeRates;
int? _gasPrice;
2023-01-04 14:51:23 +00:00
@override
WalletAddresses walletAddresses;
2023-01-03 20:19:02 +00:00
@override
SyncStatus syncStatus;
@override
2023-01-04 14:51:23 +00:00
@observable
late ObservableMap<CryptoCurrency, EthereumBalance> balance;
2023-01-03 20:19:02 +00:00
2023-01-05 19:05:44 +00:00
Future<void> init() async {
privateKey = await getPrivateKey(_mnemonic, _password);
transactionHistory = EthereumTransactionHistory();
walletAddresses.address = EthPrivateKey.fromHex(privateKey).address.toString();
}
2023-01-03 20:19:02 +00:00
@override
int calculateEstimatedFee(TransactionPriority priority, int? amount) {
2023-01-04 14:51:23 +00:00
throw UnimplementedError("calculateEstimatedFee");
2023-01-03 20:19:02 +00:00
}
@override
Future<void> changePassword(String password) {
2023-01-04 14:51:23 +00:00
throw UnimplementedError("changePassword");
2023-01-03 20:19:02 +00:00
}
@override
void close() {}
@override
2023-01-04 14:51:23 +00:00
Future<void> connectToNode({required Node node}) async {
try {
syncStatus = ConnectingSyncStatus();
final isConnected = await _client.connect(node);
if (!isConnected) {
throw Exception("Ethereum Node connection failed");
}
_updateBalance();
syncStatus = ConnectedSyncStatus();
} catch (e) {
syncStatus = FailedSyncStatus();
}
2023-01-03 20:19:02 +00:00
}
@override
Future<PendingTransaction> createTransaction(Object credentials) {
2023-01-04 14:51:23 +00:00
throw UnimplementedError("createTransaction");
2023-01-03 20:19:02 +00:00
}
@override
Future<Map<String, EthereumTransactionInfo>> fetchTransactions() {
2023-01-04 14:51:23 +00:00
throw UnimplementedError("fetchTransactions");
2023-01-03 20:19:02 +00:00
}
@override
2023-01-04 14:51:23 +00:00
Object get keys => throw UnimplementedError("keys");
2023-01-03 20:19:02 +00:00
@override
Future<void> rescan({required int height}) {
2023-01-04 14:51:23 +00:00
throw UnimplementedError("rescan");
2023-01-03 20:19:02 +00:00
}
@override
Future<void> save() async {
final path = await makePath();
await write(path: path, password: _password, data: toJSON());
await transactionHistory.save();
}
@override
2023-01-05 19:05:44 +00:00
String get seed => _mnemonic;
2023-01-03 20:19:02 +00:00
@override
2023-01-04 14:51:23 +00:00
Future<void> startSync() async {
try {
syncStatus = AttemptingSyncStatus();
await _updateBalance();
_gasPrice = await _client.getGasUnitPrice();
_feeRates = await _client.getEstimatedGasForPriorities();
2023-01-04 14:51:23 +00:00
Timer.periodic(
const Duration(minutes: 1), (timer) async => _gasPrice = await _client.getGasUnitPrice());
Timer.periodic(const Duration(minutes: 1),
(timer) async => _feeRates = await _client.getEstimatedGasForPriorities());
2023-01-04 14:51:23 +00:00
syncStatus = SyncedSyncStatus();
} catch (e, stacktrace) {
print(stacktrace);
print(e.toString());
syncStatus = FailedSyncStatus();
}
2023-01-03 20:19:02 +00:00
}
int feeRate(TransactionPriority priority) {
try {
if (priority is EthereumTransactionPriority) {
return _feeRates[priority.raw] * _gasPrice!;
}
2023-01-04 14:51:23 +00:00
return 0;
} catch (e) {
return 0;
}
2023-01-04 14:51:23 +00:00
}
2023-01-03 20:19:02 +00:00
Future<String> makePath() async => pathForWallet(name: walletInfo.name, type: walletInfo.type);
String toJSON() => json.encode({
2023-01-05 19:05:44 +00:00
'mnemonic': _mnemonic,
2023-01-04 14:51:23 +00:00
'balance': balance[currency]!.toJSON(),
2023-01-03 20:19:02 +00:00
// TODO: save other attributes
});
2023-01-04 14:51:23 +00:00
2023-01-05 19:05:44 +00:00
static Future<EthereumWallet> open({
required String name,
required String password,
required WalletInfo walletInfo,
}) async {
final path = await pathForWallet(name: name, type: walletInfo.type);
final jsonSource = await read(path: path, password: password);
final data = json.decode(jsonSource) as Map;
final mnemonic = data['mnemonic'] as String;
final balance = EthereumBalance.fromJSON(data['balance'] as String) ??
EthereumBalance(available: 0, additional: 0);
return EthereumWallet(
walletInfo: walletInfo,
password: password,
mnemonic: mnemonic,
initialBalance: balance,
);
}
2023-01-04 14:51:23 +00:00
Future<void> _updateBalance() async {
balance[currency] = await _fetchBalances();
await save();
}
Future<EthereumBalance> _fetchBalances() async {
final balance = await _client.getBalance(privateKey);
2023-01-05 19:05:44 +00:00
return EthereumBalance(
available: balance.getInEther.toInt(),
additional: balance.getInEther.toInt(),
);
}
Future<String> getPrivateKey(String mnemonic, String password) async {
final seed = bip39.mnemonicToSeedHex(mnemonic);
final master = await ED25519_HD_KEY.getMasterKeyFromSeed(
HEX.decode(seed),
masterSecret: password,
);
2023-01-05 19:05:44 +00:00
final privateKey = HEX.encode(master.key);
return privateKey;
2023-01-04 14:51:23 +00:00
}
2022-12-28 15:02:04 +00:00
}