diff --git a/src/App.tsx b/src/App.tsx index 46c2081..2fb3bd8 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from "react"; +import React, { useEffect, useMemo, useState } from "react"; import ReactGA from "react-ga4"; import "./App.css"; import socketService from "./services/socketService"; @@ -71,7 +71,12 @@ export async function sendRequestToExtension( function App() { const [userInfo, setUserInfo] = useState(null); const [qortBalance, setQortBalance] = useState(null); - const [ltcBalance, setLtcBalance] = useState(null); + const [balances, setBalances] = useState({}); + const [selectedCoin, setSelectedCoin] = useState("LITECOIN"); + + const foreignCoinBalance = useMemo(()=> { + return balances[selectedCoin] || null + }, [balances, selectedCoin]) const [isAuthenticated, setIsAuthenticated] = useState(false); const [OAuthLoading, setOAuthLoading] = useState(false); const db = useIndexedDBContext(); @@ -172,14 +177,19 @@ function App() { setQortBalance(balanceResponse.data?.value) } - const getLTCBalance = async () => { + const getLTCBalance = async (coin) => { try { const response = await qortalRequest({ action: "GET_WALLET_BALANCE", - coin: "LTC" + coin: getCoinLabel(coin) }); if(!response?.error){ - setLtcBalance(+response) + setBalances((prev)=> { + return { + ...prev, + [coin]: +response + } + }) } } catch (error) { // @@ -187,18 +197,18 @@ function App() { } useEffect(() => { - if(!userInfo?.address) return + if(!userInfo?.address || !selectedCoin) return const intervalGetTradeInfo = setInterval(() => { fetchOngoingTransactions() - getLTCBalance() + getLTCBalance(selectedCoin) getQortBalance() }, 150000) - getLTCBalance() + getLTCBalance(selectedCoin) getQortBalance() return () => { clearInterval(intervalGetTradeInfo) } - }, [userInfo?.address, isAuthenticated]) + }, [userInfo?.address, isAuthenticated, selectedCoin]) const handleMessage = async (event: any) => { @@ -208,7 +218,6 @@ function App() { setAvatar(""); setIsAuthenticated(false); setQortBalance(null) - setLtcBalance(null) localStorage.setItem("token", ""); } else if(event.data.type === "RESPONSE_FOR_TRADES"){ @@ -246,6 +255,37 @@ function App() { }; }, [userInfo?.address]); + const getCoinLabel = (coin?: string)=> { + switch(coin || selectedCoin){ + case "LITECOIN":{ + + return 'LTC' + } + case "DOGECOIN":{ + + return 'DOGE' + } + case "BITCOIN":{ + + return 'BTC' + } + case "DIGIBYTE":{ + + return 'DGB' + } + case "RAVENCOIN":{ + + return 'RVN' + } + case "PIRATECHAIN":{ + + return 'ARRR' + } + default: + return null + } + } + const gameContextValue: IContextProps = { userInfo, setUserInfo, @@ -253,7 +293,7 @@ function App() { setUserNameAvatar, onGoingTrades, fetchOngoingTransactions, - ltcBalance, + foreignCoinBalance, qortBalance, isAuthenticated, setIsAuthenticated, @@ -261,7 +301,7 @@ function App() { setOAuthLoading, updateTransactionInDB, sellOrders, - deleteTemporarySellOrder, updateTemporaryFailedTradeBots, fetchTemporarySellOrders, isUsingGateway + deleteTemporarySellOrder, updateTemporaryFailedTradeBots, fetchTemporarySellOrders, isUsingGateway, selectedCoin, setSelectedCoin, getCoinLabel }; diff --git a/src/assets/img/arrr.png b/src/assets/img/arrr.png new file mode 100644 index 0000000..d274565 Binary files /dev/null and b/src/assets/img/arrr.png differ diff --git a/src/assets/img/btc.png b/src/assets/img/btc.png new file mode 100644 index 0000000..fe3fd1a Binary files /dev/null and b/src/assets/img/btc.png differ diff --git a/src/assets/img/dgb.png b/src/assets/img/dgb.png new file mode 100644 index 0000000..6950158 Binary files /dev/null and b/src/assets/img/dgb.png differ diff --git a/src/assets/img/doge.png b/src/assets/img/doge.png new file mode 100644 index 0000000..d99fa2f Binary files /dev/null and b/src/assets/img/doge.png differ diff --git a/src/assets/img/ltc.png b/src/assets/img/ltc.png new file mode 100644 index 0000000..d743e57 Binary files /dev/null and b/src/assets/img/ltc.png differ diff --git a/src/assets/img/qort.png b/src/assets/img/qort.png new file mode 100644 index 0000000..39d090f Binary files /dev/null and b/src/assets/img/qort.png differ diff --git a/src/assets/img/rvn.png b/src/assets/img/rvn.png new file mode 100644 index 0000000..31d7fdd Binary files /dev/null and b/src/assets/img/rvn.png differ diff --git a/src/components/Grids/OngoingTrades.tsx b/src/components/Grids/OngoingTrades.tsx index 5a62d42..b3f93a4 100644 --- a/src/components/Grids/OngoingTrades.tsx +++ b/src/components/Grids/OngoingTrades.tsx @@ -1,6 +1,6 @@ import React, { useCallback, useContext, useEffect, useRef, useState } from 'react'; import { AgGridReact } from 'ag-grid-react'; -import { ColDef, SizeColumnsToContentStrategy } from 'ag-grid-community'; +import { ColDef, RowClassParams, RowStyle, SizeColumnsToContentStrategy } from 'ag-grid-community'; import 'ag-grid-community/styles/ag-grid.css'; import 'ag-grid-community/styles/ag-theme-alpine.css'; import gameContext from '../../contexts/gameContext'; @@ -10,9 +10,17 @@ const autoSizeStrategy: SizeColumnsToContentStrategy = { }; export const OngoingTrades = () => { - const { onGoingTrades } = useContext(gameContext); - + const { onGoingTrades, getCoinLabel, selectedCoin } = useContext(gameContext); + const gridRef = useRef(null) + + + const onGridReady = useCallback((params: any) => { + // params.api.sizeColumnsToFit(); // Adjust columns to fit the grid width + // const allColumnIds = params.columnApi.getAllColumns().map((col: any) => col.getColId()); + // params.columnApi.autoSizeColumns(allColumnIds); // Automatically adjust the width to fit content + }, []); + const defaultColDef = { resizable: true, // Make columns resizable by default sortable: true, // Make columns sortable by default @@ -35,9 +43,10 @@ export const OngoingTrades = () => { resizable: true , flex: 1, minWidth: 100 }, - { headerName: "Amount (QORT)", valueGetter: (params) => +params.data.tradeInfo.qortAmount, resizable: true, flex: 1, minWidth: 100 }, - { headerName: "LTC/QORT", valueGetter: (params) => +params.data.tradeInfo.expectedForeignAmount / +params.data.tradeInfo.qortAmount , resizable: true , flex: 1, minWidth: 100}, - { headerName: "Total LTC Value", valueGetter: (params) => +params.data.tradeInfo.expectedForeignAmount, resizable: true , flex: 1, minWidth: 100 }, + { headerName: "Amount (QORT)", valueGetter: (params) => +params.data.tradeInfo.qortAmount, resizable: true, flex: 1, minWidth: 150 }, + { headerName: `${getCoinLabel()}/QORT`, valueGetter: (params) => +params.data.tradeInfo.expectedForeignAmount / +params.data.tradeInfo.qortAmount , resizable: true , flex: 1, minWidth: 150}, + { headerName: `Total ${getCoinLabel()} Value`, valueGetter: (params) => +params.data.tradeInfo.expectedForeignAmount, resizable: true , flex: 1, minWidth: 150, + }, { headerName: "Notes", valueGetter: (params) => { if (params.data.tradeInfo.mode === 'TRADING') { @@ -54,7 +63,7 @@ export const OngoingTrades = () => { } if (params.data.message) return params.data.message - }, resizable: true, flex: 1, minWidth: 100 + }, resizable: true, flex: 1, minWidth:300, autoHeight: true, cellStyle: { whiteSpace: 'normal', wordBreak: 'break-word', padding: '5px' }, } ]; @@ -65,15 +74,20 @@ export const OngoingTrades = () => { // return null; // }; const getRowId = useCallback(function (params: any) { - return String(params.data._id); + return String(params.data?.qortalAtAddress); }, []); + + return (
item?.tradeInfo?.foreignBlockchain === selectedCoin)} // onRowClicked={onRowClicked} rowSelection="single" getRowId={getRowId} @@ -85,7 +99,7 @@ export const OngoingTrades = () => { // domLayout='autoHeight' // getRowStyle={getRowStyle} - + />
); diff --git a/src/components/Grids/TradeOffers.tsx b/src/components/Grids/TradeOffers.tsx index bd9797f..bdd5721 100644 --- a/src/components/Grids/TradeOffers.tsx +++ b/src/components/Grids/TradeOffers.tsx @@ -11,6 +11,9 @@ import { subscribeToEvent, unsubscribeFromEvent } from '../../utils/events'; import { useModal } from '../common/useModal'; import FileSaver from 'file-saver'; +// export const baseLocalHost = window.location.host +export const baseLocalHost = '127.0.0.1:12391' + interface RowData { amountQORT: number; priceUSD: number; @@ -32,10 +35,10 @@ export const autoSizeStrategy: SizeColumnsToContentStrategy = { type: 'fitCellContents' }; -export const TradeOffers: React.FC = ({ltcBalance}:any) => { +export const TradeOffers: React.FC = ({foreignCoinBalance}:any) => { const [offers, setOffers] = useState([]) - - const { fetchOngoingTransactions, onGoingTrades, updateTransactionInDB, isUsingGateway } = useContext(gameContext); + const [qortalNames, setQortalNames] = useState({}) + const { fetchOngoingTransactions, onGoingTrades, updateTransactionInDB, isUsingGateway, getCoinLabel, selectedCoin } = useContext(gameContext); const listOfOngoingTradesAts = useMemo(()=> { return onGoingTrades?.filter((item)=> item?.status !== 'trade-failed')?.map((trade)=> trade?.qortalAtAddress) || [] }, [onGoingTrades]) @@ -50,7 +53,7 @@ export const TradeOffers: React.FC = ({ltcBalance}:any) => { const offersWithoutOngoing = useMemo(()=> { return offers.filter((item)=> !listOfOngoingTradesAts.includes(item.qortalAtAddress)) }, [listOfOngoingTradesAts, offers]) - + const initiatedFetchPresence = useRef(false) const [selectedOffer, setSelectedOffer] = useState(null) @@ -80,6 +83,30 @@ export const TradeOffers: React.FC = ({ltcBalance}:any) => { suppressMovable: true, // Prevent columns from being movable }; + const getName = async (address)=> { + try { + const response = await fetch("/names/address/" + address); + const nameData = await response.json(); + if (nameData?.length > 0) { + setQortalNames((prev)=> { + return { + ...prev, + [address]: nameData[0].name + } + }) + } else { + setQortalNames((prev)=> { + return { + ...prev, + [address]: null + } + }) + } + } catch (error) { + // error + } + } + const columnDefs: ColDef[] = [ { headerCheckboxSelection: true, // Adds a checkbox in the header for selecting all rows @@ -92,15 +119,28 @@ export const TradeOffers: React.FC = ({ltcBalance}:any) => { { headerName: "QORT AMOUNT", field: "qortAmount" , flex: 1, // Flex makes this column responsive minWidth: 150, // Ensure it doesn't shrink too much resizable: true }, - { headerName: "LTC/QORT", valueGetter: (params) => +params.data.foreignAmount / +params.data.qortAmount, sortable: true, sort: 'asc', flex: 1, // Flex makes this column responsive + { headerName: `${getCoinLabel()}/QORT`, valueGetter: (params) => +params.data.foreignAmount / +params.data.qortAmount, sortable: true, sort: 'asc', flex: 1, // Flex makes this column responsive minWidth: 150, // Ensure it doesn't shrink too much resizable: true }, - { headerName: "Total LTC Value", field: "foreignAmount", flex: 1, // Flex makes this column responsive + { headerName: `Total ${getCoinLabel()} Value`, field: "foreignAmount", flex: 1, // Flex makes this column responsive minWidth: 150, // Ensure it doesn't shrink too much resizable: true }, { headerName: "Seller", field: "qortalCreator", flex: 1, // Flex makes this column responsive minWidth: 300, // Ensure it doesn't shrink too much - resizable: true }, + resizable: true, valueGetter: (params)=> { + if(params?.data?.qortalCreator){ + if(qortalNames[params?.data?.qortalCreator]){ + return qortalNames[params?.data?.qortalCreator] + } else if(qortalNames[params?.data?.qortalCreator] === undefined){ + getName(params?.data?.qortalCreator) + + return params?.data?.qortalCreator + } else { + return params?.data?.qortalCreator + + } + } + } }, ]; @@ -225,7 +265,7 @@ export const TradeOffers: React.FC = ({ltcBalance}:any) => { if(isUsingGateway){ socketLink = `wss://appnode.qortal.org/websockets/crosschain/tradepresence` } else { - socketLink = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/websockets/crosschain/tradepresence`; + socketLink = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${baseLocalHost}/websockets/crosschain/tradepresence`; } @@ -245,44 +285,59 @@ export const TradeOffers: React.FC = ({ltcBalance}:any) => { } socket.onerror = (e) => { clearTimeout(socketTimeout) + restartTradePresenceWebSocket() } const pingSocket = () => { socket.send('ping') socketTimeout = setTimeout(pingSocket, 295000) } } + const socketRef = useRef(null) + + const restartTradeOffers = ()=> { + if (socketRef.current) { + socketRef.current.close(1000, 'forced'); // Close with a custom reason + socketRef.current = null + } + offeringTrades.current = [] + setOffers([]) + setSelectedOffer(null) + } const initTradeOffersWebSocket = (restarted = false) => { - let tradeOffersSocketCounter = 0 + + if(socketRef.current) return let socketTimeout: any let socketLink if(isUsingGateway){ - socketLink = `wss://appnode.qortal.org/websockets/crosschain/tradeoffers?foreignBlockchain=LITECOIN&includeHistoric=true` + socketLink = `wss://appnode.qortal.org/websockets/crosschain/tradeoffers?foreignBlockchain=${selectedCoin}&includeHistoric=true` } else { - socketLink = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/websockets/crosschain/tradeoffers?foreignBlockchain=LITECOIN&includeHistoric=true` + socketLink = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${baseLocalHost}/websockets/crosschain/tradeoffers?foreignBlockchain=${selectedCoin}&includeHistoric=true` } - const socket = new WebSocket(socketLink) - socket.onopen = () => { + socketRef.current = new WebSocket(socketLink) + socketRef.current.onopen = () => { setTimeout(pingSocket, 50) - tradeOffersSocketCounter += 1 } - socket.onmessage = (e) => { - offeringTrades.current = [...offeringTrades.current, ...JSON.parse(e.data)] - tradeOffersSocketCounter += 1 + socketRef.current.onmessage = (e) => { + offeringTrades.current = [...offeringTrades.current?.filter((coin)=> coin?.foreignBlockchain === selectedCoin), ...JSON.parse(e.data)?.filter((coin)=> coin?.foreignBlockchain === selectedCoin)] restarted = false processOffersWithPresence() } - socket.onclose = () => { + socketRef.current.onclose = (event) => { clearTimeout(socketTimeout) + if (event.reason === 'forced') { + return + } restartTradeOffersWebSocket() + socketRef.current = null } - socket.onerror = (e) => { + socketRef.current.onerror = (e) => { clearTimeout(socketTimeout) } const pingSocket = () => { - socket.send('ping') + socketRef.current.send('ping') socketTimeout = setTimeout(pingSocket, 295000) } } @@ -290,8 +345,11 @@ export const TradeOffers: React.FC = ({ltcBalance}:any) => { useEffect(() => { blockedTradesList.current = JSON.parse(localStorage.getItem('failedTrades') || '[]') - initTradePresenceWebSocket() - initTradeOffersWebSocket() + if(!initiatedFetchPresence.current){ + initiatedFetchPresence.current = true + initTradePresenceWebSocket() + + } getNewBlockedTrades() const intervalBlockTrades = setInterval(() => { getNewBlockedTrades() @@ -302,6 +360,24 @@ export const TradeOffers: React.FC = ({ltcBalance}:any) => { } }, [isUsingGateway]) + + + useEffect(() => { + if(selectedCoin === null) return + restartTradeOffers() + setTimeout(() => { + initTradeOffersWebSocket() + + }, 500); + return () => { + if(socketRef.current){ + socketRef.current.close(1000, 'forced'); + } + } + }, [isUsingGateway, selectedCoin]) + + + const selectedTotalLTC = useMemo(() => { @@ -313,11 +389,11 @@ export const TradeOffers: React.FC = ({ltcBalance}:any) => { const buyOrder = async () => { try { - if(+ltcBalance < +selectedTotalLTC.toFixed(4)){ + if(+foreignCoinBalance < +selectedTotalLTC.toFixed(4)){ setOpen(true) setInfo({ type: 'error', - message: "You don't have enough LTC or your balance was not retrieved" + message: `You don't have enough ${getCoinLabel()} or your balance was not retrieved` }) return } @@ -329,11 +405,10 @@ export const TradeOffers: React.FC = ({ltcBalance}:any) => { message: "Attempting to submit buy order. Please wait..." }) const listOfATs = selectedOffers - const response = await qortalRequestWithTimeout({ action: "CREATE_TRADE_BUY_ORDER", crosschainAtInfo: listOfATs, - foreignBlockchain: 'LITECOIN' + foreignBlockchain: selectedCoin }, 900000); if(response?.error){ @@ -381,7 +456,7 @@ export const TradeOffers: React.FC = ({ltcBalance}:any) => { setOpen(true) setInfo({ type: 'error', - message: error?.message || "Failed to submit trade order." + message: error?.error || error?.message || "Failed to submit trade order." }) console.error(error) } @@ -471,7 +546,7 @@ const handleClose = ( onSelectionChanged={onSelectionChanged} getRowStyle={getRowStyle} autoSizeStrategy={autoSizeStrategy} - rowSelection="multiple" // Enable multi-select + rowSelection={selectedCoin === 'PIRATECHAIN' ? "single" :"multiple"} // Enable multi-select rowMultiSelectWithClick={true} suppressHorizontalScroll={false} // Allow horizontal scroll on mobile if needed suppressCellFocus={true} // Prevents cells from stealing focus in mobile @@ -486,6 +561,9 @@ const handleClose = ( )} */} +
ltcBalance ? 'red' : 'white', + color: selectedTotalLTC > foreignCoinBalance ? 'red' : 'white', }}>{selectedTotalLTC?.toFixed(4)} LTC + }}>{`${getCoinLabel()} `} @@ -528,9 +606,9 @@ const handleClose = ( fontSize: '16px', color: 'white', - }}>{ltcBalance?.toFixed(4)} {foreignCoinBalance?.toFixed(4)} LTC balance + }}>{`${getCoinLabel()} `} balance {BuyButton()} diff --git a/src/components/Terms.tsx b/src/components/Terms.tsx index ddba254..3ab87f2 100644 --- a/src/components/Terms.tsx +++ b/src/components/Terms.tsx @@ -55,14 +55,14 @@ export const Terms =() => { - The purpose of q-trade is to make trading LTC for QORT as easy as possible. The maintainers of this site do not profit from its use—there are no additional fees for buying QORT through this site. There are two ways to place a buy order: + The purpose of q-trade is to make trading LTC and other coins for QORT as easy as possible. The maintainers of this site do not profit from its use—there are no additional fees for buying QORT through this site. There are two ways to place a buy order: 1. Use the gateway 2. Use your local node. By using q-trade, you agree to the following terms and conditions. - Using the gateway means you trust the maintainer of the node, as your LTC private key will need to be handled by that node to execute a trade order. If you have more than 4 QORT and your public key is already on the blockchain, your LTC private key will be transmitted using q-chat. If not, the message will be encrypted in the same manner as q-chat but stored temporarily in a database to ensure it reaches its destination. + Using the gateway means you trust the maintainer of the node, as your foreign coin (i.e. LTC) private key will need to be handled by that node to execute a trade order. If you have more than 4 QORT and your public key is already on the blockchain, your foreign coin private key will be transmitted using q-chat. If not, the message will be encrypted in the same manner as q-chat but stored temporarily in a database to ensure it reaches its destination. @@ -70,7 +70,7 @@ export const Terms =() => { - The maintainers and devs of this site are not responsible for any lost LTC, QORT, or other cryptocurrencies that may result from using this site. This is a hobby project, and mistakes in the code may occur. Please proceed with caution. + The maintainers and devs of this site are not responsible for any lost foreign coin, QORT, or other cryptocurrencies that may result from using this site. This is a hobby project, and mistakes in the code may occur. diff --git a/src/components/header/Header.tsx b/src/components/header/Header.tsx index c74b2e5..7f5b829 100644 --- a/src/components/header/Header.tsx +++ b/src/components/header/Header.tsx @@ -36,6 +36,12 @@ import { } from "@mui/material"; import { sendRequestToExtension } from "../../App"; import { Terms } from "../Terms"; +import ltcIcon from '../../assets/img/ltc.png' +import btcIcon from '../../assets/img/btc.png' +import dogeIcon from '../../assets/img/doge.png' +import rvnIcon from '../../assets/img/rvn.png' +import dgbIcon from '../../assets/img/dgb.png' +import arrrIcon from '../../assets/img/arrr.png' const checkIfLocal = async () => { try { @@ -59,7 +65,47 @@ export const Label = styled("label")( ` ); -export const Header = ({ qortBalance, ltcBalance, mode, setMode }: any) => { +const SelectRow = ({coin})=> { + let img + switch (coin) { + case 'LTC': + img = ltcIcon + break; + case 'BTC': + img = btcIcon + break; + + case 'DOGE': + img = dogeIcon + break; + case 'RVN': + img = rvnIcon + break; + + case 'ARRR': + img = arrrIcon + break; + case 'DGB': + img = dgbIcon + break; + default: + null + } + + return ( +

{coin}

+ ) +} + +export const Header = ({ qortBalance, foreignCoinBalance, mode, setMode }: any) => { const [openDropdown, setOpenDropdown] = useState(false); const dropdownRef = useRef(null); const buttonRef = useRef(null); @@ -67,7 +113,6 @@ export const Header = ({ qortBalance, ltcBalance, mode, setMode }: any) => { const [open, setOpen] = useState(false); const [info, setInfo] = useState(null); const { isUsingGateway } = useContext(gameContext); - const [selectedCoin, setSelectedCoin] = useState("LITECOIN"); const handleChange = (event: ChangeEvent) => { setChecked(false); @@ -77,7 +122,7 @@ export const Header = ({ qortBalance, ltcBalance, mode, setMode }: any) => { message: "Change the node you are using at the authentication page", }); }; - const { userInfo } = useContext(gameContext); + const { userInfo, selectedCoin, setSelectedCoin, getCoinLabel } = useContext(gameContext); const { avatar, setAvatar } = useContext(UserContext); const LocalNodeSwitch = styled(Switch)(({ theme }) => ({ @@ -185,7 +230,12 @@ export const Header = ({ qortBalance, ltcBalance, mode, setMode }: any) => { value={selectedCoin} onChange={(e) => setSelectedCoin(e.target.value)} > - LTC + + + + + + @@ -195,7 +245,7 @@ export const Header = ({ qortBalance, ltcBalance, mode, setMode }: any) => { }}> Balance: {qortBalance} QORT |{" "} - {ltcBalance === null ? "N/A" : ltcBalance} LTC + {foreignCoinBalance === null ? "N/A" : foreignCoinBalance} {getCoinLabel()} {userInfo?.name ? ( @@ -247,8 +297,20 @@ export const Header = ({ qortBalance, ltcBalance, mode, setMode }: any) => { alignItems: "center", }} > - - + + { const [open, setOpen] = React.useState(false); const [qortAmount, setQortAmount] = React.useState(0) const [foreignAmount, setForeignAmount] = React.useState(0) - const {updateTemporaryFailedTradeBots, sellOrders, fetchTemporarySellOrders, isUsingGateway} = useContext(gameContext) + const {updateTemporaryFailedTradeBots, sellOrders, fetchTemporarySellOrders, isUsingGateway, getCoinLabel, selectedCoin} = useContext(gameContext) const [openAlert, setOpenAlert] = React.useState(false) const [info, setInfo] = React.useState(null) const handleClickOpen = () => { @@ -80,7 +100,6 @@ export const CreateSell = ({qortAddress, show}) => { const createSellOrder = async() => { try { - setOpen(true) setInfo({ type: 'info', message: "Attempting to create sell order. Please wait..." @@ -88,8 +107,8 @@ export const CreateSell = ({qortAddress, show}) => { const res = await qortalRequestWithTimeout({ action: "CREATE_TRADE_SELL_ORDER", qortAmount, - foreignBlockchain: 'LITECOIN', - foreignAmount + foreignBlockchain: selectedCoin, + foreignAmount: qortAmount * foreignAmount }, 900000); if(res?.error && res?.failedTradeBot){ @@ -167,7 +186,6 @@ export const CreateSell = ({qortAddress, show}) => {
) } - return (
{ }} > - New Sell Order - QORT for LTC + {`New Sell Order - QORT for ${getCoinLabel()}`} { /> - Price Each (LTC) + {`Price Each (${getCoinLabel()})`} { autoComplete="off" /> - {qortAmount * foreignAmount} LTC for {qortAmount} QORT + {`${qortAmount * foreignAmount} ${getCoinLabel()}`} for {qortAmount} QORT Total sell amount needs to be greater than: {minimumAmountSellTrades.LITECOIN.value} {' '} {minimumAmountSellTrades.LITECOIN.ticker} + }}>Total sell amount needs to be greater than: {minimumAmountSellTrades[selectedCoin]?.value} {' '} {minimumAmountSellTrades[selectedCoin]?.ticker} @@ -236,7 +254,7 @@ export const CreateSell = ({qortAddress, show}) => { - diff --git a/src/components/sell/TradeBotList.tsx b/src/components/sell/TradeBotList.tsx index 8bc86ff..c317868 100644 --- a/src/components/sell/TradeBotList.tsx +++ b/src/components/sell/TradeBotList.tsx @@ -8,7 +8,7 @@ import React, { useRef, useState, } from "react"; -import { autoSizeStrategy } from "../Grids/TradeOffers"; +import { autoSizeStrategy, baseLocalHost } from "../Grids/TradeOffers"; import { Alert, Box, Snackbar, SnackbarCloseReason, Typography } from "@mui/material"; import gameContext from "../../contexts/gameContext"; @@ -18,47 +18,47 @@ const defaultColDef = { suppressMovable: true, // Prevent columns from being movable }; -const columnDefs: ColDef[] = [ - { - headerCheckboxSelection: false, // Adds a checkbox in the header for selecting all rows - checkboxSelection: true, // Adds checkboxes in each row for selection - headerName: "Select", // You can customize the header name - width: 50, // Adjust the width as needed - pinned: "left", // Optional, to pin this column on the left - resizable: false, - }, - { - headerName: "QORT AMOUNT", - field: "qortAmount", - flex: 1, // Flex makes this column responsive - minWidth: 150, // Ensure it doesn't shrink too much - resizable: true, - }, - { - headerName: "LTC/QORT", - valueGetter: (params) => - +params.data.foreignAmount / +params.data.qortAmount, - sortable: true, - sort: "asc", - flex: 1, // Flex makes this column responsive - minWidth: 150, // Ensure it doesn't shrink too much - resizable: true, - }, - { - headerName: "Total LTC Value", - field: "foreignAmount", - flex: 1, // Flex makes this column responsive - minWidth: 150, // Ensure it doesn't shrink too much - resizable: true, - }, - { - headerName: "Status", - field: "status", - flex: 1, // Flex makes this column responsive - minWidth: 300, // Ensure it doesn't shrink too much - resizable: true, - }, -]; +// const columnDefs: ColDef[] = [ +// { +// headerCheckboxSelection: false, // Adds a checkbox in the header for selecting all rows +// checkboxSelection: true, // Adds checkboxes in each row for selection +// headerName: "Select", // You can customize the header name +// width: 50, // Adjust the width as needed +// pinned: "left", // Optional, to pin this column on the left +// resizable: false, +// }, +// { +// headerName: "QORT AMOUNT", +// field: "qortAmount", +// flex: 1, // Flex makes this column responsive +// minWidth: 150, // Ensure it doesn't shrink too much +// resizable: true, +// }, +// { +// headerName: "LTC/QORT", +// valueGetter: (params) => +// +params.data.foreignAmount / +params.data.qortAmount, +// sortable: true, +// sort: "asc", +// flex: 1, // Flex makes this column responsive +// minWidth: 150, // Ensure it doesn't shrink too much +// resizable: true, +// }, +// { +// headerName: "Total LTC Value", +// field: "foreignAmount", +// flex: 1, // Flex makes this column responsive +// minWidth: 150, // Ensure it doesn't shrink too much +// resizable: true, +// }, +// { +// headerName: "Status", +// field: "status", +// flex: 1, // Flex makes this column responsive +// minWidth: 300, // Ensure it doesn't shrink too much +// resizable: true, +// }, +// ]; export default function TradeBotList({ qortAddress, failedTradeBots }) { const [tradeBotList, setTradeBotList] = useState([]); @@ -67,7 +67,7 @@ export default function TradeBotList({ qortAddress, failedTradeBots }) { const offeringTrades = useRef([]); const qortAddressRef = useRef(null); const gridRef = useRef(null); - const {updateTemporaryFailedTradeBots, fetchTemporarySellOrders, deleteTemporarySellOrder} = useContext(gameContext) + const {updateTemporaryFailedTradeBots, fetchTemporarySellOrders, deleteTemporarySellOrder, getCoinLabel, selectedCoin} = useContext(gameContext) const [open, setOpen] = useState(false) const [info, setInfo] = useState(null) const filteredOutTradeBotListWithoutFailed = useMemo(() => { @@ -88,6 +88,51 @@ export default function TradeBotList({ qortAddress, failedTradeBots }) { params.columnApi.autoSizeColumns(allColumnIds); // Automatically adjust the width to fit content }, []); + + const columnDefs: ColDef[] = useMemo(()=> { + return [ + { + headerCheckboxSelection: false, // Adds a checkbox in the header for selecting all rows + checkboxSelection: true, // Adds checkboxes in each row for selection + headerName: "Select", // You can customize the header name + width: 50, // Adjust the width as needed + pinned: "left", // Optional, to pin this column on the left + resizable: false, + }, + { + headerName: "QORT AMOUNT", + field: "qortAmount", + flex: 1, // Flex makes this column responsive + minWidth: 150, // Ensure it doesn't shrink too much + resizable: true, + }, + { + headerName: `${getCoinLabel()}/QORT`, + valueGetter: (params) => + +params.data.foreignAmount / +params.data.qortAmount, + sortable: true, + sort: "asc", + flex: 1, // Flex makes this column responsive + minWidth: 150, // Ensure it doesn't shrink too much + resizable: true, + }, + { + headerName: `Total ${getCoinLabel()} Value`, + field: "foreignAmount", + flex: 1, // Flex makes this column responsive + minWidth: 150, // Ensure it doesn't shrink too much + resizable: true, + }, + { + headerName: "Status", + field: "status", + flex: 1, // Flex makes this column responsive + minWidth: 300, // Ensure it doesn't shrink too much + resizable: true, + }, + ]; + + }, [selectedCoin]) useEffect(() => { if (qortAddress) { qortAddressRef.current = qortAddress; @@ -154,38 +199,64 @@ export default function TradeBotList({ qortAddress, failedTradeBots }) { tradeBotListRef.current = sellTrades; }; + const restartTradeOffers = ()=> { + if (socketRef.current) { + socketRef.current.close(1000, 'forced'); // Close with a custom reason + socketRef.current = null + } + offeringTrades.current = [] + setTradeBotList([]); + tradeBotListRef.current = []; + } + + const socketRef = useRef(null) + const initTradeOffersWebSocket = (restarted = false) => { let tradeOffersSocketCounter = 0; let socketTimeout: any; // let socketLink = `ws://127.0.0.1:12391/websockets/crosschain/tradebot?foreignBlockchain=LITECOIN`; - let socketLink = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/websockets/crosschain/tradebot?foreignBlockchain=LITECOIN`; - const socket = new WebSocket(socketLink); - socket.onopen = () => { + let socketLink = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${baseLocalHost}/websockets/crosschain/tradebot?foreignBlockchain=${selectedCoin}`; + socketRef.current = new WebSocket(socketLink); + socketRef.current.onopen = () => { setTimeout(pingSocket, 50); tradeOffersSocketCounter += 1; }; - socket.onmessage = (e) => { + socketRef.current.onmessage = (e) => { tradeOffersSocketCounter += 1; restarted = false; processTradeBots(JSON.parse(e.data)); }; - socket.onclose = () => { + socketRef.current.onclose = (event) => { clearTimeout(socketTimeout); + if (event.reason === 'forced') { + return + } restartTradeOffersWebSocket(); }; - socket.onerror = (e) => { + socketRef.current.onerror = (e) => { clearTimeout(socketTimeout); }; const pingSocket = () => { - socket.send("ping"); + socketRef.current.send("ping"); socketTimeout = setTimeout(pingSocket, 295000); }; }; useEffect(() => { if(!qortAddress) return - initTradeOffersWebSocket(); - }, [qortAddress]); + if(selectedCoin === null) return + restartTradeOffers() + + setTimeout(() => { + initTradeOffersWebSocket() + + }, 500); + return () => { + if(socketRef.current){ + socketRef.current.close(1000, 'forced'); + } + } + }, [qortAddress, selectedCoin]); const onSelectionChanged = (event: any) => { const selectedRows = event.api.getSelectedRows(); @@ -222,7 +293,7 @@ export default function TradeBotList({ qortAddress, failedTradeBots }) { const res = await qortalRequestWithTimeout({ action: "CANCEL_TRADE_SELL_ORDER", qortAmount: selectedTrade.qortAmount, - foreignBlockchain: 'LITECOIN', + foreignBlockchain: selectedTrade.foreignBlockchain, foreignAmount: selectedTrade.foreignAmount, atAddress: selectedTrade.atAddress }, 900000); @@ -329,7 +400,7 @@ export default function TradeBotList({ qortAddress, failedTradeBots }) { }}> {/* ltcBalance ? 'red' : 'white', + color: selectedTotalLTC > foreignCoinBalance ? 'red' : 'white', }}>{selectedTotalLTC?.toFixed(4)} LTC */} @@ -340,7 +411,7 @@ export default function TradeBotList({ qortAddress, failedTradeBots }) { fontSize: '16px', color: 'white', - }}>{ltcBalance?.toFixed(4)} {foreignCoinBalance?.toFixed(4)} LTC balance */} diff --git a/src/contexts/gameContext.ts b/src/contexts/gameContext.ts index 487a536..ab2d9dd 100644 --- a/src/contexts/gameContext.ts +++ b/src/contexts/gameContext.ts @@ -14,7 +14,7 @@ export interface UserNameAvatar { } export interface IContextProps { - ltcBalance: number | null; + foreignCoinBalance: number | null; qortBalance: number | null; userInfo: any; setUserInfo: (val: any) => void; @@ -32,11 +32,14 @@ export interface IContextProps { updateTemporaryFailedTradeBots: (val: any)=> void; fetchTemporarySellOrders: ()=> void; isUsingGateway: boolean; + selectedCoin: string; + setSelectedCoin: (val: any)=> void; + getCoinLabel: ()=> void; } const defaultState: IContextProps = { qortBalance: null, - ltcBalance: null, + foreignCoinBalance: null, userInfo: null, setUserInfo: () => {}, userNameAvatar: {}, @@ -52,7 +55,10 @@ const defaultState: IContextProps = { deleteTemporarySellOrder: ()=> {}, updateTemporaryFailedTradeBots: ()=> {}, fetchTemporarySellOrders: ()=> {}, - isUsingGateway: true + isUsingGateway: true, + selectedCoin: 'LITECOIN', + setSelectedCoin: ()=> {}, + getCoinLabel: ()=> {} }; export default React.createContext(defaultState); diff --git a/src/pages/Home/Home.tsx b/src/pages/Home/Home.tsx index e639164..14570c5 100644 --- a/src/pages/Home/Home.tsx +++ b/src/pages/Home/Home.tsx @@ -24,7 +24,7 @@ export const HomePage: FC = ({}) => { const navigate = useNavigate(); const { qortBalance, - ltcBalance, + foreignCoinBalance, userInfo, isAuthenticated, setIsAuthenticated, @@ -53,7 +53,7 @@ export const HomePage: FC = ({}) => {
@@ -97,7 +97,7 @@ export const HomePage: FC = ({}) => { - +