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
44 changes: 44 additions & 0 deletions app/api/aggregator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -914,6 +914,50 @@ export async function updateTransactionStatus({
return response.data;
}

/**
* Confirms the user received funds for a stuck order (proxies to aggregator validate).
*/
export async function validateOrder({
orderId,
accessToken,
walletAddress,
}: {
orderId: string;
accessToken: string;
walletAddress: string;
}): Promise<{
success: boolean;
data?: { message?: string; validatedAt?: string };
error?: string;
}> {
try {
const response = await axios.post(
`/api/v1/orders/${orderId}/validate`,
{},
{
headers: {
Authorization: `Bearer ${accessToken}`,
"x-wallet-address": walletAddress.toLowerCase(),
},
},
);
return response.data;
} catch (error) {
if (axios.isAxiosError(error)) {
const message =
(error.response?.data as { error?: string })?.error ||
error.message ||
"Failed to validate order";
return { success: false, error: message };
}
console.error("Validate order error:", error);
return {
success: false,
error: "Failed to validate order. Please try again.",
};
}
}

/**
* Updates the details of a transaction including status, hash, and time spent
* @param {Object} params - The parameters object
Expand Down
240 changes: 240 additions & 0 deletions app/api/v1/orders/[id]/validate/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
import { NextRequest, NextResponse } from "next/server";
import { withRateLimit } from "@/app/lib/rate-limit";
import {
trackApiRequest,
trackApiResponse,
trackApiError,
} from "@/app/lib/server-analytics";
import config, { DEFAULT_PRIVY_CONFIG } from "@/app/lib/config";
import { verifyJWT } from "@/app/lib/jwt";
import { supabaseAdmin } from "@/app/lib/supabase";

// Route handler for POST - validate order (user confirmed payment received)
export const POST = withRateLimit(
async (
request: NextRequest,
context: { params: Promise<{ id: string }> },
) => {
const startTime = Date.now();
let orderId: string | null = null;

try {
const authHeader = request.headers.get("Authorization");
const token = authHeader?.replace(/^Bearer\s+/i, "");

if (!token) {
trackApiError(
request,
"/api/v1/orders/validate",
"POST",
new Error("Missing auth token"),
401,
);
return NextResponse.json(
{ success: false, error: "Unauthorized" },
{ status: 401 },
);
}

let authenticatedUserId: string;
try {
const jwtResult = await verifyJWT(token, DEFAULT_PRIVY_CONFIG);
authenticatedUserId = jwtResult.payload.sub ?? "";

if (!authenticatedUserId) {
trackApiError(
request,
"/api/v1/orders/validate",
"POST",
new Error("Invalid token"),
401,
);
return NextResponse.json(
{ success: false, error: "Unauthorized" },
{ status: 401 },
);
}
} catch (jwtError) {
trackApiError(
request,
"/api/v1/orders/validate",
"POST",
jwtError as Error,
401,
);
return NextResponse.json(
{ success: false, error: "Invalid or expired token" },
{ status: 401 },
);
}

const walletAddress = request.headers
.get("x-wallet-address")
?.toLowerCase();

if (!walletAddress) {
trackApiError(
request,
"/api/v1/orders/validate",
"POST",
new Error("Missing wallet address"),
401,
);
return NextResponse.json(
{ success: false, error: "Unauthorized" },
{ status: 401 },
);
}

const params = await context.params;
orderId = params.id;
if (!orderId) {
trackApiError(
request,
"/api/v1/orders/validate",
"POST",
new Error("Order ID is required"),
400,
);
return NextResponse.json(
{ success: false, error: "Order ID is required" },
{ status: 400 },
);
}

const fullPath = `/api/v1/orders/${orderId}/validate`;

// Verify the order belongs to the authenticated wallet before using sender API key
const { data: ownedTransaction, error: ownershipError } =
await supabaseAdmin
.from("transactions")
.select("id")
.eq("order_id", orderId)
.eq("wallet_address", walletAddress)
.maybeSingle();

if (ownershipError || !ownedTransaction) {
trackApiError(
request,
fullPath,
"POST",
new Error("Order not found or unauthorized"),
403,
);
return NextResponse.json(
{ success: false, error: "Order not found or unauthorized" },
{ status: 403 },
);
}

trackApiRequest(request, fullPath, "POST", {
wallet_address: walletAddress,
order_id: orderId,
});

const aggregatorUrl = config.aggregatorUrl?.trim();
const apiKeyId =
config.aggregatorSenderApiKeyId?.trim() ||
config.aggregatorSenderApiKey?.trim();
if (!aggregatorUrl || !apiKeyId) {
trackApiError(
request,
fullPath,
"POST",
new Error("Order validate service is not configured"),
503,
);
return NextResponse.json(
{
success: false,
error:
"Order validate service is not configured. Please try again later.",
},
{ status: 503 },
);
}

const url = `${aggregatorUrl}/sender/orders/${orderId}/validate`;
const FETCH_TIMEOUT_MS = 30_000;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
let res: Response;
try {
res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"API-Key": apiKeyId,
},
body: JSON.stringify({}),
signal: controller.signal,
});
} finally {
clearTimeout(timeoutId);
}

const data = await res.json().catch(() => ({}));
const rawMessage =
typeof data?.message === "string"
? data.message
: (data?.Message as string) ?? "";

if (!res.ok) {
const status =
res.status >= 400 && res.status < 600 ? res.status : 502;
const errorMessage =
rawMessage.trim() || "Failed to validate order";
trackApiError(
request,
fullPath,
"POST",
new Error(errorMessage),
status,
{ response_time_ms: Date.now() - startTime },
);
return NextResponse.json(
{ success: false, error: errorMessage },
{ status },
);
}

const responseTime = Date.now() - startTime;
trackApiResponse(fullPath, "POST", 200, responseTime, {
wallet_address: walletAddress,
order_id: orderId,
});

const successMessage =
rawMessage.trim() || "Order validated successfully";

return NextResponse.json({
success: true,
data: {
message: successMessage,
validatedAt: new Date().toISOString(),
},
});
} catch (error) {
console.error("Validate order error:", error);
const responseTime = Date.now() - startTime;
const fullPath = orderId
? `/api/v1/orders/${orderId}/validate`
: "/api/v1/orders/validate";
const isTimeout =
error instanceof Error && error.name === "AbortError";
const status = isTimeout ? 504 : 500;
trackApiError(request, fullPath, "POST", error as Error, status, {
response_time_ms: responseTime,
});
return NextResponse.json(
{
success: false,
error: isTimeout
? "Validation request timed out. Please try again."
: "Failed to validate order. Please try again.",
},
{ status },
);
}
},
);
76 changes: 73 additions & 3 deletions app/components/MainPageContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ import {
} from "../lib/pendingReferralCode";
import { isReferralEnabled } from "../utils";
import { useWalletAddress } from "../hooks/useWalletAddress";
import { networks } from "../mocks";
import {
readStuckPaymentSession,
clearStuckPaymentSession,
} from "../lib/stuckPaymentSession";

/**
* PageLayout component renders the main page structure including modals,
Expand Down Expand Up @@ -261,6 +266,7 @@ export function MainPageContent() {
const failedProviders = useRef<Set<string>>(new Set());
const autoSelectedNetworkSessionRef = useRef<string | null>(null);
const noProviderEventGuard = useRef<Set<string>>(new Set());
const restoredStuckSessionRef = useRef(false);

const [isUserVerified, setIsUserVerified] = useState(false);
const [rateError, setRateError] = useState<string | null>(null);
Expand Down Expand Up @@ -476,12 +482,74 @@ export function MainPageContent() {
}, [walletAddress]);

useEffect(function setPageLoadingState() {
setOrderId("");
setOnrampPaymentAccount(null);
setActiveOrderIsOnramp(false);
// Keep stuck-order fields intact when a session will be restored on auth ready.
if (!readStuckPaymentSession()) {
setOrderId("");
setOnrampPaymentAccount(null);
setActiveOrderIsOnramp(false);
}
setIsPageLoading(false);
}, []);

useEffect(
function restoreStuckPaymentSessionOnLoad() {
if (restoredStuckSessionRef.current) return;
if (!ready) return;
if (!authenticated && !isInjectedWallet) return;

const session = readStuckPaymentSession();
if (!session) return;

restoredStuckSessionRef.current = true;

const restoredForm: FormData = {
network: session.network || selectedNetwork.chain.name,
token: session.form.token,
currency: session.form.currency,
institution: session.form.institution,
accountIdentifier: session.form.accountIdentifier,
recipientName: session.form.recipientName,
accountType: session.form.accountType || "bank",
walletAddress: session.form.walletAddress || "",
memo: session.form.memo || "",
amountSent: session.form.amountSent,
amountReceived: session.form.amountReceived,
swapMode: session.form.swapMode || (session.isOnramp ? "onramp" : "offramp"),
isSwapped: session.isOnramp,
receiveDestinationExplicitlySelected: true,
};

formMethods.reset({
...formMethods.getValues(),
...restoredForm,
});
setFormValues(restoredForm);
setOrderId(session.orderId);
setCreatedAt(session.createdAt);
setTransactionStatus(session.transactionStatus);
setActiveOrderIsOnramp(session.isOnramp);

if (session.transactionId) {
try {
localStorage.setItem("currentTransactionId", session.transactionId);
} catch {
// ignore
}
}

if (session.network) {
const match = networks.find((n) => n.chain.name === session.network);
if (match) {
setSelectedNetwork(match);
}
}

setCurrentStep(STEPS.STATUS);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[ready, authenticated, isInjectedWallet],
);

useEffect(
function resetOnLogout() {
// Reset form when user logs out (but not for injected wallets)
Expand All @@ -490,6 +558,8 @@ export function MainPageContent() {
setFormValues({} as FormData);
setOnrampPaymentAccount(null);
setActiveOrderIsOnramp(false);
clearStuckPaymentSession();
restoredStuckSessionRef.current = false;
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
Loading