cake_wallet/cw_ethereum/lib/ethereum_wallet.dart

263 lines
7.7 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:bip39/bip39.dart' as bip39;
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-04-05 16:01:20 +00:00
{CryptoCurrency.eth: initialBalance ?? EthereumBalance(EtherAmount.zero())}),
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-04-05 16:01:20 +00:00
late final EthPrivateKey _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-04-05 16:01:20 +00:00
walletAddresses.address = _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 {
final _credentials = credentials as EthereumTransactionCredentials;
final outputs = _credentials.outputs;
final hasMultiDestination = outputs.length > 1;
2023-04-05 16:01:20 +00:00
final balance = await _client.getBalance(_privateKey.address);
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-04-05 17:20:25 +00:00
final transactionInfo = await _client.signTransaction(
2023-04-05 16:01:20 +00:00
_privateKey,
_credentials.outputs.first.address,
totalAmount.toString(),
_priorityFees[_credentials.priority!.raw],
);
2023-03-31 18:41:56 +00:00
2023-03-16 17:24:21 +00:00
return PendingEthereumTransaction(
2023-04-05 17:20:25 +00:00
sendTransaction: () => _client.sendTransaction(_privateKey, transactionInfo),
transactionInformation: transactionInfo,
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
});
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;
2023-04-05 16:01:20 +00:00
final balance =
EthereumBalance.fromJSON(data['balance'] as String) ?? EthereumBalance(EtherAmount.zero());
2023-01-05 19:05:44 +00:00
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-04-05 16:01:20 +00:00
final balance = await _client.getBalance(_privateKey.address);
return EthereumBalance(balance);
2023-01-05 19:05:44 +00:00
}
2023-04-05 16:01:20 +00:00
Future<EthPrivateKey> getPrivateKey(String mnemonic, String password) async {
2023-01-05 19:05:44 +00:00
final seed = bip39.mnemonicToSeedHex(mnemonic);
2023-04-05 16:01:20 +00:00
return EthPrivateKey.fromHex(seed);
2023-01-04 14:51:23 +00:00
}
2022-12-28 15:02:04 +00:00
}