|
| 1 | +import type { Address } from "abitype"; |
| 2 | +import type { ThirdwebClient } from "../../client/client.js"; |
| 3 | +import { getClientFetch } from "../../utils/fetch.js"; |
| 4 | +import { getPayConvertCryptoToFiatEndpoint } from "../utils/definitions.js"; |
| 5 | + |
| 6 | +export type ConvertCryptoToFiatParams = { |
| 7 | + client: ThirdwebClient; |
| 8 | + /** |
| 9 | + * The contract address of the token |
| 10 | + * For native token, use NATIVE_TOKEN_ADDRESS |
| 11 | + */ |
| 12 | + fromTokenAddress: Address; |
| 13 | + fromAmount: number; |
| 14 | + /** |
| 15 | + * The chainId that the token is deployed to |
| 16 | + */ |
| 17 | + chainId: number; |
| 18 | + /** |
| 19 | + * The fiat symbol. e.g "usd" |
| 20 | + */ |
| 21 | + to: string; |
| 22 | +}; |
| 23 | + |
| 24 | +export async function convertCryptoToFiat(options: ConvertCryptoToFiatParams) { |
| 25 | + const { client, fromTokenAddress, to, chainId, fromAmount } = options; |
| 26 | + try { |
| 27 | + const queryString = new URLSearchParams({ |
| 28 | + fromTokenAddress, |
| 29 | + to, |
| 30 | + chainId: String(chainId), |
| 31 | + fromAmount: String(fromAmount), |
| 32 | + }).toString(); |
| 33 | + const url = `${getPayConvertCryptoToFiatEndpoint()}?${queryString}`; |
| 34 | + const response = await getClientFetch(client)(url); |
| 35 | + // Assuming the response directly matches the BuyWithCryptoStatus interface |
| 36 | + if (!response.ok) { |
| 37 | + response.body?.cancel(); |
| 38 | + throw new Error(`HTTP error! status: ${response.status}`); |
| 39 | + } |
| 40 | + |
| 41 | + const data: string = (await response.json()).result; |
| 42 | + return data; |
| 43 | + } catch (error) { |
| 44 | + console.error("Fetch error:", error); |
| 45 | + throw new Error(`Fetch failed: ${error}`); |
| 46 | + } |
| 47 | +} |
0 commit comments