@swapper-finance/sdk
Version:
JavaScript SDK form Swapper
89 lines (79 loc) • 2.17 kB
text/typescript
import { IS_PRODUCTION_ENV } from "@src/constants";
import { Chain } from "@src/models";
import { useCallback } from "react";
export interface QuoteRequestPayload {
cryptoCurrencyCode: string;
fiatCurrencyCode: string;
walletAddress: string;
fiatAmount: string;
}
// Define the structure of the quote inside the response
export interface Quote {
quoteId: string;
expireTs: number;
side: string;
cryptoCurrencyCode: string;
cryptoAmount: string;
networkFeeCryptoAmount: string;
fiatCurrencyCode: string;
fiatAmount: string;
processingFeeFiatAmount: string;
networkFeeFiatAmount: string;
cryptoCostFiatAmount: string;
cryptoPrice: string;
}
// Define the structure of the API response
export interface QuoteResponse {
data: {
quote: Quote;
};
requestId: string;
}
const SHIFT4_API_URL = IS_PRODUCTION_ENV
? "https://api.crypto.shift4.com/v1"
: "https://api.sandbox.crypto.shift4.com/v1";
export const useShift4Api = () => {
async function _sendRequest<T>(
urlPath: string,
options?: RequestInit,
): Promise<T> {
const response = await fetch(`${SHIFT4_API_URL}${urlPath}`, {
method: options?.method || "GET",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache",
...options?.headers,
},
body: options?.body,
});
if (!response.ok) {
throw new Error(
`API request failed with status ${response.status}: ${response.statusText}`,
);
}
return response.json();
}
const GetQuote = useCallback(
async (
payload: QuoteRequestPayload,
srcChain: Chain,
): Promise<QuoteResponse> => {
const urlPath = "/quotes";
const options: RequestInit = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"x-public-key": srcChain.shift4Pk,
},
body: JSON.stringify(payload), // Use the payload directly
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return _sendRequest<any>(urlPath, options);
},
[],
);
return {
GetQuote,
};
};