|
| 1 | +import type { Address } from "abitype"; |
| 2 | +import type { Chain } from "../../chains/types.js"; |
| 3 | +import type { ThirdwebClient } from "../../client/client.js"; |
| 4 | +import { NATIVE_TOKEN_ADDRESS } from "../../constants/addresses.js"; |
| 5 | +import { getBytecode } from "../../contract/actions/get-bytecode.js"; |
| 6 | +import { getContract } from "../../contract/contract.js"; |
| 7 | +import { isAddress } from "../../utils/address.js"; |
| 8 | +import { getClientFetch } from "../../utils/fetch.js"; |
| 9 | +import { getPayConvertCryptoToFiatEndpoint } from "../utils/definitions.js"; |
| 10 | + |
| 11 | +/** |
| 12 | + * Props for the `convertCryptoToFiat` function |
| 13 | + * @buyCrypto |
| 14 | + */ |
| 15 | +export type ConvertCryptoToFiatParams = { |
| 16 | + client: ThirdwebClient; |
| 17 | + /** |
| 18 | + * The contract address of the token |
| 19 | + * For native token, use NATIVE_TOKEN_ADDRESS |
| 20 | + */ |
| 21 | + fromTokenAddress: Address; |
| 22 | + /** |
| 23 | + * The amount of token to convert to fiat value |
| 24 | + */ |
| 25 | + fromAmount: number; |
| 26 | + /** |
| 27 | + * The chain that the token is deployed to |
| 28 | + */ |
| 29 | + chain: Chain; |
| 30 | + /** |
| 31 | + * The fiat symbol. e.g "USD" |
| 32 | + * Only USD is supported at the moment. |
| 33 | + */ |
| 34 | + to: "USD"; |
| 35 | +}; |
| 36 | + |
| 37 | +/** |
| 38 | + * Get a price of a token (using tokenAddress + chainId) in fiat. |
| 39 | + * Only USD is supported at the moment. |
| 40 | + * @example |
| 41 | + * ### Basic usage |
| 42 | + * For native token (non-ERC20), you should use NATIVE_TOKEN_ADDRESS as the value for `tokenAddress` |
| 43 | + * ```ts |
| 44 | + * import { convertCryptoToFiat } from "thirdweb/pay"; |
| 45 | + * |
| 46 | + * // Get Ethereum price |
| 47 | + * const result = convertCryptoToFiat({ |
| 48 | + * fromTokenAddress: NATIVE_TOKEN_ADDRESS, |
| 49 | + * to: "USD", |
| 50 | + * chain: ethereum, |
| 51 | + * fromAmount: 1, |
| 52 | + * }); |
| 53 | + * |
| 54 | + * // Result: 3404.11 |
| 55 | + * ``` |
| 56 | + * @buyCrypto |
| 57 | + * @returns a number representing the price (in selected fiat) of "x" token, with "x" being the `fromAmount`. |
| 58 | + */ |
| 59 | +export async function convertCryptoToFiat( |
| 60 | + options: ConvertCryptoToFiatParams, |
| 61 | +): Promise<{ result: number }> { |
| 62 | + const { client, fromTokenAddress, to, chain, fromAmount } = options; |
| 63 | + if (Number(fromAmount) === 0) { |
| 64 | + return { result: 0 }; |
| 65 | + } |
| 66 | + // Testnets just don't work with our current provider(s) |
| 67 | + if (chain.testnet === true) { |
| 68 | + throw new Error(`Cannot fetch price for a testnet (chainId: ${chain.id})`); |
| 69 | + } |
| 70 | + // Some provider that we are using will return `0` for unsupported token |
| 71 | + // so we should do some basic input validations before sending the request |
| 72 | + |
| 73 | + // Make sure it's a valid EVM address |
| 74 | + if (!isAddress(fromTokenAddress)) { |
| 75 | + throw new Error( |
| 76 | + "Invalid fromTokenAddress. Expected a valid EVM contract address", |
| 77 | + ); |
| 78 | + } |
| 79 | + // Make sure it's either a valid contract or a native token address |
| 80 | + if (fromTokenAddress.toLowerCase() !== NATIVE_TOKEN_ADDRESS.toLowerCase()) { |
| 81 | + const bytecode = await getBytecode( |
| 82 | + getContract({ |
| 83 | + address: fromTokenAddress, |
| 84 | + chain, |
| 85 | + client, |
| 86 | + }), |
| 87 | + ).catch(() => undefined); |
| 88 | + if (!bytecode || bytecode === "0x") { |
| 89 | + throw new Error( |
| 90 | + `Error: ${fromTokenAddress} on chainId: ${chain.id} is not a valid contract address.`, |
| 91 | + ); |
| 92 | + } |
| 93 | + } |
| 94 | + const params = { |
| 95 | + fromTokenAddress, |
| 96 | + to, |
| 97 | + chainId: String(chain.id), |
| 98 | + fromAmount: String(fromAmount), |
| 99 | + }; |
| 100 | + const queryString = new URLSearchParams(params).toString(); |
| 101 | + const url = `${getPayConvertCryptoToFiatEndpoint()}?${queryString}`; |
| 102 | + const response = await getClientFetch(client)(url); |
| 103 | + if (!response.ok) { |
| 104 | + throw new Error( |
| 105 | + `Failed to fetch ${to} value for token (${fromTokenAddress}) on chainId: ${chain.id}`, |
| 106 | + ); |
| 107 | + } |
| 108 | + |
| 109 | + const data: { result: number } = await response.json(); |
| 110 | + return data; |
| 111 | +} |
0 commit comments