8000 Add Pending Investments to the Backend API by SuperJMN · Pull Request #365 · block-core/angor · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Add Pending Investments to the Backend API #365

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

Merged
merged 4 commits into from
May 9, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,78 @@
using Angor.Contexts.Funding.Projects.Domain;
using Angor.Contexts.Funding.Shared;
using Angor.Contexts.Funding.Tests.TestDoubles;
using Angor.Contexts.Wallet.Domain;
using Angor.Contexts.Wallet.Infrastructure.Interfaces;
using Angor.Shared;
using Microsoft.Extensions.DependencyInjection;
using Nostr.Client.Utils;
using Serilog;
using Xunit.Abstractions;
using Amount = Angor.Contexts.Funding.Projects.Domain.Amount;

namespace Angor.Contexts.Funding.Tests;

public class InvestmentAppServiceTests(ITestOutputHelper output)
{
[Fact]
public void CreateService()
public void Service_can_be_created()
{
// Act
CreateSut();
}

[Fact]
public async Task CreateInvestmentTransaction()
public async Task Create_investment_draft()
{
var sut = CreateSut();
var projectId = new ProjectId("angor1qkmmqqktfhe79wxp20555cdp5gfardr4s26wr00");
var result = await sut.CreateDraft(sourceWalletId: Guid.Empty, projectId, new Amount(12345));
var result = await sut.CreateInvestmentDraft(sourceWalletId: Guid.Empty, projectId, new Amount(12345));
Assert.True(result.IsSuccess, result.IsFailure ? result.Error : string.Empty);
}

[Fact]
public async Task RequestFounderSignatures()
public async Task Request_investment_in_project()
{
// Arrange
var sut = CreateSut();
var projectId = new ProjectId("angor1qkmmqqktfhe79wxp20555cdp5gfardr4s26wr00");
var investorKey = "03138f2811a0b7589d1b04a34b561f55093965757b31b239b3b201d93825455838";
var txHex = "010000000001010bd918149ebabf50f237b1a56468275694d8659ba4c027e918b2fdd2daee6ca10000000000ffffffff077b00000000000000160014b6f6005969be7c57182a7d294c3434427a368eb00000000000000000236a2103138f2811a0b7589d1b04a34b561f55093965757b31b239b3b201d938254558380e0c00000000000022512084f0525ebccdfbf25a16c17b80376dee43340abe3ccf16dd469516305f269ae70e0c0000000000002251205aae5213e93335978561dea413cf06d84e50ca3b1c4a2df0032a9f7c07e6bb280e0c000000000000225120b2f7dd8d0e803799cba4197e7c0888985f8ff69113cab0dc273953afab6ab4160e0c000000000000225120fba3b11bb17f310d7cc02b09e911119324e53ce630625297ef021938a3a861644dc933770000000016001441566be59b2062a8cc3eddb528eb027dbbcbb18302483045022100cf44e9d7d793fa549fedd4835e09461538e797245ee662322004b6f69fa2b7d202205269573bbfba88abe0a39893acf9dd074260556a92c55be56cf5fdaca153da1f0121021ffb80288cff7f0c0e8dc30a1658f1f6c54fd89d8d03226acac1e6f733d1a04800000000";
var txId = "1b55a4706d7315ea32bfe9c004781f0dee1df3ba18fd7d4423ebad2399dcf96a";
var investmentTransaction = new CreateInvestment.Draft(investorKey, txHex, txId, new Amount(0));
var result = await sut.RequestInvestment(Guid.Empty, projectId, investmentTransaction);
var draft = new CreateInvestment.Draft(investorKey, txHex, txId, new Amount(0));

// Act
var result = await sut.Invest(Guid.Empty, projectId, draft);

// Assert
Assert.True(result.IsSuccess, result.IsFailure ? result.Error : string.Empty);
}

[Fact]
public async Task GetInvestments()
public async Task Get_project_investments()
{
// Arrange
var sut = CreateSut();
var projectId = new ProjectId("angor1qkmmqqktfhe79wxp20555cdp5gfardr4s26wr00");

// Act
var result = await sut.GetInvestments(projectId);

// Assert
Assert.True(result.IsSuccess);
Assert.NotEmpty(result.Value);
}

[Fact]
public async Task Get_pending_investments()
{
// Arrange
var sut = CreateSut();

// Act
var result = await sut.GetPendingInvestments(Guid.Empty, new ProjectId("angor1qatlv9htzte8vtddgyxpgt78ruyzaj57n4l7k46"));

// Assert
Assert.True(result.IsSuccess);
Assert.NotEmpty(result.Value);
}
Expand All @@ -56,7 +85,7 @@ private IInvestmentAppService CreateSut()

var logger = new LoggerConfiguration().WriteTo.TestOutput(output).CreateLogger();
FundingContextServices.Register(serviceCollection, logger);
serviceCollection.AddSingleton<ISeedwordsProvider>(sp => new TestingSeedwordsProvider("print foil moment average quarter keep amateur shell tray roof acoustic where", "", sp.GetRequiredService<IDerivationOperations>()));
serviceCollection.AddSingleton<ISeedwordsProvider>(sp => new TestingSeedwordsProvider("oven suggest panda hip orange cheap kite focus cross never tornado forget", "", sp.GetRequiredService<IDerivationOperations>()));

var serviceProvider = serviceCollection.BuildServiceProvider();
var projectAppService = serviceProvider.GetService<IInvestmentAppService>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Angor.Contexts.Funding.Founder.Operations;
using Angor.Contexts.Funding.Projects.Domain;
using Angor.Contexts.Funding.Shared;
using Angor.Contexts.Funding.Tests.TestDoubles;
using Angor.Shared;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using Xunit.Abstractions;

namespace Angor.Contexts.Funding.Tests;

public class NostrDecrypterTests(ITestOutputHelper output)
{
[Fact]
public async Task Decrypt_Nostr_message()
{
// Arrange
var sut = CreateSut();
var nostrMessage = new NostrMessage("SOME ID", "c57cce49441740454e54fee15131b9699d54d4928a5eaa0756214dc21961cf1b", "gYpNKJuzweBOfsOXOOInoyEXI+jlOxs2dQ//Yk3CSpkvUQPs6od9eq/HCUGBPetHlTBlmlJheVNYzl+u+4NcShzgV2kmOb7rbH88UUCZXRyXdxwwnGU8rvM4BKNc/WqS3Rsyny+hDpy/YpEpsSMH46kTAqPm6+PjyyIoTGNMqAui95RdTNMHXju6hLXse6kTL93aD8xpCsLVZ773PaJxtO8qzVmCJ9Ton+TMkD3ujxcUAv/Dy03vRQWp96iNSfsBif6OUlenGPk5YUzgKscjNVVxOgLCB7hdlM9NQiTDB3EKabl6p7L9Dg77UftRcrHwYE44QYtgOjTggNRtoWYhAxgITp4IHtIOLJRIBexlxrY+2R8Zfkd1w0qvTm41zi9eITB0/rJEE/u8jMFJLVxDMLcaGVWuj1/9NlcZ9jTpf5ANOr6VnWDi2JRUsfJXDxUNyYSQttoclZVYD1gLjv/+ags+aBQzpiz5XOAC1NVOouKTE4Wj4b9MLvMJLMfyjtmBPBc++7uy0dOX6YVQqorOzNtk6NkOQFPDdCZK5zmQB2twWwwo6TlzKUT3n3msoeHi7AuBLAxoD7v2hmY61SMt7Z8tM4kOmaxMF+ed1ZKrD1gyfWniOD/4GXj+lovTPw4vOZRLmfYTTCKJROB/qBheH5tyuNahn4FiIWYxATTBO3jJoKw9evQdf8haDptwlPTZUwlf3C+T0nf+9Z+bXSWaRPsORQzNgWYnRys/G4OpodXiVFwdH+6rYeXDMXAiCMEDXBBfT2e5QZxVuJuSbhTW75jNvDEaHrg12UxvA+7nqCy4rpHC3nDQaABEprXdYK6bANqIWSsNCsmUhSjLfpH+gljJ5iiH+yE6kf/tGGNnSS4pKa9cPSMbSB68eIWwUeaNRRBtcJkvr42K35jUE2vEQhqs3ojQlMItgy4/YvcXP6+DMzGZbxdDWO8u0xsE0qNpkCavwi/+UgVsYj5dEK32nt8kiBryr6/UJyWprOa8lUQ=?iv=+uu8GD5eAnBhjP3FjCVeSQ==", DateTime.Now);

// Act
var clientKeyResult = await sut.Decrypt(Guid.NewGuid(), new ProjectId("angor1qatlv9htzte8vtddgyxpgt78ruyzaj57n4l7k46"), nostrMessage);

// Assert
Assert.True(clientKeyResult.IsSuccess);
Assert.NotEmpty(clientKeyResult.Value);
}


private NostrDecrypter CreateSut()
{
var serviceCollection = new ServiceCollection();

var logger = new LoggerConfiguration().WriteTo.TestOutput(output).CreateLogger();
FundingContextServices.Register(serviceCollection, logger);
serviceCollection.AddSingleton<ISeedwordsProvider>(sp => new TestingSeedwordsProvider("oven suggest panda hip orange cheap kite focus cross never tornado forget", "", sp.GetRequiredService<IDerivationOperations>()));

var serviceProvider = serviceCollection.BuildServiceProvider();

return ActivatorUtilities.CreateInstance<NostrDecrypter>(serviceProvider);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Angor.Contexts.Funding.Tests;
public class ProjectAppServiceTests(ITestOutputHelper output)
{
[Fact]
public async Task GetProjects()
public async Task Get_latest_projects()
{
var sut = CreateSut();
var result = await sut.Latest();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Angor.Contexts.Funding.Projects.Domain;
using Angor.Shared;
using Angor.Shared.Models;
using Angor.Shared.Services;
using CSharpFunctionalExtensions;
using MediatR;

namespace Angor.Contexts.Funding.Founder.Operations;

public class GetPendingInvestments
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be honest I am not crazy about multiple classes in one file, it means I can't see the logic and structure when I look at the solution files, how many of these IRequests do we have so far?

{
public class GetPendingInvestmentsRequest(Guid walletId, ProjectId projectId) : IRequest<Result<IEnumerable<PendingInvestmentDto>>>
{
public Guid WalletId { get; } = walletId;
public ProjectId ProjectId { get; } = projectId;
}

public class GetPendingInvestmentsHandler(IProjectRepository projectRepository,
ISignService signService,
INostrDecrypter nostrDecrypter,
INetworkConfiguration networkConfiguration,
ISerializer serializer) : IRequestHandler<GetPendingInvestmentsRequest, Result<IEnumerable<PendingInvestmentDto>>>
{
public async Task<Result<IEnumerable<PendingInvestmentDto>>> Handle(GetPendingInvestmentsRequest request, CancellationToken cancellationToken)
{
var project = await projectRepository.Get(request.ProjectId);
if (project.IsFailure)
{
return Result.Failure<IEnumerable<PendingInvestmentDto>>(project.Error);
}

var nostrPubKey = project.Value.NostrPubKey;
var investingMessages = InvestmentMessages(nostrPubKey);
var pendingInvestmentResults = await investingMessages.SelectMany(nostrMessage => DecryptInvestmentMessage(request.WalletId, project, nostrMessage)).ToList();

return pendingInvestmentResults.Combine();
}

private Task<Result<PendingInvestmentDto>> DecryptInvestmentMessage(Guid walletId, Result<Project> project, NostrMessage nostrMessage)
{
return from decrypted in nostrDecrypter.Decrypt(walletId, project.Value.Id, nostrMessage)
from signRecoveryRequest in Result.Try(() => serializer.Deserialize<SignRecoveryRequest>(decrypted))
select new PendingInvestmentDto(nostrMessage.Created, GetAmount(signRecoveryRequest), nostrMessage.InvestorNostrPubKey);
}

private IObservable<NostrMessage> InvestmentMessages(string nostrPubKey)
{
return Observable.Create<NostrMessage>(observer =>
{
signService.LookupInvestmentRequestsAsync(nostrPubKey, null, null,
(id, pubKey, content, created) => observer.OnNext(new NostrMessage(id, pubKey, content, created)),
observer.OnCompleted
);

return Disposable.Empty;
});
}

private decimal GetAmount(SignRecoveryRequest signRecoveryRequest)
{
var investorTrx = networkConfiguration.GetNetwork().CreateTransaction(signRecoveryRequest.InvestmentTransactionHex);

return investorTrx.Outputs.AsIndexedOutputs()
.Skip(2)
.Take(investorTrx.Outputs.Count - 3)
.Sum(x => x.TxOut.Value.Satoshi);
}
}

public record PendingInvestmentDto(DateTime Created, decimal Amount, string InvestorNostrPubKey);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Angor.Contexts.Funding.Projects.Domain;
using Angor.Contexts.Funding.Projects.Infrastructure.Impl;
using Angor.Contexts.Funding.Projects.Infrastructure.Interfaces;
using Angor.Contexts.Funding.Shared;
using Angor.Contexts.Wallet.Infrastructure.Impl;
using Angor.Shared;
using Angor.Shared.Networks;
Expand All @@ -30,6 +31,7 @@ public static ServiceCollection Register(ServiceCollection services, ILogger log
services.AddSingleton<IInvestmentAppService, InvestmentAppService>();
services.AddSingleton<IInvestmentRepository, InvestmentRepository>();
services.AddSingleton<IProjectRepository, ProjectRepository>();
services.AddSingleton<INostrDecrypter, NostrDecrypter>();
services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(CreateInvestment.CreateInvestmentTransactionHandler).Assembly));

services.TryAddSingleton<ISerializer, Serializer>();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Angor.Contexts.Funding.Founder.Operations;
using Angor.Contexts.Funding.Investor.Dtos;
using Angor.Contexts.Funding.Investor.Operations;
using Angor.Contexts.Funding.Projects.Domain;
Expand All @@ -8,6 +9,7 @@ namespace Angor.Contexts.Funding.Investor;
public interface IInvestmentAppService
{
Task<Result<IEnumerable<InvestmentDto>>> GetInvestments(ProjectId projectId);
Task<Result<CreateInvestment.Draft>> CreateDraft(Guid sourceWalletId, ProjectId projectId, Amount amount);
Task<Result<Guid>> RequestInvestment(Guid sourceWalletId, ProjectId projectId, CreateInvestment.Draft draft);
Task<Result<CreateInvestment.Draft>> CreateInvestmentDraft(Guid sourceWalletId, ProjectId projectId, Amount amount);
Task<Result<Guid>> Invest(Guid sourceWalletId, ProjectId projectId, CreateInvestment.Draft draft);
Task<Result<IEnumerable<GetPendingInvestments.PendingInvestmentDto>>> GetPendingInvestments(Guid walletId, ProjectId projectId);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name should be single because the project id is only ever for 1 investment at the time

}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Angor.Contexts.Funding.Founder.Operations;
using Angor.Contexts.Funding.Investor.Dtos;
using Angor.Contexts.Funding.Investor.Operations;
using Angor.Contexts.Funding.Projects.Domain;
Expand All @@ -14,13 +15,18 @@ public Task<Result<IEnumerable<InvestmentDto>>> GetInvestments(ProjectId project
return investmentRepository.GetByProject(projectId);
}

public Task<Result<CreateInvestment.Draft>> CreateDraft(Guid sourceWalletId, ProjectId projectId, Amount amount)
public Task<Result<CreateInvestment.Draft>> CreateInvestmentDraft(Guid sourceWalletId, ProjectId projectId, Amount amount)
{
return mediator.Send(new CreateInvestment.CreateInvestmentTransactionRequest(sourceWalletId, projectId, amount));
}

public Task<Result<Guid>> RequestInvestment(Guid sourceWalletId, ProjectId projectId, CreateInvestment.Draft draft)
public Task<Result<Guid>> Invest(Guid sourceWalletId, ProjectId projectId, CreateInvestment.Draft draft)
{
return mediator.Send(new RequestInvestment.RequestFounderSignaturesRequest(sourceWalletId, projectId, draft));
}

public Task<Result<IEnumerable<GetPendingInvestments.PendingInvestmentDto>>> GetPendingInvestments(Guid walletId, ProjectId projectId)
{
return mediator.Send(new GetPendingInvestments.GetPendingInvestmentsRequest(walletId, projectId));
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
using Angor.Client.Services;
using Angor.Contests.CrossCutting;
using Angor.Contexts.Funding.Projects.Domain;
using Angor.Contexts.Funding.Projects.Infrastructure.Impl;
using Angor.Contexts.Funding.Shared;
using Angor.Shared;
using Angor.Shared.Models;
using Angor.Shared.Protocol;
using Angor.Shared.Services;
using Blockcore.Consensus.TransactionInfo;
using CSharpFunctionalExtensions;
using MediatR;
Expand Down Expand Up @@ -36,10 +34,7 @@ public class CreateInvestmentTransactionHandler(
IInvestorTransactionActions investorTransactionActions,
ISeedwordsProvider seedwordsProvider,
IWalletOperations walletOperations,
IDerivationOperations derivationOperations,
IEncryptionService encryptionService,
ISerializer serializer,
IRelayService relayService) : IRequestHandler<CreateInvestmentTransactionRequest, Result<Draft>>
IDerivationOperations derivationOperations) : IRequestHandler<CreateInvestmentTransactionRequest, Result<Draft>>
{
public async Task<Result<Draft>> Handle(CreateInvestmentTransactionRequest transactionRequest, CancellationToken cancellationToken)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ public class RequestFounderSignaturesHandler(
INetworkConfiguration networkConfiguration,
ISerializer serializer,
IWalletOperations walletOperations,
ISignService signService,
IRelayService relayService) : IRequestHandler<RequestFounderSignaturesRequest, Result<Guid>>
ISignService signService) : IRequestHandler<RequestFounderSignaturesRequest, Result<Guid>>
{
public async Task<Result<Guid>> Handle(RequestFounderSignaturesRequest request, CancellationToken cancellationToken)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,7 @@ public Task<Result<IEnumerable<InvestmentDto>>> GetByProject(ProjectId projectId
}));
}

// public Task<Result<PendingInvestment>> GetPendingInvestment(Guid walletId, ProjectId projectId)
// {
// throw new NotImplementedException();
// }
//
// public Task<Result<SignedInvestment>> GetSignedInvestment(Guid walletId, ProjectId projectId)
// {
// throw new NotImplementedException();
// }

private async Task<List<Domain.Investment>> GetAllConfirmedInvestments()
private async Task<List<Investment>> GetAllConfirmedInvestments()
{
var allProjects = await indexerService.GetProjectsAsync(0, 20);
var investments = new List<Domain.Investment>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Angor.Contexts.Funding.Founder.Operations;
using Angor.Contexts.Funding.Projects.Domain;
using CSharpFunctionalExtensions;

namespace Angor.Contexts.Funding;

public interface INostrDecrypter
{
Task<Result<string>> Decrypt(Guid walletId, ProjectId projectId, NostrMessage nostrMessage);
}
27 changes: 27 additions & 0 deletions src/Angor/Avalonia/Angor.Contexts.Funding/Shared/NostrDecrypter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Angor.Client.Services;
using Angor.Contests.CrossCutting;
using Angor.Contexts.Funding.Founder.Operations;
using Angor.Contexts.Funding.Projects.Domain;
using Angor.Shared;
using Blockcore.NBitcoin;
using Blockcore.NBitcoin.DataEncoders;
using CSharpFunctionalExtensions;

namespace Angor.Contexts.Funding.Shared;

public class NostrDecrypter(IDerivationOperations derivationOperations, IEncryptionService encryptionService, ISeedwordsProvider provider, IProjectRepository projectRepository) : INostrDecrypter
{
public Task<Result<string>> Decrypt(Guid walletId, ProjectId projectId, NostrMessage nostrMessage)
{
return from sensitiveData in provider.GetSensitiveData(walletId)
from project in projectRepository.Get(projectId)
from nostrPrivateKey in Result.Try(() => derivationOperations.DeriveProjectNostrPrivateKeyAsync(sensitiveData.ToWalletWords(), project.FounderKey))
from decrypted in Result.Try(() =>
{
var bytes = nostrPrivateKey.ToBytes();
var hex = Encoders.Hex.EncodeData(bytes);
return encryptionService.DecryptNostrContentAsync(hex, nostrMessage.InvestorNostrPubKey, nostrMessage.Content);
})
select decrypted;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Angor.Contexts.Funding.Founder.Operations;

public record NostrMessage(string Id, string InvestorNostrPubKey, string Content, DateTime Created);
Loading
0