Skip to content

Commit

Permalink
Updated the request builder to maintain the original path and query (#12
Browse files Browse the repository at this point in the history
)
  • Loading branch information
jopmiddelkamp authored Mar 26, 2024
1 parent 2de0d74 commit 7d8d8f3
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 134 deletions.
160 changes: 55 additions & 105 deletions stellar-dotnet-sdk-console/Program.cs
Original file line number Diff line number Diff line change
@@ -1,124 +1,74 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using stellar_dotnet_sdk;
using stellar_dotnet_sdk.requests;
using stellar_dotnet_sdk.responses;

namespace TestConsole
{
public class Program
{
//For testing use the following account info, this only exists on test network and may be wiped at any time...
//Public: GAZHWW2NBPDVJ6PEEOZ2X43QV5JUDYS3XN4OWOTBR6WUACTUML2CCJLI
//Secret: SCD74D46TJYXOUXFC5YOA72UTPCCVHK2GRSLKSPRB66VK6UJHQX2Y3R3

public static async Task Main(string[] args)
{
//Network.UseTestNetwork();
//using (var server = new Server("https://horizon-testnet.stellar.org"))
//{
// //var friendBot = await server.TestNetFriendBot
// // .FundAccount(KeyPair.Random())
// // .Execute();
namespace TestConsole;

// //await GetLedgerTransactions(server);
// //await ShowAccountTransactions(server);
// ShowTestKeyValue(server);
//}


using (var server = new Server("https://horizon.stellar.org"))
{
Console.WriteLine("-- Streaming All New Ledgers On The Network --");
await server.Ledgers
.Cursor("now")
.Stream((sender, response) => { ShowOperationResponse(server, sender, response); })
.Connect();
}

Console.ReadLine();
}

private static async Task ShowAccountTransactions(Server server)
{
Console.WriteLine("-- Show Account Transactions (ForAccount) --");

var transactions = await server.Transactions
.ForAccount("GAZHWW2NBPDVJ6PEEOZ2X43QV5JUDYS3XN4OWOTBR6WUACTUML2CCJLI")
.Execute();
public class Program
{
private const int DefaultFee = 1000000;

ShowTransactionRecords(transactions.Records);
Console.WriteLine();
}
public static async Task Main(string[] args)
{
Network.UsePublicNetwork();
using var server = new Server("https://horizon.stellar.org");

await CreateAccount(server).ConfigureAwait(false);
}

private static async Task CreateAccount(Server server)
{
var source = KeyPair.FromSecretSeed("{TO_BE_CONFIGURED}");
Console.WriteLine("Source account: {TO_BE_CONFIGURED}");
var destination = KeyPair.Random();
Console.WriteLine("Destination account: " + destination.AccountId);

private static async Task GetLedgerTransactions(Server server)
{
Console.WriteLine("-- Show Ledger Transactions (ForLedger) --");
// get a list of transactions that occurred in ledger 1400
var transactions = await server.Transactions
.ForLedger(2365)
.Execute();
var sourceAccount = await server.Accounts.Account(source.AccountId).ConfigureAwait(false);
var transaction = new TransactionBuilder(sourceAccount)
.SetFee(DefaultFee)
.AddOperation(new CreateAccountOperation.Builder(destination, "1").Build())
.Build();

ShowTransactionRecords(transactions.Records);
Console.WriteLine();
}
transaction.Sign(source);

private static void ShowTransactionRecords(List<TransactionResponse> transactions)
var response = await server.SubmitTransaction(transaction).ConfigureAwait(false);
if (response.IsSuccess())
{
foreach (var tran in transactions)
ShowTransactionRecord(tran);
Console.WriteLine("Create account response: " + response.Hash);
await DeleteAccount(server, destination, source).ConfigureAwait(false);
}

private static void ShowTransactionRecord(TransactionResponse tran)
else
{
Console.WriteLine($"Ledger: {tran.Ledger}, Hash: {tran.Hash}, Fee Paid: {tran.FeeCharged}, Pt:{tran.PagingToken}");
Console.WriteLine("Create account failed.");
Console.WriteLine("TransactionResultCode: " + response.SubmitTransactionResponseExtras.ExtrasResultCodes.TransactionResultCode ?? "null");
Console.WriteLine("TransactionResultCodeOperations: " + string.Join(", ", response.SubmitTransactionResponseExtras.ExtrasResultCodes.OperationsResultCodes));
}
}

private static async void ShowOperationResponse(Server server, object sender, LedgerResponse lr)
private static async Task DeleteAccount(Server server, KeyPair source, KeyPair destination)
{
var accountToDelete = await server.Accounts.Account(source.AccountId).ConfigureAwait(false);
var transaction = new TransactionBuilder(accountToDelete)
.SetFee(DefaultFee)
.AddOperation(new AccountMergeOperation.Builder(destination).Build())
.Build();

transaction.Sign(source);

var feeBumpTransaction = TransactionBuilder.BuildFeeBumpTransaction(destination, transaction, DefaultFee);

feeBumpTransaction.Sign(destination);

var response = await server.SubmitTransaction(feeBumpTransaction).ConfigureAwait(false);
if (response.IsSuccess())
{
var operationRequestBuilder = server.Operations.ForLedger(lr.Sequence);
var operations = await operationRequestBuilder.Execute();

var accts = 0;
var payments = 0;
var offers = 0;
var options = 0;

foreach (var op in operations.Records)
switch (op.Type)
{
case "create_account":
accts++;
break;
case "payment":
payments++;
break;
case "manage_offer":
offers++;
break;
case "set_options":
options++;
break;
}

Console.WriteLine($"id: {lr.Sequence}, tx/ops: {lr.SuccessfulTransactionCount + "/" + lr.OperationCount}, accts: {accts}, payments: {payments}, offers: {offers}, options: {options}");
Console.WriteLine($"Uri: {((LedgersRequestBuilder)sender).Uri}");
Console.WriteLine("Delete account response: " + response.Hash);
}

private static void ShowTestKeyValue(Server server)
else
{
Console.WriteLine("-- Getting TestKey for Account --");

var data = server.Accounts.AccountData("GAZHWW2NBPDVJ6PEEOZ2X43QV5JUDYS3XN4OWOTBR6WUACTUML2CCJLI", "TestKey");

var dataResult = data.Result;

Console.WriteLine("Encoded Value: " + dataResult.Value);
Console.WriteLine("Decoded Value: " + dataResult.ValueDecoded);

Console.WriteLine();
Console.WriteLine("Delete account failed.");
Console.WriteLine("TransactionResultCode: " + response.SubmitTransactionResponseExtras.ExtrasResultCodes.TransactionResultCode);
Console.WriteLine("TransactionResultCodeOperations: " + string.Join(", ", response.SubmitTransactionResponseExtras.ExtrasResultCodes.OperationsResultCodes));
}

}
}
}
11 changes: 7 additions & 4 deletions stellar-dotnet-sdk/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,18 +168,21 @@ public async Task<SubmitTransactionResponse> SubmitTransaction(string transactio
await CheckMemoRequired(tx);
}

var transactionUri = new UriBuilder(_serverUri).SetPath("/transactions").Uri;
var transactionUriBuilder = new UriBuilder(_serverUri);

var path = _serverUri.AbsolutePath.TrimEnd('/');
transactionUriBuilder.SetPath($"{path}/transactions");

var paramsPairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("tx", transactionEnvelopeBase64)
new("tx", transactionEnvelopeBase64)
};

var response = await _httpClient.PostAsync(transactionUri, new FormUrlEncodedContent(paramsPairs.ToArray()));
var response = await _httpClient.PostAsync(transactionUriBuilder.Uri, new FormUrlEncodedContent(paramsPairs.ToArray()));

if (options.EnsureSuccess && !response.IsSuccessStatusCode)
{
string responseString = string.Empty;
var responseString = string.Empty;
if (response.Content != null)
{
responseString = await response.Content.ReadAsStringAsync();
Expand Down
2 changes: 1 addition & 1 deletion stellar-dotnet-sdk/UriBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public static UriBuilder SetQueryParam(this UriBuilder uri, string key, string v

public static UriBuilder SetPath(this UriBuilder uri, string path)
{
uri.Path = path;
uri.Path = path.StartsWith("/") ? path : $"/{path}";
return uri;
}

Expand Down
41 changes: 17 additions & 24 deletions stellar-dotnet-sdk/requests/RequestBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ public class RequestBuilder<T> where T : class
{
private readonly List<string> _segments;
private bool _segmentsAdded;
protected UriBuilder UriBuilder;
private readonly string _serverPathPrefix;
protected readonly UriBuilder UriBuilder;
private readonly Uri _serverUri;

public static HttpClient HttpClient { get; set; }

Expand All @@ -31,19 +31,15 @@ public async Task<TZ> Execute<TZ>(Uri uri) where TZ : class
return await responseHandler.HandleResponse(response);
}

public string Uri
{
get => BuildUri().ToString();
}
public string Uri => BuildUri().ToString();

public RequestBuilder(Uri serverUri, string defaultSegment, HttpClient httpClient)
{
_serverUri = serverUri;

UriBuilder = new UriBuilder(serverUri);
_segments = new List<string>();

// Store the required path part of the serverUri
_serverPathPrefix = UriBuilder.Path;

if (!string.IsNullOrEmpty(defaultSegment))
SetSegments(defaultSegment);

Expand Down Expand Up @@ -121,26 +117,23 @@ public virtual T Order(OrderDirection direction)
/// <returns>EventSource object, so you can close() connection when not needed anymore</returns>
public Uri BuildUri()

Check warning on line 118 in stellar-dotnet-sdk/requests/RequestBuilder.cs

View workflow job for this annotation

GitHub Actions / run_test

XML comment has badly formed XML -- 'Expected an end tag for element 'param'.'

Check warning on line 118 in stellar-dotnet-sdk/requests/RequestBuilder.cs

View workflow job for this annotation

GitHub Actions / create_nuget

XML comment has badly formed XML -- 'Expected an end tag for element 'param'.'

Check warning on line 118 in stellar-dotnet-sdk/requests/RequestBuilder.cs

View workflow job for this annotation

GitHub Actions / run_test

XML comment has badly formed XML -- 'Expected an end tag for element 'param'.'
{
if (_segments.Count > 0)
{
var path = _serverPathPrefix;

foreach (var segment in _segments)
path += (path.EndsWith("/") ? string.Empty : "/") + segment;
if (_segments.Count <= 0)
throw new NotSupportedException("No segments defined.");

var path = _serverUri.AbsolutePath.TrimEnd('/');

UriBuilder.Path = path;

try
{
return UriBuilder.Uri;
}
catch (UriFormatException)
foreach (var segment in _segments)
{
if (!path.EndsWith("/"))
{
throw;
path += "/";
}
path += segment;
}

throw new NotSupportedException("No segments defined.");
UriBuilder.Path = path;

return UriBuilder.Uri;
}
}
}

0 comments on commit 7d8d8f3

Please sign in to comment.