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
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Badge } from "@tokenization/ui/badge";
import { Button } from "@tokenization/ui/button";
import { CampaignCard as SharedCampaignCard } from "@tokenization/ui/campaign-card";
import { cn } from "@tokenization/shared/lib/utils";
import { Landmark } from "lucide-react";
import { Banknote, CheckCircle, Circle, Landmark } from "lucide-react";
import { useGetEscrowFromIndexerByContractIds } from "@trustless-work/escrow";
import type { MultiReleaseMilestone } from "@trustless-work/escrow/types";
import type { Campaign } from "@/features/campaigns/types/campaign.types";
Expand Down Expand Up @@ -39,9 +39,12 @@ export function CampaignCard({ campaign }: CampaignCardProps) {
staleTime: 1000 * 60 * 5,
});

const milestones = (escrowData?.milestones ?? []) as MultiReleaseMilestone[];
const assigned = milestones.reduce((sum, m) => sum + fromStroops(m.amount ?? 0), 0);
const progressValue = campaign.poolSize > 0 ? Math.min(100, (assigned / campaign.poolSize) * 100) : 0;
const allMilestones = (escrowData?.milestones ?? []) as MultiReleaseMilestone[];
const visibleMilestones = allMilestones.slice(1);
const assigned = allMilestones.reduce((sum, m) => sum + fromStroops(m.amount ?? 0), 0);
const loansCompleted = visibleMilestones.filter((m) => m.status === "Approved").length;
const totalLoans = visibleMilestones.length;
const progressValue = totalLoans > 0 ? Math.min(100, (loansCompleted / totalLoans) * 100) : 0;

return (
<SharedCampaignCard
Expand All @@ -68,16 +71,36 @@ export function CampaignCard({ campaign }: CampaignCardProps) {
footer={
<div className="flex flex-col gap-1">
<span className="text-xs font-bold text-foreground">
USDC {formatCurrency(assigned)} / USDC {formatCurrency(campaign.poolSize)}
<span className="font-bold">Pool Size:</span> USDC {formatCurrency(assigned)} / USDC {formatCurrency(campaign.poolSize)}
</span>
{campaign.vaultId ? (
<span className="text-[10px] text-muted-foreground font-mono truncate max-w-[280px]" title={campaign.vaultId}>
Vault: {campaign.vaultId}
</span>
) : null}
</div>
}
progress={{ label: "Dinero recaudado", value: progressValue }}
/>
progress={{ label: "Loans Completed", value: progressValue }}
>
{visibleMilestones.length > 0 ? (
<>
<p className="text-xs font-semibold uppercase tracking-widest text-text-muted">
Loans
</p>
<ul className="flex flex-col gap-1">
{visibleMilestones.map((m, i) => (
<li key={i} className="flex items-center gap-2 text-xs text-muted-foreground">
{m.flags?.approved ? (
<CheckCircle className="size-3.5 text-green-500 shrink-0" />
) : m.flags?.released ? (
<Banknote className="size-3.5 text-blue-500 shrink-0" />
) : (
<Circle className="size-3.5 shrink-0" />
)}
<span className="truncate">{m.description || `Loan ${i + 1}`}</span>
<span className="ml-auto font-medium">{m.amount} USDC</span>
</li>
))}
</ul>
</>
) : (
<p className="text-xs text-muted-foreground">No loans available.</p>
)}
</SharedCampaignCard>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -245,18 +245,17 @@ export function ManageLoansView({ contractId }: ManageLoansViewProps) {
milestones.map((milestone, index) => {
const isApproved = milestone.flags?.approved === true;
const isReleased = milestone.flags?.released === true;
const milestoneAmount = fromStroops(milestone.amount || 0);
const milestoneAmount = milestone.amount
const insufficientFunds = escrowBalance < milestoneAmount;


return (
<div
key={index}
className={`flex items-center justify-between rounded-xl border px-4 py-3 transition-colors ${
isReleased
className={`flex items-center justify-between rounded-xl border px-4 py-3 transition-colors ${isReleased
? "border-border bg-secondary/20 opacity-60"
: "border-border bg-card"
}`}
}`}
>
<div className="flex flex-col gap-0.5">
<span
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { useWalletContext } from "@tokenization/tw-blocks-shared/src/wallet-kit/WalletProvider";
import { useEscrowsMutations } from "@tokenization/tw-blocks-shared/src/tanstack/useEscrowsMutations";
import {
Expand Down Expand Up @@ -112,6 +113,7 @@ const TOTAL_STEPS = 3;

export function useCreateCampaign() {
const router = useRouter();
const queryClient = useQueryClient();
const { walletAddress } = useWalletContext();
const { deployEscrow } = useEscrowsMutations();
const [step, setStep] = useState(1);
Expand Down Expand Up @@ -288,6 +290,8 @@ export function useCreateCampaign() {
saveFlowState({ campaignDbId: created.id });
setPhaseStatus(1, "success");

await queryClient.invalidateQueries({ queryKey: ["campaigns"] });

setTimeout(() => {
clearFlowState();
router.push("/campaigns");
Expand All @@ -298,7 +302,7 @@ export function useCreateCampaign() {
setPhaseStatus(currentPhase, "error", message);
setDeployFailedAt(currentPhase);
}
}, [walletAddress, router]);
}, [walletAddress, router, queryClient]);

const retryDeploy = useCallback(() => {
if (deployFailedAt === null) return;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
"use client";

import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useWalletContext } from "@tokenization/tw-blocks-shared/src/wallet-kit/WalletProvider";
import { signTransaction } from "@tokenization/tw-blocks-shared/src/wallet-kit/wallet-kit";
import { submitAndExtractAddress } from "@/features/campaigns/services/soroban.service";
import { enableVault } from "@/features/campaigns/services/campaigns.api";
import {
enableVault,
updateCampaignStatusByVaultId,
} from "@/features/campaigns/services/campaigns.api";

interface UseToggleVaultParams {
onSuccess?: () => void;
}

export function useToggleVault({ onSuccess }: UseToggleVaultParams = {}) {
const { walletAddress } = useWalletContext();
const queryClient = useQueryClient();
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);

Expand Down Expand Up @@ -39,6 +44,16 @@ export function useToggleVault({ onSuccess }: UseToggleVaultParams = {}) {

await submitAndExtractAddress(signedXdr);

try {
await updateCampaignStatusByVaultId(
vaultContractId,
enabled ? "CLAIMABLE" : "FUNDRAISING",
);
await queryClient.invalidateQueries({ queryKey: ["campaigns"] });
} catch {
// Campaign may not exist or vaultId not linked; status update is best-effort
}

onSuccess?.();
} catch (e) {
const message = e instanceof Error ? e.message : "Unexpected error";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,39 +1,14 @@
import { httpClient } from "@/lib/httpClient";
import type { Campaign } from "@/features/campaigns/types/campaign.types";

const CORE_API = "/core-api";

const API_KEY = process.env.NEXT_PUBLIC_CORE_API_KEY ?? "";

async function post<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(`${CORE_API}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json", "x-api-key": API_KEY },
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(
(err as { message?: string }).message ??
`Error ${res.status} en ${path}`,
);
}
return res.json() as Promise<T>;
}

export async function getCampaigns(): Promise<Campaign[]> {
const res = await fetch(`${CORE_API}/campaigns`, {
headers: { "x-api-key": API_KEY },
});
if (!res.ok) throw new Error("No se pudieron cargar las campañas.");
return res.json();
const { data } = await httpClient.get<Campaign[]>("/campaigns");
return data;
}

export async function getCampaignById(id: string): Promise<Campaign> {
const res = await fetch(`${CORE_API}/campaigns/${id}`, {
headers: { "x-api-key": API_KEY },
});
if (!res.ok) throw new Error("No se pudo cargar la campaña.");
return res.json();
const { data } = await httpClient.get<Campaign>(`/campaigns/${id}`);
return data;
}

export async function deployAll(params: {
Expand All @@ -46,25 +21,32 @@ export async function deployAll(params: {
maxPerInvestor: number;
callerPublicKey: string;
}): Promise<{ unsignedXdr: string }> {
return post("/deploy/all", params);
const { data } = await httpClient.post<{ unsignedXdr: string }>(
"/deploy/all",
params,
);
return data;
}

export async function updateCampaignStatus(
id: string,
status: string,
): Promise<unknown> {
const res = await fetch(`${CORE_API}/campaigns/${id}/status`, {
method: "PATCH",
headers: { "Content-Type": "application/json", "x-api-key": API_KEY },
body: JSON.stringify({ status }),
const { data } = await httpClient.patch(`/campaigns/${id}/status`, {
status,
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(
(err as { message?: string }).message ?? `Error ${res.status}`,
);
}
return res.json();
return data;
}

export async function updateCampaignStatusByVaultId(
vaultId: string,
status: string,
): Promise<unknown> {
const { data } = await httpClient.patch(
`/campaigns/by-vault/${vaultId}/status`,
{ status },
);
return data;
}

export async function createCampaign(params: {
Expand All @@ -80,35 +62,11 @@ export async function createCampaign(params: {
tokenSaleId: string;
vaultId?: string;
}): Promise<{ id: string }> {
return post("/campaigns", params);
}

async function get<T>(path: string): Promise<T> {
const res = await fetch(`${CORE_API}${path}`, {
headers: { "x-api-key": API_KEY },
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(
(err as { message?: string }).message ?? `Error ${res.status} on ${path}`,
);
}
return res.json() as Promise<T>;
}

async function patch<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(`${CORE_API}${path}`, {
method: "PATCH",
headers: { "Content-Type": "application/json", "x-api-key": API_KEY },
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(
(err as { message?: string }).message ?? `Error ${res.status} on ${path}`,
);
}
return res.json() as Promise<T>;
const { data } = await httpClient.post<{ id: string }>(
"/campaigns",
params,
);
return data;
}

export async function enableVault(params: {
Expand All @@ -117,21 +75,29 @@ export async function enableVault(params: {
enabled: boolean;
callerPublicKey: string;
}): Promise<{ unsignedXdr: string }> {
return post("/vault/availability-for-exchange", params);
const { data } = await httpClient.post<{ unsignedXdr: string }>(
"/vault/availability-for-exchange",
params,
);
return data;
}

export async function getVaultIsEnabled(
contractId: string,
callerPublicKey: string,
): Promise<{ enabled: boolean }> {
return get(
const { data } = await httpClient.get<{ enabled: boolean }>(
`/vault/is-enabled?contractId=${contractId}&callerPublicKey=${callerPublicKey}`,
);
return data;
}

export async function updateCampaignVaultId(
campaignId: string,
vaultId: string,
): Promise<unknown> {
return patch(`/campaigns/${campaignId}`, { vaultId });
const { data } = await httpClient.patch(`/campaigns/${campaignId}`, {
vaultId,
});
return data;
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const HeroSection = () => {
project, from contract deployment to milestone execution.
</p>

<Link href="/manage-escrows">
<Link href="/campaigns">
<RainbowButton variant="outline">Open App</RainbowButton>
</Link>
</div>
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 DeployTokenResponse = {
success: boolean;
Expand All @@ -13,22 +13,8 @@ export type DeployTokenParams = {
};

export class TokenService {
private readonly apiUrl: string;
private readonly axios: AxiosInstance;

constructor() {
// If NEXT_PUBLIC_API_URL is set, use it. Otherwise, use relative path /api
// This allows the service to work both with external APIs and Next.js route handlers
const envApiUrl = process.env.NEXT_PUBLIC_API_URL;
this.apiUrl = envApiUrl && envApiUrl.trim() !== "" ? envApiUrl : "/api";

this.axios = axios.create({
baseURL: this.apiUrl,
});
}

async deployToken(params: DeployTokenParams): Promise<DeployTokenResponse> {
const response = await this.axios.post<DeployTokenResponse>("/deploy", {
const response = await httpClient.post<DeployTokenResponse>("/deploy", {
escrowContractId: params.escrowContractId,
tokenName: params.tokenName,
tokenSymbol: params.tokenSymbol,
Expand Down
Loading