-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.dart
671 lines (587 loc) · 21.8 KB
/
client.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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
part of '../stellar_client.dart';
class Client {
final NetworkType _network;
late StellarSDK _sdk;
late KeyPair _keyPair;
late currency.Currencies _currencies;
late Map<String, String> _serviceUrls;
late Map<String, String> _horizonServerUrls;
late Network _stellarNetwork;
String get accountId => _keyPair.accountId;
String get secretSeed => _keyPair.secretSeed;
Uint8List? get privateKey => _keyPair.privateKey;
var logger = Logger(
printer: PrettyPrinter(),
);
Client(this._network, String secretSeed) {
_keyPair = KeyPair.fromSecretSeed(secretSeed);
_initialize();
}
factory Client.create(NetworkType network) {
final keyPair = KeyPair.random();
return Client(network, keyPair.secretSeed);
}
factory Client.fromSecretSeedHex(NetworkType network, String secretSeedHex) {
final seed = Uint8List.fromList(hex.decode(secretSeedHex));
final keyPair = KeyPair.fromSecretSeedList(seed);
return Client(network, keyPair.secretSeed);
}
static Future<Client> fromMnemonic(
NetworkType network, String mnemonic) async {
Wallet wallet = await Wallet.from(mnemonic);
final keyPair = await wallet.getKeyPair();
return Client(network, keyPair.secretSeed);
}
void _initialize() {
late final currency.Currency tft;
late final currency.Currency usdc;
_serviceUrls = {
'PUBLIC': 'https://tokenservices.threefold.io/threefoldfoundation',
'TESTNET': 'https://testnet.threefold.io/threefoldfoundation'
};
_horizonServerUrls = {
'PUBLIC': 'https://horizon.stellar.org/',
'TESTNET': 'https://horizon-testnet.stellar.org/'
};
switch (_network) {
case NetworkType.TESTNET:
_sdk = StellarSDK.TESTNET;
_stellarNetwork = Network.TESTNET;
tft = currency.Currency(
assetCode: 'TFT',
issuer: "GA47YZA3PKFUZMPLQ3B5F2E3CJIB57TGGU7SPCQT2WAEYKN766PWIMB3",
);
usdc = currency.Currency(
assetCode: 'USDC',
issuer: 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5');
break;
case NetworkType.PUBLIC:
_sdk = StellarSDK.PUBLIC;
_stellarNetwork = Network.PUBLIC;
tft = currency.Currency(
assetCode: 'TFT',
issuer: "GBOVQKJYHXRR3DX6NOX2RRYFRCUMSADGDESTDNBDS6CDVLGVESRTAC47",
);
usdc = currency.Currency(
assetCode: 'USDC',
issuer: 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN');
break;
default:
throw Exception('Unsupported network type');
}
_currencies = currency.Currencies({
'TFT': tft,
'USDC': usdc,
'XLM': currency.Currency(assetCode: 'XLM', issuer: "")
});
}
Future<bool> activateThroughThreefoldService() async {
Transaction? transaction = await _getActivationTransaction();
if (transaction != null) {
transaction.sign(_keyPair, _stellarNetwork);
await _sdk.submitTransaction(transaction);
logger.i("Account Activated Successfully.");
logger.i("TFT Asset was added Successfully ");
return true;
} else {
throw Exception("Failed to retrieve activation transaction.");
}
}
Future<Transaction?> _getActivationTransaction() async {
try {
final response = await http.post(
Uri.parse(
'${_serviceUrls[_network.toString()]}/activation_service/activate_account'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'address': accountId}),
);
final data = jsonDecode(jsonDecode(response.body));
String activationTransaction = data['activation_transaction'];
XdrTransactionEnvelope xdrTxEnvelope =
XdrTransactionEnvelope.fromEnvelopeXdrString(activationTransaction);
Transaction transaction =
Transaction.fromV1EnvelopeXdr(xdrTxEnvelope.v1!);
return transaction;
} catch (error) {
throw Exception("Failed to activate: $error");
}
}
Future<bool> activateThroughFriendBot({required String accountId}) async {
if (_stellarNetwork != Network.TESTNET) {
throw Exception("Network should be TEST");
}
try {
bool funded = await FriendBot.fundTestAccount(accountId);
if (funded) {
logger.i("Account funded successfully");
} else {
logger.e("Failed to fund account");
}
return funded;
} catch (error) {
logger.e("Error while funding account: $error");
return false;
}
}
Future<bool> addTrustLine() async {
for (var entry in _currencies.currencies.entries) {
String currencyCode = entry.key;
currency.Currency currentCurrency = entry.value;
String issuerAccountId = currentCurrency.issuer;
Asset currencyAsset =
AssetTypeCreditAlphaNum4(currentCurrency.assetCode, issuerAccountId);
ChangeTrustOperationBuilder changeTrustOperation =
ChangeTrustOperationBuilder(currencyAsset, "300000");
final account = await _sdk.accounts.account(accountId);
Transaction transaction = TransactionBuilder(account)
.addOperation(changeTrustOperation.build())
.build();
transaction.sign(_keyPair, _stellarNetwork);
SubmitTransactionResponse response =
await _sdk.submitTransaction(transaction);
if (!response.success) {
logger.e("Failed to add trustline for $currencyCode");
return false;
} else {
logger.i("trustline for $currencyCode was added successfully");
return true;
}
}
logger.i("No trustlines were processed");
return false;
}
Future<bool> transfer(
{required String destinationAddress,
required String amount,
required String currency,
String? memoText}) async {
try {
Transaction? transaction = await _buildTransaction(
destinationAddress: destinationAddress,
amount: amount,
currency: currency,
funded: false);
transaction!.sign(_keyPair, _stellarNetwork);
await _sdk.submitTransaction(transaction);
logger.i("Transaction successful.");
return true;
} catch (error) {
logger.e("Failed to send transaction: $error");
return false;
}
}
Future<bool> activateThroughActivationWallet(
{required String activationWalletSecretSeed}) async {
try {
KeyPair walletKeyPair =
KeyPair.fromSecretSeed(activationWalletSecretSeed);
AccountResponse existingAccount =
await _sdk.accounts.account(walletKeyPair.accountId);
Transaction transaction = TransactionBuilder(existingAccount)
.addOperation(CreateAccountOperationBuilder(accountId, "1").build())
.build();
transaction.sign(walletKeyPair, _stellarNetwork);
await _sdk.submitTransaction(transaction);
return true;
} catch (error) {
logger.e("Failed to create account $error");
return false;
}
}
// take asset code && issuer (optional)
Future<bool> addTrustLineThroughThreefoldService(String asset_code) async {
final asset = _currencies.currencies[asset_code];
if (asset == null) {
throw Exception("Asset $asset_code not supported");
}
try {
final response = await http.post(
Uri.parse(
'${_serviceUrls[_network.toString()]}/activation_service/fund_trustline'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'asset': '${asset.assetCode}:${asset.issuer}',
'address': accountId
}),
);
final data = jsonDecode(response.body);
String trustlineTransaction = data['addtrustline_transaction'];
XdrTransactionEnvelope xdrTxEnvelope =
XdrTransactionEnvelope.fromEnvelopeXdrString(trustlineTransaction);
Transaction transaction =
Transaction.fromV1EnvelopeXdr(xdrTxEnvelope.v1!);
transaction.sign(_keyPair, _stellarNetwork);
SubmitTransactionResponse response2 =
await _sdk.submitTransaction(transaction);
if (response2.success) {
logger.i("Trustline for $asset_code added successfully.");
return true;
} else {
logger.e("Failed to add trustline for $asset_code.");
return false;
}
} catch (error) {
throw Exception("Error funding trustline : $error");
}
}
Future<TransactionData?> _fetchFundDetails(
{required String assetCode}) async {
try {
final response = await http.get(
Uri.parse(
'${_serviceUrls[_network.toString()]}/transactionfunding_service/conditions'),
headers: {'Content-Type': 'application/json'},
);
final body = jsonDecode(response.body);
Map<String, dynamic>? details;
for (var item in body) {
if (item['asset'].startsWith(assetCode)) {
details = item;
break;
}
}
if (details != null) {
TransactionData transactionData = TransactionData.fromJson(details);
logger.i(transactionData);
return transactionData;
} else {
logger.e('Failed to details for asset: ');
}
return null;
} catch (error) {
throw Exception("Failed to get fund details, $error");
}
}
Future<Operation?> _makeFundPaymentOperation(
{required String assetCode, required String issuer}) async {
TransactionData? transactionData =
await _fetchFundDetails(assetCode: assetCode);
Asset asset = AssetTypeCreditAlphaNum4(assetCode, issuer);
return PaymentOperationBuilder(
transactionData!.feeAccountId, asset, transactionData.feeFixed)
.build();
}
Future<Transaction?> _buildTransaction(
{required String destinationAddress,
required String amount,
required String currency,
String? memoText,
required bool funded}) async {
// check if I have enough balance
final accountBalances = await this.getBalance();
accountBalances.firstWhere(
(b) =>
b.assetCode == currency &&
double.parse(b.balance) > double.parse(amount), orElse: () {
if (accountBalances.contains(currency)) {
throw Exception('Balance is not enough.');
}
throw Exception('Balance with asset code ${currency} not found.');
});
// check that receiver account exists
final receiver = await _sdk.accounts.account(accountId);
// check that asset exists
var specificBalance = receiver.balances.firstWhere(
(balance) => balance.assetCode == currency,
orElse: () {
throw Exception('Balance with asset code ${currency} not found.');
},
);
final asset = _currencies.currencies[currency];
if (asset == null) {
throw Exception('${currency} not supported');
}
AccountResponse sender = await _sdk.accounts.account(accountId);
Asset tftAsset = AssetTypeCreditAlphaNum4(asset.assetCode, asset.issuer);
Transaction? transaction;
if (funded) {
Operation? paymentOperation = await _makeFundPaymentOperation(
assetCode: asset.assetCode, issuer: asset.issuer);
transaction = TransactionBuilder(sender)
.addOperation(paymentOperation!)
.addOperation(
PaymentOperationBuilder(destinationAddress, tftAsset, amount)
.build())
.addMemo(memoText != null ? Memo.text(memoText) : Memo.none())
.build();
} else {
transaction = TransactionBuilder(sender)
.addOperation(
PaymentOperationBuilder(destinationAddress, tftAsset, amount)
.build())
.addMemo(memoText != null ? Memo.text(memoText) : Memo.none())
.build();
}
return transaction;
}
Future<void> transferThroughThreefoldService(
{required String destinationAddress,
required String amount,
required String currency,
String? memoText}) async {
Transaction? fundedTransaction = await _buildTransaction(
destinationAddress: destinationAddress,
amount: amount,
currency: currency,
memoText: memoText,
funded: true);
fundedTransaction!.sign(_keyPair, _stellarNetwork);
logger.i('Sending to');
logger.i(
'${_serviceUrls[_network.toString()]}/transactionfunding_service/fund_transaction');
try {
final response = await http.post(
Uri.parse(
'${_serviceUrls[_network.toString()]}/transactionfunding_service/fund_transaction'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(
{'transaction': fundedTransaction.toEnvelopeXdrBase64()}),
);
logger.i(response.body);
} catch (error) {
throw Exception('Something went wrong! $error');
}
}
Future<List<ITransaction>> getTransactions({String? assetCodeFilter}) async {
Page<OperationResponse> payments = await _sdk.payments
.forAccount(accountId)
.order(RequestBuilderOrder.DESC)
.execute();
List<ITransaction> transactionDetails = [];
if (payments.records.isNotEmpty) {
for (OperationResponse response in payments.records) {
if (response is PaymentOperationResponse) {
final memoText = await this
.getMemoText(response.links.transaction.toJson()["href"]);
String assetCode = response.assetCode ?? 'XLM';
if (assetCodeFilter == null || assetCode == assetCodeFilter) {
final details = PaymentTransaction(
hash: response.transactionHash,
from: response.from,
to: response.to,
asset: response.assetCode.toString(),
amount: response.amount,
type: response.to == this.accountId
? TransactionType.Receive
: TransactionType.Payment,
status: response.transactionSuccessful,
date: DateTime.parse(response.createdAt).toLocal().toString(),
memo: memoText);
transactionDetails.add(details);
}
} else {
logger.i("Unhandled operation type: ${response.runtimeType}");
}
}
} else {
logger.i("No payment records found.");
}
return transactionDetails;
}
Future<List<BalanceInfo>> getBalance() async {
try {
List<BalanceInfo> balancesList =
await getBalanceByAccountID(network: _network, accountId: accountId);
return balancesList;
} catch (error) {
throw Exception('Could not get balance due to $error');
}
}
Future<List<VestingAccount>?> getVestingAccounts() async {
try {
final response = await http.post(
Uri.parse(
'${_serviceUrls[_network.toString()]}/vesting_service/vesting_accounts'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'owner_address': accountId}),
);
final body = jsonDecode(response.body);
if (body['vesting_accounts'] is List &&
body['vesting_accounts'].isEmpty) {
logger.i("no vesting account found");
return [];
} else {
List<VestingAccount> accountsList = [];
for (var account in body['vesting_accounts']) {
String address = account['address'];
VestingAccount vestingAccount = VestingAccount.fromJson(account);
accountsList.add(vestingAccount);
}
return accountsList;
}
} catch (error) {
throw Exception('Could not create vestingAccount due to $error');
}
}
Future<String> getMemoText(String url) async {
try {
final response = await http.get(
Uri.parse(url),
headers: {'Content-Type': 'application/json'},
);
final body = jsonDecode(response.body);
final memoText = body['memo'] ?? "";
return memoText;
} catch (e) {
throw Exception("Couldn't get memo text due to ${e}");
}
}
Future<SubmitTransactionResponse> createOrder(
{required String sellingAsset,
required String buyingAsset,
required String amount,
required String price,
String? memo}) async {
if (!_currencies.currencies.containsKey(sellingAsset)) {
throw Exception('Sell asset $sellingAsset is not available.');
}
if (!_currencies.currencies.containsKey(buyingAsset)) {
throw Exception('Buy asset $buyingAsset is not available.');
}
late final Asset sellAsset;
late final Asset buyAsset;
if (sellingAsset == 'XLM') {
sellAsset = AssetTypeNative();
} else {
sellAsset = AssetTypeCreditAlphaNum4(
_currencies.currencies[sellingAsset]!.assetCode,
_currencies.currencies[sellingAsset]!.issuer);
}
if (sellingAsset == 'XLM') {
buyAsset = AssetTypeNative();
} else {
buyAsset = AssetTypeCreditAlphaNum4(
_currencies.currencies[buyingAsset]!.assetCode,
_currencies.currencies[buyingAsset]!.issuer);
}
final ManageBuyOfferOperation buyOfferOperation =
ManageBuyOfferOperationBuilder(sellAsset, buyAsset, amount, price)
.build();
final account = await _sdk.accounts.account(accountId);
final balances = account.balances;
final sellAssetBalance = balances.firstWhere(
(balance) => balance.assetCode == sellingAsset,
orElse: () => throw Exception('Insufficient balance in $sellingAsset'),
);
final double sellAmount = double.parse(amount);
final double availableBalance = double.parse(sellAssetBalance.balance);
if (sellAmount > availableBalance) {
throw Exception(
'Insufficient balance in $sellingAsset. Available: $availableBalance');
}
final Transaction transaction = TransactionBuilder(account)
.addOperation(buyOfferOperation)
.addMemo(memo != null ? Memo.text(memo) : Memo.none())
.build();
transaction.sign(_keyPair, _stellarNetwork);
try {
final SubmitTransactionResponse response =
await _sdk.submitTransaction(transaction);
if (!response.success) {
logger.e('Transaction failed with result: ${response.resultXdr}');
}
return response;
} catch (error) {
throw Exception('Transaction failed due to: ${error.toString()}');
}
}
Future<SubmitTransactionResponse> cancelOrder(
{required String sellingAsset,
required String buyingAsset,
required String offerId,
String? memo}) async {
if (!_currencies.currencies.containsKey(sellingAsset)) {
throw Exception('Sell asset $sellingAsset is not available.');
}
if (!_currencies.currencies.containsKey(buyingAsset)) {
throw Exception('Buy asset $buyingAsset is not available.');
}
final offers = (await _sdk.offers.forAccount(accountId).execute()).records;
final OfferResponse? targetOffer = offers.firstWhere(
(offer) => offer.id == offerId,
orElse: () => throw Exception(
'Offer with ID $offerId not found in user\'s account.'),
);
late final Asset sellAsset;
late final Asset buyAsset;
if (sellingAsset == 'XLM') {
sellAsset = AssetTypeNative();
} else {
sellAsset = AssetTypeCreditAlphaNum4(
_currencies.currencies[sellingAsset]!.assetCode,
_currencies.currencies[sellingAsset]!.issuer);
}
if (sellingAsset == 'XLM') {
buyAsset = AssetTypeNative();
} else {
buyAsset = AssetTypeCreditAlphaNum4(
_currencies.currencies[buyingAsset]!.assetCode,
_currencies.currencies[buyingAsset]!.issuer);
}
final ManageBuyOfferOperation cancelOfferOperation =
ManageBuyOfferOperationBuilder(sellAsset, buyAsset, '0', '1')
.setOfferId(offerId)
.build();
final account = await _sdk.accounts.account(accountId);
final Transaction transaction = TransactionBuilder(account)
.addOperation(cancelOfferOperation)
.addMemo(memo != null ? Memo.text(memo) : Memo.none())
.build();
transaction.sign(_keyPair, _stellarNetwork);
try {
final SubmitTransactionResponse response =
await _sdk.submitTransaction(transaction);
if (!response.success) {
logger.e('Transaction failed with result: ${response.resultXdr}');
}
return response;
} catch (error) {
throw Exception('Transaction failed due to: ${error.toString()}');
}
}
Future<Stream<OrderBookResponse>> getOrderBook(
{required String sellingAssetCode,
required String buyingAssetCode}) async {
if (!_currencies.currencies.containsKey(sellingAssetCode)) {
throw Exception('Sell asset $sellingAssetCode is not available.');
}
if (!_currencies.currencies.containsKey(buyingAssetCode)) {
throw Exception('Buy asset $buyingAssetCode is not available.');
}
http.Client httpClient = http.Client();
Uri serverURI = Uri.parse(_horizonServerUrls[_network.toString()]!);
late final Asset sellingAsset;
late final Asset buyingAsset;
if (sellingAssetCode == 'XLM') {
sellingAsset = AssetTypeNative();
} else {
sellingAsset = AssetTypeCreditAlphaNum4(
_currencies.currencies[sellingAssetCode]!.assetCode,
_currencies.currencies[sellingAssetCode]!.issuer);
}
if (buyingAssetCode == 'XLM') {
buyingAsset = AssetTypeNative();
} else {
buyingAsset = AssetTypeCreditAlphaNum4(
_currencies.currencies[buyingAssetCode]!.assetCode,
_currencies.currencies[buyingAssetCode]!.issuer);
}
OrderBookRequestBuilder orderBookRequest =
OrderBookRequestBuilder(httpClient, serverURI)
..sellingAsset(sellingAsset)
..buyingAsset(buyingAsset);
return await orderBookRequest.stream();
}
Future<List<OfferResponse>> listMyOffers() async {
try {
final offers = await _sdk.offers.forAccount(accountId).execute();
if (offers.records.isEmpty) {
logger.i('No offers found for account: $accountId');
return [];
}
return offers.records;
} catch (error) {
throw Exception('Error listing offers for account $accountId: $error');
}
}
}