From 300b9dee5054cb26f36e9da3ede04d53d4c296a1 Mon Sep 17 00:00:00 2001 From: MathisZerbib Date: Tue, 4 Jun 2024 20:50:39 +0200 Subject: [PATCH] removed api and added ton api free --- package.json | 3 +- src/components/BuyCard.tsx | 4 +- src/components/MapWithGeocoder.tsx | 3 +- src/components/PriceConverter.tsx | 18 +++-- src/components/SearchComponent.tsx | 119 ---------------------------- src/services/exchangeRateService.ts | 60 ++++++++------ 6 files changed, 53 insertions(+), 154 deletions(-) delete mode 100644 src/components/SearchComponent.tsx diff --git a/package.json b/package.json index 0105b65..69be79b 100644 --- a/package.json +++ b/package.json @@ -25,10 +25,9 @@ "@tonconnect/ui-react": "^2.0.0-beta.2", "@twa-dev/sdk": "^6.4.2", "axios": "^1.7.2", + "binance": "^2.11.2", "buffer": "^6.0.3", - "leaflet": "^1.9.4", "mapbox-gl": "^3.4.0", - "nominatim-client": "^3.2.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-leaflet": "^4.2.1", diff --git a/src/components/BuyCard.tsx b/src/components/BuyCard.tsx index 235c30e..02b5d98 100644 --- a/src/components/BuyCard.tsx +++ b/src/components/BuyCard.tsx @@ -12,7 +12,7 @@ import { HalfStar, BuyCardStyled, } from "./styled/styled"; -import performCurrencyConversion from "../services/exchangeRateService"; +import { convertToTon } from "../services/exchangeRateService"; import { useCurrency } from "../providers/useCurrency"; interface ProductProps { @@ -58,7 +58,7 @@ const BuyCard: React.FC = ({ useEffect(() => { const convertPrice = async () => { try { - const convertedPrice = await performCurrencyConversion( + const convertedPrice = await convertToTon( price, selectedCurrency ); diff --git a/src/components/MapWithGeocoder.tsx b/src/components/MapWithGeocoder.tsx index 4547129..7de06f1 100644 --- a/src/components/MapWithGeocoder.tsx +++ b/src/components/MapWithGeocoder.tsx @@ -24,7 +24,8 @@ const MapWithGeocoder: React.FC = ({ const map = new mapboxgl.Map({ container: mapRef.current, style: "mapbox://styles/mapbox/streets-v12", - center: [-79.4512, 43.6568], // Starting position [lng, lat] + // Starting position in south of france montpellier + center: [3.8767, 43.6116], // Starting position [lng, lat] zoom: 13, // Starting zoom }); diff --git a/src/components/PriceConverter.tsx b/src/components/PriceConverter.tsx index fb6ab82..939cec8 100644 --- a/src/components/PriceConverter.tsx +++ b/src/components/PriceConverter.tsx @@ -71,28 +71,34 @@ const PriceConverter: React.FC = () => { const [usdAmount, setUsdAmount] = useState(""); const [tonAmount, setTonAmount] = useState(""); const [openDrawer, setOpenDrawer] = useState(false); + const [cachedRates, setCachedRates] = useState<{ [key: string]: number }>({}); useEffect(() => { const getInitialRate = async () => { try { - const rate = await fetchInitialExchangeRate("TON", "USDT"); - setTonUsdtRate(rate); + // Check if the rate is already cached + if (!cachedRates["TON_USDT"]) { + const rate = await fetchInitialExchangeRate(); + setTonUsdtRate(rate); + cachedRates["TON_USDT"] = rate; // Cache the rate + } else { + setTonUsdtRate(cachedRates["TON_USDT"]); + } } catch (error) { console.error("Failed to fetch initial exchange rate:", error); } }; getInitialRate(); - }, []); - + }, [cachedRates]); const convertUsdToTon = (amount: string): number => { if (!tonUsdtRate || !amount) return 0; - return parseFloat(amount) / tonUsdtRate; + return parseFloat(amount) * tonUsdtRate; }; const convertTonToUsd = (amount: string): number => { if (!tonUsdtRate || !amount) return 0; - return parseFloat(amount) * tonUsdtRate; + return parseFloat(amount) / tonUsdtRate; }; const handleUsdAmountChange = (e: React.ChangeEvent) => { diff --git a/src/components/SearchComponent.tsx b/src/components/SearchComponent.tsx deleted file mode 100644 index e95545d..0000000 --- a/src/components/SearchComponent.tsx +++ /dev/null @@ -1,119 +0,0 @@ -// SearchComponent.tsx -import React, { useState, useCallback } from "react"; -import styled from "styled-components"; -import { Options, SearchResultItem } from "nominatim-client"; -import nominatim from "nominatim-client"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { faLocationArrow } from "@fortawesome/free-solid-svg-icons"; - -const SearchContainer = styled.div` - margin-top: 20px; -`; - -const SearchInput = styled.input` - padding: 10px; - width: 300px; - border-radius: 4px; - border: 1px solid #ccc; - margin-bottom: 10px; -`; - -const SuggestionsList = styled.ul` - list-style-type: none; - padding: 0; - margin: 0; - border: 1px solid #ccc; - border-radius: 4px; - max-height: 150px; - overflow-y: auto; - width: 300px; - margin: 0 auto; - text-align: left; -`; - -const SuggestionItem = styled.li` - padding: 10px; - cursor: pointer; - background-color: #f9f9f9; - color: #333; - - &:hover { - background-color: #f0f0f0; - } -`; - -const ButtonGeoLocation = styled.button` - padding: 10px; - border: none; - border-radius: 4px; - background-color: #333; - color: white; - cursor: pointer; - margin-bottom: 10px; - - &:hover { - background-color: #555; - } -`; - -interface SearchComponentProps { - onAddressSelect: (address: string) => void; -} - -const SearchComponent: React.FC = ({ - onAddressSelect, -}) => { - const [searchTerm, setSearchTerm] = useState(""); - const [suggestions, setSuggestions] = useState([]); - - const fetchSuggestions = useCallback(async () => { - if (searchTerm.length < 3) { - setSuggestions([]); - return; - } - - try { - const client = nominatim.createClient({ - useragent: "ReactApp", - referer: "http://localhost", - }); - const data = await client.search({ q: searchTerm, addressdetails: 1 }); - setSuggestions(data); - } catch (error) { - console.error("Error fetching address suggestions:", error); - } - }, [searchTerm]); - - const handleInputChange = (e: React.ChangeEvent) => { - setSearchTerm(e.target.value); - fetchSuggestions(); - }; - - const handleSuggestionClick = (suggestion: SearchResultItem) => { - onAddressSelect(suggestion.display_name); - setSuggestions([]); - }; - - return ( - - - - {suggestions.map((suggestion) => ( - handleSuggestionClick(suggestion)} - > - {suggestion.display_name} - - ))} - - - ); -}; - -export default SearchComponent; diff --git a/src/services/exchangeRateService.ts b/src/services/exchangeRateService.ts index 0e63992..ab37b98 100644 --- a/src/services/exchangeRateService.ts +++ b/src/services/exchangeRateService.ts @@ -1,42 +1,54 @@ -import axios from 'axios'; +// services/exchangeRateService.js -const API_KEY = import.meta.env.VITE_COINAPI_API_KEY!; -const API_URL = `https://rest.coinapi.io/v1/exchangerate/`; +import axios from 'axios'; +import { useEffect, useState } from 'react'; // Import useState for local state management -interface ExchangeRateResponse { - time: string; - asset_id_base: string; - asset_id_quote: string; - rate: number; +interface TonApiResponse { + rates: { + [token: string]: { + prices: { + [currency: string]: number; + }; + diff_24h?: { + [token: string]: string; + }; + diff_7d?: { + [token: string]: string; + }; + diff_30d?: { + [token: string]: string; + }; + }; + }; } -export const fetchInitialExchangeRate = async (baseCurrency: string, quoteCurrency: string): Promise => { +let cachedRates = {}; // Global variable to store cached rates + +export const fetchInitialExchangeRate = async (): Promise => { try { - const response = await axios.get(`${API_URL}${baseCurrency}/${quoteCurrency}`, { - params: { - apikey: API_KEY, - }, - }); - return response.data.rate; + const response = await axios.get(`https://tonapi.io/v2/rates?tokens=USD¤cies=TON`); + const priceInUsd = response.data.rates['USD']?.prices['TON']; + console.log('Initial exchange rate:', priceInUsd); + return priceInUsd; } catch (error) { + console.error('Failed to fetch initial exchange rate:', error); return 0; } }; - -export const performCurrencyConversion = async (price: number, currency: string | null) => { +export const convertToTon = async (amount: number, currency: string): Promise => { try { - if (currency === 'USDT') { - return price; + if (currency == "USDT") { + return amount; } else { - const response = await axios.get(`${API_URL}USDT/${currency}?apikey=${API_KEY}`); - return price * response.data.rate; + const response = await axios.get(`https://tonapi.io/v2/rates?tokens=USD¤cies=TON`); + const priceInUsd = response.data.rates['USD']?.prices[currency] || 0; + return amount * priceInUsd; } } catch (error) { - // console.error('Failed to perform currency conversion:', error); - // throw error; + console.error('Failed to perform currency conversion:', error); return 0; } }; -export default performCurrencyConversion; +