Skip to content

Commit

Permalink
added usdt switcher + converter + env variable safely
Browse files Browse the repository at this point in the history
  • Loading branch information
MathisZerbib committed Jun 2, 2024
1 parent 4152eea commit 6091dd7
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 46 deletions.
13 changes: 1 addition & 12 deletions src/components/PriceConverter.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import React, { useState, useEffect } from "react";
import styled from "styled-components";
import {
fetchInitialExchangeRate,
connectWebSocket,
} from "../services/exchangeRateService";
import { fetchInitialExchangeRate } from "../services/exchangeRateService";

const PriceConverter: React.FC = () => {
const [tonUsdtRate, setTonUsdtRate] = useState<number>(0);
Expand All @@ -23,14 +20,6 @@ const PriceConverter: React.FC = () => {
getInitialRate();
}, []);

useEffect(() => {
const ws = connectWebSocket((rate) => setTonUsdtRate(rate));

return () => {
ws.close();
};
}, []);

const convertUsdToTon = (amount: string): number => {
if (!tonUsdtRate || !amount) return 0;
return parseFloat(amount) / tonUsdtRate;
Expand Down
35 changes: 1 addition & 34 deletions src/services/exchangeRateService.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import axios from 'axios';

const API_KEY = 'FD3DCB80-D05F-4E79-A156-2C6BFB7A7981';
const API_KEY = import.meta.env.VITE_COINAPI_API_KEY ?? "";
const API_URL = `https://rest.coinapi.io/v1/exchangerate/`;
const WS_URL = 'wss://ws.coinapi.io/v1/';

interface ExchangeRateResponse {
time: string;
Expand All @@ -21,38 +20,6 @@ export const fetchInitialExchangeRate = async (): Promise<number> => {
}
};

export const connectWebSocket = (onRateUpdate: (rate: number) => void): WebSocket => {
const ws = new WebSocket(WS_URL);

ws.onopen = () => {
const msg = {
type: 'hello',
apikey: API_KEY,
heartbeat: false,
subscribe_data_type: ['exrate'],
subscribe_filter_asset_id: ['TON/USDT'],
};
ws.send(JSON.stringify(msg));
};

ws.onmessage = (event) => {
const data: any = JSON.parse(event.data);
if (data.rate && data.asset_id_base === 'TON' && data.asset_id_quote === 'USDT') {
onRateUpdate(data.rate);
}
};

ws.onerror = (error) => {
console.error('WebSocket error:', error);
};

ws.onclose = () => {
console.log('WebSocket connection closed, reconnecting...');
setTimeout(() => connectWebSocket(onRateUpdate), 1000);
};

return ws;
};

const performCurrencyConversion = async (price: number, currency: string | null) => {
try {
Expand Down

0 comments on commit 6091dd7

Please sign in to comment.