Skip to content
Open
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
158 changes: 158 additions & 0 deletions p2p-safe-swap/app/api/escrow/single-release/v2/deploy/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import { NextRequest, NextResponse } from "next/server";
import {
trustlessWork,
TrustlessWorkApiError,
type DeploySingleReleaseV2Request,
} from "@/lib/trustless-work";

function getPlatformAddresses() {
const platformAddress = process.env.PLATFORM_WALLET_ADDRESS;
const disputeResolver = process.env.DISPUTE_RESOLVER_ADDRESS;

if (!platformAddress) throw new Error("PLATFORM_WALLET_ADDRESS is not set");
if (!disputeResolver) throw new Error("DISPUTE_RESOLVER_ADDRESS is not set");

return { platformAddress, disputeResolver };
}

interface DeployRequestBody {
signer: string;
orderId: string;
buyerAddress: string;
sellerAddress: string;
amount: number;
platformFee: number;
trustline: {
address: string;
symbol: string;
};
}

function isNonEmptyString(v: unknown): v is string {
return typeof v === "string" && v.trim().length > 0;
}

function isPositiveNumber(v: unknown): v is number {
return typeof v === "number" && Number.isFinite(v) && v > 0;
}

function validateBody(
raw: unknown
): { ok: true; body: DeployRequestBody } | { ok: false; message: string } {
if (!raw || typeof raw !== "object") {
return { ok: false, message: "Request body must be a JSON object" };
}

const b = raw as Record<string, unknown>;

if (!isNonEmptyString(b.signer)) return { ok: false, message: "signer is required" };
if (!isNonEmptyString(b.orderId)) return { ok: false, message: "orderId is required" };
if (!isNonEmptyString(b.buyerAddress)) return { ok: false, message: "buyerAddress is required" };
if (!isNonEmptyString(b.sellerAddress))
return { ok: false, message: "sellerAddress is required" };
if (!isPositiveNumber(b.amount)) return { ok: false, message: "amount must be a positive number" };
if (typeof b.platformFee !== "number" || b.platformFee < 0 || b.platformFee >= 100)
return { ok: false, message: "platformFee must be a number between 0 and 99" };

const tl = b.trustline as Record<string, unknown> | undefined;
if (!tl || !isNonEmptyString(tl.address) || !isNonEmptyString(tl.symbol)) {
return { ok: false, message: "trustline.address and trustline.symbol are required" };
}

return {
ok: true,
body: {
signer: b.signer as string,
orderId: b.orderId as string,
buyerAddress: b.buyerAddress as string,
sellerAddress: b.sellerAddress as string,
amount: b.amount as number,
platformFee: b.platformFee as number,
trustline: { address: tl.address as string, symbol: tl.symbol as string },
},
};
}

function getErrorResponse(error: unknown) {
if (error instanceof TrustlessWorkApiError) {
return NextResponse.json({ error: error.details }, { status: error.status });
}

const message =
error instanceof Error ? error.message : "Unable to deploy escrow";
return NextResponse.json({ error: message }, { status: 500 });
}

export async function POST(request: NextRequest) {
let raw: unknown;
try {
raw = await request.json();
} catch {
return NextResponse.json(
{ error: "Request body must be valid JSON" },
{ status: 400 }
);
}

const validation = validateBody(raw);
if (!validation.ok) {
return NextResponse.json({ error: validation.message }, { status: 400 });
}

const { signer, orderId, buyerAddress, sellerAddress, amount, platformFee, trustline } =
validation.body;

let platformAddress: string;
let disputeResolver: string;
try {
({ platformAddress, disputeResolver } = getPlatformAddresses());
} catch (error) {
return getErrorResponse(error);
}

const deployPayload: DeploySingleReleaseV2Request = {
signer,
engagementId: orderId,
title: `SafeSwap P2P Order ${orderId}`,
description: `P2P escrow for order ${orderId} β€” fiat payment confirmation`,
roles: {
approver: sellerAddress,
serviceProvider: buyerAddress,
platformAddress,
releaseSigner: sellerAddress,
disputeResolver,
receiver: buyerAddress,
},
amount,
platformFee,
milestones: [
{
description: "Fiat payment confirmed",
status: "pending",
approved: false,
},
],
trustline,
};

try {
const data = await trustlessWork.escrow.deploySingleReleaseV2(deployPayload);

if (!data.unsignedTransaction) {
return NextResponse.json(
{ error: "Escrow service did not return a deployment transaction" },
{ status: 502 }
);
}

return NextResponse.json(
{
unsignedXdr: data.unsignedTransaction,
contractId: data.contractId,
},
{ status: 201 }
);
} catch (error) {
return getErrorResponse(error);
}
}
72 changes: 72 additions & 0 deletions p2p-safe-swap/app/api/escrow/single-release/v2/fund/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { NextRequest, NextResponse } from "next/server";
import {
trustlessWork,
TrustlessWorkApiError,
type FundSingleReleaseEscrowRequest,
} from "@/lib/trustless-work";

function isPositiveAmount(value: unknown): value is string | number {
if (typeof value === "number") {
return Number.isFinite(value) && value > 0;
}

return (
typeof value === "string" &&
/^\d+(?:\.\d+)?$/.test(value) &&
Number.isFinite(Number(value)) &&
Number(value) > 0
);
}

function getErrorResponse(error: unknown) {
if (error instanceof TrustlessWorkApiError) {
return NextResponse.json({ error: error.details }, { status: error.status });
}

const message = error instanceof Error ? error.message : "Unable to fund escrow";
return NextResponse.json({ error: message }, { status: 500 });
}

export async function POST(request: NextRequest) {
let body: Partial<FundSingleReleaseEscrowRequest>;

try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Request body must be valid JSON" }, { status: 400 });
}

if (
typeof body.contractId !== "string" ||
!body.contractId.trim() ||
typeof body.signer !== "string" ||
!body.signer.trim() ||
!isPositiveAmount(body.amount)
) {
return NextResponse.json(
{ error: "contractId, signer, and a positive decimal amount are required" },
{ status: 400 }
);
}

try {
const data = await trustlessWork.escrow.fundSingleReleaseV2({
contractId: body.contractId,
signer: body.signer,
amount: body.amount,
});

if (!data.unsignedTransaction) {
return NextResponse.json(
{ error: "Funding transaction was not returned by the escrow service" },
{ status: 502 }
);
}

return NextResponse.json({
unsignedXdr: data.unsignedTransaction,
});
} catch (error) {
return getErrorResponse(error);
}
}
30 changes: 30 additions & 0 deletions p2p-safe-swap/app/api/stellar/send-transaction/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from "next/server";
import { trustlessWork, TrustlessWorkApiError } from "@/lib/trustless-work";

export async function POST(request: NextRequest) {
let body: { signedXdr?: unknown };

try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Request body must be valid JSON" }, { status: 400 });
}

if (typeof body.signedXdr !== "string" || !body.signedXdr.trim()) {
return NextResponse.json({ error: "signedXdr is required" }, { status: 400 });
}

try {
const data = await trustlessWork.stellar.sendTransaction({
signedXdr: body.signedXdr,
});
return NextResponse.json(data);
} catch (error) {
if (error instanceof TrustlessWorkApiError) {
return NextResponse.json({ error: error.details }, { status: error.status });
}

const message = error instanceof Error ? error.message : "Unable to submit transaction";
return NextResponse.json({ error: message }, { status: 500 });
}
}
Loading