Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replacing conversion helper for conversion service #280

Merged
merged 2 commits into from
Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 0 additions & 71 deletions src/Helpers/PriceConversionHelper.cs

This file was deleted.

11 changes: 6 additions & 5 deletions src/Pages/ChannelRequests.razor
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@
<FieldHelp>
@if (_selectedWalletId != null)
{
@($"Wallet balance: {_selectedWalletBalance:f8} BTC ({Math.Round(PriceConversionHelper.BtcToUsdConversion(_selectedWalletBalance, _btcPrice), 2)} USD)")
@($"Wallet balance: {_selectedWalletBalance:f8} BTC ({Math.Round(PriceConversionService.BtcToUsdConversion(_selectedWalletBalance, _btcPrice), 2)} USD)")
}
else
{
Expand All @@ -131,7 +131,7 @@
<DisplayTemplate>
@{
@($"{context.Amount:f8} BTC")
@($" ({Math.Round(PriceConversionHelper.BtcToUsdConversion(context.Amount, _btcPrice), 2)} USD)")
@($" ({Math.Round(PriceConversionService.BtcToUsdConversion(context.Amount, _btcPrice), 2)} USD)")
}
</DisplayTemplate>
<EditTemplate>
Expand All @@ -143,7 +143,7 @@
</NumericPicker>
<FieldHelp>

@($"Amount in Satoshis. Minimum {_minimumChannelCapacity:f8}. Current amount: {Math.Round(PriceConversionHelper.SatToUsdConversion(new Money(_amount, MoneyUnit.BTC).Satoshi, _btcPrice), 2)} USD")
@($"Amount in Satoshis. Minimum {_minimumChannelCapacity:f8}. Current amount: {Math.Round(PriceConversionService.SatToUsdConversion(new Money(_amount, MoneyUnit.BTC).Satoshi, _btcPrice), 2)} USD")

</FieldHelp>
</Validation>
Expand Down Expand Up @@ -293,7 +293,7 @@
<DisplayTemplate>
@{
@($"{context.Amount:f8} BTC")
@($" ({Math.Round(PriceConversionHelper.BtcToUsdConversion(context.Amount, _btcPrice), 2)} USD)")
@($" ({Math.Round(PriceConversionService.BtcToUsdConversion(context.Amount, _btcPrice), 2)} USD)")
}
</DisplayTemplate>
</DataGridColumn>
Expand Down Expand Up @@ -385,7 +385,7 @@
TemplatePsbtString="@_templatePSBTString"
SignedPSBT="@_psbt"/>

<CancelOrRejectPopup

Check warning on line 388 in src/Pages/ChannelRequests.razor

View workflow job for this annotation

GitHub Actions / build-and-test

Component 'CancelOrRejectPopup' expects a value for the parameter 'Reason', but a value may not have been provided.
@ref=@_rejectCancelModalRef
Title='@(_selectedStatusActionString + " operation: " + _selectedRequest?.Id)'
Validator="@RejectReasonValidator"
Expand Down Expand Up @@ -422,6 +422,7 @@
@inject ICoinSelectionService CoinSelectionService
@inject INBXplorerService NBXplorerService
@inject ILocalStorageService LocalStorageService
@inject IPriceConversionService PriceConversionService

@code {
private List<ChannelOperationRequest>? _channelRequests;
Expand Down Expand Up @@ -514,7 +515,7 @@
_isFinanceManager = ClaimsPrincipal != null && ClaimsPrincipal.IsInRole(ApplicationUserRole.FinanceManager.ToString());
_isNodeManager = ClaimsPrincipal != null && ClaimsPrincipal.IsInRole(ApplicationUserRole.NodeManager.ToString());

_btcPrice = PriceConversionHelper.GetBtcToUsdPrice();
_btcPrice = await PriceConversionService.GetBtcToUsdPrice();
if (_btcPrice == 0)
{
ToastService.ShowError("Bitcoin price in USD could not be retrieved.");
Expand Down
7 changes: 4 additions & 3 deletions src/Pages/Channels.razor
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@
@{
var btcAmount = new Money(context.SatsAmount, MoneyUnit.Satoshi).ToUnit(MoneyUnit.BTC);
@($"{btcAmount:f8} BTC")
@($" ({Math.Round(PriceConversionHelper.BtcToUsdConversion(btcAmount, _btcPrice), 2)} USD)")
@($" ({Math.Round(PriceConversionService.BtcToUsdConversion(btcAmount, _btcPrice), 2)} USD)")
}
</DisplayTemplate>
</DataGridNumericColumn>
Expand Down Expand Up @@ -225,7 +225,7 @@
<DisplayTemplate>
@{
@($"{context.Amount:f8} BTC")
@($" ({Math.Round(PriceConversionHelper.BtcToUsdConversion(context.Amount, _btcPrice), 2)} USD)")
@($" ({Math.Round(PriceConversionService.BtcToUsdConversion(context.Amount, _btcPrice), 2)} USD)")
}
</DisplayTemplate>
</DataGridColumn>
Expand Down Expand Up @@ -342,6 +342,7 @@
@inject IWalletRepository WalletRepository
@inject INodeRepository NodeRepository
@inject ILocalStorageService LocalStorageService
@inject IPriceConversionService PriceConversionService

@code {
private List<Channel>? _channels = new List<Channel>();
Expand Down Expand Up @@ -394,7 +395,7 @@

protected override async Task OnInitializedAsync()
{
_btcPrice = PriceConversionHelper.GetBtcToUsdPrice();
_btcPrice = await PriceConversionService.GetBtcToUsdPrice();
if (_btcPrice == 0)
{
ToastService.ShowError("Bitcoin price in USD could not be retrieved.");
Expand Down
13 changes: 7 additions & 6 deletions src/Pages/Wallets.razor
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
@inject ILightningService LightningService
@inject ILocalStorageService LocalStorageService
@inject ISchedulerFactory SchedulerFactory
@inject IPriceConversionService PriceConversionService

@attribute [Authorize(Roles = "NodeManager, FinanceManager, Superadmin")]

Expand Down Expand Up @@ -434,7 +435,7 @@
</NumericPicker>
</FieldBody>
<FieldHelp>
@($"Current amount: {Math.Round(PriceConversionHelper.BtcToUsdConversion((decimal)_amountToTransfer, _btcPrice), 2)} USD")
@($"Current amount: {Math.Round(PriceConversionService.BtcToUsdConversion((decimal)_amountToTransfer, _btcPrice), 2)} USD")
</FieldHelp>
</Field>
</Validation>
Expand Down Expand Up @@ -563,7 +564,7 @@

protected override async Task OnInitializedAsync()
{
_btcPrice = PriceConversionHelper.GetBtcToUsdPrice();
_btcPrice = await PriceConversionService.GetBtcToUsdPrice();
if (_btcPrice == 0)
{
ToastService.ShowError("Bitcoin price in USD could not be retrieved.");
Expand Down Expand Up @@ -830,8 +831,8 @@
if (balance != null)
{
_textModalTitle = $"Wallet: {wallet.Name} On-chain Balance";
_textModalContent = $"Confirmed: {((Money)balance.Confirmed).ToUnit(MoneyUnit.BTC):f8} BTC ({Math.Round(PriceConversionHelper.BtcToUsdConversion(((Money)balance.Confirmed).ToUnit(MoneyUnit.BTC), _btcPrice), 2)} USD) - " +
$"Unconfirmed: {((Money)balance.Unconfirmed).ToUnit(MoneyUnit.BTC):f8} BTC ({Math.Round(PriceConversionHelper.BtcToUsdConversion(((Money)balance.Unconfirmed).ToUnit(MoneyUnit.BTC), _btcPrice), 2)} USD)";
_textModalContent = $"Confirmed: {((Money)balance.Confirmed).ToUnit(MoneyUnit.BTC):f8} BTC ({Math.Round(PriceConversionService.BtcToUsdConversion(((Money)balance.Confirmed).ToUnit(MoneyUnit.BTC), _btcPrice), 2)} USD) - " +
$"Unconfirmed: {((Money)balance.Unconfirmed).ToUnit(MoneyUnit.BTC):f8} BTC ({Math.Round(PriceConversionService.BtcToUsdConversion(((Money)balance.Unconfirmed).ToUnit(MoneyUnit.BTC), _btcPrice), 2)} USD)";
_textModalCopy = false;

await _textModalRef.Show();
Expand Down Expand Up @@ -986,7 +987,7 @@
_targetTransferWallet = null;

var (balance,_) = await BitcoinService.GetWalletConfirmedBalance(wallet);
_sourceWalletBalance = $"{balance:f8} BTC ({Math.Round(PriceConversionHelper.BtcToUsdConversion((decimal)balance, _btcPrice), 2)} USD)";
_sourceWalletBalance = $"{balance:f8} BTC ({Math.Round(PriceConversionService.BtcToUsdConversion((decimal)balance, _btcPrice), 2)} USD)";

await _transferFundsModal?.Show();
}
Expand Down Expand Up @@ -1184,7 +1185,7 @@
{
var (targetBalance,_) = await BitcoinService.GetWalletConfirmedBalance(targetWallet);

_transferTargetWalletBalance = $"{targetBalance:f8} BTC ({Math.Round(PriceConversionHelper.BtcToUsdConversion((decimal)targetBalance, _btcPrice), 2)} USD)";
_transferTargetWalletBalance = $"{targetBalance:f8} BTC ({Math.Round(PriceConversionService.BtcToUsdConversion((decimal)targetBalance, _btcPrice), 2)} USD)";
}
}

Expand Down
11 changes: 6 additions & 5 deletions src/Pages/Withdrawals.razor
Original file line number Diff line number Diff line change
Expand Up @@ -154,14 +154,14 @@
<EditTemplate>
@if (_selectedRequestWalletBalance != null)
{
<p>@($"{_selectedRequestWalletBalance:f8} BTC ({Math.Round(PriceConversionHelper.BtcToUsdConversion((decimal)_selectedRequestWalletBalance, _btcPrice), 2)} USD)")</p>
<p>@($"{_selectedRequestWalletBalance:f8} BTC ({Math.Round(PriceConversionService.BtcToUsdConversion((decimal)_selectedRequestWalletBalance, _btcPrice), 2)} USD)")</p>
}
</EditTemplate>
</DataGridColumn>
<DataGridColumn TItem="WalletWithdrawalRequest" Filterable="false" PopupFieldColumnSize="ColumnSize.Is12" Editable="true" Field="@nameof(WalletWithdrawalRequest.Amount)" Caption="Amount (BTC)" Sortable="false" Displayable="@IsPendingRequestsColumnVisible(PendingWithdrawalsColumnName.Amount)" >
<DisplayTemplate>
@{
@($"{context.Amount:f8} BTC ({Math.Round(PriceConversionHelper.BtcToUsdConversion(context.Amount, _btcPrice), 2)} USD)")
@($"{context.Amount:f8} BTC ({Math.Round(PriceConversionService.BtcToUsdConversion(context.Amount, _btcPrice), 2)} USD)")
}
</DisplayTemplate>
<EditTemplate>
Expand All @@ -174,7 +174,7 @@
</Feedback>
</NumericPicker>
<FieldHelp>
@($"Current amount: {Math.Round(PriceConversionHelper.BtcToUsdConversion((decimal)context.CellValue, _btcPrice), 2)} USD")
@($"Current amount: {Math.Round(PriceConversionService.BtcToUsdConversion((decimal)context.CellValue, _btcPrice), 2)} USD")
</FieldHelp>
</Validation>
}
Expand Down Expand Up @@ -300,7 +300,7 @@
<DataGridColumn TItem="WalletWithdrawalRequest" Editable="true" Field="@nameof(WalletWithdrawalRequest.Amount)" Caption="Amount (BTC)" Sortable="false" Displayable="@IsAllRequestsColumnVisible(AllWithdrawalsColumnName.Amount)">
<DisplayTemplate>
@{
@($"{context.Amount:f8} BTC ({Math.Round(PriceConversionHelper.BtcToUsdConversion(context.Amount, _btcPrice), 2)} USD)")
@($"{context.Amount:f8} BTC ({Math.Round(PriceConversionService.BtcToUsdConversion(context.Amount, _btcPrice), 2)} USD)")
}
</DisplayTemplate>

Expand Down Expand Up @@ -373,7 +373,7 @@
ApproveRequestDelegate="async ()=> await ApproveRequestDelegate()"
/>

<CancelOrRejectPopup

Check warning on line 376 in src/Pages/Withdrawals.razor

View workflow job for this annotation

GitHub Actions / build-and-test

Component 'CancelOrRejectPopup' expects a value for the parameter 'Reason', but a value may not have been provided.
@ref="@_rejectCancelModalRef"
Title='@("Wallet withdrawal:"+_selectedRequest?.Id)'
Validator="@RejectReasonValidator"
Expand All @@ -397,6 +397,7 @@
@inject IBitcoinService BitcoinService
@inject ISchedulerFactory SchedulerFactory
@inject ILocalStorageService LocalStorageService
@inject IPriceConversionService PriceConversionService

@code {
[CascadingParameter]
Expand Down Expand Up @@ -467,7 +468,7 @@
{
if (LoggedUser == null) return;

_btcPrice = PriceConversionHelper.GetBtcToUsdPrice();
_btcPrice = await PriceConversionService.GetBtcToUsdPrice();
if (_btcPrice == 0)
{
ToastService.ShowError("Bitcoin price in USD could not be retrieved.");
Expand Down
1 change: 1 addition & 0 deletions src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ public static void Main(string[] args)
builder.Services.AddTransient<IRemoteSignerService, RemoteSignerServiceService>();
builder.Services.AddTransient<ILiquidityRuleRepository, LiquidityRuleRepository>();
builder.Services.AddTransient<ICoinSelectionService, CoinSelectionService>();
builder.Services.AddTransient<IPriceConversionService, PriceConversionService>();
builder.Services.AddSingleton<ILightningClientService, LightningClientService>();

//BlazoredToast
Expand Down
59 changes: 59 additions & 0 deletions src/Services/PriceConversionService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System.Text.Json;
using NBitcoin;
using NuGet.Protocol;

namespace NodeGuard.Services;

public interface IPriceConversionService
{
public Task<decimal> GetBtcToUsdPrice();
public decimal SatToUsdConversion(decimal sats, decimal btcPrice);
public decimal BtcToUsdConversion(decimal btc, decimal btcPrice);
}
public class PriceConversionService: IPriceConversionService
{

private readonly HttpClient _httpClient;
private readonly ILogger<PriceConversionService> _logger;

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


public async Task<decimal> GetBtcToUsdPrice()
{
decimal btcPrice;

try
{
using var requestMessage = new HttpRequestMessage(HttpMethod.Get, Constants.COINGECKO_ENDPOINT);

requestMessage.Headers.Add("x-cg-pro-api-key", Constants.COINGECKO_KEY);

var response = await _httpClient.SendAsync(requestMessage);
string json = await response.Content.ReadAsStringAsync();
JsonDocument document = JsonDocument.Parse(json);
return document.RootElement[0].GetProperty("current_price").GetDecimal();
}
catch (Exception e)
{
_logger.LogError("Bitcoin price could not be retrieved {Message}", e.Message);
btcPrice = 0;
}

return btcPrice;
}

public decimal SatToUsdConversion(decimal sats, decimal btcPrice)
{
return Money.Satoshis(sats).ToUnit(MoneyUnit.BTC) * btcPrice;
}

public decimal BtcToUsdConversion(decimal btc, decimal btcPrice)
{
return btc * btcPrice;
}
}
11 changes: 6 additions & 5 deletions src/Shared/UTXOSelectorModal.razor
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
</FieldLabel>
<NumericPicker TValue="decimal" Min="0" Decimals="8" Step="0.00001m" CurrencySymbol=" BTC" CurrencySymbolPlacement="CurrencySymbolPlacement.Suffix" Disabled="@(_selectedStrategy != CoinSelectionStrategy.ClosestToTargetFirst)" Value="_closestTo" ValueChanged="OnClosestToChanged" Debounce="true"/>
<FieldHelp>
@($"{Math.Round(PriceConversionHelper.BtcToUsdConversion(_closestTo, _btcPrice), 2)} USD")
@($"{Math.Round(PriceConversionService.BtcToUsdConversion(_closestTo, _btcPrice), 2)} USD")
</FieldHelp>
</Field>
}
Expand All @@ -60,7 +60,7 @@
</FieldLabel>
<NumericPicker TValue="decimal" Min="0" Decimals="8" Step="0.00001m" CurrencySymbol=" BTC" CurrencySymbolPlacement="CurrencySymbolPlacement.Suffix" Value="_amount" ValueChanged="OnAmountChanged" Debounce="true"/>
<FieldHelp>
@($"{Math.Round(PriceConversionHelper.BtcToUsdConversion(_amount, _btcPrice), 2)} USD")
@($"{Math.Round(PriceConversionService.BtcToUsdConversion(_amount, _btcPrice), 2)} USD")
</FieldHelp>
</Field>
<Field>
Expand Down Expand Up @@ -92,7 +92,7 @@
<DataGridColumn Field="@nameof(UTXO.Value)" Caption="BTC" Sortable="true"/>
<DataGridColumn Field="@nameof(UTXO.Value)" Caption="USD" Sortable="true">
<DisplayTemplate>
@($"{Math.Round(PriceConversionHelper.BtcToUsdConversion(((Money)context.Value).ToDecimal(MoneyUnit.BTC), _btcPrice), 2)} USD")
@($"{Math.Round(PriceConversionService.BtcToUsdConversion(((Money)context.Value).ToDecimal(MoneyUnit.BTC), _btcPrice), 2)} USD")
</DisplayTemplate>
</DataGridColumn>
<DataGridColumn Field="@nameof(UTXO.KeyPath)" Caption="Path" Sortable="false"/>
Expand All @@ -101,10 +101,10 @@
</div>
</div>
<Row Class="mx-1">
<Feedback>@String.Join(",", GetUTXOsValues())</Feedback>

Check warning on line 104 in src/Shared/UTXOSelectorModal.razor

View workflow job for this annotation

GitHub Actions / build-and-test

Found markup element with unexpected name 'Feedback'. If this is intended to be a component, add a @using directive for its namespace.
</Row>
<Row Class="mx-1">
<Feedback class="text-danger">@(_validation.Messages != null ? String.Join(",", _validation.Messages) : "")</Feedback>

Check warning on line 107 in src/Shared/UTXOSelectorModal.razor

View workflow job for this annotation

GitHub Actions / build-and-test

Found markup element with unexpected name 'Feedback'. If this is intended to be a component, add a @using directive for its namespace.
</Row>
</ModalBody>
<ModalFooter>
Expand All @@ -116,6 +116,7 @@

@inject ICoinSelectionService CoinSelectionService
@inject IWalletRepository WalletRepository
@inject IPriceConversionService PriceConversionService

@code {
private Network network = CurrentNetworkHelper.GetCurrentNetwork();
Expand Down Expand Up @@ -193,15 +194,15 @@
}


_btcPrice = PriceConversionHelper.GetBtcToUsdPrice();
_btcPrice = await PriceConversionService.GetBtcToUsdPrice();
await _modalRef.Show();
StateHasChanged();
}

private string[] GetUTXOsValues()
{
var value = SelectedUTXOs.Sum(x => ((Money)x.Value).ToUnit(MoneyUnit.BTC));
var usd = Math.Round(PriceConversionHelper.BtcToUsdConversion(value, _btcPrice), 2);
var usd = Math.Round(PriceConversionService.BtcToUsdConversion(value, _btcPrice), 2);

return new[]
{
Expand Down
Loading