Skip to content

Commit

Permalink
Client Configuration (#2)
Browse files Browse the repository at this point in the history
Updated CryptoExchange.Net to version 8.3.0
Added support for loading client settings from IConfiguration
Added DI registration method for configuring Rest and Socket options at the same time
Added DisplayName and ImageUrl properties to CryptoComExchange class
Updated client constructors to accept IOptions from DI
Removed redundant CryptoComSocketClient constructor
  • Loading branch information
JKorf authored Nov 19, 2024
1 parent ab1894e commit aeebee7
Show file tree
Hide file tree
Showing 14 changed files with 411 additions and 104 deletions.
104 changes: 104 additions & 0 deletions CryptoCom.Net.UnitTests/CryptoComRestClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
using System.Collections.Generic;
using System.Net.Http;
using CryptoCom.Net.Clients;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using CryptoExchange.Net.Objects;
using CryptoCom.Net.Interfaces.Clients;

namespace CryptoCom.Net.UnitTests
{
Expand All @@ -17,5 +21,105 @@ public void CheckInterfaces()
CryptoExchange.Net.Testing.TestHelpers.CheckForMissingRestInterfaces<CryptoComRestClient>();
CryptoExchange.Net.Testing.TestHelpers.CheckForMissingSocketInterfaces<CryptoComSocketClient>();
}

[Test]
[TestCase(TradeEnvironmentNames.Live, "https://api.crypto.com/exchange/v1")]
[TestCase("", "https://api.crypto.com/exchange/v1")]
public void TestConstructorEnvironments(string environmentName, string expected)
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{ "CryptoCom:Environment:Name", environmentName },
}).Build();

var collection = new ServiceCollection();
collection.AddCryptoCom(configuration.GetSection("CryptoCom"));
var provider = collection.BuildServiceProvider();

var client = provider.GetRequiredService<ICryptoComRestClient>();

var address = client.ExchangeApi.BaseAddress;

Assert.That(address, Is.EqualTo(expected));
}

[Test]
public void TestConstructorNullEnvironment()
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{ "CryptoCom", null },
}).Build();

var collection = new ServiceCollection();
collection.AddCryptoCom(configuration.GetSection("CryptoCom"));
var provider = collection.BuildServiceProvider();

var client = provider.GetRequiredService<ICryptoComRestClient>();

var address = client.ExchangeApi.BaseAddress;

Assert.That(address, Is.EqualTo("https://api.crypto.com/exchange/v1"));
}

[Test]
public void TestConstructorApiOverwriteEnvironment()
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{ "CryptoCom:Environment:Name", "test" },
{ "CryptoCom:Rest:Environment:Name", "live" },
}).Build();

var collection = new ServiceCollection();
collection.AddCryptoCom(configuration.GetSection("CryptoCom"));
var provider = collection.BuildServiceProvider();

var client = provider.GetRequiredService<ICryptoComRestClient>();

var address = client.ExchangeApi.BaseAddress;

Assert.That(address, Is.EqualTo("https://api.crypto.com/exchange/v1"));
}

[Test]
public void TestConstructorConfiguration()
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{ "ApiCredentials:Key", "123" },
{ "ApiCredentials:Secret", "456" },
{ "ApiCredentials:Memo", "000" },
{ "Socket:ApiCredentials:Key", "456" },
{ "Socket:ApiCredentials:Secret", "789" },
{ "Socket:ApiCredentials:Memo", "xxx" },
{ "Rest:OutputOriginalData", "true" },
{ "Socket:OutputOriginalData", "false" },
{ "Rest:Proxy:Host", "host" },
{ "Rest:Proxy:Port", "80" },
{ "Socket:Proxy:Host", "host2" },
{ "Socket:Proxy:Port", "81" },
}).Build();

var collection = new ServiceCollection();
collection.AddCryptoCom(configuration);
var provider = collection.BuildServiceProvider();

var restClient = provider.GetRequiredService<ICryptoComRestClient>();
var socketClient = provider.GetRequiredService<ICryptoComSocketClient>();

Assert.That(((BaseApiClient)restClient.ExchangeApi).OutputOriginalData, Is.True);
Assert.That(((BaseApiClient)socketClient.ExchangeApi).OutputOriginalData, Is.False);
Assert.That(((BaseApiClient)restClient.ExchangeApi).AuthenticationProvider.ApiKey, Is.EqualTo("123"));
Assert.That(((BaseApiClient)socketClient.ExchangeApi).AuthenticationProvider.ApiKey, Is.EqualTo("456"));
Assert.That(((BaseApiClient)restClient.ExchangeApi).ClientOptions.Proxy.Host, Is.EqualTo("host"));
Assert.That(((BaseApiClient)restClient.ExchangeApi).ClientOptions.Proxy.Port, Is.EqualTo(80));
Assert.That(((BaseApiClient)socketClient.ExchangeApi).ClientOptions.Proxy.Host, Is.EqualTo("host2"));
Assert.That(((BaseApiClient)socketClient.ExchangeApi).ClientOptions.Proxy.Port, Is.EqualTo(81));
}
}
}
9 changes: 5 additions & 4 deletions CryptoCom.Net.UnitTests/CryptoComRestIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Testing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
Expand All @@ -23,11 +24,11 @@ public override CryptoComRestClient GetClient(ILoggerFactory loggerFactory)
var sec = Environment.GetEnvironmentVariable("APISECRET");

Authenticated = key != null && sec != null;
return new CryptoComRestClient(null, loggerFactory, opts =>
return new CryptoComRestClient(null, loggerFactory, Options.Create(new Objects.Options.CryptoComRestOptions
{
opts.OutputOriginalData = true;
opts.ApiCredentials = Authenticated ? new ApiCredentials(key, sec) : null;
});
OutputOriginalData = true,
ApiCredentials = Authenticated ? new ApiCredentials(key, sec) : null
}));
}

[Test]
Expand Down
10 changes: 6 additions & 4 deletions CryptoCom.Net.UnitTests/SocketSubscriptionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using CryptoCom.Net.Objects.Options;

namespace CryptoCom.Net.UnitTests
{
Expand All @@ -20,11 +22,11 @@ public async Task ValidateSpotExchangeDataSubscriptions()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddProvider(new TraceLoggerProvider());
var client = new CryptoComSocketClient(opts =>
var client = new CryptoComSocketClient(Options.Create(new CryptoComSocketOptions
{
opts.DelayAfterConnect = TimeSpan.Zero;
opts.ApiCredentials = new CryptoExchange.Net.Authentication.ApiCredentials("123", "456");
}, loggerFactory);
DelayAfterConnect = TimeSpan.Zero,
ApiCredentials = new CryptoExchange.Net.Authentication.ApiCredentials("123", "456")
}), loggerFactory);
var tester = new SocketSubscriptionValidator<CryptoComSocketClient>(client, "Subscriptions/ExchangeApi", "wss://stream.crypto.com", stjCompare: true);
await tester.ValidateAsync<CryptoComOrderBookUpdate>((client, handler) => client.ExchangeApi.SubscribeToOrderBookSnapshotUpdatesAsync("ETH_USDT", 10, handler), "BookSnapshot", nestedJsonProperty: "result.data", useFirstUpdateItem: true);
await tester.ValidateAsync<CryptoComTicker>((client, handler) => client.ExchangeApi.SubscribeToTickerUpdatesAsync("ETH_USDT", handler), "Ticker", nestedJsonProperty: "result.data", useFirstUpdateItem: true);
Expand Down
21 changes: 8 additions & 13 deletions CryptoCom.Net/Clients/CryptoComRestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using CryptoExchange.Net.Clients;
using CryptoCom.Net.Interfaces.Clients.ExchangeApi;
using CryptoCom.Net.Clients.ExchangeApi;
using Microsoft.Extensions.Options;

namespace CryptoCom.Net.Clients
{
Expand All @@ -28,26 +29,22 @@ public class CryptoComRestClient : BaseRestClient, ICryptoComRestClient
/// Create a new instance of the CryptoComRestClient using provided options
/// </summary>
/// <param name="optionsDelegate">Option configuration delegate</param>
public CryptoComRestClient(Action<CryptoComRestOptions>? optionsDelegate = null) : this(null, null, optionsDelegate)
public CryptoComRestClient(Action<CryptoComRestOptions>? optionsDelegate = null)
: this(null, null, Options.Create(ApplyOptionsDelegate(optionsDelegate)))
{
}

/// <summary>
/// Create a new instance of the CryptoComRestClient using provided options
/// </summary>
/// <param name="optionsDelegate">Option configuration delegate</param>
/// <param name="options">Option configuration</param>
/// <param name="loggerFactory">The logger factory</param>
/// <param name="httpClient">Http client for this client</param>
public CryptoComRestClient(HttpClient? httpClient, ILoggerFactory? loggerFactory, Action<CryptoComRestOptions>? optionsDelegate = null) : base(loggerFactory, "CryptoCom")
public CryptoComRestClient(HttpClient? httpClient, ILoggerFactory? loggerFactory, IOptions<CryptoComRestOptions> options) : base(loggerFactory, "CryptoCom")
{
var options = CryptoComRestOptions.Default.Copy();
if (optionsDelegate != null)
optionsDelegate(options);
Initialize(options);


ExchangeApi = AddApiClient(new CryptoComRestClientExchangeApi(_logger, httpClient, options));
Initialize(options.Value);

ExchangeApi = AddApiClient(new CryptoComRestClientExchangeApi(_logger, httpClient, options.Value));
}

#endregion
Expand All @@ -58,9 +55,7 @@ public CryptoComRestClient(HttpClient? httpClient, ILoggerFactory? loggerFactory
/// <param name="optionsDelegate">Option configuration delegate</param>
public static void SetDefaultOptions(Action<CryptoComRestOptions> optionsDelegate)
{
var options = CryptoComRestOptions.Default.Copy();
optionsDelegate(options);
CryptoComRestOptions.Default = options;
CryptoComRestOptions.Default = ApplyOptionsDelegate(optionsDelegate);
}

/// <inheritdoc />
Expand Down
27 changes: 9 additions & 18 deletions CryptoCom.Net/Clients/CryptoComSocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using CryptoCom.Net.Objects.Options;
using CryptoCom.Net.Interfaces.Clients.ExchangeApi;
using CryptoCom.Net.Clients.ExchangeApi;
using Microsoft.Extensions.Options;

namespace CryptoCom.Net.Clients
{
Expand All @@ -25,34 +26,26 @@ public class CryptoComSocketClient : BaseSocketClient, ICryptoComSocketClient
#endregion

#region constructor/destructor
/// <summary>
/// Create a new instance of CryptoComSocketClient
/// </summary>
/// <param name="loggerFactory">The logger factory</param>
public CryptoComSocketClient(ILoggerFactory? loggerFactory = null) : this((x) => { }, loggerFactory)
{
}

/// <summary>
/// Create a new instance of CryptoComSocketClient
/// </summary>
/// <param name="optionsDelegate">Option configuration delegate</param>
public CryptoComSocketClient(Action<CryptoComSocketOptions> optionsDelegate) : this(optionsDelegate, null)
public CryptoComSocketClient(Action<CryptoComSocketOptions>? optionsDelegate = null)
: this(Options.Create(ApplyOptionsDelegate(optionsDelegate)), null)
{
}

/// <summary>
/// Create a new instance of CryptoComSocketClient
/// </summary>
/// <param name="loggerFactory">The logger factory</param>
/// <param name="optionsDelegate">Option configuration delegate</param>
public CryptoComSocketClient(Action<CryptoComSocketOptions>? optionsDelegate, ILoggerFactory? loggerFactory = null) : base(loggerFactory, "CryptoCom")
/// <param name="options">Option configuration</param>
public CryptoComSocketClient(IOptions<CryptoComSocketOptions> options, ILoggerFactory? loggerFactory = null) : base(loggerFactory, "CryptoCom")
{
var options = CryptoComSocketOptions.Default.Copy();
optionsDelegate?.Invoke(options);
Initialize(options);

ExchangeApi = AddApiClient(new CryptoComSocketClientExchangeApi(_logger, options));
Initialize(options.Value);

ExchangeApi = AddApiClient(new CryptoComSocketClientExchangeApi(_logger, options.Value));
}
#endregion

Expand All @@ -62,9 +55,7 @@ public CryptoComSocketClient(Action<CryptoComSocketOptions>? optionsDelegate, IL
/// <param name="optionsDelegate">Option configuration delegate</param>
public static void SetDefaultOptions(Action<CryptoComSocketOptions> optionsDelegate)
{
var options = CryptoComSocketOptions.Default.Copy();
optionsDelegate(options);
CryptoComSocketOptions.Default = options;
CryptoComSocketOptions.Default = ApplyOptionsDelegate(optionsDelegate);
}

/// <inheritdoc />
Expand Down
4 changes: 2 additions & 2 deletions CryptoCom.Net/CryptoCom.Net.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>
<LangVersion>12.0</LangVersion>
Expand Down Expand Up @@ -48,7 +48,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="CryptoExchange.Net" Version="8.2.0" />
<PackageReference Include="CryptoExchange.Net" Version="8.3.0" />
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
Loading

0 comments on commit aeebee7

Please sign in to comment.