mirror of
https://github.com/cake-tech/cake_wallet.git
synced 2025-06-28 12:29:51 +00:00
CW-551-Refactor-EVM-Chains (#1256)
* feat: Create central package for EVM chains * chore: Cleanup pubspec and add core evm dependencies * feat: Replicated core evm chain files, time to start fixing the issues * feat: Setup evm central package to handle all evm chains * feat: Link up Polygon and Ethereum wallets to the centra evm package, fix bugs and issues, and optimze for better performance * feat: Setup and adjust configs to reflect new evm configurations * Remove unneeded file * fix: Changes done while re-reviewing entire structure and refactor * fix: Add evm chain wallet path to imports in configure file * feat: Adjust implementation of parent class, remove unneeded files, remove windows, linux and mac directories, restructure the evm child classes * fix: Make EVMChainWallet a central abstract class and adjust accordingly * fix: Adjust transaction info, restructure EVMWalletChain to be an abstract, adjust external facing interfaces for polygon and ethereum, adjust configuration for ethereum and polygon in configure file * fix: Testing issues * fix: Add localization for nft tile and details page texts and add dashes for null responses * fix: merge conflicts * Minor fixes for building Monero.com --------- Co-authored-by: OmarHatem <omarh.ismail1@gmail.com>
This commit is contained in:
parent
b92ccb5c0b
commit
7410daacff
90 changed files with 1775 additions and 2041 deletions
30
cw_evm/.gitignore
vendored
Normal file
30
cw_evm/.gitignore
vendored
Normal file
|
@ -0,0 +1,30 @@
|
|||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
.packages
|
||||
build/
|
10
cw_evm/.metadata
Normal file
10
cw_evm/.metadata
Normal file
|
@ -0,0 +1,10 @@
|
|||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: f468f3366c26a5092eb964a230ce7892fda8f2f8
|
||||
channel: stable
|
||||
|
||||
project_type: package
|
3
cw_evm/CHANGELOG.md
Normal file
3
cw_evm/CHANGELOG.md
Normal file
|
@ -0,0 +1,3 @@
|
|||
## 0.0.1
|
||||
|
||||
* TODO: Describe initial release.
|
1
cw_evm/LICENSE
Normal file
1
cw_evm/LICENSE
Normal file
|
@ -0,0 +1 @@
|
|||
TODO: Add your license here.
|
39
cw_evm/README.md
Normal file
39
cw_evm/README.md
Normal file
|
@ -0,0 +1,39 @@
|
|||
<!--
|
||||
This README describes the package. If you publish this package to pub.dev,
|
||||
this README's contents appear on the landing page for your package.
|
||||
|
||||
For information about how to write a good package README, see the guide for
|
||||
[writing package pages](https://dart.dev/guides/libraries/writing-package-pages).
|
||||
|
||||
For general information about developing packages, see the Dart guide for
|
||||
[creating packages](https://dart.dev/guides/libraries/create-library-packages)
|
||||
and the Flutter guide for
|
||||
[developing packages and plugins](https://flutter.dev/developing-packages).
|
||||
-->
|
||||
|
||||
TODO: Put a short description of the package here that helps potential users
|
||||
know whether this package might be useful for them.
|
||||
|
||||
## Features
|
||||
|
||||
TODO: List what your package can do. Maybe include images, gifs, or videos.
|
||||
|
||||
## Getting started
|
||||
|
||||
TODO: List prerequisites and provide or point to information on how to
|
||||
start using the package.
|
||||
|
||||
## Usage
|
||||
|
||||
TODO: Include short and useful examples for package users. Add longer examples
|
||||
to `/example` folder.
|
||||
|
||||
```dart
|
||||
const like = 'sample';
|
||||
```
|
||||
|
||||
## Additional information
|
||||
|
||||
TODO: Tell users more about the package: where to find more information, how to
|
||||
contribute to the package, how to file issues, what response they can expect
|
||||
from the package authors, and more.
|
4
cw_evm/analysis_options.yaml
Normal file
4
cw_evm/analysis_options.yaml
Normal file
|
@ -0,0 +1,4 @@
|
|||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
# Additional information about this file can be found at
|
||||
# https://dart.dev/guides/language/analysis-options
|
7
cw_evm/lib/cw_evm.dart
Normal file
7
cw_evm/lib/cw_evm.dart
Normal file
|
@ -0,0 +1,7 @@
|
|||
library cw_evm;
|
||||
|
||||
/// A Calculator.
|
||||
class Calculator {
|
||||
/// Returns [value] plus 1.
|
||||
int addOne(int value) => value + 1;
|
||||
}
|
251
cw_evm/lib/evm_chain_client.dart
Normal file
251
cw_evm/lib/evm_chain_client.dart
Normal file
|
@ -0,0 +1,251 @@
|
|||
import 'dart:async';
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:cw_core/node.dart';
|
||||
import 'package:cw_core/erc20_token.dart';
|
||||
import 'package:cw_core/crypto_currency.dart';
|
||||
|
||||
import 'package:cw_evm/evm_erc20_balance.dart';
|
||||
import 'package:cw_evm/evm_chain_transaction_model.dart';
|
||||
import 'package:cw_evm/pending_evm_chain_transaction.dart';
|
||||
import 'package:cw_evm/evm_chain_transaction_priority.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'package:http/http.dart';
|
||||
import 'package:erc20/erc20.dart';
|
||||
import 'package:web3dart/web3dart.dart';
|
||||
|
||||
abstract class EVMChainClient {
|
||||
final httpClient = Client();
|
||||
Web3Client? _client;
|
||||
|
||||
//! To be overridden by all child classes
|
||||
|
||||
int get chainId;
|
||||
|
||||
Future<List<EVMChainTransactionModel>> fetchTransactions(String address,
|
||||
{String? contractAddress});
|
||||
|
||||
Uint8List prepareSignedTransactionForSending(Uint8List signedTransaction);
|
||||
|
||||
//! Common methods across all child classes
|
||||
|
||||
bool connect(Node node) {
|
||||
try {
|
||||
_client = Web3Client(node.uri.toString(), httpClient);
|
||||
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void setListeners(EthereumAddress userAddress, Function() onNewTransaction) async {
|
||||
// _client?.pendingTransactions().listen((transactionHash) async {
|
||||
// final transaction = await _client!.getTransactionByHash(transactionHash);
|
||||
//
|
||||
// if (transaction.from.hex == userAddress || transaction.to?.hex == userAddress) {
|
||||
// onNewTransaction();
|
||||
// }
|
||||
// });
|
||||
}
|
||||
|
||||
Future<EtherAmount> getBalance(EthereumAddress address) async {
|
||||
try {
|
||||
return await _client!.getBalance(address);
|
||||
} catch (_) {
|
||||
return EtherAmount.zero();
|
||||
}
|
||||
}
|
||||
|
||||
Future<int> getGasUnitPrice() async {
|
||||
try {
|
||||
final gasPrice = await _client!.getGasPrice();
|
||||
return gasPrice.getInWei.toInt();
|
||||
} catch (_) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Future<int> getEstimatedGas() async {
|
||||
try {
|
||||
final estimatedGas = await _client!.estimateGas();
|
||||
return estimatedGas.toInt();
|
||||
} catch (_) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Future<PendingEVMChainTransaction> signTransaction({
|
||||
required EthPrivateKey privateKey,
|
||||
required String toAddress,
|
||||
required String amount,
|
||||
required int gas,
|
||||
required EVMChainTransactionPriority priority,
|
||||
required CryptoCurrency currency,
|
||||
required int exponent,
|
||||
String? contractAddress,
|
||||
}) async {
|
||||
assert(currency == CryptoCurrency.eth ||
|
||||
currency == CryptoCurrency.maticpoly ||
|
||||
contractAddress != null);
|
||||
|
||||
bool isEVMCompatibleChain =
|
||||
currency == CryptoCurrency.eth || currency == CryptoCurrency.maticpoly;
|
||||
|
||||
final price = _client!.getGasPrice();
|
||||
|
||||
final Transaction transaction = createTransaction(
|
||||
from: privateKey.address,
|
||||
to: EthereumAddress.fromHex(toAddress),
|
||||
maxPriorityFeePerGas: EtherAmount.fromInt(EtherUnit.gwei, priority.tip),
|
||||
amount: isEVMCompatibleChain ? EtherAmount.inWei(BigInt.parse(amount)) : EtherAmount.zero(),
|
||||
);
|
||||
|
||||
final signedTransaction =
|
||||
await _client!.signTransaction(privateKey, transaction, chainId: chainId);
|
||||
|
||||
final Function _sendTransaction;
|
||||
|
||||
if (isEVMCompatibleChain) {
|
||||
_sendTransaction = () async => await sendTransaction(signedTransaction);
|
||||
} else {
|
||||
final erc20 = ERC20(
|
||||
client: _client!,
|
||||
address: EthereumAddress.fromHex(contractAddress!),
|
||||
chainId: chainId,
|
||||
);
|
||||
|
||||
_sendTransaction = () async {
|
||||
await erc20.transfer(
|
||||
EthereumAddress.fromHex(toAddress),
|
||||
BigInt.parse(amount),
|
||||
credentials: privateKey,
|
||||
transaction: transaction,
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
return PendingEVMChainTransaction(
|
||||
signedTransaction: signedTransaction,
|
||||
amount: amount,
|
||||
fee: BigInt.from(gas) * (await price).getInWei,
|
||||
sendTransaction: _sendTransaction,
|
||||
exponent: exponent,
|
||||
);
|
||||
}
|
||||
|
||||
Transaction createTransaction({
|
||||
required EthereumAddress from,
|
||||
required EthereumAddress to,
|
||||
required EtherAmount amount,
|
||||
EtherAmount? maxPriorityFeePerGas,
|
||||
}) {
|
||||
return Transaction(
|
||||
from: from,
|
||||
to: to,
|
||||
maxPriorityFeePerGas: maxPriorityFeePerGas,
|
||||
value: amount,
|
||||
);
|
||||
}
|
||||
|
||||
Future<String> sendTransaction(Uint8List signedTransaction) async =>
|
||||
await _client!.sendRawTransaction(prepareSignedTransactionForSending(signedTransaction));
|
||||
|
||||
Future getTransactionDetails(String transactionHash) async {
|
||||
// Wait for the transaction receipt to become available
|
||||
TransactionReceipt? receipt;
|
||||
while (receipt == null) {
|
||||
receipt = await _client!.getTransactionReceipt(transactionHash);
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
}
|
||||
|
||||
// Print the receipt information
|
||||
log('Transaction Hash: ${receipt.transactionHash}');
|
||||
log('Block Hash: ${receipt.blockHash}');
|
||||
log('Block Number: ${receipt.blockNumber}');
|
||||
log('Gas Used: ${receipt.gasUsed}');
|
||||
|
||||
/*
|
||||
Transaction Hash: [112, 244, 4, 238, 89, 199, 171, 191, 210, 236, 110, 42, 185, 202, 220, 21, 27, 132, 123, 221, 137, 90, 77, 13, 23, 43, 12, 230, 93, 63, 221, 116]
|
||||
I/flutter ( 4474): Block Hash: [149, 44, 250, 119, 111, 104, 82, 98, 17, 89, 30, 190, 25, 44, 218, 118, 127, 189, 241, 35, 213, 106, 25, 95, 195, 37, 55, 131, 185, 180, 246, 200]
|
||||
I/flutter ( 4474): Block Number: 17120242
|
||||
I/flutter ( 4474): Gas Used: 21000
|
||||
*/
|
||||
|
||||
// Wait for the transaction receipt to become available
|
||||
TransactionInformation? transactionInformation;
|
||||
while (transactionInformation == null) {
|
||||
log("********************************");
|
||||
transactionInformation = await _client!.getTransactionByHash(transactionHash);
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
}
|
||||
// Print the receipt information
|
||||
log('Transaction Hash: ${transactionInformation.hash}');
|
||||
log('Block Hash: ${transactionInformation.blockHash}');
|
||||
log('Block Number: ${transactionInformation.blockNumber}');
|
||||
log('Gas Used: ${transactionInformation.gas}');
|
||||
|
||||
/*
|
||||
Transaction Hash: 0x70f404ee59c7abbfd2ec6e2ab9cadc151b847bdd895a4d0d172b0ce65d3fdd74
|
||||
I/flutter ( 4474): Block Hash: 0x952cfa776f68526211591ebe192cda767fbdf123d56a195fc3253783b9b4f6c8
|
||||
I/flutter ( 4474): Block Number: 17120242
|
||||
I/flutter ( 4474): Gas Used: 53000
|
||||
*/
|
||||
}
|
||||
|
||||
Future<EVMChainERC20Balance> fetchERC20Balances(
|
||||
EthereumAddress userAddress, String contractAddress) async {
|
||||
final erc20 = ERC20(address: EthereumAddress.fromHex(contractAddress), client: _client!);
|
||||
final balance = await erc20.balanceOf(userAddress);
|
||||
|
||||
int exponent = (await erc20.decimals()).toInt();
|
||||
|
||||
return EVMChainERC20Balance(balance, exponent: exponent);
|
||||
}
|
||||
|
||||
Future<Erc20Token?> getErc20Token(String contractAddress) async {
|
||||
try {
|
||||
final erc20 = ERC20(address: EthereumAddress.fromHex(contractAddress), client: _client!);
|
||||
final name = await erc20.name();
|
||||
final symbol = await erc20.symbol();
|
||||
final decimal = await erc20.decimals();
|
||||
|
||||
return Erc20Token(
|
||||
name: name,
|
||||
symbol: symbol,
|
||||
contractAddress: contractAddress,
|
||||
decimal: decimal.toInt(),
|
||||
);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void stop() {
|
||||
_client?.dispose();
|
||||
}
|
||||
|
||||
Web3Client? getWeb3Client() {
|
||||
return _client;
|
||||
}
|
||||
|
||||
// Future<int> _getDecimalPlacesForContract(DeployedContract contract) async {
|
||||
// final String abi = await rootBundle.loadString("assets/abi_json/erc20_abi.json");
|
||||
// final contractAbi = ContractAbi.fromJson(abi, "ERC20");
|
||||
//
|
||||
// final contract = DeployedContract(
|
||||
// contractAbi,
|
||||
// EthereumAddress.fromHex(_erc20Currencies[erc20Currency]!),
|
||||
// );
|
||||
// final decimalsFunction = contract.function('decimals');
|
||||
// final decimals = await _client!.call(
|
||||
// contract: contract,
|
||||
// function: decimalsFunction,
|
||||
// params: [],
|
||||
// );
|
||||
//
|
||||
// int exponent = int.parse(decimals.first.toString());
|
||||
// return exponent;
|
||||
// }
|
||||
}
|
11
cw_evm/lib/evm_chain_exceptions.dart
Normal file
11
cw_evm/lib/evm_chain_exceptions.dart
Normal file
|
@ -0,0 +1,11 @@
|
|||
import 'package:cw_core/crypto_currency.dart';
|
||||
|
||||
class EVMChainTransactionCreationException implements Exception {
|
||||
final String exceptionMessage;
|
||||
|
||||
EVMChainTransactionCreationException(CryptoCurrency currency)
|
||||
: exceptionMessage = 'Wrong balance. Not enough ${currency.title} on your balance.';
|
||||
|
||||
@override
|
||||
String toString() => exceptionMessage;
|
||||
}
|
25
cw_evm/lib/evm_chain_formatter.dart
Normal file
25
cw_evm/lib/evm_chain_formatter.dart
Normal file
|
@ -0,0 +1,25 @@
|
|||
import 'package:intl/intl.dart';
|
||||
|
||||
const evmChainAmountLength = 12;
|
||||
const evmChainAmountDivider = 1000000000000;
|
||||
final evmChainAmountFormat = NumberFormat()
|
||||
..maximumFractionDigits = evmChainAmountLength
|
||||
..minimumFractionDigits = 1;
|
||||
|
||||
class EVMChainFormatter {
|
||||
static int parseEVMChainAmount(String amount) {
|
||||
try {
|
||||
return (double.parse(amount) * evmChainAmountDivider).round();
|
||||
} catch (_) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static double parseEVMChainAmountToDouble(int amount) {
|
||||
try {
|
||||
return amount / evmChainAmountDivider;
|
||||
} catch (_) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
2052
cw_evm/lib/evm_chain_mnemonics.dart
Normal file
2052
cw_evm/lib/evm_chain_mnemonics.dart
Normal file
File diff suppressed because it is too large
Load diff
17
cw_evm/lib/evm_chain_transaction_credentials.dart
Normal file
17
cw_evm/lib/evm_chain_transaction_credentials.dart
Normal file
|
@ -0,0 +1,17 @@
|
|||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_core/output_info.dart';
|
||||
import 'package:cw_evm/evm_chain_transaction_priority.dart';
|
||||
|
||||
class EVMChainTransactionCredentials {
|
||||
EVMChainTransactionCredentials(
|
||||
this.outputs, {
|
||||
required this.priority,
|
||||
required this.currency,
|
||||
this.feeRate,
|
||||
});
|
||||
|
||||
final List<OutputInfo> outputs;
|
||||
final EVMChainTransactionPriority? priority;
|
||||
final int? feeRate;
|
||||
final CryptoCurrency currency;
|
||||
}
|
88
cw_evm/lib/evm_chain_transaction_history.dart
Normal file
88
cw_evm/lib/evm_chain_transaction_history.dart
Normal file
|
@ -0,0 +1,88 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:core';
|
||||
import 'dart:developer';
|
||||
import 'package:cw_core/pathForWallet.dart';
|
||||
import 'package:cw_core/wallet_info.dart';
|
||||
import 'package:cw_evm/evm_chain_transaction_info.dart';
|
||||
import 'package:cw_evm/file.dart';
|
||||
import 'package:mobx/mobx.dart';
|
||||
import 'package:cw_core/transaction_history.dart';
|
||||
|
||||
part 'evm_chain_transaction_history.g.dart';
|
||||
|
||||
abstract class EVMChainTransactionHistory = EVMChainTransactionHistoryBase
|
||||
with _$EVMChainTransactionHistory;
|
||||
|
||||
abstract class EVMChainTransactionHistoryBase
|
||||
extends TransactionHistoryBase<EVMChainTransactionInfo> with Store {
|
||||
EVMChainTransactionHistoryBase({required this.walletInfo, required String password})
|
||||
: _password = password {
|
||||
transactions = ObservableMap<String, EVMChainTransactionInfo>();
|
||||
}
|
||||
|
||||
String _password;
|
||||
|
||||
final WalletInfo walletInfo;
|
||||
|
||||
//! Method to be overridden by all child classes
|
||||
|
||||
String getTransactionHistoryFileName();
|
||||
|
||||
EVMChainTransactionInfo getTransactionInfo(Map<String, dynamic> val);
|
||||
|
||||
//! Common methods across all child classes
|
||||
|
||||
Future<void> init() async => await _load();
|
||||
|
||||
@override
|
||||
Future<void> save() async {
|
||||
final transactionsHistoryFileNameForWallet = getTransactionHistoryFileName();
|
||||
try {
|
||||
final dirPath = await pathForWalletDir(name: walletInfo.name, type: walletInfo.type);
|
||||
String path = '$dirPath/$transactionsHistoryFileNameForWallet';
|
||||
final data = json.encode({'transactions': transactions});
|
||||
await writeData(path: path, password: _password, data: data);
|
||||
} catch (e, s) {
|
||||
log('Error while saving ${walletInfo.type.name} transaction history: ${e.toString()}');
|
||||
log(s.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void addOne(EVMChainTransactionInfo transaction) => transactions[transaction.id] = transaction;
|
||||
|
||||
@override
|
||||
void addMany(Map<String, EVMChainTransactionInfo> transactions) =>
|
||||
this.transactions.addAll(transactions);
|
||||
|
||||
Future<Map<String, dynamic>> _read() async {
|
||||
final transactionsHistoryFileNameForWallet = getTransactionHistoryFileName();
|
||||
final dirPath = await pathForWalletDir(name: walletInfo.name, type: walletInfo.type);
|
||||
String path = '$dirPath/$transactionsHistoryFileNameForWallet';
|
||||
final content = await read(path: path, password: _password);
|
||||
if (content.isEmpty) {
|
||||
return {};
|
||||
}
|
||||
return json.decode(content) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
try {
|
||||
final content = await _read();
|
||||
final txs = content['transactions'] as Map<String, dynamic>? ?? {};
|
||||
|
||||
for (var entry in txs.entries) {
|
||||
final val = entry.value;
|
||||
|
||||
if (val is Map<String, dynamic>) {
|
||||
final tx = getTransactionInfo(val);
|
||||
_update(tx);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
void _update(EVMChainTransactionInfo transaction) => transactions[transaction.id] = transaction;
|
||||
}
|
77
cw_evm/lib/evm_chain_transaction_info.dart
Normal file
77
cw_evm/lib/evm_chain_transaction_info.dart
Normal file
|
@ -0,0 +1,77 @@
|
|||
// ignore_for_file: overridden_fields, annotate_overrides
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:cw_core/format_amount.dart';
|
||||
import 'package:cw_core/transaction_direction.dart';
|
||||
import 'package:cw_core/transaction_info.dart';
|
||||
|
||||
abstract class EVMChainTransactionInfo extends TransactionInfo {
|
||||
EVMChainTransactionInfo({
|
||||
required this.id,
|
||||
required this.height,
|
||||
required this.ethAmount,
|
||||
required this.ethFee,
|
||||
required this.tokenSymbol,
|
||||
this.exponent = 18,
|
||||
required this.direction,
|
||||
required this.isPending,
|
||||
required this.date,
|
||||
required this.confirmations,
|
||||
required this.to,
|
||||
required this.from,
|
||||
}) : amount = ethAmount.toInt(),
|
||||
fee = ethFee.toInt();
|
||||
|
||||
final String id;
|
||||
final int height;
|
||||
final int amount;
|
||||
final BigInt ethAmount;
|
||||
final int exponent;
|
||||
final TransactionDirection direction;
|
||||
final DateTime date;
|
||||
final bool isPending;
|
||||
final int fee;
|
||||
final BigInt ethFee;
|
||||
final int confirmations;
|
||||
final String tokenSymbol;
|
||||
String? _fiatAmount;
|
||||
final String? to;
|
||||
final String? from;
|
||||
|
||||
//! Getter to be overridden in child classes
|
||||
String get feeCurrency;
|
||||
|
||||
@override
|
||||
String amountFormatted() {
|
||||
final amount = formatAmount((ethAmount / BigInt.from(10).pow(exponent)).toString());
|
||||
return '${amount.substring(0, min(10, amount.length))} $tokenSymbol';
|
||||
}
|
||||
|
||||
@override
|
||||
String fiatAmount() => _fiatAmount ?? '';
|
||||
|
||||
@override
|
||||
void changeFiatAmount(String amount) => _fiatAmount = formatAmount(amount);
|
||||
|
||||
@override
|
||||
String feeFormatted() {
|
||||
final amount = (ethFee / BigInt.from(10).pow(18)).toString();
|
||||
return '${amount.substring(0, min(10, amount.length))} $feeCurrency';
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'height': height,
|
||||
'amount': ethAmount.toString(),
|
||||
'exponent': exponent,
|
||||
'fee': ethFee.toString(),
|
||||
'direction': direction.index,
|
||||
'date': date.millisecondsSinceEpoch,
|
||||
'isPending': isPending,
|
||||
'confirmations': confirmations,
|
||||
'tokenSymbol': tokenSymbol,
|
||||
'to': to,
|
||||
'from': from,
|
||||
};
|
||||
}
|
48
cw_evm/lib/evm_chain_transaction_model.dart
Normal file
48
cw_evm/lib/evm_chain_transaction_model.dart
Normal file
|
@ -0,0 +1,48 @@
|
|||
class EVMChainTransactionModel {
|
||||
final DateTime date;
|
||||
final String hash;
|
||||
final String from;
|
||||
final String to;
|
||||
final BigInt amount;
|
||||
final int gasUsed;
|
||||
final BigInt gasPrice;
|
||||
final String contractAddress;
|
||||
final int confirmations;
|
||||
final int blockNumber;
|
||||
final String? tokenSymbol;
|
||||
final int? tokenDecimal;
|
||||
final bool isError;
|
||||
|
||||
EVMChainTransactionModel({
|
||||
required this.date,
|
||||
required this.hash,
|
||||
required this.from,
|
||||
required this.to,
|
||||
required this.amount,
|
||||
required this.gasUsed,
|
||||
required this.gasPrice,
|
||||
required this.contractAddress,
|
||||
required this.confirmations,
|
||||
required this.blockNumber,
|
||||
required this.tokenSymbol,
|
||||
required this.tokenDecimal,
|
||||
required this.isError,
|
||||
});
|
||||
|
||||
factory EVMChainTransactionModel.fromJson(Map<String, dynamic> json, String defaultSymbol) =>
|
||||
EVMChainTransactionModel(
|
||||
date: DateTime.fromMillisecondsSinceEpoch(int.parse(json["timeStamp"]) * 1000),
|
||||
hash: json["hash"],
|
||||
from: json["from"],
|
||||
to: json["to"],
|
||||
amount: BigInt.parse(json["value"]),
|
||||
gasUsed: int.parse(json["gasUsed"]),
|
||||
gasPrice: BigInt.parse(json["gasPrice"]),
|
||||
contractAddress: json["contractAddress"],
|
||||
confirmations: int.parse(json["confirmations"]),
|
||||
blockNumber: int.parse(json["blockNumber"]),
|
||||
tokenSymbol: json["tokenSymbol"] ?? defaultSymbol,
|
||||
tokenDecimal: int.tryParse(json["tokenDecimal"] ?? ""),
|
||||
isError: json["isError"] == "1",
|
||||
);
|
||||
}
|
52
cw_evm/lib/evm_chain_transaction_priority.dart
Normal file
52
cw_evm/lib/evm_chain_transaction_priority.dart
Normal file
|
@ -0,0 +1,52 @@
|
|||
import 'package:cw_core/transaction_priority.dart';
|
||||
|
||||
class EVMChainTransactionPriority extends TransactionPriority {
|
||||
final int tip;
|
||||
|
||||
const EVMChainTransactionPriority({required String title, required int raw, required this.tip})
|
||||
: super(title: title, raw: raw);
|
||||
|
||||
static const List<EVMChainTransactionPriority> all = [fast, medium, slow];
|
||||
static const EVMChainTransactionPriority slow =
|
||||
EVMChainTransactionPriority(title: 'slow', raw: 0, tip: 1);
|
||||
static const EVMChainTransactionPriority medium =
|
||||
EVMChainTransactionPriority(title: 'Medium', raw: 1, tip: 2);
|
||||
static const EVMChainTransactionPriority fast =
|
||||
EVMChainTransactionPriority(title: 'Fast', raw: 2, tip: 4);
|
||||
|
||||
static EVMChainTransactionPriority deserialize({required int raw}) {
|
||||
switch (raw) {
|
||||
case 0:
|
||||
return slow;
|
||||
case 1:
|
||||
return medium;
|
||||
case 2:
|
||||
return fast;
|
||||
default:
|
||||
throw Exception('Unexpected token: $raw for EVMChainTransactionPriority deserialize');
|
||||
}
|
||||
}
|
||||
|
||||
String get units => 'gas';
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
var label = '';
|
||||
|
||||
switch (this) {
|
||||
case EVMChainTransactionPriority.slow:
|
||||
label = 'Slow';
|
||||
break;
|
||||
case EVMChainTransactionPriority.medium:
|
||||
label = 'Medium';
|
||||
break;
|
||||
case EVMChainTransactionPriority.fast:
|
||||
label = 'Fast';
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return label;
|
||||
}
|
||||
}
|
512
cw_evm/lib/evm_chain_wallet.dart
Normal file
512
cw_evm/lib/evm_chain_wallet.dart
Normal file
|
@ -0,0 +1,512 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:bip32/bip32.dart' as bip32;
|
||||
import 'package:bip39/bip39.dart' as bip39;
|
||||
import 'package:cw_core/cake_hive.dart';
|
||||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_core/erc20_token.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';
|
||||
import 'package:cw_core/wallet_base.dart';
|
||||
import 'package:cw_core/wallet_info.dart';
|
||||
import 'package:cw_core/wallet_type.dart';
|
||||
import 'package:cw_evm/evm_chain_client.dart';
|
||||
import 'package:cw_evm/evm_chain_exceptions.dart';
|
||||
import 'package:cw_evm/evm_chain_formatter.dart';
|
||||
import 'package:cw_evm/evm_chain_transaction_credentials.dart';
|
||||
import 'package:cw_evm/evm_chain_transaction_history.dart';
|
||||
import 'package:cw_evm/evm_chain_transaction_model.dart';
|
||||
import 'package:cw_evm/evm_chain_transaction_priority.dart';
|
||||
import 'package:cw_evm/evm_chain_wallet_addresses.dart';
|
||||
import 'package:cw_evm/file.dart';
|
||||
import 'package:hex/hex.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
import 'package:mobx/mobx.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:web3dart/crypto.dart';
|
||||
import 'package:web3dart/web3dart.dart';
|
||||
|
||||
import 'evm_chain_transaction_info.dart';
|
||||
import 'evm_erc20_balance.dart';
|
||||
|
||||
part 'evm_chain_wallet.g.dart';
|
||||
|
||||
abstract class EVMChainWallet = EVMChainWalletBase with _$EVMChainWallet;
|
||||
|
||||
abstract class EVMChainWalletBase
|
||||
extends WalletBase<EVMChainERC20Balance, EVMChainTransactionHistory, EVMChainTransactionInfo>
|
||||
with Store {
|
||||
EVMChainWalletBase({
|
||||
required WalletInfo walletInfo,
|
||||
required EVMChainClient client,
|
||||
required CryptoCurrency nativeCurrency,
|
||||
String? mnemonic,
|
||||
String? privateKey,
|
||||
required String password,
|
||||
EVMChainERC20Balance? initialBalance,
|
||||
}) : syncStatus = const NotConnectedSyncStatus(),
|
||||
_password = password,
|
||||
_mnemonic = mnemonic,
|
||||
_hexPrivateKey = privateKey,
|
||||
_isTransactionUpdating = false,
|
||||
_client = client,
|
||||
walletAddresses = EVMChainWalletAddresses(walletInfo),
|
||||
balance = ObservableMap<CryptoCurrency, EVMChainERC20Balance>.of(
|
||||
{
|
||||
// Not sure of this yet, will it work? will it not?
|
||||
nativeCurrency: initialBalance ?? EVMChainERC20Balance(BigInt.zero),
|
||||
},
|
||||
),
|
||||
super(walletInfo) {
|
||||
this.walletInfo = walletInfo;
|
||||
transactionHistory = setUpTransactionHistory(walletInfo, password);
|
||||
|
||||
if (!CakeHive.isAdapterRegistered(Erc20Token.typeId)) {
|
||||
CakeHive.registerAdapter(Erc20TokenAdapter());
|
||||
}
|
||||
|
||||
sharedPrefs.complete(SharedPreferences.getInstance());
|
||||
}
|
||||
|
||||
final String? _mnemonic;
|
||||
final String? _hexPrivateKey;
|
||||
final String _password;
|
||||
|
||||
late final Box<Erc20Token> erc20TokensBox;
|
||||
|
||||
late final Box<Erc20Token> evmChainErc20TokensBox;
|
||||
|
||||
late final EthPrivateKey _evmChainPrivateKey;
|
||||
|
||||
EthPrivateKey get evmChainPrivateKey => _evmChainPrivateKey;
|
||||
|
||||
late EVMChainClient _client;
|
||||
|
||||
int? _gasPrice;
|
||||
int? _estimatedGas;
|
||||
bool _isTransactionUpdating;
|
||||
|
||||
// TODO: remove after integrating our own node and having eth_newPendingTransactionFilter
|
||||
Timer? _transactionsUpdateTimer;
|
||||
|
||||
@override
|
||||
WalletAddresses walletAddresses;
|
||||
|
||||
@override
|
||||
@observable
|
||||
SyncStatus syncStatus;
|
||||
|
||||
@override
|
||||
@observable
|
||||
late ObservableMap<CryptoCurrency, EVMChainERC20Balance> balance;
|
||||
|
||||
Completer<SharedPreferences> sharedPrefs = Completer();
|
||||
|
||||
//! Methods to be overridden by every child
|
||||
|
||||
void addInitialTokens();
|
||||
|
||||
// Future<EVMChainWallet> open({
|
||||
// required String name,
|
||||
// required String password,
|
||||
// required WalletInfo walletInfo,
|
||||
// });
|
||||
|
||||
Future<void> initErc20TokensBox();
|
||||
|
||||
String getTransactionHistoryFileName();
|
||||
|
||||
Future<bool> checkIfScanProviderIsEnabled();
|
||||
|
||||
EVMChainTransactionInfo getTransactionInfo(
|
||||
EVMChainTransactionModel transactionModel, String address);
|
||||
|
||||
Erc20Token createNewErc20TokenObject(Erc20Token token, String? iconPath);
|
||||
|
||||
EVMChainTransactionHistory setUpTransactionHistory(WalletInfo walletInfo, String password);
|
||||
|
||||
//! Common Methods across child classes
|
||||
|
||||
String idFor(String name, WalletType type) => '${walletTypeToString(type).toLowerCase()}_$name';
|
||||
|
||||
Future<void> init() async {
|
||||
await initErc20TokensBox();
|
||||
|
||||
await walletAddresses.init();
|
||||
await transactionHistory.init();
|
||||
_evmChainPrivateKey = await getPrivateKey(
|
||||
mnemonic: _mnemonic,
|
||||
privateKey: _hexPrivateKey,
|
||||
password: _password,
|
||||
);
|
||||
walletAddresses.address = _evmChainPrivateKey.address.toString();
|
||||
await save();
|
||||
}
|
||||
|
||||
@override
|
||||
int calculateEstimatedFee(TransactionPriority priority, int? amount) {
|
||||
try {
|
||||
if (priority is EVMChainTransactionPriority) {
|
||||
final priorityFee = EtherAmount.fromInt(EtherUnit.gwei, priority.tip).getInWei.toInt();
|
||||
return (_gasPrice! + priorityFee) * (_estimatedGas ?? 0);
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> changePassword(String password) {
|
||||
throw UnimplementedError("changePassword");
|
||||
}
|
||||
|
||||
@override
|
||||
void close() {
|
||||
_client.stop();
|
||||
_transactionsUpdateTimer?.cancel();
|
||||
}
|
||||
|
||||
@action
|
||||
@override
|
||||
Future<void> connectToNode({required Node node}) async {
|
||||
try {
|
||||
syncStatus = ConnectingSyncStatus();
|
||||
|
||||
final isConnected = _client.connect(node);
|
||||
|
||||
if (!isConnected) {
|
||||
throw Exception("${walletInfo.type.name.toUpperCase()} Node connection failed");
|
||||
}
|
||||
|
||||
_client.setListeners(_evmChainPrivateKey.address, _onNewTransaction);
|
||||
|
||||
_setTransactionUpdateTimer();
|
||||
|
||||
syncStatus = ConnectedSyncStatus();
|
||||
} catch (e) {
|
||||
syncStatus = FailedSyncStatus();
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
@override
|
||||
Future<void> startSync() async {
|
||||
try {
|
||||
syncStatus = AttemptingSyncStatus();
|
||||
await _updateBalance();
|
||||
await _updateTransactions();
|
||||
_gasPrice = await _client.getGasUnitPrice();
|
||||
_estimatedGas = await _client.getEstimatedGas();
|
||||
|
||||
Timer.periodic(
|
||||
const Duration(minutes: 1), (timer) async => _gasPrice = await _client.getGasUnitPrice());
|
||||
Timer.periodic(const Duration(seconds: 10),
|
||||
(timer) async => _estimatedGas = await _client.getEstimatedGas());
|
||||
|
||||
syncStatus = SyncedSyncStatus();
|
||||
} catch (e) {
|
||||
syncStatus = FailedSyncStatus();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<PendingTransaction> createTransaction(Object credentials) async {
|
||||
final _credentials = credentials as EVMChainTransactionCredentials;
|
||||
final outputs = _credentials.outputs;
|
||||
final hasMultiDestination = outputs.length > 1;
|
||||
|
||||
final CryptoCurrency transactionCurrency =
|
||||
balance.keys.firstWhere((element) => element.title == _credentials.currency.title);
|
||||
|
||||
final _erc20Balance = balance[transactionCurrency]!;
|
||||
BigInt totalAmount = BigInt.zero;
|
||||
int exponent = transactionCurrency is Erc20Token ? transactionCurrency.decimal : 18;
|
||||
num amountToEVMChainMultiplier = pow(10, exponent);
|
||||
|
||||
// so far this can not be made with Ethereum as Ethereum does not support multiple recipients
|
||||
if (hasMultiDestination) {
|
||||
if (outputs.any((item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) {
|
||||
throw EVMChainTransactionCreationException(transactionCurrency);
|
||||
}
|
||||
|
||||
final totalOriginalAmount = EVMChainFormatter.parseEVMChainAmountToDouble(
|
||||
outputs.fold(0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0)));
|
||||
totalAmount = BigInt.from(totalOriginalAmount * amountToEVMChainMultiplier);
|
||||
|
||||
if (_erc20Balance.balance < totalAmount) {
|
||||
throw EVMChainTransactionCreationException(transactionCurrency);
|
||||
}
|
||||
} else {
|
||||
final output = outputs.first;
|
||||
// since the fees are taken from Ethereum
|
||||
// then no need to subtract the fees from the amount if send all
|
||||
final BigInt allAmount;
|
||||
if (transactionCurrency is Erc20Token) {
|
||||
allAmount = _erc20Balance.balance;
|
||||
} else {
|
||||
allAmount = _erc20Balance.balance -
|
||||
BigInt.from(calculateEstimatedFee(_credentials.priority!, null));
|
||||
}
|
||||
final totalOriginalAmount =
|
||||
EVMChainFormatter.parseEVMChainAmountToDouble(output.formattedCryptoAmount ?? 0);
|
||||
totalAmount = output.sendAll
|
||||
? allAmount
|
||||
: BigInt.from(totalOriginalAmount * amountToEVMChainMultiplier);
|
||||
|
||||
if (_erc20Balance.balance < totalAmount) {
|
||||
throw EVMChainTransactionCreationException(transactionCurrency);
|
||||
}
|
||||
}
|
||||
|
||||
final pendingEVMChainTransaction = await _client.signTransaction(
|
||||
privateKey: _evmChainPrivateKey,
|
||||
toAddress: _credentials.outputs.first.isParsedAddress
|
||||
? _credentials.outputs.first.extractedAddress!
|
||||
: _credentials.outputs.first.address,
|
||||
amount: totalAmount.toString(),
|
||||
gas: _estimatedGas!,
|
||||
priority: _credentials.priority!,
|
||||
currency: transactionCurrency,
|
||||
exponent: exponent,
|
||||
contractAddress:
|
||||
transactionCurrency is Erc20Token ? transactionCurrency.contractAddress : null,
|
||||
);
|
||||
|
||||
return pendingEVMChainTransaction;
|
||||
}
|
||||
|
||||
Future<void> _updateTransactions() async {
|
||||
try {
|
||||
if (_isTransactionUpdating) {
|
||||
return;
|
||||
}
|
||||
|
||||
final isProviderEnabled = await checkIfScanProviderIsEnabled();
|
||||
|
||||
if (!isProviderEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
_isTransactionUpdating = true;
|
||||
final transactions = await fetchTransactions();
|
||||
transactionHistory.addMany(transactions);
|
||||
await transactionHistory.save();
|
||||
_isTransactionUpdating = false;
|
||||
} catch (_) {
|
||||
_isTransactionUpdating = false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, EVMChainTransactionInfo>> fetchTransactions() async {
|
||||
final address = _evmChainPrivateKey.address.hex;
|
||||
final transactions = await _client.fetchTransactions(address);
|
||||
|
||||
final List<Future<List<EVMChainTransactionModel>>> erc20TokensTransactions = [];
|
||||
|
||||
for (var token in balance.keys) {
|
||||
if (token is Erc20Token) {
|
||||
erc20TokensTransactions.add(_client.fetchTransactions(
|
||||
address,
|
||||
contractAddress: token.contractAddress,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
final tokensTransaction = await Future.wait(erc20TokensTransactions);
|
||||
transactions.addAll(tokensTransaction.expand((element) => element));
|
||||
|
||||
final Map<String, EVMChainTransactionInfo> result = {};
|
||||
|
||||
for (var transactionModel in transactions) {
|
||||
if (transactionModel.isError) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result[transactionModel.hash] = getTransactionInfo(transactionModel, address);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
Object get keys => throw UnimplementedError("keys");
|
||||
|
||||
@override
|
||||
Future<void> rescan({required int height}) {
|
||||
throw UnimplementedError("rescan");
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save() async {
|
||||
await walletAddresses.updateAddressesInBox();
|
||||
final path = await makePath();
|
||||
await write(path: path, password: _password, data: toJSON());
|
||||
await transactionHistory.save();
|
||||
}
|
||||
|
||||
@override
|
||||
String? get seed => _mnemonic;
|
||||
|
||||
@override
|
||||
String get privateKey => HEX.encode(_evmChainPrivateKey.privateKey);
|
||||
|
||||
Future<String> makePath() async => pathForWallet(name: walletInfo.name, type: walletInfo.type);
|
||||
|
||||
String toJSON() => json.encode({
|
||||
'mnemonic': _mnemonic,
|
||||
'private_key': privateKey,
|
||||
'balance': balance[currency]!.toJSON(),
|
||||
});
|
||||
|
||||
Future<void> _updateBalance() async {
|
||||
balance[currency] = await _fetchEVMChainBalance();
|
||||
|
||||
await _fetchErc20Balances();
|
||||
await save();
|
||||
}
|
||||
|
||||
Future<EVMChainERC20Balance> _fetchEVMChainBalance() async {
|
||||
final balance = await _client.getBalance(_evmChainPrivateKey.address);
|
||||
return EVMChainERC20Balance(balance.getInWei);
|
||||
}
|
||||
|
||||
Future<void> _fetchErc20Balances() async {
|
||||
for (var token in evmChainErc20TokensBox.values) {
|
||||
try {
|
||||
if (token.enabled) {
|
||||
balance[token] = await _client.fetchERC20Balances(
|
||||
_evmChainPrivateKey.address,
|
||||
token.contractAddress,
|
||||
);
|
||||
} else {
|
||||
balance.remove(token);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
Future<EthPrivateKey> getPrivateKey(
|
||||
{String? mnemonic, String? privateKey, required String password}) async {
|
||||
assert(mnemonic != null || privateKey != null);
|
||||
|
||||
if (privateKey != null) {
|
||||
return EthPrivateKey.fromHex(privateKey);
|
||||
}
|
||||
|
||||
final seed = bip39.mnemonicToSeed(mnemonic!);
|
||||
|
||||
final root = bip32.BIP32.fromSeed(seed);
|
||||
|
||||
const hdPathEVMChain = "m/44'/60'/0'/0";
|
||||
const index = 0;
|
||||
final addressAtIndex = root.derivePath("$hdPathEVMChain/$index");
|
||||
|
||||
return EthPrivateKey.fromHex(HEX.encode(addressAtIndex.privateKey as List<int>));
|
||||
}
|
||||
|
||||
Future<void>? updateBalance() async => await _updateBalance();
|
||||
|
||||
List<Erc20Token> get erc20Currencies => evmChainErc20TokensBox.values.toList();
|
||||
|
||||
Future<void> addErc20Token(Erc20Token token) async {
|
||||
String? iconPath;
|
||||
try {
|
||||
iconPath = CryptoCurrency.all
|
||||
.firstWhere((element) => element.title.toUpperCase() == token.symbol.toUpperCase())
|
||||
.iconPath;
|
||||
} catch (_) {}
|
||||
|
||||
final newToken = createNewErc20TokenObject(token, iconPath);
|
||||
|
||||
await evmChainErc20TokensBox.put(newToken.contractAddress, newToken);
|
||||
|
||||
if (newToken.enabled) {
|
||||
balance[newToken] = await _client.fetchERC20Balances(
|
||||
_evmChainPrivateKey.address,
|
||||
newToken.contractAddress,
|
||||
);
|
||||
} else {
|
||||
balance.remove(newToken);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteErc20Token(Erc20Token token) async {
|
||||
await token.delete();
|
||||
|
||||
balance.remove(token);
|
||||
_updateBalance();
|
||||
}
|
||||
|
||||
Future<Erc20Token?> getErc20Token(String contractAddress) async =>
|
||||
await _client.getErc20Token(contractAddress);
|
||||
|
||||
void _onNewTransaction() {
|
||||
_updateBalance();
|
||||
_updateTransactions();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> renameWalletFiles(String newWalletName) async {
|
||||
final transactionHistoryFileNameForWallet = getTransactionHistoryFileName();
|
||||
|
||||
final currentWalletPath = await pathForWallet(name: walletInfo.name, type: type);
|
||||
final currentWalletFile = File(currentWalletPath);
|
||||
|
||||
final currentDirPath = await pathForWalletDir(name: walletInfo.name, type: type);
|
||||
final currentTransactionsFile = File('$currentDirPath/$transactionHistoryFileNameForWallet');
|
||||
|
||||
// Copies current wallet files into new wallet name's dir and files
|
||||
if (currentWalletFile.existsSync()) {
|
||||
final newWalletPath = await pathForWallet(name: newWalletName, type: type);
|
||||
await currentWalletFile.copy(newWalletPath);
|
||||
}
|
||||
if (currentTransactionsFile.existsSync()) {
|
||||
final newDirPath = await pathForWalletDir(name: newWalletName, type: type);
|
||||
await currentTransactionsFile.copy('$newDirPath/$transactionHistoryFileNameForWallet');
|
||||
}
|
||||
|
||||
// Delete old name's dir and files
|
||||
await Directory(currentDirPath).delete(recursive: true);
|
||||
}
|
||||
|
||||
void _setTransactionUpdateTimer() {
|
||||
if (_transactionsUpdateTimer?.isActive ?? false) {
|
||||
_transactionsUpdateTimer!.cancel();
|
||||
}
|
||||
|
||||
_transactionsUpdateTimer = Timer.periodic(const Duration(seconds: 10), (_) {
|
||||
_updateTransactions();
|
||||
_updateBalance();
|
||||
});
|
||||
}
|
||||
|
||||
/// Scan Providers:
|
||||
///
|
||||
/// EtherScan for Ethereum.
|
||||
///
|
||||
/// PolygonScan for Polygon.
|
||||
void updateScanProviderUsageState(bool isEnabled) {
|
||||
if (isEnabled) {
|
||||
_updateTransactions();
|
||||
_setTransactionUpdateTimer();
|
||||
} else {
|
||||
_transactionsUpdateTimer?.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
String signMessage(String message, {String? address}) =>
|
||||
bytesToHex(_evmChainPrivateKey.signPersonalMessageToUint8List(ascii.encode(message)));
|
||||
|
||||
Web3Client? getWeb3Client() => _client.getWeb3Client();
|
||||
}
|
35
cw_evm/lib/evm_chain_wallet_addresses.dart
Normal file
35
cw_evm/lib/evm_chain_wallet_addresses.dart
Normal file
|
@ -0,0 +1,35 @@
|
|||
import 'dart:developer';
|
||||
|
||||
import 'package:cw_core/wallet_addresses.dart';
|
||||
import 'package:cw_core/wallet_info.dart';
|
||||
import 'package:mobx/mobx.dart';
|
||||
|
||||
part 'evm_chain_wallet_addresses.g.dart';
|
||||
|
||||
class EVMChainWalletAddresses = EVMChainWalletAddressesBase with _$EVMChainWalletAddresses;
|
||||
|
||||
abstract class EVMChainWalletAddressesBase extends WalletAddresses with Store {
|
||||
EVMChainWalletAddressesBase(WalletInfo walletInfo)
|
||||
: address = '',
|
||||
super(walletInfo);
|
||||
|
||||
@override
|
||||
String address;
|
||||
|
||||
@override
|
||||
Future<void> init() async {
|
||||
address = walletInfo.address;
|
||||
await updateAddressesInBox();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> updateAddressesInBox() async {
|
||||
try {
|
||||
addressesMap.clear();
|
||||
addressesMap[address] = '';
|
||||
await saveAddressesInBox();
|
||||
} catch (e) {
|
||||
log(e.toString());
|
||||
}
|
||||
}
|
||||
}
|
29
cw_evm/lib/evm_chain_wallet_creation_credentials.dart
Normal file
29
cw_evm/lib/evm_chain_wallet_creation_credentials.dart
Normal file
|
@ -0,0 +1,29 @@
|
|||
import 'package:cw_core/wallet_credentials.dart';
|
||||
import 'package:cw_core/wallet_info.dart';
|
||||
|
||||
class EVMChainNewWalletCredentials extends WalletCredentials {
|
||||
EVMChainNewWalletCredentials({required String name, WalletInfo? walletInfo})
|
||||
: super(name: name, walletInfo: walletInfo);
|
||||
}
|
||||
|
||||
class EVMChainRestoreWalletFromSeedCredentials extends WalletCredentials {
|
||||
EVMChainRestoreWalletFromSeedCredentials({
|
||||
required String name,
|
||||
required String password,
|
||||
required this.mnemonic,
|
||||
WalletInfo? walletInfo,
|
||||
}) : super(name: name, password: password, walletInfo: walletInfo);
|
||||
|
||||
final String mnemonic;
|
||||
}
|
||||
|
||||
class EVMChainRestoreWalletFromPrivateKey extends WalletCredentials {
|
||||
EVMChainRestoreWalletFromPrivateKey({
|
||||
required String name,
|
||||
required String password,
|
||||
required this.privateKey,
|
||||
WalletInfo? walletInfo,
|
||||
}) : super(name: name, password: password, walletInfo: walletInfo);
|
||||
|
||||
final String privateKey;
|
||||
}
|
50
cw_evm/lib/evm_chain_wallet_service.dart
Normal file
50
cw_evm/lib/evm_chain_wallet_service.dart
Normal file
|
@ -0,0 +1,50 @@
|
|||
import 'dart:io';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:cw_core/pathForWallet.dart';
|
||||
import 'package:cw_core/wallet_base.dart';
|
||||
import 'package:cw_core/wallet_info.dart';
|
||||
import 'package:cw_core/wallet_service.dart';
|
||||
import 'package:cw_core/wallet_type.dart';
|
||||
import 'package:cw_evm/evm_chain_wallet.dart';
|
||||
import 'package:cw_evm/evm_chain_wallet_creation_credentials.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
|
||||
abstract class EVMChainWalletService<T extends EVMChainWallet> extends WalletService<
|
||||
EVMChainNewWalletCredentials,
|
||||
EVMChainRestoreWalletFromSeedCredentials,
|
||||
EVMChainRestoreWalletFromPrivateKey> {
|
||||
EVMChainWalletService(this.walletInfoSource);
|
||||
|
||||
final Box<WalletInfo> walletInfoSource;
|
||||
|
||||
@override
|
||||
WalletType getType();
|
||||
|
||||
@override
|
||||
Future<T> create(EVMChainNewWalletCredentials credentials);
|
||||
|
||||
@override
|
||||
Future<T> openWallet(String name, String password);
|
||||
|
||||
@override
|
||||
Future<void> rename(String currentName, String password, String newName);
|
||||
|
||||
@override
|
||||
Future<T> restoreFromKeys(EVMChainRestoreWalletFromPrivateKey credentials);
|
||||
|
||||
@override
|
||||
Future<T> restoreFromSeed(EVMChainRestoreWalletFromSeedCredentials credentials);
|
||||
|
||||
@override
|
||||
Future<bool> isWalletExit(String name) async =>
|
||||
File(await pathForWallet(name: name, type: getType())).existsSync();
|
||||
|
||||
@override
|
||||
Future<void> remove(String wallet) async {
|
||||
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
|
||||
final walletInfo = walletInfoSource.values
|
||||
.firstWhereOrNull((info) => info.id == WalletBase.idFor(wallet, getType()))!;
|
||||
await walletInfoSource.delete(walletInfo.key);
|
||||
}
|
||||
}
|
46
cw_evm/lib/evm_erc20_balance.dart
Normal file
46
cw_evm/lib/evm_erc20_balance.dart
Normal file
|
@ -0,0 +1,46 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:cw_core/balance.dart';
|
||||
|
||||
class EVMChainERC20Balance extends Balance {
|
||||
EVMChainERC20Balance(this.balance, {this.exponent = 18})
|
||||
: super(balance.toInt(), balance.toInt());
|
||||
|
||||
final BigInt balance;
|
||||
final int exponent;
|
||||
|
||||
@override
|
||||
String get formattedAdditionalBalance {
|
||||
final String formattedBalance = (balance / BigInt.from(10).pow(exponent)).toString();
|
||||
return formattedBalance.substring(0, min(12, formattedBalance.length));
|
||||
}
|
||||
|
||||
@override
|
||||
String get formattedAvailableBalance {
|
||||
final String formattedBalance = (balance / BigInt.from(10).pow(exponent)).toString();
|
||||
return formattedBalance.substring(0, min(12, formattedBalance.length));
|
||||
}
|
||||
|
||||
String toJSON() => json.encode({
|
||||
'balanceInWei': balance.toString(),
|
||||
'exponent': exponent,
|
||||
});
|
||||
|
||||
static EVMChainERC20Balance? fromJSON(String? jsonSource) {
|
||||
if (jsonSource == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final decoded = json.decode(jsonSource) as Map;
|
||||
|
||||
try {
|
||||
return EVMChainERC20Balance(
|
||||
BigInt.parse(decoded['balanceInWei']),
|
||||
exponent: decoded['exponent'],
|
||||
);
|
||||
} catch (e) {
|
||||
return EVMChainERC20Balance(BigInt.zero);
|
||||
}
|
||||
}
|
||||
}
|
39
cw_evm/lib/file.dart
Normal file
39
cw_evm/lib/file.dart
Normal file
|
@ -0,0 +1,39 @@
|
|||
import 'dart:io';
|
||||
import 'package:cw_core/key.dart';
|
||||
import 'package:encrypt/encrypt.dart' as encrypt;
|
||||
|
||||
Future<void> write(
|
||||
{required String path,
|
||||
required String password,
|
||||
required String data}) async {
|
||||
final keys = extractKeys(password);
|
||||
final key = encrypt.Key.fromBase64(keys.first);
|
||||
final iv = encrypt.IV.fromBase64(keys.last);
|
||||
final encrypted = await encode(key: key, iv: iv, data: data);
|
||||
final f = File(path);
|
||||
f.writeAsStringSync(encrypted);
|
||||
}
|
||||
|
||||
Future<void> writeData(
|
||||
{required String path,
|
||||
required String password,
|
||||
required String data}) async {
|
||||
final keys = extractKeys(password);
|
||||
final key = encrypt.Key.fromBase64(keys.first);
|
||||
final iv = encrypt.IV.fromBase64(keys.last);
|
||||
final encrypted = await encode(key: key, iv: iv, data: data);
|
||||
final f = File(path);
|
||||
f.writeAsStringSync(encrypted);
|
||||
}
|
||||
|
||||
Future<String> read({required String path, required String password}) async {
|
||||
final file = File(path);
|
||||
|
||||
if (!file.existsSync()) {
|
||||
file.createSync();
|
||||
}
|
||||
|
||||
final encrypted = file.readAsStringSync();
|
||||
|
||||
return decode(password: password, data: encrypted);
|
||||
}
|
42
cw_evm/lib/pending_evm_chain_transaction.dart
Normal file
42
cw_evm/lib/pending_evm_chain_transaction.dart
Normal file
|
@ -0,0 +1,42 @@
|
|||
import 'dart:math';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:cw_core/pending_transaction.dart';
|
||||
import 'package:web3dart/crypto.dart';
|
||||
|
||||
class PendingEVMChainTransaction with PendingTransaction {
|
||||
final Function sendTransaction;
|
||||
final Uint8List signedTransaction;
|
||||
final BigInt fee;
|
||||
final String amount;
|
||||
final int exponent;
|
||||
|
||||
PendingEVMChainTransaction({
|
||||
required this.sendTransaction,
|
||||
required this.signedTransaction,
|
||||
required this.fee,
|
||||
required this.amount,
|
||||
required this.exponent,
|
||||
});
|
||||
|
||||
@override
|
||||
String get amountFormatted {
|
||||
final _amount = (BigInt.parse(amount) / BigInt.from(pow(10, exponent))).toString();
|
||||
return _amount.substring(0, min(10, _amount.length));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> commit() async => await sendTransaction();
|
||||
|
||||
@override
|
||||
String get feeFormatted {
|
||||
final _fee = (fee / BigInt.from(pow(10, 18))).toString();
|
||||
return _fee.substring(0, min(10, _fee.length));
|
||||
}
|
||||
|
||||
@override
|
||||
String get hex => bytesToHex(signedTransaction, include0x: true);
|
||||
|
||||
@override
|
||||
String get id => '';
|
||||
}
|
45
cw_evm/pubspec.yaml
Normal file
45
cw_evm/pubspec.yaml
Normal file
|
@ -0,0 +1,45 @@
|
|||
name: cw_evm
|
||||
description: A new Flutter package project.
|
||||
version: 0.0.1
|
||||
publish_to: none
|
||||
author: Cake Wallet
|
||||
homepage: https://cakewallet.com
|
||||
|
||||
environment:
|
||||
sdk: '>=3.0.6 <4.0.0'
|
||||
flutter: ">=1.17.0"
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
web3dart: ^2.7.1
|
||||
erc20: ^1.0.1
|
||||
bip39: ^1.0.6
|
||||
bip32: ^2.0.0
|
||||
hex: ^0.2.0
|
||||
http: ^1.1.0
|
||||
hive: ^2.2.3
|
||||
collection: ^1.17.1
|
||||
shared_preferences: ^2.0.15
|
||||
cw_core:
|
||||
path: ../cw_core
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
build_runner: ^2.1.11
|
||||
mobx_codegen: ^2.0.7
|
||||
hive_generator: ^1.1.3
|
||||
flutter_lints: ^2.0.0
|
||||
|
||||
flutter:
|
||||
# assets:
|
||||
# - images/a_dot_burr.jpeg
|
||||
# - images/a_dot_ham.jpeg
|
||||
#
|
||||
# fonts:
|
||||
# - family: Schyler
|
||||
# fonts:
|
||||
# - asset: fonts/Schyler-Regular.ttf
|
||||
# - asset: fonts/Schyler-Italic.ttf
|
||||
# style: italic
|
12
cw_evm/test/cw_evm_test.dart
Normal file
12
cw_evm/test/cw_evm_test.dart
Normal file
|
@ -0,0 +1,12 @@
|
|||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:cw_evm/cw_evm.dart';
|
||||
|
||||
void main() {
|
||||
test('adds one to input values', () {
|
||||
final calculator = Calculator();
|
||||
expect(calculator.addOne(2), 3);
|
||||
expect(calculator.addOne(-7), -6);
|
||||
expect(calculator.addOne(0), 1);
|
||||
});
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue