-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloud_coin_service.dart
88 lines (82 loc) · 2.75 KB
/
cloud_coin_service.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import 'package:convert/convert.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart';
import 'package:web3dart/web3dart.dart';
import '../../config/ethereum_config.dart';
import '../../data/wallet_connect/wallet_connect_service.dart';
import '../../logger/logger.dart';
import 'coin_service.dart';
class CloudCoinService implements CoinService {
CloudCoinService({
required EthereumConfig ethereumConfig,
required WalletConnectService walletConnectService,
Logger? logger,
}) : _walletConnectService = walletConnectService,
_ethereumConfig = ethereumConfig,
_logger = logger {
_ethereumClient = Web3Client(_ethereumConfig.ethereumRpcUrl, _httpClient);
_contractAddress =
EthereumAddress.fromHex(_ethereumConfig.coinContractAddress);
}
final EthereumConfig _ethereumConfig;
final WalletConnectService _walletConnectService;
final Logger? _logger;
late final Web3Client _ethereumClient;
late final EthereumAddress _contractAddress;
DeployedContract? _contractInner;
final _httpClient = Client();
Future<DeployedContract> get _contract async {
if (_contractInner == null) {
final abiCode =
await rootBundle.loadString('assets/abi/TaroCoin.abi.json');
_contractInner = DeployedContract(
ContractAbi.fromJson(abiCode, 'TaroCoin'),
_contractAddress,
);
}
return _contractInner!;
}
@override
Future<BigInt?> getBalance({required String addressHex}) async {
try {
final contract = await _contract;
final balanceFunction = contract.function('balanceOf');
final response = await _ethereumClient.call(
contract: contract,
function: balanceFunction,
params: [EthereumAddress.fromHex(addressHex)],
);
final balance = EtherAmount.fromBigInt(EtherUnit.wei, response[0]);
_logger?.i('balance : $balance');
return balance.getInEther;
} catch (e) {
_logger?.e('error - ${e.toString()}');
return null;
}
}
@override
Future<bool> transfer({
required String toAddress,
required BigInt value,
}) async {
try {
final contract = await _contract;
final to = EthereumAddress.fromHex(toAddress);
final amount = EtherAmount.fromBigInt(EtherUnit.ether, value).getInWei;
final transaction = Transaction.callContract(
contract: contract,
function: contract.function('transfer'),
parameters: [to, amount],
);
final hexEncodedData = hex.encode(transaction.data!);
final response = _walletConnectService.sendTransaction(
to: _contractAddress.toString(),
data: hexEncodedData,
);
return true;
} catch (e) {
_logger?.e('error - ${e.toString()}');
return false;
}
}
}