-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwallet_service.dart
More file actions
216 lines (195 loc) · 7.91 KB
/
wallet_service.dart
File metadata and controls
216 lines (195 loc) · 7.91 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_pkid/flutter_pkid.dart';
import 'package:gridproxy_client/models/farms.dart';
import 'package:threebotlogin/apps/wallet/wallet_config.dart';
import 'package:threebotlogin/helpers/globals.dart';
import 'package:threebotlogin/helpers/logger.dart';
import 'package:threebotlogin/models/wallet.dart';
import 'package:threebotlogin/services/idenfy_service.dart';
import 'package:threebotlogin/services/gridproxy_service.dart';
import 'package:threebotlogin/services/pkid_service.dart';
import 'package:threebotlogin/services/shared_preference_service.dart';
import 'package:stellar_client/stellar_client.dart' as Stellar;
import 'package:tfchain_client/tfchain_client.dart' as TFChain;
import 'package:bip39/bip39.dart' as bip39;
import 'package:convert/convert.dart';
import 'package:threebotlogin/services/stellar_service.dart' as StellarService;
import 'package:threebotlogin/services/tfchain_service.dart' as TFChainService;
import 'package:hashlib/hashlib.dart';
Future<FlutterPkid> _getPkidClient() async {
Uint8List seed = await getDerivedSeed(WalletConfig().appId());
final mnemonic = bip39.entropyToMnemonic(hex.encode(seed));
FlutterPkid client = await getPkidClient(seedPhrase: mnemonic);
return client;
}
Future<List<PkidWallet>> getPkidWallets() async {
FlutterPkid client = await _getPkidClient();
Map<String, dynamic> pKidResult;
try {
pKidResult = await client.getPKidDoc('purse');
if (pKidResult.containsKey('error')) {
if (pKidResult.containsValue('Key is not found')) {
return [];
}
logger.e('Error in pKidResult : ${pKidResult['error']}');
throw Exception('Error fetching wallets');
}
} catch (e) {
logger.e('Error while requesting pkidWallets: $e');
throw Exception('Error fetching wallets');
}
final result =
pKidResult.containsKey('data') && pKidResult.containsKey('success')
? jsonDecode(pKidResult['data'])
: {};
if (result.isEmpty) {
return [];
}
Map<int, dynamic> dataMap = result.asMap();
final pkidWallets =
dataMap.values.map((e) => PkidWallet.fromJson(e)).toSet().toList();
return pkidWallets;
}
Future<List<Wallet>> listWallets() async {
final pkidWallets = await getPkidWallets();
final String chainUrl = Globals().chainUrl;
final idenfyServiceUrl = Globals().idenfyServiceUrl;
final List<Wallet> wallets = await compute((void _) async {
final List<Future<Wallet>> walletFutures = [];
for (final w in pkidWallets) {
final walletFuture =
loadWallet(w.name, w.seed, w.type, chainUrl, idenfyServiceUrl);
walletFutures.add(walletFuture);
}
return await Future.wait(walletFutures);
}, null);
return wallets;
}
Future<(Stellar.Client, TFChain.Client)> loadWalletClients(String walletName,
String walletSeed, WalletType walletType, String chainUrl) async {
Stellar.Client stellarClient;
TFChain.Client tfchainClient;
if (' '.allMatches(walletSeed).length == 11) {
tfchainClient = TFChain.Client(chainUrl, walletSeed, 'sr25519');
final entropy = bip39.mnemonicToEntropy(walletSeed);
final seed = entropy.padRight(64, '0');
stellarClient =
Stellar.Client.fromSecretSeedHex(Stellar.NetworkType.PUBLIC, seed);
} else if (' '.allMatches(walletSeed).length == 23) {
final entropy = bip39.mnemonicToEntropy(walletSeed);
final seedList = hex.decode(entropy).toList();
seedList.addAll([0, 0, 0, 0, 0, 0, 0, 0]); // instead of sia binary encoder
final seed = Blake2b(32).hex(seedList);
stellarClient =
Stellar.Client.fromSecretSeedHex(Stellar.NetworkType.PUBLIC, seed);
tfchainClient = TFChain.Client(chainUrl, '0x$seed', 'sr25519');
} else if (StellarService.isValidStellarSecret(walletSeed)) {
stellarClient = Stellar.Client(Stellar.NetworkType.PUBLIC, walletSeed);
final hexSecret =
hex.encode(stellarClient.privateKey!.toList().sublist(0, 32));
tfchainClient = TFChain.Client(chainUrl, '0x$hexSecret', 'sr25519');
} else {
if (walletSeed.startsWith(RegExp(r'0[xX]'))) {
walletSeed = walletSeed.substring(2);
}
stellarClient = Stellar.Client.fromSecretSeedHex(
Stellar.NetworkType.PUBLIC, walletSeed);
final hexSecret =
hex.encode(stellarClient.privateKey!.toList().sublist(0, 32));
tfchainClient = TFChain.Client(chainUrl, '0x$hexSecret', 'sr25519');
}
return (stellarClient, tfchainClient);
}
Future<Wallet> loadWallet(String walletName, String walletSeed,
WalletType walletType, String chainUrl, String idenfyServiceUrl) async {
final (stellarClient, tfchainClient) =
await loadWalletClients(walletName, walletSeed, walletType, chainUrl);
final balances = await Future.wait([
StellarService.getBalanceByClient(stellarClient),
TFChainService.getBalanceByClient(tfchainClient)
]);
final stellarBalance = balances.first.toString();
final tfchainBalance =
balances.last.toString() == '0.0' ? '0' : balances.last.toString();
final kycVerified = await getVerificationStatus(
address: tfchainClient.keypair!.address,
idenfyServiceUrl: idenfyServiceUrl);
final twinId = await TFChainService.getTwinIdByClient(tfchainClient);
final wallet = Wallet(
name: walletName,
stellarSecret: stellarClient.secretSeed,
stellarAddress: stellarClient.accountId,
tfchainSecret: tfchainClient.mnemonicOrSecretSeed,
tfchainAddress: tfchainClient.address,
stellarBalance: stellarBalance,
tfchainBalance: tfchainBalance,
type: walletType,
verificationStatus: kycVerified.status,
twinId: twinId,
);
return wallet;
}
Future<void> addWallet(String walletName, String walletSecret,
{WalletType type = WalletType.IMPORTED}) async {
List<PkidWallet> wallets = await getPkidWallets();
wallets.any((w) => w.seed == walletSecret)
? throw Exception('Wallet already exists.')
: wallets.add(PkidWallet(
name: walletName,
index: type == WalletType.NATIVE ? 0 : -1,
seed: walletSecret,
type: type));
await saveWalletsToPkid(wallets);
}
Future<void> editWallet(String oldName, String newName) async {
List<PkidWallet> wallets = await getPkidWallets();
for (final w in wallets) {
if (w.name == oldName) {
w.name = newName;
break;
}
}
await saveWalletsToPkid(wallets);
}
Future<void> deleteWallet(String walletName) async {
List<PkidWallet> wallets = await getPkidWallets();
wallets = wallets.where((w) => w.name != walletName).toList();
await saveWalletsToPkid(wallets);
}
Future<void> saveWalletsToPkid(List<PkidWallet> wallets) async {
FlutterPkid client = await _getPkidClient();
final encodedWallets = json.encode(wallets.map((w) => w.toMap()).toList());
await client.setPKidDoc('purse', encodedWallets);
}
Future<Map<int, Map<String, String>>> getWalletTwinId(String walletName,
String walletSeed, WalletType walletType, String chainUrl) async {
final (stellarClient, tfchainClient) =
await loadWalletClients(walletName, walletSeed, walletType, chainUrl);
final twinId = await TFChainService.getTwinIdByClient(tfchainClient);
final Map<int, Map<String, String>> twinIdWallet = {
twinId: {
'tfchainSeed': tfchainClient.mnemonicOrSecretSeed,
'name': walletName,
'stellarAddress': stellarClient.accountId
}
};
return twinIdWallet;
}
Future<List<Farm>> getDaoFarms(List<Wallet> wallets) async {
final Map<int, Wallet> twinIdWallets = {};
final twinIdFutures = wallets.map((w) async {
final twinId = await TFChainService.getTwinId(w.tfchainSecret);
if (twinId != 0) {
twinIdWallets[twinId] = w;
}
}).toList();
await Future.wait(twinIdFutures);
final farms =
await getFarmsByTwinIds(twinIdWallets.keys.toList(), hasUpNode: true);
return farms;
}
Future<void> initializeWallet(String stellarSecret, String tfchainSeed) async {
await StellarService.initialize(stellarSecret);
await TFChainService.activateAccount(tfchainSeed);
}