cake_wallet/cw_ethereum/lib/ethereum_wallet.dart

273 lines
8 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';
2023-03-16 17:24:21 +00:00
import 'package:cw_ethereum/ethereum_exceptions.dart';
import 'package:cw_ethereum/ethereum_transaction_credentials.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';
2023-03-16 17:24:21 +00:00
import 'package:cw_ethereum/pending_ethereum_transaction.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,
2023-01-13 17:10:38 +00:00
_priorityFees = [],
_client = EthereumClient(),
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-03-16 17:24:21 +00:00
late final String _privateKey;
2023-01-05 19:05:44 +00:00
2023-01-04 14:51:23 +00:00
late EthereumClient _client;
2023-01-13 17:10:38 +00:00
List<int> _priorityFees;
int? _gasPrice;
2023-01-04 14:51:23 +00:00
@override
WalletAddresses walletAddresses;
2023-01-03 20:19:02 +00:00
@override
@observable
2023-01-03 20:19:02 +00:00
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 {
2023-03-31 18:41:56 +00:00
await walletAddresses.init();
2023-03-16 17:24:21 +00:00
_privateKey = await getPrivateKey(_mnemonic, _password);
2023-01-05 19:05:44 +00:00
transactionHistory = EthereumTransactionHistory();
2023-03-16 17:24:21 +00:00
walletAddresses.address = EthPrivateKey.fromHex(_privateKey).address.toString();
2023-01-05 19:05:44 +00:00
}
2023-01-03 20:19:02 +00:00
@override
int calculateEstimatedFee(TransactionPriority priority, int? amount) {
2023-01-13 17:10:38 +00:00
try {
if (priority is EthereumTransactionPriority) {
return _gasPrice! * _priorityFees[priority.raw];
}
return 0;
} catch (e) {
return 0;
}
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() {}
@action
2023-01-03 20:19:02 +00:00
@override
2023-01-04 14:51:23 +00:00
Future<void> connectToNode({required Node node}) async {
try {
syncStatus = ConnectingSyncStatus();
2023-01-13 17:10:38 +00:00
final isConnected = _client.connect(node);
2023-01-04 14:51:23 +00:00
if (!isConnected) {
throw Exception("Ethereum Node connection failed");
}
_updateBalance();
syncStatus = ConnectedSyncStatus();
} catch (e) {
syncStatus = FailedSyncStatus();
}
2023-01-03 20:19:02 +00:00
}
@override
2023-03-16 17:24:21 +00:00
Future<PendingTransaction> createTransaction(Object credentials) async {
2023-03-31 18:41:56 +00:00
print("!!!!!!!!!!!!!!!!!!!");
2023-03-16 17:24:21 +00:00
final _credentials = credentials as EthereumTransactionCredentials;
final outputs = _credentials.outputs;
final hasMultiDestination = outputs.length > 1;
final balance = await _client.getBalance(_privateKey);
2023-03-31 18:41:56 +00:00
int totalAmount = 0;
2023-03-16 17:24:21 +00:00
if (hasMultiDestination) {
2023-03-31 18:41:56 +00:00
if (outputs.any((item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) {
throw EthereumTransactionCreationException();
}
2023-03-31 18:41:56 +00:00
totalAmount = outputs.fold(0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0));
2023-03-31 18:41:56 +00:00
if (balance.getInWei < EtherAmount.inWei(totalAmount as BigInt).getInWei) {
throw EthereumTransactionCreationException();
}
} else {
final output = outputs.first;
2023-03-31 18:41:56 +00:00
final int allAmount = balance.getInWei.toInt() - feeRate(_credentials.priority!);
totalAmount = output.sendAll ? allAmount : output.formattedCryptoAmount ?? 0;
2023-03-31 18:41:56 +00:00
if ((output.sendAll &&
balance.getInWei < EtherAmount.inWei(totalAmount as BigInt).getInWei) ||
(!output.sendAll && balance.getInWei.toInt() <= 0)) {
throw EthereumTransactionCreationException();
}
}
2023-03-16 17:24:21 +00:00
2023-03-31 18:41:56 +00:00
await _client.signTransaction(_privateKey, _credentials.outputs.first.address, totalAmount.toString());
2023-03-16 17:24:21 +00:00
return PendingEthereumTransaction(
client: _client,
credentials: _credentials,
privateKey: _privateKey,
2023-03-31 18:41:56 +00:00
amount: totalAmount,
2023-03-16 17:24:21 +00:00
);
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 {
2023-03-31 18:41:56 +00:00
await walletAddresses.updateAddressesInBox();
2023-01-03 20:19:02 +00:00
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
@action
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();
2023-01-13 17:10:38 +00:00
_priorityFees = 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),
2023-01-13 17:10:38 +00:00
(timer) async => _priorityFees = 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) {
2023-01-13 17:10:38 +00:00
return _priorityFees[priority.raw];
}
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 {
2023-03-16 17:24:21 +00:00
final balance = await _client.getBalance(_privateKey);
2023-01-04 14:51:23 +00:00
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
}