Skip to content
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
9 changes: 6 additions & 3 deletions apps/backoffice-tokenization/.env.example
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# Trustless Work API Configuration
NEXT_PUBLIC_API_KEY=""
NEXT_PUBLIC_API_KEY=

# Server-side only (for contract deployment)
SOURCE_SECRET=""
SOURCE_SECRET=

# Core API URL (NestJS backend)
NEXT_PUBLIC_CORE_API_URL="http://localhost:4000"
NEXT_PUBLIC_CORE_API_URL=http://localhost:4000

# Core API Authentication
NEXT_PUBLIC_BACKOFFICE_API_KEY=
6 changes: 6 additions & 0 deletions apps/backoffice-tokenization/src/lib/httpClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { createHttpClient } from "@tokenization/shared/lib/httpClient";

export const httpClient = createHttpClient({
baseURL: process.env.NEXT_PUBLIC_CORE_API_URL ?? "http://localhost:4000",
apiKey: process.env.NEXT_PUBLIC_BACKOFFICE_API_KEY ?? "",
});
1 change: 1 addition & 0 deletions apps/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"@stellar/stellar-sdk": "^14.6.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"dotenv": "^16.6.1",
"prisma": "^6.19.2",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1"
Expand Down
13 changes: 9 additions & 4 deletions apps/core/src/investments/investments.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,28 @@ import { CreateInvestmentDto } from './dto/create-investment.dto';

@Controller('investments')
export class InvestmentsController {
constructor(private readonly investmentsService: InvestmentsService) {}
constructor(private readonly investmentsService: InvestmentsService) { }

@Get()
findAll() {
return this.investmentsService.findAll();
}

@Get(':id')
findOne(@Param('id') id: string) {
return this.investmentsService.findOne(id);
@Get('investor/:address')
findByInvestor(@Param('address') address: string) {
return this.investmentsService.findByInvestor(address);
}

@Get('campaign/:campaignId')
findByCampaign(@Param('campaignId') campaignId: string) {
return this.investmentsService.findByCampaign(campaignId);
}

@Get(':id')
findOne(@Param('id') id: string) {
return this.investmentsService.findOne(id);
}

@Post()
create(@Body() dto: CreateInvestmentDto) {
return this.investmentsService.create(dto);
Expand Down
8 changes: 8 additions & 0 deletions apps/core/src/investments/investments.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ export class InvestmentsService {
return investment;
}

findByInvestor(investorAddress: string) {
return this.prisma.investment.findMany({
where: { investorAddress },
orderBy: { createdAt: 'desc' },
include: { campaign: true },
});
}

findByCampaign(campaignId: string) {
return this.prisma.investment.findMany({
where: { campaignId },
Expand Down
3 changes: 3 additions & 0 deletions apps/core/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dotenv/config';

import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
Expand All @@ -16,5 +18,6 @@ async function bootstrap() {

app.useGlobalGuards(new ApiKeyGuard());
await app.listen(process.env.PORT ?? 4000);
console.log(`Core API is running on port ${process.env.PORT ?? 4000}`);
}
bootstrap();
14 changes: 14 additions & 0 deletions apps/core/src/prisma/prisma.service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

function buildDatasourceUrl(): string | undefined {
const raw = process.env.DATABASE_URL;
if (!raw) return undefined;
if (raw.includes('pgbouncer=true')) return raw;
const separator = raw.includes('?') ? '&' : '?';
return `${raw}${separator}pgbouncer=true`;
}

@Injectable()
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
constructor() {
super({
datasources: { db: { url: buildDatasourceUrl() } },
});
}

async onModuleInit() {
await this.$connect();
}
Expand Down
2 changes: 1 addition & 1 deletion apps/core/src/token-sale/token-sale.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { SetAdminDto } from './dto/set-admin.dto';

@Controller('token-sale')
export class TokenSaleController {
constructor(private readonly tokenSaleService: TokenSaleService) {}
constructor(private readonly tokenSaleService: TokenSaleService) { }

// ── POST endpoints (writes) ──

Expand Down
6 changes: 5 additions & 1 deletion apps/investor-tokenization/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@ NEXT_PUBLIC_DEFAULT_USDC_ADDRESS=
NEXT_PUBLIC_API_KEY=

# Server-side only (for contract deployment)
SOURCE_SECRET=
SOURCE_SECRET=

# Core API Authentication
NEXT_PUBLIC_INVESTORS_API_KEY=
NEXT_PUBLIC_CORE_API_URL=http://localhost:4000
109 changes: 103 additions & 6 deletions apps/investor-tokenization/src/app/my-investments/page.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,117 @@
"use client";

import { useState, useMemo } from "react";
import { useState, useMemo, useCallback } from "react";
import { SectionTitle } from "@/components/shared/section-title";
import { CampaignToolbar } from "@/features/roi/components/campaign-toolbar";
import { CampaignList } from "@/features/roi/components/campaign-list";
import { mockCampaigns } from "@/features/roi/data/mock-campaigns";
import type { CampaignStatus } from "@/features/roi/types/campaign.types";
import type { Campaign, CampaignStatus } from "@/features/roi/types/campaign.types";
import { useUserInvestments } from "@/features/investments/hooks/useUserInvestments.hook";
import type { InvestmentFromApi } from "@/features/investments/services/investment.service";
import { ClaimROIService } from "@/features/claim-roi/services/claim.service";
import { useWalletContext } from "@tokenization/tw-blocks-shared/src/wallet-kit/WalletProvider";
import { signTransaction } from "@tokenization/tw-blocks-shared/src/wallet-kit/wallet-kit";
import { SendTransactionService } from "@/lib/sendTransactionService";
import { toastSuccessWithTx } from "@/lib/toastWithTx";
import { toast } from "sonner";

function toCampaign(inv: InvestmentFromApi): Campaign {
return {
id: inv.campaign.id,
title: inv.campaign.name,
description: inv.campaign.description ?? "",
status: inv.campaign.status as CampaignStatus,
loansCompleted: 0,
minInvestCents: Number(inv.usdcAmount) * 100,
currency: "USD",
vaultId: inv.campaign.vaultId ?? null,
};
}

function deduplicateByCampaign(investments: InvestmentFromApi[]): Campaign[] {
const seen = new Set<string>();
const campaigns: Campaign[] = [];
for (const inv of investments) {
if (!seen.has(inv.campaign.id)) {
seen.add(inv.campaign.id);
campaigns.push(toCampaign(inv));
}
}
return campaigns;
}

export default function MyInvestmentsPage() {
const [search, setSearch] = useState("");
const [filter, setFilter] = useState<CampaignStatus | "all">("all");
const { data: investments, isLoading } = useUserInvestments();
const { walletAddress } = useWalletContext();

const campaigns = useMemo(
() => deduplicateByCampaign(investments ?? []),
[investments],
);

const filteredCampaigns = useMemo(() => {
return mockCampaigns.filter((c) => {
return campaigns.filter((c) => {
const matchesStatus = filter === "all" || c.status === filter;
const matchesSearch =
search.trim() === "" ||
c.title.toLowerCase().includes(search.toLowerCase()) ||
c.description.toLowerCase().includes(search.toLowerCase());
return matchesStatus && matchesSearch;
});
}, [search, filter]);
}, [campaigns, search, filter]);

const handleClaimRoi = useCallback(
async (campaignId: string) => {
const campaign = campaigns.find((c) => c.id === campaignId);

if (!campaign?.vaultId) {
toast.error("Vault contract not available for this campaign.");
return;
}

if (!walletAddress) {
toast.error("Please connect your wallet to claim ROI.");
return;
}

try {
const svc = new ClaimROIService();
const claimResponse = await svc.claimROI({
vaultContractId: campaign.vaultId,
beneficiaryAddress: walletAddress,
});

if (!claimResponse?.success || !claimResponse?.xdr) {
throw new Error(
claimResponse?.message ?? "Failed to build claim transaction.",
);
}

const signedTxXdr = await signTransaction({
unsignedTransaction: claimResponse.xdr,
address: walletAddress,
});

const sender = new SendTransactionService();
const submitResponse = await sender.sendTransaction({
signedXdr: signedTxXdr,
});

if (submitResponse.status !== "SUCCESS") {
throw new Error(
submitResponse.message ?? "Transaction submission failed.",
);
}

toastSuccessWithTx("ROI claimed successfully!", submitResponse.hash);
} catch (e) {
const msg = e instanceof Error ? e.message : "Unexpected error while claiming ROI.";
toast.error(msg);
}
},
[campaigns, walletAddress],
);

return (
<div className="flex flex-col gap-6">
Expand All @@ -32,7 +123,13 @@ export default function MyInvestmentsPage() {
onSearchChange={setSearch}
onFilterChange={setFilter}
/>
<CampaignList campaigns={filteredCampaigns} />
{isLoading ? (
<p className="text-sm text-muted-foreground text-center py-8">
Loading your investments...
</p>
) : (
<CampaignList campaigns={filteredCampaigns} onClaimRoi={handleClaimRoi} />
)}
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ type Card = {
tokenSale?: string;
tokenFactory?: string;
vaultContractId?: string;
campaignId?: string;
src: string;
content: React.ReactNode;
};
Expand Down Expand Up @@ -400,6 +401,7 @@ export const Card = ({
escrowId: card.escrowId,
tokenSaleContractId: card.tokenSale,
imageSrc: card.src,
campaignId: card.campaignId,
}}
>
<InvestDialog tokenSaleContractId={card.tokenSale} />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import axios, { AxiosInstance } from "axios";
import { httpClient } from "@/lib/httpClient";

export type ClaimROIPayload = {
vaultContractId: string;
Expand All @@ -12,20 +12,20 @@ export type ClaimROIResponse = {
};

export class ClaimROIService {
private readonly axios: AxiosInstance;

constructor() {
this.axios = axios.create({
baseURL: "/api",
});
}

async claimROI(payload: ClaimROIPayload): Promise<ClaimROIResponse> {
const response = await this.axios.post<ClaimROIResponse>(
"/vault-contract/claim",
payload
const { data } = await httpClient.post<{ unsignedXdr: string }>(
"/vault/claim",
{
contractId: payload.vaultContractId,
beneficiary: payload.beneficiaryAddress,
callerPublicKey: payload.beneficiaryAddress,
},
);

return response.data;
return {
success: true,
xdr: data.unsignedXdr,
message: "Transaction built successfully.",
};
}
}
Loading