Skip to content

Commit

Permalink
Removed long operation and changed lifetime of nostr services to fit …
Browse files Browse the repository at this point in the history
…WASM (#36)
  • Loading branch information
DavidGershony committed Jan 25, 2024
1 parent 3ebd0f0 commit 2fd0e09
Show file tree
Hide file tree
Showing 12 changed files with 104 additions and 159 deletions.
28 changes: 18 additions & 10 deletions src/Angor/Client/Pages/Browse.razor
Original file line number Diff line number Diff line change
Expand Up @@ -87,29 +87,38 @@
foreach (var project in projects.OrderByDescending(project => project.CreatedOnBlock))
{
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title">@project.ProjectIdentifier</h5>
<p class="card-text">Nostr ID: @(NostrPublicKey.FromHex(project.NostrPubKey).Bech32)</p>
@if (SessionStorage.IsProjectMetadataStorageByPubkey(project.NostrPubKey))
{
var metadata = SessionStorage.GetProjectMetadataByPubkey(project.NostrPubKey);
if (metadata?.Banner != null)
{
<div class="card-header overflow-hidden">
<img class="card-img-top" src="@metadata.Banner" alt=""/>
</div>
}
}

<div class="card-body">
@if (SessionStorage.IsProjectInStorageById(project.ProjectIdentifier))
{
@if (SessionStorage.IsProjectMetadataStorageByPubkey(project.NostrPubKey))
{
var metadata = SessionStorage.GetProjectMetadataByPubkey(project.NostrPubKey);
<hr />
<h3 class="card-title">@metadata?.Name</h3>
<p class="card-subtitle">@metadata?.About</p>
<hr />
<hr>
}

//var info = SessionStorage.GetProjectById(project.ProjectIdentifier);
<button @onclick="() => ViewProjectDetails(project.ProjectIdentifier)" class="btn btn-primary">View</button>
}
else
{
<p class="text-warning-emphasis">Project not found in any relay!</p>
}
<p>
Project ID:@project.ProjectIdentifier
<br/>
Nostr ID :@(NostrPublicKey.FromHex(project.NostrPubKey).Bech32)
</p>
<button @onclick="() => ViewProjectDetails(project.ProjectIdentifier)" class="btn btn-primary card-">View</button>
</div>
</div>
}
Expand Down Expand Up @@ -246,7 +255,6 @@
{
if (SessionStorage.IsProjectInStorageById(projectIdentifier))
{
_RelayService.CloseConnection();
NavigationManager.NavigateTo($"/view/{projectIdentifier}");
}
else
Expand Down
148 changes: 46 additions & 102 deletions src/Angor/Client/Pages/Create.razor
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,12 @@
@using Angor.Shared
@using Angor.Client.Storage
@using Blockcore.Consensus.TransactionInfo
@using Angor.Client.Services
@using Angor.Shared.ProtocolNew
@using Angor.Shared.Services
@using Blockcore.NBitcoin
@using Blockcore.NBitcoin.DataEncoders
@using Nostr.Client.Messages
@using Nostr.Client.Messages.Metadata
@using Angor.Client.Models

@implements IDisposable
@inherits BaseComponent
@inject IDerivationOperations _derivationOperations
@inject IWalletStorage _walletStorage;
Expand Down Expand Up @@ -251,38 +247,25 @@
{
if (hasWallet)
{
var operationResult = await notificationComponent.LongOperation(async () =>
_RelayService.RequestProjectCreateEventsByPubKey(_ => //TODO change the state to be storage driven and not event driven
{
_RelayService.RequestProjectCreateEventsByPubKey(_ => //TODO change the state to be storage driven and not event driven
{
nostrProfileCreated = _.Kind == NostrKind.Metadata;

if (_.Kind != NostrKind.ApplicationSpecificData)
return; //In case of a crashed application in the middle of the call
if (_.Content == null)
return;
var nostrProject = System.Text.Json.JsonSerializer.Deserialize<ProjectInfo>(_.Content, RelayService.settings);
var findProject = storage.GetFounderProjects().FirstOrDefault(p => p.ProjectInfo.ProjectIdentifier == nostrProject!.ProjectIdentifier);
if (findProject == null)
storage.AddFounderProject(new FounderProject { ProjectInfo = nostrProject });
NavigationManager.NavigateTo($"/view/{nostrProject.ProjectIdentifier}");
}, () =>
{
notificationComponent.StopLoading();
StateHasChanged();
},project.NostrPubKey);

// let the request a few seconds to look for a project
await Task.Delay(TimeSpan.FromSeconds(5));

return new SuccessOperationResult();
});

if (operationResult.Success)
nostrProfileCreated = _.Kind == NostrKind.Metadata;

if (_.Kind != NostrKind.ApplicationSpecificData)
return; //In case of a crashed application in the middle of the call
if (_.Content == null)
return;
var nostrProject = System.Text.Json.JsonSerializer.Deserialize<ProjectInfo>(_.Content, RelayService.settings);
var findProject = storage.GetFounderProjects().FirstOrDefault(p => p.ProjectInfo.ProjectIdentifier == nostrProject!.ProjectIdentifier);
if (findProject == null)
storage.AddFounderProject(new FounderProject { ProjectInfo = nostrProject });
NavigationManager.NavigateTo($"/view/{nostrProject.ProjectIdentifier}");
}, () =>
{
notificationComponent.StopLoading();
StateHasChanged();
}
}, project.NostrPubKey);
}
}
}
Expand All @@ -291,8 +274,6 @@

private async Task CreatNostrProfile()
{
var operationResult = await notificationComponent.LongOperation(async () =>
{
var nostrKey = _derivationOperations.DeriveProjectNostrPrivateKey(_walletStorage.GetWallet(), project.ProjectIndex);

await _RelayService.CreateNostrProfileAsync(NostrMetadata.ToNostrMetadata(),
Expand All @@ -304,14 +285,6 @@
nostrProfileCreated = true;
StateHasChanged();
});

return new SuccessOperationResult();
});

if (!operationResult.Success)
{
notificationComponent.ShowErrorMessage(operationResult.Message);
}
}

private async Task CreatProject()
Expand Down Expand Up @@ -378,34 +351,23 @@
prev = stage.ReleaseDate;
}

var operationResult = await notificationComponent.LongOperation(async () =>
{
var accountInfo = storage.GetAccountInfo(network.Name);
var unconfirmedInfo = _cacheStorage.GetUnconfirmedInboundFunds();
var accountInfo = storage.GetAccountInfo(network.Name);
var unconfirmedInfo = _cacheStorage.GetUnconfirmedInboundFunds();

var fetchFees = await _WalletOperations.GetFeeEstimationAsync();
feeData.FeeEstimations.Fees.Clear();
feeData.FeeEstimations.Fees.AddRange(fetchFees);
feeData.SelectedFeeEstimation = feeData.FeeEstimations.Fees.First();
var fetchFees = await _WalletOperations.GetFeeEstimationAsync();
feeData.FeeEstimations.Fees.Clear();
feeData.FeeEstimations.Fees.AddRange(fetchFees);
feeData.SelectedFeeEstimation = feeData.FeeEstimations.Fees.First();

unsignedTransaction = _founderTransactionActions.CreateNewProjectTransaction(project.FounderKey, _derivationOperations.AngorKeyToScript(project.ProjectIdentifier), 10000, project.NostrPubKey);
unsignedTransaction = _founderTransactionActions.CreateNewProjectTransaction(project.FounderKey, _derivationOperations.AngorKeyToScript(project.ProjectIdentifier), 10000, project.NostrPubKey);

signedTransaction = _WalletOperations.AddInputsAndSignTransaction(accountInfo.GetNextChangeReceiveAddress(), unsignedTransaction, _walletStorage.GetWallet(), accountInfo, feeData.SelectedFeeEstimation);
signedTransaction = _WalletOperations.AddInputsAndSignTransaction(accountInfo.GetNextChangeReceiveAddress(), unsignedTransaction, _walletStorage.GetWallet(), accountInfo, feeData.SelectedFeeEstimation);

project.CreationTransactionId = signedTransaction.GetHash().ToString();
project.CreationTransactionId = signedTransaction.GetHash().ToString();

return new OperationResult { Success = true };
showCreateModal = true;

});

if (operationResult.Success)
{
showCreateModal = true;
}
else
{
notificationComponent.ShowErrorMessage(operationResult.Message);
}
StateHasChanged();
}

private void FeeRangeChanged(ChangeEventArgs e)
Expand Down Expand Up @@ -433,44 +395,32 @@

private async Task Send()
{
var operationResult = await notificationComponent.LongOperation(async () =>
{
showCreateModal = false;

var nostrKey = _derivationOperations.DeriveProjectNostrPrivateKey(_walletStorage.GetWallet(), project.ProjectIndex);

var nostrKeyHex = NBitcoin.DataEncoders.Encoders.Hex.EncodeData(nostrKey.ToBytes());

var resultId = await _RelayService.AddProjectAsync(project, nostrKeyHex,
_ =>
{
if (!_.Accepted)
notificationComponent.ShowErrorMessage("Failed to store the project information on the relay!!!"); //TODO add export project info
});

var response = await _WalletOperations.PublishTransactionAsync(network, signedTransaction);
showCreateModal = false;

if (!response.Success)
{
await _RelayService.DeleteProjectAsync(resultId, nostrKeyHex);
return response;
}
var nostrKey = _derivationOperations.DeriveProjectNostrPrivateKey(_walletStorage.GetWallet(), project.ProjectIndex);

storage.AddFounderProject(new FounderProject { ProjectInfo = project });
var nostrKeyHex = NBitcoin.DataEncoders.Encoders.Hex.EncodeData(nostrKey.ToBytes());

return new OperationResult { Success = response.Success, Message = response.Message };
});
var resultId = await _RelayService.AddProjectAsync(project, nostrKeyHex,
_ =>
{
if (!_.Accepted)
notificationComponent.ShowErrorMessage("Failed to store the project information on the relay!!!"); //TODO add export project info
});

if (operationResult.Success)
{
notificationComponent.ShowNotificationMessage("Project created", 1);
var response = await _WalletOperations.PublishTransactionAsync(network, signedTransaction);

NavigationManager.NavigateTo($"/view/{project.ProjectIdentifier}");
}
else
if (!response.Success)
{
notificationComponent.ShowErrorMessage(operationResult.Message);
await _RelayService.DeleteProjectAsync(resultId, nostrKeyHex);
notificationComponent.ShowErrorMessage(response.Message);
// notificationComponent.ShowErrorMessage("Failed to post the transaction to the blockchain.(try refreshing the wallet)");
return;
}

storage.AddFounderProject(new FounderProject { ProjectInfo = project });

NavigationManager.NavigateTo($"/view/{project.ProjectIdentifier}");
}

private void AddStage()
Expand All @@ -482,10 +432,4 @@
{
project.Stages.Remove(stage);
}

public void Dispose()
{
_RelayService.CloseConnection();
}

}
8 changes: 0 additions & 8 deletions src/Angor/Client/Pages/Founder.razor
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
@using Nostr.Client.Messages
@using System.Text.Json

@implements IDisposable

@inject NavigationManager NavigationManager
@inject IWalletStorage _walletStorage;
@inject IClientStorage storage;
Expand Down Expand Up @@ -154,10 +152,4 @@
{
NavigationManager.NavigateTo("/create");
}

public void Dispose()
{
RelayService.CloseConnection();
}

}
8 changes: 0 additions & 8 deletions src/Angor/Client/Pages/Invest.razor
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@

@inherits BaseComponent

@implements IDisposable

@inject ILogger<Invest> _Logger;
@inject IDerivationOperations _derivationOperations
@inject IClientStorage storage;
Expand Down Expand Up @@ -584,10 +582,4 @@
public DateTime StageDateTime { get; set; }
public int DaysFromStartDate { get; set; }
}

public void Dispose()
{
_SignService.CloseConnection();
}

}
8 changes: 0 additions & 8 deletions src/Angor/Client/Pages/Signatures.razor
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@

@inject IJSRuntime JS

@implements IDisposable

@inject ILogger<Signatures> Logger
@inject IDerivationOperations DerivationOperations
@inject IClientStorage Storage;
Expand Down Expand Up @@ -314,10 +312,4 @@

public string? TransactionHex { get; set; }
}

public void Dispose()
{
SignService.CloseConnection();
}

}
8 changes: 4 additions & 4 deletions src/Angor/Client/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,11 @@
builder.Services.AddScoped<NavMenuState>();

builder.Services.AddScoped<IIndexerService, IndexerService>();
builder.Services.AddScoped<IRelayService, RelayService>();
builder.Services.AddScoped<ISignService, SignService>();
builder.Services.AddScoped<INetworkService, NetworkService>();

builder.Services.AddTransient<IRelayService, RelayService>();
builder.Services.AddTransient<ISignService, SignService>();

builder.Services.AddTransient<IFounderTransactionActions, FounderTransactionActions>();
builder.Services.AddTransient<ISeederTransactionActions, SeederTransactionActions>();
builder.Services.AddTransient<IInvestorTransactionActions, InvestorTransactionActions>();
Expand All @@ -48,7 +49,6 @@
builder.Services.AddTransient<ITaprootScriptBuilder, TaprootScriptBuilder>();

builder.Services.AddSingleton<INostrCommunicationFactory,NostrCommunicationFactory>();
builder.Services.AddScoped<IRelaySubscriptionsHandling, RelaySubscriptionsHandling>(); //TODO should this be singleton?

builder.Services.AddScoped<IRelaySubscriptionsHandling, RelaySubscriptionsHandling>();

await builder.Build().RunAsync();
2 changes: 1 addition & 1 deletion src/Angor/Shared/Services/IRelayService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ public interface IRelayService
void RequestProjectCreateEventsByPubKey(Action<NostrEvent> onResponseAction, Action? onEoseAction,params string[] nostrPubKeys);

Task LookupDirectMessagesForPubKeyAsync(string nostrPubKey, DateTime? since, int? limit, Action<NostrEvent> onResponseAction);
void CloseConnection();
// void CloseConnection();
}
2 changes: 0 additions & 2 deletions src/Angor/Shared/Services/ISignService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,4 @@ public interface ISignService

DateTime SendSignaturesToInvestor(string encryptedSignatureInfo, string nostrPrivateKey,
string investorNostrPubKey);

void CloseConnection(); //TODO call close connection from the pages
}
Loading

0 comments on commit 2fd0e09

Please sign in to comment.