Skip to content

Commit

Permalink
change CurrencyRate to its own service named CurrencyRateService.cs
Browse files Browse the repository at this point in the history
  • Loading branch information
itailiors committed Aug 29, 2024
1 parent 477c979 commit fd3ecdf
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 55 deletions.
4 changes: 3 additions & 1 deletion src/Angor/Client/Pages/Wallet.razor
Original file line number Diff line number Diff line change
Expand Up @@ -1281,6 +1281,7 @@ else
{
return await _currencyService.GetBtcValueInPreferredCurrency(btcBalance);
}


private async Task PrecomputeFiatValues()
{
Expand All @@ -1290,8 +1291,9 @@ else
foreach (var addressInfo in addresses)
{
var total = Money.Satoshis(addressInfo.Balance).ToUnit(MoneyUnit.BTC);
var fiatValue = await _currencyService.GetBtcValueInPreferredCurrency(total);
var fiatValue = await _currencyService.GetBtcValueInPreferredCurrency(total); // Calls the method from ICurrencyService
fiatValues[addressInfo.Address] = fiatValue;
}
}

}
9 changes: 5 additions & 4 deletions src/Angor/Client/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,17 @@
builder.Services.AddSingleton<ISerializer, Serializer>();
builder.Services.AddSingleton<INetworkConfiguration, NetworkConfiguration>();
builder.Services.AddTransient<IHdOperations, HdOperations>();
builder.Services.AddTransient <IClientStorage, ClientStorage>();
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<INetworkStorage, ClientStorage>();
builder.Services.AddTransient <IWalletStorage, WalletStorage>();
builder.Services.AddTransient<IWalletStorage, WalletStorage>();
builder.Services.AddScoped<ICacheStorage, LocalSessionStorage>();
builder.Services.AddTransient<IWalletOperations, WalletOperations>();
builder.Services.AddScoped<IClipboardService, ClipboardService>();
builder.Services.AddScoped<IEncryptionService, EncryptionService>();
builder.Services.AddScoped<IDerivationOperations, DerivationOperations>();
builder.Services.AddScoped<NavMenuState>();
builder.Services.AddScoped<ICurrencyService, CurrencyService>();
builder.Services.AddScoped<ICurrencyRateService, CurrencyRateService>();

builder.Services.AddScoped<IIndexerService, IndexerService>();
builder.Services.AddScoped<INetworkService, NetworkService>();
Expand All @@ -51,10 +52,10 @@
builder.Services.AddTransient<ISeederScriptTreeBuilder, SeederScriptTreeBuilder>();
builder.Services.AddTransient<ITaprootScriptBuilder, TaprootScriptBuilder>();

builder.Services.AddSingleton<INostrCommunicationFactory,NostrCommunicationFactory>();
builder.Services.AddSingleton<INostrCommunicationFactory, NostrCommunicationFactory>();
builder.Services.AddScoped<IRelaySubscriptionsHandling, RelaySubscriptionsHandling>();
builder.Services.AddSingleton<IPasswordCacheService, PasswordCacheService>();

builder.Services.AddScoped<IconService>();

await builder.Build().RunAsync();
await builder.Build().RunAsync();
53 changes: 53 additions & 0 deletions src/Angor/Client/Services/CurrencyRateService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System.Collections.Concurrent;
using System.Text.Json;

public class CurrencyRateService : ICurrencyRateService
{
private readonly TimeSpan _cacheDuration = TimeSpan.FromMinutes(10); // Cache duration of 10 minutes
private readonly HttpClient _httpClient;
private readonly ILogger<CurrencyRateService> _logger;
private readonly ConcurrentDictionary<string, (decimal rate, DateTime timestamp)> _rateCache = new();

public CurrencyRateService(HttpClient httpClient, ILogger<CurrencyRateService> logger)
{
_httpClient = httpClient;
_logger = logger;
}

public async Task<decimal> GetBtcToCurrencyRate(string currencyCode)
{
// Normalize currency code
var preferredCurrency = currencyCode.ToUpper();

// Check if we have a recent rate in the cache
if (_rateCache.ContainsKey(preferredCurrency) &&
DateTime.UtcNow - _rateCache[preferredCurrency].timestamp < _cacheDuration)
{
_logger.LogInformation($"Using cached rate for {preferredCurrency}");
return _rateCache[preferredCurrency].rate;
}

// Fetch new rate if not cached or cache is stale
var apiUrl = "https://mempool.space/api/v1/prices";
var response = await _httpClient.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"API Response: {jsonString}");

var data = JsonSerializer.Deserialize<Dictionary<string, decimal>>(jsonString);

if (data != null && data.ContainsKey(preferredCurrency))
{
var rate = data[preferredCurrency];
// Update the cache
_rateCache[preferredCurrency] = (rate, DateTime.UtcNow);
return rate;
}

throw new Exception($"Currency '{preferredCurrency}' not found in the API response.");
}

throw new Exception("Failed to fetch BTC rate from the API.");
}
}
57 changes: 7 additions & 50 deletions src/Angor/Client/Services/CurrencyService.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
using System;
using System.Globalization;
using System.Net.Http;
using System.Threading.Tasks;
using Angor.Client.Storage;
using System.Text.Json;
using System.Collections.Generic;

public class CurrencyService : ICurrencyService
{
private readonly HttpClient _httpClient;
private readonly IClientStorage _storage;
private readonly ICurrencyRateService _currencyRateService;
private readonly ILogger<CurrencyService> _logger;
private readonly IClientStorage _storage;

// Cache fields - does it work or need of redis cache/storage?
private Dictionary<string, (decimal rate, DateTime timestamp)> _rateCache = new();
private readonly TimeSpan _cacheDuration = TimeSpan.FromMinutes(10); // Cache duration of 10 minutes

public CurrencyService(HttpClient httpClient, IClientStorage storage, ILogger<CurrencyService> logger)
public CurrencyService(ICurrencyRateService currencyRateService, IClientStorage storage,
ILogger<CurrencyService> logger)
{
_httpClient = httpClient;
_currencyRateService = currencyRateService;
_storage = storage;
_logger = logger;
}
Expand All @@ -27,8 +19,8 @@ public async Task<string> GetBtcValueInPreferredCurrency(decimal btcBalance)
{
try
{
var rate = await GetBtcToPreferredCurrencyRate();
var currencyCode = _storage.GetCurrencyDisplaySetting();
var rate = await _currencyRateService.GetBtcToCurrencyRate(currencyCode);
var currencySymbol = GetCurrencySymbol(currencyCode);
var cultureInfo = new CultureInfo(GetCultureCode(currencyCode));
var value = btcBalance * rate;
Expand All @@ -41,41 +33,6 @@ public async Task<string> GetBtcValueInPreferredCurrency(decimal btcBalance)
}
}

private async Task<decimal> GetBtcToPreferredCurrencyRate()
{
string preferredCurrency = _storage.GetCurrencyDisplaySetting().ToUpper();

// Check if we have a recent rate in the cache
if (_rateCache.ContainsKey(preferredCurrency) &&
DateTime.UtcNow - _rateCache[preferredCurrency].timestamp < _cacheDuration)
{
_logger.LogInformation($"Using cached rate for {preferredCurrency}");
return _rateCache[preferredCurrency].rate;
}

// Fetch new rate if not cached or cache is stale
string apiUrl = "https://mempool.space/api/v1/prices";
var response = await _httpClient.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"API Response: {jsonString}");

var data = JsonSerializer.Deserialize<Dictionary<string, decimal>>(jsonString);

if (data != null && data.ContainsKey(preferredCurrency))
{
var rate = data[preferredCurrency];
// Update the cache
_rateCache[preferredCurrency] = (rate, DateTime.UtcNow);
return rate;
}
throw new Exception($"Currency '{preferredCurrency}' not found in the API response.");
}

throw new Exception("Failed to fetch BTC rate from the API.");
}

public string GetCurrencySymbol(string currencyCode)
{
return currencyCode.ToUpper() switch
Expand Down Expand Up @@ -105,4 +62,4 @@ private static string GetCultureCode(string currencyCode)
_ => "en-US"
};
}
}
}
4 changes: 4 additions & 0 deletions src/Angor/Client/Services/ICurrencyRateService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
public interface ICurrencyRateService
{
Task<decimal> GetBtcToCurrencyRate(string currencyCode);
}

0 comments on commit fd3ecdf

Please sign in to comment.