cake_wallet/cw_ethereum/lib/ethereum_client.dart

75 lines
2.1 KiB
Dart
Raw Normal View History

2023-01-04 14:51:23 +00:00
import 'package:cw_core/node.dart';
import 'package:cw_ethereum/ethereum_transaction_priority.dart';
2023-01-04 14:51:23 +00:00
import 'package:http/http.dart';
2023-03-31 18:41:56 +00:00
import 'package:web3dart/crypto.dart';
2023-01-04 14:51:23 +00:00
import 'package:web3dart/web3dart.dart';
class EthereumClient {
Web3Client? _client;
2023-01-04 14:51:23 +00:00
2023-01-13 17:10:38 +00:00
bool connect(Node node) {
2023-01-04 14:51:23 +00:00
try {
_client = Web3Client(node.uri.toString(), Client());
2023-01-04 14:51:23 +00:00
return true;
} catch (e) {
return false;
}
}
Future<EtherAmount> getBalance(String privateKey) async {
final private = EthPrivateKey.fromHex(privateKey);
return _client!.getBalance(private.address);
2023-01-04 14:51:23 +00:00
}
Future<int> getGasUnitPrice() async {
final gasPrice = await _client!.getGasPrice();
return gasPrice.getInWei.toInt();
}
Future<List<int>> getEstimatedGasForPriorities() async {
2023-01-13 17:10:38 +00:00
final result = await Future.wait(EthereumTransactionPriority.all.map(
(priority) => _client!.estimateGas(
2023-03-31 18:41:56 +00:00
// maxPriorityFeePerGas: EtherAmount.fromUnitAndValue(EtherUnit.gwei, priority.tip),
// maxFeePerGas: EtherAmount.fromUnitAndValue(EtherUnit.gwei, 100),
),
2023-01-13 17:10:38 +00:00
));
return result.map((e) => e.toInt()).toList();
}
2023-03-16 17:24:21 +00:00
2023-03-31 18:41:56 +00:00
Future<String> signTransaction(String privateKey, String toAddress, String amount) async {
final credentials = EthPrivateKey.fromHex(privateKey);
final transaction = Transaction(
from: credentials.address,
to: EthereumAddress.fromHex(toAddress),
value: EtherAmount.zero(),
);
print("@@@@@@@@@@@@@@@@@");
print(transaction);
String tr = bytesToHex(await _client!.signTransaction(credentials, transaction));
print("@@@@@@@@@@@@@@@@@");
print(tr);
return tr;
}
2023-03-16 17:24:21 +00:00
Future<String> sendTransaction(String privateKey, String toAddress, String amount) async {
final credentials = EthPrivateKey.fromHex(privateKey);
final transaction = Transaction(
from: credentials.address,
to: EthereumAddress.fromHex(toAddress),
value: EtherAmount.fromUnitAndValue(EtherUnit.ether, amount),
);
return await _client!.sendTransaction(
credentials,
transaction,
);
}
}