cake_wallet/cw_ethereum/lib/ethereum_wallet.dart

314 lines
9.4 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-06-21 00:46:58 +00:00
import 'package:cw_ethereum/models/erc20_token.dart';
import 'package:hive/hive.dart';
import 'package:hex/hex.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;
import 'package:bip32/bip32.dart' as bip32;
2022-12-28 15:02:04 +00:00
part 'ethereum_wallet.g.dart';
class EthereumWallet = EthereumWalletBase with _$EthereumWallet;
abstract class EthereumWalletBase
2023-05-23 18:31:54 +00:00
extends WalletBase<ERC20Balance, EthereumTransactionHistory, EthereumTransactionInfo>
2022-12-28 15:02:04 +00:00
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-05-23 18:31:54 +00:00
ERC20Balance? 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-05-23 18:31:54 +00:00
balance = ObservableMap<CryptoCurrency, ERC20Balance>.of(
{CryptoCurrency.eth: initialBalance ?? ERC20Balance(BigInt.zero)}),
2023-01-03 20:19:02 +00:00
super(walletInfo) {
this.walletInfo = walletInfo;
2023-06-21 00:46:58 +00:00
if (!Hive.isAdapterRegistered(Erc20Token.typeId)) {
Hive.registerAdapter(Erc20TokenAdapter());
}
2023-01-03 20:19:02 +00:00
}
2023-01-05 19:05:44 +00:00
final String _mnemonic;
2023-01-03 20:19:02 +00:00
final String _password;
2023-06-21 00:46:58 +00:00
late final Box<Erc20Token> erc20TokensBox;
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
2023-05-23 18:31:54 +00:00
late ObservableMap<CryptoCurrency, ERC20Balance> balance;
2023-01-03 20:19:02 +00:00
2023-01-05 19:05:44 +00:00
Future<void> init() async {
2023-06-21 00:46:58 +00:00
erc20TokensBox = await Hive.openBox<Erc20Token>(Erc20Token.boxName);
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() {
_client.stop();
}
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> 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");
}
_client.setListeners(_privateKey.address, _onNewTransaction);
2023-01-04 14:51:23 +00:00
_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-06-02 01:02:43 +00:00
final _erc20Balance = balance[_credentials.currency]!;
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-06-02 01:02:43 +00:00
if (_erc20Balance.balance < EtherAmount.inWei(totalAmount as BigInt).getInWei) {
2023-03-31 18:41:56 +00:00
throw EthereumTransactionCreationException();
}
} else {
final output = outputs.first;
2023-06-02 01:02:43 +00:00
final int allAmount = _erc20Balance.balance.toInt() - feeRate(_credentials.priority!);
2023-03-31 18:41:56 +00:00
totalAmount = output.sendAll ? allAmount : output.formattedCryptoAmount ?? 0;
2023-03-31 18:41:56 +00:00
if ((output.sendAll &&
2023-06-02 01:02:43 +00:00
_erc20Balance.balance < EtherAmount.inWei(totalAmount as BigInt).getInWei) ||
(!output.sendAll && _erc20Balance.balance.toInt() <= 0)) {
2023-03-31 18:41:56 +00:00
throw EthereumTransactionCreationException();
}
}
2023-03-16 17:24:21 +00:00
final pendingEthereumTransaction = await _client.signTransaction(
2023-06-02 01:02:43 +00:00
privateKey: _privateKey,
toAddress: _credentials.outputs.first.address,
amount: totalAmount.toString(),
gas: _priorityFees[_credentials.priority!.raw],
priority: _credentials.priority!,
currency: _credentials.currency,
2023-04-05 16:01:20 +00:00
);
2023-03-31 18:41:56 +00:00
return pendingEthereumTransaction;
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) {
2023-01-04 14:51:23 +00:00
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-06-02 01:02:43 +00:00
final balance = ERC20Balance.fromJSON(data['balance'] as String) ?? ERC20Balance(BigInt.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();
2023-06-21 00:46:58 +00:00
/// Get Erc20 Tokens balances
for (var token in erc20TokensBox.values) {
try {
final currency = erc20Currencies.firstWhere((element) => element.title == token.symbol);
balance[currency] =
await _client.fetchERC20Balances(_privateKey.address, token.contractAddress);
} catch (_) {}
}
2023-01-04 14:51:23 +00:00
await save();
}
2023-05-23 18:31:54 +00:00
Future<ERC20Balance> _fetchBalances() async {
2023-04-05 16:01:20 +00:00
final balance = await _client.getBalance(_privateKey.address);
2023-05-23 18:31:54 +00:00
return ERC20Balance(balance.getInWei);
2023-01-05 19:05:44 +00:00
}
2023-04-05 16:01:20 +00:00
Future<EthPrivateKey> getPrivateKey(String mnemonic, String password) async {
final seed = bip39.mnemonicToSeed(mnemonic);
final root = bip32.BIP32.fromSeed(seed);
const _hdPathEthereum = "m/44'/60'/0'/0";
const index = 0;
final addressAtIndex = root.derivePath("$_hdPathEthereum/$index");
return EthPrivateKey.fromHex(HEX.encode(addressAtIndex.privateKey as List<int>));
2023-01-04 14:51:23 +00:00
}
2023-04-28 02:39:54 +00:00
Future<void>? updateBalance() => null;
2023-06-02 01:02:43 +00:00
2023-06-21 00:46:58 +00:00
List<CryptoCurrency> get erc20Currencies => erc20TokensBox.values
.map((token) => CryptoCurrency.all.firstWhere(
(currency) => currency.title.toLowerCase() == token.symbol.toLowerCase(),
orElse: () => CryptoCurrency(
name: token.name,
title: token.symbol,
fullName: token.name,
),
))
.toList();
Future<CryptoCurrency> addErc20Token(String contractAddress) async {
final token = await _client.addErc20Token(contractAddress);
erc20TokensBox.add(token);
return CryptoCurrency(name: token.name, title: token.symbol, fullName: token.name);
}
void _onNewTransaction(FilterEvent event) {
_updateBalance();
// TODO: Add in transaction history
}
2022-12-28 15:02:04 +00:00
}