Skip to content

Commit

Permalink
Refactor API response
Browse files Browse the repository at this point in the history
  • Loading branch information
Coding-Enthusiast committed Dec 31, 2024
1 parent 0db8d20 commit 6e8404e
Show file tree
Hide file tree
Showing 11 changed files with 174 additions and 271 deletions.
21 changes: 21 additions & 0 deletions SharpPusher/Models/Response.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// SharpPusher
// Copyright (c) 2017 Coding Enthusiast
// Distributed under the MIT software license, see the accompanying
// file LICENCE or http://www.opensource.org/licenses/mit-license.php.

namespace SharpPusher.Models
{
public class Response
{
public bool IsSuccess { get; private set; } = true;
public string Message { get; private set; } = string.Empty;

private void SetMsg(string msg, bool success)
{
IsSuccess = success;
Message = msg;
}
public void SetMessage(string msg) => SetMsg(msg, true);
public void SetError(string msg) => SetMsg(msg, false);
}
}
15 changes: 15 additions & 0 deletions SharpPusher/Models/State.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// SharpPusher
// Copyright (c) 2017 Coding Enthusiast
// Distributed under the MIT software license, see the accompanying
// file LICENCE or http://www.opensource.org/licenses/mit-license.php.

namespace SharpPusher.Models
{
public enum State
{
Ready,
Broadcasting,
Success,
Failed
}
}
15 changes: 10 additions & 5 deletions SharpPusher/Services/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// file LICENCE or http://www.opensource.org/licenses/mit-license.php.

using Newtonsoft.Json.Linq;
using SharpPusher.Models;
using System;
using System.Net.Http;
using System.Threading.Tasks;
Expand All @@ -23,7 +24,7 @@ public abstract class Api
/// </summary>
/// <param name="txHex">Signed raw transaction in hex format</param>
/// <returns>Result of broadcasting.</returns>
public abstract Task<Response<string>> PushTx(string txHex);
public abstract Task<Response> PushTx(string txHex);


/// <summary>
Expand All @@ -33,9 +34,9 @@ public abstract class Api
/// <param name="jKey">The JSON key used for making the HttpContent in JSON format.</param>
/// <param name="url">Api url to use.</param>
/// <returns>Result of broadcasting.</returns>
protected static async Task<Response<string>> PushTx(string txHex, string jKey, string url)
protected static async Task<Response> PushTx(string txHex, string jKey, string url)
{
Response<string> resp = new();
Response resp = new();

using HttpClient client = new();
try
Expand All @@ -46,12 +47,16 @@ protected static async Task<Response<string>> PushTx(string txHex, string jKey,
};

HttpResponseMessage httpResp = await client.PostAsync(url, new StringContent(tx.ToString()));
resp.Result = await httpResp.Content.ReadAsStringAsync();
if (!httpResp.IsSuccessStatusCode)
{
resp.SetError("API response doesn't indicate success.");
}
resp.SetMessage(await httpResp.Content.ReadAsStringAsync());
}
catch (Exception ex)
{
string errMsg = (ex.InnerException == null) ? ex.Message : ex.Message + " " + ex.InnerException;
resp.Errors.Add(errMsg);
resp.SetError(errMsg);
}

return resp;
Expand Down
87 changes: 0 additions & 87 deletions SharpPusher/Services/ErrorCollection.cs

This file was deleted.

14 changes: 7 additions & 7 deletions SharpPusher/Services/P2P.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Autarkysoft.Bitcoin.Clients;
using Autarkysoft.Bitcoin.P2PNetwork.Messages;
using Autarkysoft.Bitcoin.P2PNetwork.Messages.MessagePayloads;
using SharpPusher.Models;
using System.Threading.Tasks;

namespace SharpPusher.Services
Expand Down Expand Up @@ -46,25 +47,24 @@ public P2P(bool isMainNet)

public override string ApiName => "P2P";

public override async Task<Response<string>> PushTx(string txHex)
public override async Task<Response> PushTx(string txHex)
{
Response resp = new();

Transaction tx = new(txHex);
Message msg = new(new TxPayload(tx), netType);

MinimalClientSettings settings = new(netType, 4, null)
{
DnsSeeds = netType == NetworkType.MainNet ? DnsMain : DnsTest
};
MinimalClient client = new(settings);
using MinimalClient client = new(settings);
client.Start();
await Task.Delay(TimeConstants.MilliSeconds.FiveSec);
client.Send(msg);

return new Response<string>()
{
Result = $"Transaction was sent to {settings.MaxConnectionCount} nodes. " +
$"Transaction ID: {tx.GetTransactionId()}"
};
resp.SetMessage($"Transaction was sent to {settings.MaxConnectionCount} nodes. Transaction ID: {tx.GetTransactionId()}");
return resp;
}
}
}
18 changes: 8 additions & 10 deletions SharpPusher/Services/PushServices/BlockCypher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,32 @@
// file LICENCE or http://www.opensource.org/licenses/mit-license.php.

using Newtonsoft.Json.Linq;
using SharpPusher.Models;
using System.Threading.Tasks;

namespace SharpPusher.Services.PushServices
{
public sealed class BlockCypher : Api
{
public override string ApiName
{
get { return "BlockCypher"; }
}
public override string ApiName => "BlockCypher";


public override async Task<Response<string>> PushTx(string txHex)
public override async Task<Response> PushTx(string txHex)
{
Response<string> resp = await PushTx(txHex, "tx", "https://api.blockcypher.com/v1/bcy/test/txs/push");
if (resp.Errors.Any())
Response resp = await PushTx(txHex, "tx", "https://api.blockcypher.com/v1/bcy/test/txs/push");
if (!resp.IsSuccess)
{
return resp;
}

JObject jResult = JObject.Parse(resp.Result);
JObject jResult = JObject.Parse(resp.Message);
if (jResult["error"] != null)
{
resp.Errors.Add(jResult["error"].ToString());
resp.SetError(jResult["error"].ToString());

Check warning on line 28 in SharpPusher/Services/PushServices/BlockCypher.cs

View workflow job for this annotation

GitHub Actions / Windows

Dereference of a possibly null reference.

Check warning on line 28 in SharpPusher/Services/PushServices/BlockCypher.cs

View workflow job for this annotation

GitHub Actions / Windows

Dereference of a possibly null reference.

Check warning on line 28 in SharpPusher/Services/PushServices/BlockCypher.cs

View workflow job for this annotation

GitHub Actions / Linux

Dereference of a possibly null reference.

Check warning on line 28 in SharpPusher/Services/PushServices/BlockCypher.cs

View workflow job for this annotation

GitHub Actions / Linux

Dereference of a possibly null reference.

Check warning on line 28 in SharpPusher/Services/PushServices/BlockCypher.cs

View workflow job for this annotation

GitHub Actions / Mac

Dereference of a possibly null reference.

Check warning on line 28 in SharpPusher/Services/PushServices/BlockCypher.cs

View workflow job for this annotation

GitHub Actions / Mac

Dereference of a possibly null reference.
}
else
{
resp.Result = "Successfully done. Tx ID: " + jResult["hash"].ToString();
resp.SetMessage($"Successfully done. Tx ID: {jResult["hash"]}");
}

return resp;
Expand Down
60 changes: 28 additions & 32 deletions SharpPusher/Services/PushServices/BlockchainInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SharpPusher.Models;
using System;
using System.Net.Http;
using System.Text;
Expand All @@ -14,53 +15,48 @@ namespace SharpPusher.Services.PushServices
{
public sealed class BlockchainInfo : Api
{
public override string ApiName
{
get { return "Blockchain.Info"; }
}
public override string ApiName => "Blockchain.Info";

public async override Task<Response<string>> PushTx(string txHex)
public async override Task<Response> PushTx(string txHex)
{
Response<string> resp = new Response<string>();
using HttpClient client = new();
Response resp = new();

using (HttpClient client = new HttpClient())
try
{
try
{
client.BaseAddress = new Uri("https://blockchain.info");
client.BaseAddress = new Uri("https://blockchain.info");

string json = JsonConvert.SerializeObject(txHex);
string contentType = "application/x-www-form-urlencoded";
HttpContent httpContent = new MultipartFormDataContent
{
new StringContent(json, Encoding.UTF8, contentType)
};
string json = JsonConvert.SerializeObject(txHex);
string contentType = "application/x-www-form-urlencoded";
HttpContent httpContent = new MultipartFormDataContent
{
new StringContent(json, Encoding.UTF8, contentType)
};

HttpResponseMessage result = await client.PostAsync("pushtx", httpContent);
string sResult = await result.Content.ReadAsStringAsync();
if (result.IsSuccessStatusCode)
HttpResponseMessage result = await client.PostAsync("pushtx", httpContent);
string sResult = await result.Content.ReadAsStringAsync();
if (result.IsSuccessStatusCode)
{
if (sResult != null && sResult.StartsWith("{\"error\":"))
{
if (sResult != null && sResult.StartsWith("{\"error\":"))
{
JObject jObject = JObject.Parse(sResult);
resp.Errors.Add(jObject["error"].ToString());
}
else
{
resp.Result = sResult;
}
JObject jObject = JObject.Parse(sResult);
resp.SetError(jObject["error"].ToString());

Check warning on line 43 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Windows

Dereference of a possibly null reference.

Check warning on line 43 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Windows

Dereference of a possibly null reference.

Check warning on line 43 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Linux

Dereference of a possibly null reference.

Check warning on line 43 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Linux

Dereference of a possibly null reference.

Check warning on line 43 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Mac

Dereference of a possibly null reference.

Check warning on line 43 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Mac

Dereference of a possibly null reference.
}
else
{
resp.Errors.Add(sResult);
resp.SetMessage(sResult);

Check warning on line 47 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Windows

Possible null reference argument for parameter 'msg' in 'void Response.SetMessage(string msg)'.

Check warning on line 47 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Windows

Possible null reference argument for parameter 'msg' in 'void Response.SetMessage(string msg)'.

Check warning on line 47 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Linux

Possible null reference argument for parameter 'msg' in 'void Response.SetMessage(string msg)'.

Check warning on line 47 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Linux

Possible null reference argument for parameter 'msg' in 'void Response.SetMessage(string msg)'.

Check warning on line 47 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Mac

Possible null reference argument for parameter 'msg' in 'void Response.SetMessage(string msg)'.

Check warning on line 47 in SharpPusher/Services/PushServices/BlockchainInfo.cs

View workflow job for this annotation

GitHub Actions / Mac

Possible null reference argument for parameter 'msg' in 'void Response.SetMessage(string msg)'.
}
}
catch (Exception ex)
else
{
string errMsg = (ex.InnerException == null) ? ex.Message : ex.Message + " " + ex.InnerException;
resp.Errors.Add(errMsg);
resp.SetError(sResult);
}
}
catch (Exception ex)
{
string errMsg = (ex.InnerException == null) ? ex.Message : ex.Message + " " + ex.InnerException;
resp.SetError(errMsg);
}

return resp;
}
Expand Down
Loading

0 comments on commit 6e8404e

Please sign in to comment.