Skip to content

Commit

Permalink
removed api and added ton api free
Browse files Browse the repository at this point in the history
  • Loading branch information
MathisZerbib committed Jun 4, 2024
1 parent 2dfa5da commit 300b9de
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 154 deletions.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions src/components/BuyCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -58,7 +58,7 @@ const BuyCard: React.FC<ProductProps> = ({
useEffect(() => {
const convertPrice = async () => {
try {
const convertedPrice = await performCurrencyConversion(
const convertedPrice = await convertToTon(
price,
selectedCurrency
);
Expand Down
3 changes: 2 additions & 1 deletion src/components/MapWithGeocoder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ const MapWithGeocoder: React.FC<MapWithGeocoderProps> = ({
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
});

Expand Down
18 changes: 12 additions & 6 deletions src/components/PriceConverter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,28 +71,34 @@ const PriceConverter: React.FC = () => {
const [usdAmount, setUsdAmount] = useState<string>("");
const [tonAmount, setTonAmount] = useState<string>("");
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<HTMLInputElement>) => {
Expand Down
119 changes: 0 additions & 119 deletions src/components/SearchComponent.tsx

This file was deleted.

60 changes: 36 additions & 24 deletions src/services/exchangeRateService.ts
Original file line number Diff line number Diff line change
@@ -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<number> => {
let cachedRates = {}; // Global variable to store cached rates

export const fetchInitialExchangeRate = async (): Promise<number> => {
try {
const response = await axios.get<ExchangeRateResponse>(`${API_URL}${baseCurrency}/${quoteCurrency}`, {
params: {
apikey: API_KEY,
},
});
return response.data.rate;
const response = await axios.get<TonApiResponse>(`https://tonapi.io/v2/rates?tokens=USD&currencies=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<number> => {
try {
if (currency === 'USDT') {
return price;
if (currency == "USDT") {
return amount;
} else {
const response = await axios.get<ExchangeRateResponse>(`${API_URL}USDT/${currency}?apikey=${API_KEY}`);
return price * response.data.rate;
const response = await axios.get<TonApiResponse>(`https://tonapi.io/v2/rates?tokens=USD&currencies=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;

0 comments on commit 300b9de

Please sign in to comment.