From 5f75e2889cdcb659456774bec3b228e5c9cef849 Mon Sep 17 00:00:00 2001 From: AlaaElattar Date: Tue, 3 Dec 2024 01:38:52 +0200 Subject: [PATCH 1/7] WIP: support creating && cancelling orders --- .../stellar_client/bin/stellar_client.dart | 26 ++- packages/stellar_client/lib/src/client.dart | 182 +++++++++++++++--- 2 files changed, 175 insertions(+), 33 deletions(-) diff --git a/packages/stellar_client/bin/stellar_client.dart b/packages/stellar_client/bin/stellar_client.dart index c66f7d75..f380f188 100644 --- a/packages/stellar_client/bin/stellar_client.dart +++ b/packages/stellar_client/bin/stellar_client.dart @@ -1,14 +1,24 @@ import 'package:stellar_client/stellar_client.dart'; void main() async { - final stellarClient = Client.create(NetworkType.PUBLIC); - await stellarClient.activateThroughThreefoldService(); + // final stellarClient = Client.create(NetworkType.PUBLIC); + // await stellarClient.activateThroughThreefoldService(); - await stellarClient.transfer( - destinationAddress: "destination-public-key", - amount: "20", - currency: "TFT", - memoText: "Memo Text"); + // await stellarClient.transfer( + // destinationAddress: "destination-public-key", + // amount: "20", + // currency: "TFT", + // memoText: "Memo Text"); - await stellarClient.getTransactions(); + // await stellarClient.getTransactions(); + + final stellarClient = Client.create(NetworkType.TESTNET); + await stellarClient.activateThroughFriendBot( + accountId: stellarClient.accountId); + await stellarClient.addTrustLine(); + final balances = await stellarClient.getBalance(); + print(balances); + await stellarClient.listOffers(); + // await stellarClient.getOrderBook( + // sellingAssetCode: 'USDC', buyingAssetCode: 'TFT'); } diff --git a/packages/stellar_client/lib/src/client.dart b/packages/stellar_client/lib/src/client.dart index 99b99320..67495f4f 100644 --- a/packages/stellar_client/lib/src/client.dart +++ b/packages/stellar_client/lib/src/client.dart @@ -6,6 +6,7 @@ class Client { late KeyPair _keyPair; late currency.Currencies _currencies; late Map _serviceUrls; + late Map _horizonServerUrls; late Network _stellarNetwork; String get accountId => _keyPair.accountId; @@ -37,10 +38,16 @@ class Client { 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; @@ -49,6 +56,9 @@ class Client { assetCode: 'TFT', issuer: "GA47YZA3PKFUZMPLQ3B5F2E3CJIB57TGGU7SPCQT2WAEYKN766PWIMB3", ); + usdc = currency.Currency( + assetCode: 'USDC', + issuer: 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5'); break; case NetworkType.PUBLIC: _sdk = StellarSDK.PUBLIC; @@ -57,12 +67,15 @@ class Client { assetCode: 'TFT', issuer: "GBOVQKJYHXRR3DX6NOX2RRYFRCUMSADGDESTDNBDS6CDVLGVESRTAC47", ); + usdc = currency.Currency( + assetCode: 'USDC', + issuer: 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN'); break; default: throw Exception('Unsupported network type'); } - _currencies = currency.Currencies({'TFT': tft}); + _currencies = currency.Currencies({'TFT': tft, 'USDC': usdc}); } Future activateThroughThreefoldService() async { @@ -121,38 +134,41 @@ class Client { } Future addTrustLine() async { - for (var entry in _currencies.currencies.entries) { - String currencyCode = entry.key; - currency.Currency currentCurrency = entry.value; + try { + 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); + String issuerAccountId = currentCurrency.issuer; + Asset currencyAsset = AssetTypeCreditAlphaNum4( + currentCurrency.assetCode, issuerAccountId); - ChangeTrustOperationBuilder changeTrustOperation = - ChangeTrustOperationBuilder(currencyAsset, "300000"); + ChangeTrustOperationBuilder changeTrustOperation = + ChangeTrustOperationBuilder(currencyAsset, "300000"); - final account = await _sdk.accounts.account(accountId); + final account = await _sdk.accounts.account(accountId); - Transaction transaction = TransactionBuilder(account) - .addOperation(changeTrustOperation.build()) - .build(); - transaction.sign(_keyPair, _stellarNetwork); + Transaction transaction = TransactionBuilder(account) + .addOperation(changeTrustOperation.build()) + .build(); + transaction.sign(_keyPair, _stellarNetwork); - SubmitTransactionResponse response = - await _sdk.submitTransaction(transaction); + SubmitTransactionResponse response = + await _sdk.submitTransaction(transaction); - if (!response.success) { - print("Failed to add trustline for $currencyCode"); - return false; - } else { - print("trustline for $currencyCode was added successfully"); - return true; + if (!response.success) { + print("Failed to add trustline for $currencyCode"); + return false; + } else { + print("trustline for $currencyCode was added successfully"); + } } - } - print("No trustlines were processed"); - return false; + return true; + } catch (error) { + print("An error occurred while adding trustlines: $error"); + return false; + } } Future transfer( @@ -479,4 +495,120 @@ class Client { throw Exception("Couldn't get memo text due to ${e}"); } } + + Future createOrder( + {required String fromAssetCode, + required String toAssetCode, + required String amount, + required String price, + String? memo}) async { + if (!_currencies.currencies.containsKey(fromAssetCode)) { + throw Exception('Sell asset $fromAssetCode is not available.'); + } + if (!_currencies.currencies.containsKey(toAssetCode)) { + throw Exception('Buy asset $toAssetCode is not available.'); + } + + final Asset buyAsset = AssetTypeCreditAlphaNum12( + _currencies.currencies[fromAssetCode]!.assetCode, + _currencies.currencies[fromAssetCode]!.issuer); + final Asset sellAsset = AssetTypeCreditAlphaNum12( + _currencies.currencies[toAssetCode]!.assetCode, + _currencies.currencies[toAssetCode]!.issuer); + final ManageBuyOfferOperation buyOfferOperation = + ManageBuyOfferOperationBuilder(buyAsset, sellAsset, amount, price) + .build(); + + final account = await _sdk.accounts.account(accountId); + + final balances = account.balances; + final sellAssetBalance = balances.firstWhere( + (balance) => balance.assetCode == fromAssetCode, + orElse: () => throw Exception('Insufficient balance in $fromAssetCode'), + ); + + final double sellAmount = double.parse(amount); + final double availableBalance = double.parse(sellAssetBalance.balance); + if (sellAmount > availableBalance) { + throw Exception( + 'Insufficient balance in $fromAssetCode. 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); + return response; + } catch (error) { + throw Exception('Transaction failed due to: ${error.toString()}'); + } + } + + // native --> Represents the Stellar native asset (XLM) + // credit_alphanum4: Represents a credit asset with a 4-character code. + // credit_alphanum12: Represents a credit asset with a 12-character code. + Future getOrderBook({ + // required String sellingAssetType, + required String sellingAssetCode, + // required String buyingAssetType, + required String buyingAssetCode, + int limit = 200, + }) 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.'); + } + + final sellingAssetIssuer = _currencies.currencies[sellingAssetCode]!.issuer; + final buyingAssetIssuer = _currencies.currencies[buyingAssetCode]!.issuer; + + final String horizonUrl = _horizonServerUrls[_network.toString()]!; + + final String endpoint = + '/order_book?selling_asset_type=credit_alphanum4&selling_asset_code=$sellingAssetCode&selling_asset_issuer=$sellingAssetIssuer&buying_asset_type=credit_alphanum4&buying_asset_code=$buyingAssetCode&buying_asset_issuer=$buyingAssetIssuer&limit=$limit'; + + final Uri uri = Uri.parse(horizonUrl + endpoint); + + try { + final response = await http.get(uri); + + if (response.statusCode == 200) { + final Map data = json.decode(response.body); + print(data); + + } else { + print('Failed to load order book. Status code: ${response.statusCode}'); + } + } catch (e) { + print('Error fetching order book: $e'); + } + } + + Future listOffers() async { + try { + final offers = await _sdk.offers.forAccount(accountId).execute(); + print(offers); + + if (offers.records.isEmpty) { + print('No offers found for account: $accountId'); + return; + } + + for (var offer in offers.records) { + print('Offer ID: ${offer.id}'); + print('Selling Asset: ${offer.selling}'); + print('Buying Asset: ${offer.buying}'); + print('Amount: ${offer.amount}'); + print('Price: ${offer.price}'); + print('-----------------------------------'); + } + } catch (error) { + print('Error listing offers for account $accountId: $error'); + } + } } From 0f603abd8eb2009dd33437898631cf899372301d Mon Sep 17 00:00:00 2001 From: AlaaElattar Date: Thu, 5 Dec 2024 12:41:42 +0200 Subject: [PATCH 2/7] support creating && cancelling orders --- .../stellar_client/bin/stellar_client.dart | 26 +-- packages/stellar_client/lib/src/client.dart | 153 ++++++++++++------ 2 files changed, 112 insertions(+), 67 deletions(-) diff --git a/packages/stellar_client/bin/stellar_client.dart b/packages/stellar_client/bin/stellar_client.dart index f380f188..c66f7d75 100644 --- a/packages/stellar_client/bin/stellar_client.dart +++ b/packages/stellar_client/bin/stellar_client.dart @@ -1,24 +1,14 @@ import 'package:stellar_client/stellar_client.dart'; void main() async { - // final stellarClient = Client.create(NetworkType.PUBLIC); - // await stellarClient.activateThroughThreefoldService(); + final stellarClient = Client.create(NetworkType.PUBLIC); + await stellarClient.activateThroughThreefoldService(); - // await stellarClient.transfer( - // destinationAddress: "destination-public-key", - // amount: "20", - // currency: "TFT", - // memoText: "Memo Text"); + await stellarClient.transfer( + destinationAddress: "destination-public-key", + amount: "20", + currency: "TFT", + memoText: "Memo Text"); - // await stellarClient.getTransactions(); - - final stellarClient = Client.create(NetworkType.TESTNET); - await stellarClient.activateThroughFriendBot( - accountId: stellarClient.accountId); - await stellarClient.addTrustLine(); - final balances = await stellarClient.getBalance(); - print(balances); - await stellarClient.listOffers(); - // await stellarClient.getOrderBook( - // sellingAssetCode: 'USDC', buyingAssetCode: 'TFT'); + await stellarClient.getTransactions(); } diff --git a/packages/stellar_client/lib/src/client.dart b/packages/stellar_client/lib/src/client.dart index f2716b77..3d6b70b1 100644 --- a/packages/stellar_client/lib/src/client.dart +++ b/packages/stellar_client/lib/src/client.dart @@ -487,42 +487,87 @@ class Client { } Future createOrder( - {required String fromAssetCode, - required String toAssetCode, + {required String sellingAsset, + required String buyingAsset, required String amount, required String price, String? memo}) async { - if (!_currencies.currencies.containsKey(fromAssetCode)) { - throw Exception('Sell asset $fromAssetCode is not available.'); + if (!_currencies.currencies.containsKey(sellingAsset)) { + throw Exception('Sell asset $sellingAsset is not available.'); } - if (!_currencies.currencies.containsKey(toAssetCode)) { - throw Exception('Buy asset $toAssetCode is not available.'); + if (!_currencies.currencies.containsKey(buyingAsset)) { + throw Exception('Buy asset $buyingAsset is not available.'); } - final Asset buyAsset = AssetTypeCreditAlphaNum12( - _currencies.currencies[fromAssetCode]!.assetCode, - _currencies.currencies[fromAssetCode]!.issuer); - final Asset sellAsset = AssetTypeCreditAlphaNum12( - _currencies.currencies[toAssetCode]!.assetCode, - _currencies.currencies[toAssetCode]!.issuer); + final Asset sellAsset = AssetTypeCreditAlphaNum4( + _currencies.currencies[sellingAsset]!.assetCode, + _currencies.currencies[sellingAsset]!.issuer); + final Asset buyAsset = AssetTypeCreditAlphaNum4( + _currencies.currencies[buyingAsset]!.assetCode, + _currencies.currencies[buyingAsset]!.issuer); + final ManageBuyOfferOperation buyOfferOperation = - ManageBuyOfferOperationBuilder(buyAsset, sellAsset, amount, price) + ManageBuyOfferOperationBuilder(sellAsset, buyAsset, amount, price) .build(); final account = await _sdk.accounts.account(accountId); final balances = account.balances; final sellAssetBalance = balances.firstWhere( - (balance) => balance.assetCode == fromAssetCode, - orElse: () => throw Exception('Insufficient balance in $fromAssetCode'), + (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 $fromAssetCode. Available: $availableBalance'); + 'Insufficient balance in $sellingAsset. Available: $availableBalance'); + } + final Transaction transaction = TransactionBuilder(account) + .addOperation(buyOfferOperation) + .addMemo(memo != null ? Memo.text(memo) : Memo.none()) + .build(); + print('Transaction XDR: ${transaction.toEnvelopeXdrBase64()}'); + + transaction.sign(_keyPair, _stellarNetwork); + try { + final SubmitTransactionResponse response = + await _sdk.submitTransaction(transaction); + if (!response.success) { + print('Transaction failed with result: ${response.resultXdr}'); + } + return response; + } catch (error) { + throw Exception('Transaction failed due to: ${error.toString()}'); + } + } + + Future 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 Asset sellAsset = AssetTypeCreditAlphaNum12( + _currencies.currencies[sellingAsset]!.assetCode, + _currencies.currencies[sellingAsset]!.issuer); + final Asset buyAsset = AssetTypeCreditAlphaNum12( + _currencies.currencies[buyingAsset]!.assetCode, + _currencies.currencies[buyingAsset]!.issuer); + + final ManageBuyOfferOperation buyOfferOperation = + ManageBuyOfferOperationBuilder(sellAsset, buyAsset, '0', '0') + .setOfferId(offerId) + .build(); + + final account = await _sdk.accounts.account(accountId); final Transaction transaction = TransactionBuilder(account) .addOperation(buyOfferOperation) .addMemo(memo != null ? Memo.text(memo) : Memo.none()) @@ -539,54 +584,63 @@ class Client { // native --> Represents the Stellar native asset (XLM) // credit_alphanum4: Represents a credit asset with a 4-character code. - // credit_alphanum12: Represents a credit asset with a 12-character code. - Future getOrderBook({ - // required String sellingAssetType, - required String sellingAssetCode, - // required String buyingAssetType, - required String buyingAssetCode, - int limit = 200, - }) async { + // credit_alphanum12: Represents a credit asset with a 12-character code + + Future 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()]!); + + Asset sellingAsset = Asset.createNonNativeAsset( + sellingAssetCode, _currencies.currencies[sellingAssetCode]!.issuer); + Asset buyingAsset = Asset.createNonNativeAsset( + buyingAssetCode, _currencies.currencies[buyingAssetCode]!.issuer); + + OrderBookRequestBuilder orderBookRequest = + OrderBookRequestBuilder(httpClient, serverURI) + ..sellingAsset(sellingAsset) + ..buyingAsset(buyingAsset); + + Stream orderBookStream = orderBookRequest.stream(); + orderBookStream.listen((orderBookResponse) { + print("Received OrderBookResponse:"); + print("Base: ${orderBookResponse.base}"); + print("Counter: ${orderBookResponse.counter}"); + + print("\nBids:"); + for (var offer in orderBookResponse.bids) { + // priceR numerator/denominator + print( + 'Bid - Amount: ${offer.amount}, Price: ${offer.price}, PriceR: ${offer.priceR}'); + } - final sellingAssetIssuer = _currencies.currencies[sellingAssetCode]!.issuer; - final buyingAssetIssuer = _currencies.currencies[buyingAssetCode]!.issuer; - - final String horizonUrl = _horizonServerUrls[_network.toString()]!; - - final String endpoint = - '/order_book?selling_asset_type=credit_alphanum4&selling_asset_code=$sellingAssetCode&selling_asset_issuer=$sellingAssetIssuer&buying_asset_type=credit_alphanum4&buying_asset_code=$buyingAssetCode&buying_asset_issuer=$buyingAssetIssuer&limit=$limit'; - - final Uri uri = Uri.parse(horizonUrl + endpoint); - - try { - final response = await http.get(uri); - - if (response.statusCode == 200) { - final Map data = json.decode(response.body); - print(data); - - } else { - print('Failed to load order book. Status code: ${response.statusCode}'); + print("\nAsks:"); + for (var offer in orderBookResponse.asks) { + print( + 'Ask - Amount: ${offer.amount}, Price: ${offer.price}, PriceR: ${offer.priceR}'); } - } catch (e) { - print('Error fetching order book: $e'); - } + }, onError: (error) { + print("Error while listening to order book stream: $error"); + }, onDone: () { + print("Order book stream is closed."); + }); } - Future listOffers() async { + Future> listMyOffers() async { try { final offers = await _sdk.offers.forAccount(accountId).execute(); print(offers); if (offers.records.isEmpty) { print('No offers found for account: $accountId'); - return; + return []; } for (var offer in offers.records) { @@ -597,8 +651,9 @@ class Client { print('Price: ${offer.price}'); print('-----------------------------------'); } + return offers.records; } catch (error) { - print('Error listing offers for account $accountId: $error'); + throw Exception('Error listing offers for account $accountId: $error'); } } } From 3d6c32086a4f4c697e714328885392580710ec23 Mon Sep 17 00:00:00 2001 From: AlaaElattar Date: Sun, 8 Dec 2024 10:15:44 +0200 Subject: [PATCH 3/7] WIP: trying to create orders with TF service --- .../stellar_client/bin/stellar_client.dart | 55 +++++++-- packages/stellar_client/lib/src/client.dart | 111 +++++++++++++++++- 2 files changed, 152 insertions(+), 14 deletions(-) diff --git a/packages/stellar_client/bin/stellar_client.dart b/packages/stellar_client/bin/stellar_client.dart index c66f7d75..de0de7a6 100644 --- a/packages/stellar_client/bin/stellar_client.dart +++ b/packages/stellar_client/bin/stellar_client.dart @@ -1,14 +1,53 @@ import 'package:stellar_client/stellar_client.dart'; void main() async { - final stellarClient = Client.create(NetworkType.PUBLIC); - await stellarClient.activateThroughThreefoldService(); + // final stellarClient = Client.create(NetworkType.PUBLIC); + // await stellarClient.activateThroughThreefoldService(); - await stellarClient.transfer( - destinationAddress: "destination-public-key", - amount: "20", - currency: "TFT", - memoText: "Memo Text"); + // await stellarClient.transfer( + // destinationAddress: "destination-public-key", + // amount: "20", + // currency: "TFT", + // memoText: "Memo Text"); - await stellarClient.getTransactions(); + // await stellarClient.getTransactions(); + + final stellarClient = Client(NetworkType.PUBLIC, + "SDSVD7L2OZXHW2PLARRJ34ZRJVBPMJWKVG4HNIEJKFHI35E3D3WWAUL4"); + print(stellarClient.accountId); + print(stellarClient.secretSeed); + + // final response = await stellarClient.createOrderThroughThreefoldService( + // sellingAsset: 'TFT', buyingAsset: 'USDC', amount: '5', price: '0.9'); + + // // await stellarClient.addTrustLineThroughThreefoldService('USDC'); + await stellarClient.createOrderThroughThreefoldService( + sellingAsset: 'TFT', buyingAsset: 'USDC', amount: '3', price: '1'); + final balances = await stellarClient.getBalance(); + print(balances); + // // final orderbook = await stellarClient.getOrderBook( + // // sellingAssetCode: 'TFT', buyingAssetCode: 'USDC'); + // await stellarClient.listMyOffers(); + // await stellarClient.getOrderBook( + // sellingAssetCode: 'USDC', buyingAssetCode: 'TFT'); + + // final stellarClient = Client(NetworkType.TESTNET, + // "SA7C4BONCZUVAMPOAGKJMKIHN4FQYLRF6KVFEFUDQS6EBIOCLLNKQQCY"); + // print(stellarClient.accountId); + // print(stellarClient.secretSeed); +//SCG2NAYKV2AS4N3INA3DMFXKLMBAOH2MN2TA3FSGF6FUUJXJQVDYPXRN + // await stellarClient.activateThroughFriendBot( + // accountId: stellarClient.accountId); + + // await stellarClient.addTrustLine(); + // final balances = await stellarClient.getBalance(); + // print(balances); + + // await stellarClient.createOrder( + // sellingAsset: 'TFT', buyingAsset: 'USDC', amount: '3', price: '1'); + // await stellarClient.listMyOffers(); + // final res = await stellarClient.cancelOrder( + // sellingAsset: 'TFT', buyingAsset: 'USDC', offerId: '12910'); + // print(res.success); + // await stellarClient.listMyOffers(); } diff --git a/packages/stellar_client/lib/src/client.dart b/packages/stellar_client/lib/src/client.dart index 3d6b70b1..6226c483 100644 --- a/packages/stellar_client/lib/src/client.dart +++ b/packages/stellar_client/lib/src/client.dart @@ -234,7 +234,6 @@ class Client { ); final data = jsonDecode(response.body); - String trustlineTransaction = data['addtrustline_transaction']; XdrTransactionEnvelope xdrTxEnvelope = XdrTransactionEnvelope.fromEnvelopeXdrString(trustlineTransaction); @@ -555,27 +554,37 @@ class Client { throw Exception('Buy asset $buyingAsset is not available.'); } - final Asset sellAsset = AssetTypeCreditAlphaNum12( + 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.'), + ); + + final Asset sellAsset = AssetTypeCreditAlphaNum4( _currencies.currencies[sellingAsset]!.assetCode, _currencies.currencies[sellingAsset]!.issuer); - final Asset buyAsset = AssetTypeCreditAlphaNum12( + final Asset buyAsset = AssetTypeCreditAlphaNum4( _currencies.currencies[buyingAsset]!.assetCode, _currencies.currencies[buyingAsset]!.issuer); - final ManageBuyOfferOperation buyOfferOperation = - ManageBuyOfferOperationBuilder(sellAsset, buyAsset, '0', '0') + final ManageBuyOfferOperation cancelOfferOperation = + ManageBuyOfferOperationBuilder(sellAsset, buyAsset, '0', '1') .setOfferId(offerId) .build(); final account = await _sdk.accounts.account(accountId); final Transaction transaction = TransactionBuilder(account) - .addOperation(buyOfferOperation) + .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) { + print('Transaction failed with result: ${response.resultXdr}'); + } return response; } catch (error) { throw Exception('Transaction failed due to: ${error.toString()}'); @@ -656,4 +665,94 @@ class Client { throw Exception('Error listing offers for account $accountId: $error'); } } + + Future _buildOrderTransaction( + {required String sellingAsset, + required String buyingAsset, + required String amount, + required String price, + String? memo, + required bool funded}) 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 Asset sellAsset = AssetTypeCreditAlphaNum4( + _currencies.currencies[sellingAsset]!.assetCode, + _currencies.currencies[sellingAsset]!.issuer); + final Asset 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'); + } + Transaction? transaction; + if (funded) { + Operation? operation = await _makeFundPaymentOperation( + assetCode: sellingAsset, + issuer: _currencies.currencies[sellingAsset]!.issuer); + transaction = TransactionBuilder(account) + .addOperation(operation!) + .addOperation(buyOfferOperation) + .addMemo(memo != null ? Memo.text(memo) : Memo.none()) + .build(); + } else { + transaction = TransactionBuilder(account) + .addOperation(buyOfferOperation) + .addMemo(memo != null ? Memo.text(memo) : Memo.none()) + .build(); + } + return transaction; + } + + Future createOrderThroughThreefoldService( + {required String sellingAsset, + required String buyingAsset, + required String amount, + required String price, + String? memo}) async { + Transaction? fundedOrder = await _buildOrderTransaction( + sellingAsset: sellingAsset, + buyingAsset: buyingAsset, + amount: amount, + price: price, + funded: true); + + fundedOrder!.sign(_keyPair, _stellarNetwork); + + print('Sending to'); + print( + '${_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': fundedOrder.toEnvelopeXdrBase64()}), + ); + + print(response.body); + } catch (error) { + throw Exception('Something went wrong! $error'); + } + } } From 3b94cab0f9cbf128091165b95dd616f794a9f1bf Mon Sep 17 00:00:00 2001 From: AlaaElattar Date: Sun, 8 Dec 2024 12:58:45 +0200 Subject: [PATCH 4/7] support native asset && comment orders with TF service --- .../stellar_client/bin/stellar_client.dart | 55 +--- packages/stellar_client/lib/src/client.dart | 266 ++++++++++-------- 2 files changed, 159 insertions(+), 162 deletions(-) diff --git a/packages/stellar_client/bin/stellar_client.dart b/packages/stellar_client/bin/stellar_client.dart index de0de7a6..c66f7d75 100644 --- a/packages/stellar_client/bin/stellar_client.dart +++ b/packages/stellar_client/bin/stellar_client.dart @@ -1,53 +1,14 @@ import 'package:stellar_client/stellar_client.dart'; void main() async { - // final stellarClient = Client.create(NetworkType.PUBLIC); - // await stellarClient.activateThroughThreefoldService(); + final stellarClient = Client.create(NetworkType.PUBLIC); + await stellarClient.activateThroughThreefoldService(); - // await stellarClient.transfer( - // destinationAddress: "destination-public-key", - // amount: "20", - // currency: "TFT", - // memoText: "Memo Text"); + await stellarClient.transfer( + destinationAddress: "destination-public-key", + amount: "20", + currency: "TFT", + memoText: "Memo Text"); - // await stellarClient.getTransactions(); - - final stellarClient = Client(NetworkType.PUBLIC, - "SDSVD7L2OZXHW2PLARRJ34ZRJVBPMJWKVG4HNIEJKFHI35E3D3WWAUL4"); - print(stellarClient.accountId); - print(stellarClient.secretSeed); - - // final response = await stellarClient.createOrderThroughThreefoldService( - // sellingAsset: 'TFT', buyingAsset: 'USDC', amount: '5', price: '0.9'); - - // // await stellarClient.addTrustLineThroughThreefoldService('USDC'); - await stellarClient.createOrderThroughThreefoldService( - sellingAsset: 'TFT', buyingAsset: 'USDC', amount: '3', price: '1'); - final balances = await stellarClient.getBalance(); - print(balances); - // // final orderbook = await stellarClient.getOrderBook( - // // sellingAssetCode: 'TFT', buyingAssetCode: 'USDC'); - // await stellarClient.listMyOffers(); - // await stellarClient.getOrderBook( - // sellingAssetCode: 'USDC', buyingAssetCode: 'TFT'); - - // final stellarClient = Client(NetworkType.TESTNET, - // "SA7C4BONCZUVAMPOAGKJMKIHN4FQYLRF6KVFEFUDQS6EBIOCLLNKQQCY"); - // print(stellarClient.accountId); - // print(stellarClient.secretSeed); -//SCG2NAYKV2AS4N3INA3DMFXKLMBAOH2MN2TA3FSGF6FUUJXJQVDYPXRN - // await stellarClient.activateThroughFriendBot( - // accountId: stellarClient.accountId); - - // await stellarClient.addTrustLine(); - // final balances = await stellarClient.getBalance(); - // print(balances); - - // await stellarClient.createOrder( - // sellingAsset: 'TFT', buyingAsset: 'USDC', amount: '3', price: '1'); - // await stellarClient.listMyOffers(); - // final res = await stellarClient.cancelOrder( - // sellingAsset: 'TFT', buyingAsset: 'USDC', offerId: '12910'); - // print(res.success); - // await stellarClient.listMyOffers(); + await stellarClient.getTransactions(); } diff --git a/packages/stellar_client/lib/src/client.dart b/packages/stellar_client/lib/src/client.dart index 6226c483..33d08e69 100644 --- a/packages/stellar_client/lib/src/client.dart +++ b/packages/stellar_client/lib/src/client.dart @@ -491,19 +491,32 @@ class Client { required String amount, required String price, String? memo}) async { - if (!_currencies.currencies.containsKey(sellingAsset)) { + if (!_currencies.currencies.containsKey(sellingAsset) || + sellingAsset == 'XLM') { throw Exception('Sell asset $sellingAsset is not available.'); } - if (!_currencies.currencies.containsKey(buyingAsset)) { + if (!_currencies.currencies.containsKey(buyingAsset) || + buyingAsset == 'XLM') { throw Exception('Buy asset $buyingAsset is not available.'); } - final Asset sellAsset = AssetTypeCreditAlphaNum4( - _currencies.currencies[sellingAsset]!.assetCode, - _currencies.currencies[sellingAsset]!.issuer); - final Asset buyAsset = AssetTypeCreditAlphaNum4( - _currencies.currencies[buyingAsset]!.assetCode, - _currencies.currencies[buyingAsset]!.issuer); + 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) @@ -547,10 +560,12 @@ class Client { required String buyingAsset, required String offerId, String? memo}) async { - if (!_currencies.currencies.containsKey(sellingAsset)) { + if (!_currencies.currencies.containsKey(sellingAsset) || + sellingAsset == 'XLM') { throw Exception('Sell asset $sellingAsset is not available.'); } - if (!_currencies.currencies.containsKey(buyingAsset)) { + if (!_currencies.currencies.containsKey(buyingAsset) || + buyingAsset == 'XLM') { throw Exception('Buy asset $buyingAsset is not available.'); } @@ -561,12 +576,23 @@ class Client { 'Offer with ID $offerId not found in user\'s account.'), ); - final Asset sellAsset = AssetTypeCreditAlphaNum4( - _currencies.currencies[sellingAsset]!.assetCode, - _currencies.currencies[sellingAsset]!.issuer); - final Asset buyAsset = AssetTypeCreditAlphaNum4( - _currencies.currencies[buyingAsset]!.assetCode, - _currencies.currencies[buyingAsset]!.issuer); + 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') @@ -591,26 +617,36 @@ class Client { } } - // native --> Represents the Stellar native asset (XLM) - // credit_alphanum4: Represents a credit asset with a 4-character code. - // credit_alphanum12: Represents a credit asset with a 12-character code - Future getOrderBook( {required String sellingAssetCode, required String buyingAssetCode}) async { - if (!_currencies.currencies.containsKey(sellingAssetCode)) { + if (!_currencies.currencies.containsKey(sellingAssetCode) || + sellingAssetCode == 'XLM') { throw Exception('Sell asset $sellingAssetCode is not available.'); } - if (!_currencies.currencies.containsKey(buyingAssetCode)) { + if (!_currencies.currencies.containsKey(buyingAssetCode) || + buyingAssetCode == 'XLM') { 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; - Asset sellingAsset = Asset.createNonNativeAsset( - sellingAssetCode, _currencies.currencies[sellingAssetCode]!.issuer); - Asset buyingAsset = Asset.createNonNativeAsset( - buyingAssetCode, _currencies.currencies[buyingAssetCode]!.issuer); + 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) @@ -666,93 +702,93 @@ class Client { } } - Future _buildOrderTransaction( - {required String sellingAsset, - required String buyingAsset, - required String amount, - required String price, - String? memo, - required bool funded}) 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 Asset sellAsset = AssetTypeCreditAlphaNum4( - _currencies.currencies[sellingAsset]!.assetCode, - _currencies.currencies[sellingAsset]!.issuer); - final Asset 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'); - } - Transaction? transaction; - if (funded) { - Operation? operation = await _makeFundPaymentOperation( - assetCode: sellingAsset, - issuer: _currencies.currencies[sellingAsset]!.issuer); - transaction = TransactionBuilder(account) - .addOperation(operation!) - .addOperation(buyOfferOperation) - .addMemo(memo != null ? Memo.text(memo) : Memo.none()) - .build(); - } else { - transaction = TransactionBuilder(account) - .addOperation(buyOfferOperation) - .addMemo(memo != null ? Memo.text(memo) : Memo.none()) - .build(); - } - return transaction; - } - - Future createOrderThroughThreefoldService( - {required String sellingAsset, - required String buyingAsset, - required String amount, - required String price, - String? memo}) async { - Transaction? fundedOrder = await _buildOrderTransaction( - sellingAsset: sellingAsset, - buyingAsset: buyingAsset, - amount: amount, - price: price, - funded: true); - - fundedOrder!.sign(_keyPair, _stellarNetwork); - - print('Sending to'); - print( - '${_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': fundedOrder.toEnvelopeXdrBase64()}), - ); - - print(response.body); - } catch (error) { - throw Exception('Something went wrong! $error'); - } - } + // Future _buildOrderTransaction( + // {required String sellingAsset, + // required String buyingAsset, + // required String amount, + // required String price, + // String? memo, + // required bool funded}) 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 Asset sellAsset = AssetTypeCreditAlphaNum4( + // _currencies.currencies[sellingAsset]!.assetCode, + // _currencies.currencies[sellingAsset]!.issuer); + // final Asset 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'); + // } + // Transaction? transaction; + // if (funded) { + // // Operation? operation = await _makeFundPaymentOperation( + // // assetCode: sellingAsset, + // // issuer: _currencies.currencies[sellingAsset]!.issuer); + // transaction = TransactionBuilder(account) + // .addOperation(buyOfferOperation) + // .addOperation(buyOfferOperation) + // .addMemo(memo != null ? Memo.text(memo) : Memo.none()) + // .build(); + // } else { + // transaction = TransactionBuilder(account) + // .addOperation(buyOfferOperation) + // .addMemo(memo != null ? Memo.text(memo) : Memo.none()) + // .build(); + // } + // return transaction; + // } + + // Future createOrderThroughThreefoldService( + // {required String sellingAsset, + // required String buyingAsset, + // required String amount, + // required String price, + // String? memo}) async { + // Transaction? fundedOrder = await _buildOrderTransaction( + // sellingAsset: sellingAsset, + // buyingAsset: buyingAsset, + // amount: amount, + // price: price, + // funded: true); + + // fundedOrder!.sign(_keyPair, _stellarNetwork); + + // print('Sending to'); + // print( + // '${_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': fundedOrder.toEnvelopeXdrBase64()}), + // ); + + // print(response.body); + // } catch (error) { + // throw Exception('Something went wrong! $error'); + // } + // } } From 8bdabab0c908407e595e0bc9f5f3e8f5a0b28162 Mon Sep 17 00:00:00 2001 From: AlaaElattar Date: Sun, 22 Dec 2024 17:29:05 +0200 Subject: [PATCH 5/7] remova commented code --- packages/stellar_client/lib/src/client.dart | 90 --------------------- 1 file changed, 90 deletions(-) diff --git a/packages/stellar_client/lib/src/client.dart b/packages/stellar_client/lib/src/client.dart index 33d08e69..2a12d1f7 100644 --- a/packages/stellar_client/lib/src/client.dart +++ b/packages/stellar_client/lib/src/client.dart @@ -701,94 +701,4 @@ class Client { throw Exception('Error listing offers for account $accountId: $error'); } } - - // Future _buildOrderTransaction( - // {required String sellingAsset, - // required String buyingAsset, - // required String amount, - // required String price, - // String? memo, - // required bool funded}) 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 Asset sellAsset = AssetTypeCreditAlphaNum4( - // _currencies.currencies[sellingAsset]!.assetCode, - // _currencies.currencies[sellingAsset]!.issuer); - // final Asset 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'); - // } - // Transaction? transaction; - // if (funded) { - // // Operation? operation = await _makeFundPaymentOperation( - // // assetCode: sellingAsset, - // // issuer: _currencies.currencies[sellingAsset]!.issuer); - // transaction = TransactionBuilder(account) - // .addOperation(buyOfferOperation) - // .addOperation(buyOfferOperation) - // .addMemo(memo != null ? Memo.text(memo) : Memo.none()) - // .build(); - // } else { - // transaction = TransactionBuilder(account) - // .addOperation(buyOfferOperation) - // .addMemo(memo != null ? Memo.text(memo) : Memo.none()) - // .build(); - // } - // return transaction; - // } - - // Future createOrderThroughThreefoldService( - // {required String sellingAsset, - // required String buyingAsset, - // required String amount, - // required String price, - // String? memo}) async { - // Transaction? fundedOrder = await _buildOrderTransaction( - // sellingAsset: sellingAsset, - // buyingAsset: buyingAsset, - // amount: amount, - // price: price, - // funded: true); - - // fundedOrder!.sign(_keyPair, _stellarNetwork); - - // print('Sending to'); - // print( - // '${_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': fundedOrder.toEnvelopeXdrBase64()}), - // ); - - // print(response.body); - // } catch (error) { - // throw Exception('Something went wrong! $error'); - // } - // } } From 3f4b8d1e18bb2776984b6e60a5dd77e3e2ad5417 Mon Sep 17 00:00:00 2001 From: AlaaElattar Date: Wed, 25 Dec 2024 10:12:48 +0200 Subject: [PATCH 6/7] fix workflow --- packages/stellar_client/lib/src/client.dart | 32 ++++++++++----------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/packages/stellar_client/lib/src/client.dart b/packages/stellar_client/lib/src/client.dart index 7681b5ec..f043a253 100644 --- a/packages/stellar_client/lib/src/client.dart +++ b/packages/stellar_client/lib/src/client.dart @@ -138,27 +138,26 @@ class Client { } Future addTrustLine() async { - try { - for (var entry in _currencies.currencies.entries) { - String currencyCode = entry.key; - currency.Currency currentCurrency = entry.value; + 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); + String issuerAccountId = currentCurrency.issuer; + Asset currencyAsset = + AssetTypeCreditAlphaNum4(currentCurrency.assetCode, issuerAccountId); - ChangeTrustOperationBuilder changeTrustOperation = - ChangeTrustOperationBuilder(currencyAsset, "300000"); + ChangeTrustOperationBuilder changeTrustOperation = + ChangeTrustOperationBuilder(currencyAsset, "300000"); - final account = await _sdk.accounts.account(accountId); + final account = await _sdk.accounts.account(accountId); - Transaction transaction = TransactionBuilder(account) - .addOperation(changeTrustOperation.build()) - .build(); - transaction.sign(_keyPair, _stellarNetwork); + Transaction transaction = TransactionBuilder(account) + .addOperation(changeTrustOperation.build()) + .build(); + transaction.sign(_keyPair, _stellarNetwork); - SubmitTransactionResponse response = - await _sdk.submitTransaction(transaction); + SubmitTransactionResponse response = + await _sdk.submitTransaction(transaction); if (!response.success) { logger.e("Failed to add trustline for $currencyCode"); @@ -167,6 +166,7 @@ class Client { logger.i("trustline for $currencyCode was added successfully"); return true; } + } logger.i("No trustlines were processed"); return false; From 5c44c9c7468474979687cf801b3d997159abe589 Mon Sep 17 00:00:00 2001 From: AlaaElattar Date: Wed, 25 Dec 2024 10:41:39 +0200 Subject: [PATCH 7/7] added native asset in currencies list && remove all prints --- packages/stellar_client/lib/src/client.dart | 66 +++++---------------- 1 file changed, 16 insertions(+), 50 deletions(-) diff --git a/packages/stellar_client/lib/src/client.dart b/packages/stellar_client/lib/src/client.dart index f043a253..7c4b5452 100644 --- a/packages/stellar_client/lib/src/client.dart +++ b/packages/stellar_client/lib/src/client.dart @@ -79,7 +79,11 @@ class Client { throw Exception('Unsupported network type'); } - _currencies = currency.Currencies({'TFT': tft, 'USDC': usdc}); + _currencies = currency.Currencies({ + 'TFT': tft, + 'USDC': usdc, + 'XLM': currency.Currency(assetCode: 'XLM', issuer: "") + }); } Future activateThroughThreefoldService() async { @@ -492,12 +496,10 @@ class Client { required String amount, required String price, String? memo}) async { - if (!_currencies.currencies.containsKey(sellingAsset) || - sellingAsset == 'XLM') { + if (!_currencies.currencies.containsKey(sellingAsset)) { throw Exception('Sell asset $sellingAsset is not available.'); } - if (!_currencies.currencies.containsKey(buyingAsset) || - buyingAsset == 'XLM') { + if (!_currencies.currencies.containsKey(buyingAsset)) { throw Exception('Buy asset $buyingAsset is not available.'); } @@ -541,14 +543,13 @@ class Client { .addOperation(buyOfferOperation) .addMemo(memo != null ? Memo.text(memo) : Memo.none()) .build(); - print('Transaction XDR: ${transaction.toEnvelopeXdrBase64()}'); transaction.sign(_keyPair, _stellarNetwork); try { final SubmitTransactionResponse response = await _sdk.submitTransaction(transaction); if (!response.success) { - print('Transaction failed with result: ${response.resultXdr}'); + logger.e('Transaction failed with result: ${response.resultXdr}'); } return response; } catch (error) { @@ -561,12 +562,10 @@ class Client { required String buyingAsset, required String offerId, String? memo}) async { - if (!_currencies.currencies.containsKey(sellingAsset) || - sellingAsset == 'XLM') { + if (!_currencies.currencies.containsKey(sellingAsset)) { throw Exception('Sell asset $sellingAsset is not available.'); } - if (!_currencies.currencies.containsKey(buyingAsset) || - buyingAsset == 'XLM') { + if (!_currencies.currencies.containsKey(buyingAsset)) { throw Exception('Buy asset $buyingAsset is not available.'); } @@ -610,7 +609,7 @@ class Client { final SubmitTransactionResponse response = await _sdk.submitTransaction(transaction); if (!response.success) { - print('Transaction failed with result: ${response.resultXdr}'); + logger.e('Transaction failed with result: ${response.resultXdr}'); } return response; } catch (error) { @@ -618,15 +617,13 @@ class Client { } } - Future getOrderBook( + Future> getOrderBook( {required String sellingAssetCode, required String buyingAssetCode}) async { - if (!_currencies.currencies.containsKey(sellingAssetCode) || - sellingAssetCode == 'XLM') { + if (!_currencies.currencies.containsKey(sellingAssetCode)) { throw Exception('Sell asset $sellingAssetCode is not available.'); } - if (!_currencies.currencies.containsKey(buyingAssetCode) || - buyingAssetCode == 'XLM') { + if (!_currencies.currencies.containsKey(buyingAssetCode)) { throw Exception('Buy asset $buyingAssetCode is not available.'); } http.Client httpClient = http.Client(); @@ -654,49 +651,18 @@ class Client { ..sellingAsset(sellingAsset) ..buyingAsset(buyingAsset); - Stream orderBookStream = orderBookRequest.stream(); - orderBookStream.listen((orderBookResponse) { - print("Received OrderBookResponse:"); - print("Base: ${orderBookResponse.base}"); - print("Counter: ${orderBookResponse.counter}"); - - print("\nBids:"); - for (var offer in orderBookResponse.bids) { - // priceR numerator/denominator - print( - 'Bid - Amount: ${offer.amount}, Price: ${offer.price}, PriceR: ${offer.priceR}'); - } - - print("\nAsks:"); - for (var offer in orderBookResponse.asks) { - print( - 'Ask - Amount: ${offer.amount}, Price: ${offer.price}, PriceR: ${offer.priceR}'); - } - }, onError: (error) { - print("Error while listening to order book stream: $error"); - }, onDone: () { - print("Order book stream is closed."); - }); + return await orderBookRequest.stream(); } Future> listMyOffers() async { try { final offers = await _sdk.offers.forAccount(accountId).execute(); - print(offers); if (offers.records.isEmpty) { - print('No offers found for account: $accountId'); + logger.i('No offers found for account: $accountId'); return []; } - for (var offer in offers.records) { - print('Offer ID: ${offer.id}'); - print('Selling Asset: ${offer.selling}'); - print('Buying Asset: ${offer.buying}'); - print('Amount: ${offer.amount}'); - print('Price: ${offer.price}'); - print('-----------------------------------'); - } return offers.records; } catch (error) { throw Exception('Error listing offers for account $accountId: $error');