x0-react-sdk
Version:
React SDK for X0Pay Hyperlane token bridging with MetaMask and Safe wallet integration
108 lines (94 loc) • 3.08 kB
text/typescript
import { OrderValidationResponse } from '../types';
/**
* Validates an order ID with the X0-worker API
* @param workerApiUrl - The base URL of the X0-worker API
* @param orderId - The order ID to validate
* @returns Promise<OrderValidationResponse>
*/
export const validateOrderId = async (
workerApiUrl: string,
orderId: string
): Promise<OrderValidationResponse> => {
try {
if (!workerApiUrl) {
throw new Error('Worker API URL is required for order validation');
}
if (!orderId || typeof orderId !== 'string' || orderId.trim() === '') {
throw new Error('Order ID is required and must be a non-empty string');
}
const response = await fetch(`${workerApiUrl}/api/validate-order`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ orderId: orderId.trim() }),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result: OrderValidationResponse = await response.json();
if (!result.success) {
throw new Error(result.error || 'Order validation failed');
}
return result;
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred during order validation',
};
}
};
/**
* Checks if an order ID is available for use
* @param workerApiUrl - The base URL of the X0-worker API
* @param orderId - The order ID to check
* @returns Promise<boolean> - true if order ID is available, false if it exists
*/
export const isOrderIdAvailable = async (
workerApiUrl: string,
orderId: string
): Promise<boolean> => {
try {
const result = await validateOrderId(workerApiUrl, orderId);
if (!result.success) {
throw new Error(result.error || 'Order validation failed');
}
return !result.data?.exists;
} catch (error) {
throw new Error(`Failed to check order ID availability: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
};
/**
* Gets order details if the order ID exists
* @param workerApiUrl - The base URL of the X0-worker API
* @param orderId - The order ID to get details for
* @returns Promise<OrderValidationResponse['data']['event'] | null>
*/
export const getOrderDetails = async (
workerApiUrl: string,
orderId: string
): Promise<{
messageId: string;
orderId: string;
transferAmount: string;
feeAmount: string;
isInnerFee: boolean;
exchangeRate: string;
chainId: number;
chainName: string;
transactionHash: string;
blockNumber: number;
processed: boolean;
timestamp: string;
createdAt: string;
} | null> => {
try {
const result = await validateOrderId(workerApiUrl, orderId);
if (!result.success) {
throw new Error(result.error || 'Order validation failed');
}
return result.data?.exists && result.data.event ? result.data.event : null;
} catch (error) {
throw new Error(`Failed to get order details: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
};