From 95db6655e7cf030ee17f4f137e6b2310ef833765 Mon Sep 17 00:00:00 2001 From: nahuhh <50635951+nahuhh@users.noreply.github.com> Date: Thu, 28 Nov 2024 15:37:38 +0000 Subject: [PATCH] doge: static/js/offerstable.js --- basicswap/static/js/offerstable.js | 263 +++++++++++++++-------------- 1 file changed, 132 insertions(+), 131 deletions(-) diff --git a/basicswap/static/js/offerstable.js b/basicswap/static/js/offerstable.js index cec0722..db64b3b 100644 --- a/basicswap/static/js/offerstable.js +++ b/basicswap/static/js/offerstable.js @@ -12,7 +12,7 @@ let filterTimeout = null; // Time Constants const MIN_REFRESH_INTERVAL = 60; // 60 sec -const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes +const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes const FALLBACK_CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours // Application Constants @@ -67,7 +67,8 @@ const coinNameToDisplayName = { const coinIdToName = { 1: 'particl', 2: 'bitcoin', 3: 'litecoin', 4: 'decred', 6: 'monero', 7: 'particl blind', 8: 'particl anon', - 9: 'wownero', 11: 'pivx', 13: 'firo', 17: 'bitcoincash' + 9: 'wownero', 11: 'pivx', 13: 'firo', 17: 'bitcoincash', + 18: 'dogecoin' }; // DOM ELEMENT REFERENCES @@ -92,7 +93,7 @@ const WebSocketManager = { reconnectDelay: 5000, maxQueueSize: 1000, isIntentionallyClosed: false, - + connectionState: { isConnecting: false, lastConnectAttempt: null, @@ -271,7 +272,7 @@ const WebSocketManager = { try { const response = await fetch(endpoint); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); - + const newData = await response.json(); const fetchedOffers = Array.isArray(newData) ? newData : Object.values(newData); @@ -300,7 +301,7 @@ const WebSocketManager = { this.reconnectAttempts++; if (this.reconnectAttempts <= this.maxReconnectAttempts) { console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})`); - + const delay = Math.min( this.reconnectDelay * Math.pow(1.5, this.reconnectAttempts - 1), 30000 @@ -324,11 +325,11 @@ const WebSocketManager = { cleanup() { console.log('Cleaning up WebSocket resources'); - + clearTimeout(this.debounceTimeout); clearTimeout(this.reconnectTimeout); clearTimeout(this.connectionState.connectTimeout); - + this.messageQueue = []; this.processingQueue = false; this.connectionState.isConnecting = false; @@ -365,7 +366,7 @@ const CacheManager = { set: function(key, value, customTtl = null) { try { this.cleanup(); - + const item = { value: value, timestamp: Date.now(), @@ -396,7 +397,7 @@ const CacheManager = { return false; } }, - + get: function(key) { try { const itemStr = localStorage.getItem(key); @@ -404,14 +405,14 @@ const CacheManager = { const item = JSON.parse(itemStr); const now = Date.now(); - + if (now < item.expiresAt) { return { value: item.value, remainingTime: item.expiresAt - now }; } - + localStorage.removeItem(key); } catch (error) { localStorage.removeItem(key); @@ -433,7 +434,7 @@ const CacheManager = { const itemStr = localStorage.getItem(key); const size = new Blob([itemStr]).size; const item = JSON.parse(itemStr); - + if (now >= item.expiresAt) { localStorage.removeItem(key); continue; @@ -445,7 +446,7 @@ const CacheManager = { expiresAt: item.expiresAt, timestamp: item.timestamp }); - + totalSize += size; itemCount++; } catch (error) { @@ -455,7 +456,7 @@ const CacheManager = { if (aggressive || totalSize > this.maxSize || itemCount > this.maxItems) { items.sort((a, b) => b.timestamp - a.timestamp); - + while ((totalSize > this.maxSize || itemCount > this.maxItems) && items.length > 0) { const item = items.pop(); localStorage.removeItem(item.key); @@ -473,7 +474,7 @@ const CacheManager = { keys.push(key); } } - + keys.forEach(key => localStorage.removeItem(key)); }, @@ -491,10 +492,10 @@ const CacheManager = { const itemStr = localStorage.getItem(key); const size = new Blob([itemStr]).size; const item = JSON.parse(itemStr); - + totalSize += size; itemCount++; - + if (now >= item.expiresAt) { expiredCount++; } @@ -528,7 +529,7 @@ window.tableRateModule = { 'Bitcoin Cash': 'BCH', 'Dogecoin': 'DOGE' }, - + cache: {}, processedOffers: new Set(), @@ -564,7 +565,7 @@ window.tableRateModule = { this.processedOffers.add(offerId); return true; }, - + formatUSD(value) { if (Math.abs(value) < 0.000001) { return value.toExponential(8) + ' USD'; @@ -654,23 +655,23 @@ async function initializePriceData() { while (retryCount < PRICE_INIT_RETRIES) { try { prices = await fetchLatestPrices(); - + if (prices && Object.keys(prices).length > 0) { console.log('Successfully fetched initial price data'); latestPrices = prices; CacheManager.set(PRICES_CACHE_KEY, prices, CACHE_DURATION); return true; } - + retryCount++; - + if (retryCount < PRICE_INIT_RETRIES) { await new Promise(resolve => setTimeout(resolve, PRICE_INIT_RETRY_DELAY)); } } catch (error) { console.error(`Error fetching prices (attempt ${retryCount + 1}):`, error); retryCount++; - + if (retryCount < PRICE_INIT_RETRIES) { await new Promise(resolve => setTimeout(resolve, PRICE_INIT_RETRY_DELAY)); } @@ -706,7 +707,7 @@ function checkOfferAgainstFilters(offer, filters) { const currentTime = Math.floor(Date.now() / 1000); const isExpired = offer.expire_at <= currentTime; const isRevoked = Boolean(offer.is_revoked); - + switch (filters.status) { case 'active': return !isExpired && !isRevoked; @@ -726,7 +727,7 @@ function initializeFlowbiteTooltips() { console.warn('Tooltip is not defined. Make sure the required library is loaded.'); return; } - + const tooltipElements = document.querySelectorAll('[data-tooltip-target]'); tooltipElements.forEach((el) => { const tooltipId = el.getAttribute('data-tooltip-target'); @@ -740,10 +741,10 @@ function initializeFlowbiteTooltips() { // DATA PROCESSING FUNCTIONS async function checkExpiredAndFetchNew() { if (isSentOffers) return Promise.resolve(); - + console.log('Starting checkExpiredAndFetchNew'); const OFFERS_CACHE_KEY = 'offers_received'; - + try { const response = await fetch('/json/offers'); const data = await response.json(); @@ -772,9 +773,9 @@ async function checkExpiredAndFetchNew() { CacheManager.set(OFFERS_CACHE_KEY, newListings, CACHE_DURATION); const currentFilters = new FormData(filterForm); - const hasActiveFilters = currentFilters.get('coin_to') !== 'any' || + const hasActiveFilters = currentFilters.get('coin_to') !== 'any' || currentFilters.get('coin_from') !== 'any'; - + if (hasActiveFilters) { jsonData = filterAndSortData(); } else { @@ -784,7 +785,7 @@ async function checkExpiredAndFetchNew() { updateOffersTable(); updateJsonView(); updatePaginationInfo(); - + if (jsonData.length === 0) { handleNoOffersScenario(); } @@ -810,7 +811,7 @@ function getValidOffers() { function filterAndSortData() { //console.log('[Debug] Starting filter with data length:', originalJsonData.length); - + const formData = new FormData(filterForm); const filters = Object.fromEntries(formData); //console.log('[Debug] Active filters:', filters); @@ -825,7 +826,7 @@ function filterAndSortData() { let filteredData = [...originalJsonData]; const sentFromFilter = filters.sent_from || 'any'; - + filteredData = filteredData.filter(offer => { if (sentFromFilter === 'public') { return offer.is_public; @@ -842,13 +843,13 @@ function filterAndSortData() { const coinFrom = (offer.coin_from || '').toLowerCase(); const coinTo = (offer.coin_to || '').toLowerCase(); - + if (filters.coin_to !== 'any') { if (!coinMatches(coinTo, filters.coin_to)) { return false; } } - + if (filters.coin_from !== 'any') { if (!coinMatches(coinFrom, filters.coin_from)) { return false; @@ -859,7 +860,7 @@ function filterAndSortData() { const currentTime = Math.floor(Date.now() / 1000); const isExpired = offer.expire_at <= currentTime; const isRevoked = Boolean(offer.is_revoked); - + switch (filters.status) { case 'active': return !isExpired && !isRevoked; @@ -878,7 +879,7 @@ function filterAndSortData() { if (currentSortColumn !== null) { filteredData.sort((a, b) => { let comparison = 0; - + switch(currentSortColumn) { case 0: // Time comparison = a.created_at - b.created_at; @@ -891,32 +892,32 @@ function filterAndSortData() { const aToSymbol = getCoinSymbolLowercase(a.coin_to); const bFromSymbol = getCoinSymbolLowercase(b.coin_from); const bToSymbol = getCoinSymbolLowercase(b.coin_to); - + const aFromPrice = latestPrices[aFromSymbol]?.usd || 0; const aToPrice = latestPrices[aToSymbol]?.usd || 0; const bFromPrice = latestPrices[bFromSymbol]?.usd || 0; const bToPrice = latestPrices[bToSymbol]?.usd || 0; - + const aMarketRate = aToPrice / aFromPrice; const bMarketRate = bToPrice / bFromPrice; - + const aOfferedRate = parseFloat(a.rate); const bOfferedRate = parseFloat(b.rate); - + const aPercentDiff = ((aOfferedRate - aMarketRate) / aMarketRate) * 100; const bPercentDiff = ((bOfferedRate - bMarketRate) / bMarketRate) * 100; - + comparison = aPercentDiff - bPercentDiff; break; case 7: // Trade comparison = a.offer_id.localeCompare(b.offer_id); break; } - + return currentSortDirection === 'desc' ? -comparison : comparison; }); } - + //console.log(`[Debug] Filtered data length: ${filteredData.length}`); return filteredData; } @@ -1019,7 +1020,7 @@ async function fetchLatestPrices() { } const url = `${config.apiEndpoints.coinGecko}/simple/price?ids=bitcoin,bitcoin-cash,dash,dogecoin,decred,litecoin,particl,pivx,monero,zano,wownero,zcoin&vs_currencies=USD,BTC&api_key=${config.apiKeys.coinGecko}`; - + try { console.log('Fetching fresh price data...'); const response = await fetch('/json/readurl', { @@ -1041,7 +1042,7 @@ async function fetchLatestPrices() { if (data.Error) { throw new Error(data.Error); } - + if (data && Object.keys(data).length > 0) { console.log('Fresh price data received'); @@ -1052,7 +1053,7 @@ async function fetchLatestPrices() { Object.entries(data).forEach(([coin, prices]) => { tableRateModule.setFallbackValue(coin, prices.usd); }); - + return data; } else { //console.warn('Received empty price data'); @@ -1075,18 +1076,18 @@ async function fetchOffers(manualRefresh = false) { refreshIcon.classList.add('animate-spin'); refreshText.textContent = 'Refreshing...'; refreshButton.classList.add('opacity-75', 'cursor-wait'); - + const endpoint = isSentOffers ? '/json/sentoffers' : '/json/offers'; const response = await fetch(endpoint); const data = await response.json(); - + jsonData = formatInitialData(data); originalJsonData = [...jsonData]; await updateOffersTable(); updateJsonView(); updatePaginationInfo(); - + } catch (error) { console.error('[Debug] Error fetching offers:', error); ui.displayErrorMessage('Failed to fetch offers. Please try again later.'); @@ -1120,12 +1121,12 @@ function formatInitialData(data) { function updateConnectionStatus(status) { const dot = document.getElementById('status-dot'); const text = document.getElementById('status-text'); - + if (!dot || !text) { //console.warn('Status indicators not found in DOM'); return; } - + switch(status) { case 'connected': dot.className = 'w-2.5 h-2.5 rounded-full bg-green-500 mr-2'; @@ -1159,10 +1160,10 @@ function updateRowTimes() { const newPostedTime = formatTime(offer.created_at, true); const newExpiresIn = formatTimeLeft(offer.expire_at); - + const postedElement = row.querySelector('.text-xs:first-child'); const expiresElement = row.querySelector('.text-xs:last-child'); - + if (postedElement && postedElement.textContent !== `Posted: ${newPostedTime}`) { postedElement.textContent = `Posted: ${newPostedTime}`; } @@ -1212,14 +1213,14 @@ function updatePaginationInfo() { const showPrev = currentPage > 1; const showNext = currentPage < totalPages && totalItems > 0; - + prevPageButton.style.display = showPrev ? 'inline-flex' : 'none'; nextPageButton.style.display = showNext ? 'inline-flex' : 'none'; if (lastRefreshTime) { lastRefreshTimeSpan.textContent = new Date(lastRefreshTime).toLocaleTimeString(); } - + if (newEntriesCountSpan) { newEntriesCountSpan.textContent = totalItems; } @@ -1255,13 +1256,13 @@ function updateProfitLoss(row, fromCoin, toCoin, fromAmount, toAmount, isOwnOffe } const formattedPercentDiff = percentDiff.toFixed(2); - const percentDiffDisplay = formattedPercentDiff === "0.00" ? "0.00" : + const percentDiffDisplay = formattedPercentDiff === "0.00" ? "0.00" : (percentDiff > 0 ? `+${formattedPercentDiff}` : formattedPercentDiff); const colorClass = getProfitColorClass(percentDiff); profitLossElement.textContent = `${percentDiffDisplay}%`; profitLossElement.className = `profit-loss text-lg font-bold ${colorClass}`; - + const tooltipId = `percentage-tooltip-${row.getAttribute('data-offer-id')}`; const tooltipElement = document.getElementById(tooltipId); if (tooltipElement) { @@ -1310,7 +1311,7 @@ function updateClearFiltersButton() { const hasFilters = hasActiveFilters(); clearButton.classList.toggle('opacity-50', !hasFilters); clearButton.disabled = !hasFilters; - + // Update button styles based on state if (hasFilters) { clearButton.classList.add('hover:bg-green-600', 'hover:text-white'); @@ -1325,10 +1326,10 @@ function updateClearFiltersButton() { function handleNoOffersScenario() { const formData = new FormData(filterForm); const filters = Object.fromEntries(formData); - const hasActiveFilters = filters.coin_to !== 'any' || + const hasActiveFilters = filters.coin_to !== 'any' || filters.coin_from !== 'any' || (filters.status && filters.status !== 'any'); - + stopRefreshAnimation(); if (hasActiveFilters) { @@ -1336,7 +1337,7 @@ function handleNoOffersScenario() {
- No offers match the selected filters. Try different filter options or + No offers match the selected filters. Try different filter options or @@ -1357,7 +1358,7 @@ async function updateOffersTable() { try { const PRICES_CACHE_KEY = 'prices_coingecko'; const cachedPrices = CacheManager.get(PRICES_CACHE_KEY); - + if (!cachedPrices || !cachedPrices.remainingTime || cachedPrices.remainingTime < 60000) { console.log('Fetching fresh price data...'); const priceData = await fetchLatestPrices(); @@ -1374,12 +1375,12 @@ async function updateOffersTable() { const endIndex = Math.min(startIndex + itemsPerPage, validOffers.length); const itemsToDisplay = validOffers.slice(startIndex, endIndex); - const identityPromises = itemsToDisplay.map(offer => + const identityPromises = itemsToDisplay.map(offer => offer.addr_from ? getIdentityData(offer.addr_from) : Promise.resolve(null) ); - + const identities = await Promise.all(identityPromises); - + if (validOffers.length === 0) { handleNoOffersScenario(); return; @@ -1405,7 +1406,7 @@ async function updateOffersTable() { initializeFlowbiteTooltips(); updateRowTimes(); updatePaginationControls(totalPages); - + if (tableRateModule?.initializeTable) { tableRateModule.initializeTable(); } @@ -1482,7 +1483,7 @@ function getIdentityInfo(address, identity) { function createTableRow(offer, identity = null) { const row = document.createElement('tr'); const uniqueId = `${offer.offer_id}_${offer.created_at}`; - + row.className = 'relative opacity-100 text-gray-500 dark:text-gray-100 hover:bg-coolGray-200 dark:hover:bg-gray-600'; row.setAttribute('data-offer-id', uniqueId); @@ -1504,7 +1505,7 @@ function createTableRow(offer, identity = null) { const coinToDisplay = getDisplayName(coinTo); const postedTime = formatTime(createdAt, true); const expiresIn = formatTime(expireAt); - + const currentTime = Math.floor(Date.now() / 1000); const isActuallyExpired = currentTime > expireAt; const fromAmount = parseFloat(amountFrom) || 0; @@ -1585,19 +1586,19 @@ function shouldShowPublicTag(offers) { function truncateText(text, maxLength = 15) { if (typeof text !== 'string') return ''; - return text.length > maxLength - ? text.slice(0, maxLength) + '...' + return text.length > maxLength + ? text.slice(0, maxLength) + '...' : text; } function createDetailsColumn(offer, identity = null) { const addrFrom = offer.addr_from || ''; const identityInfo = getIdentityInfo(addrFrom, identity); - + const showPublicPrivateTags = originalJsonData.some(o => o.is_public !== offer.is_public); - const tagClass = offer.is_public - ? 'bg-green-600 dark:bg-green-600' + const tagClass = offer.is_public + ? 'bg-green-600 dark:bg-green-600' : 'bg-red-500 dark:bg-red-500'; const tagText = offer.is_public ? 'Public' : 'Private'; @@ -1605,16 +1606,16 @@ function createDetailsColumn(offer, identity = null) { identityInfo.label || addrFrom || 'Unspecified' ); - const identifierTextClass = identityInfo.label - ? 'text-white dark:text-white' + const identifierTextClass = identityInfo.label + ? 'text-white dark:text-white' : 'monospace'; - + return `
${showPublicPrivateTags ? `${tagText} ` : ''} - + @@ -1635,8 +1636,8 @@ function createTakerAmountColumn(offer, coinTo, coinFrom) {
-
-
${fromAmount.toFixed(4)}
+
+
${fromAmount.toFixed(4)}
${coinTo}
@@ -1679,8 +1680,8 @@ function createOrderbookColumn(offer, coinFrom, coinTo) {
-
-
${toAmount.toFixed(4)}
+
+
${toAmount.toFixed(4)}
${coinFrom}
@@ -1694,7 +1695,7 @@ function createRateColumn(offer, coinFrom, coinTo) { const inverseRate = 1 / rate; const fromSymbol = getCoinSymbol(coinFrom); const toSymbol = getCoinSymbol(coinTo); - + const getPriceKey = (coin) => { const lowerCoin = coin.toLowerCase(); if (lowerCoin === 'firo' || lowerCoin === 'zcoin') { @@ -1746,9 +1747,9 @@ function createPercentageColumn(offer) { function createActionColumn(offer, isActuallyExpired = false) { const isRevoked = Boolean(offer.is_revoked); const isTreatedAsSentOffer = offer.is_own_offer; - + let buttonClass, buttonText; - + if (isRevoked) { buttonClass = 'bg-red-500 text-white hover:bg-red-600 transition duration-200'; buttonText = 'Revoked'; @@ -1786,14 +1787,14 @@ function createTooltips(offer, treatAsSentOffer, coinFrom, coinTo, fromAmount, t const identityInfo = getIdentityInfo(addrFrom, identity); const totalBids = identity ? ( - identityInfo.stats.sentBidsSuccessful + - identityInfo.stats.recvBidsSuccessful + - identityInfo.stats.sentBidsFailed + - identityInfo.stats.recvBidsFailed + - identityInfo.stats.sentBidsRejected + + identityInfo.stats.sentBidsSuccessful + + identityInfo.stats.recvBidsSuccessful + + identityInfo.stats.sentBidsFailed + + identityInfo.stats.recvBidsFailed + + identityInfo.stats.sentBidsRejected + identityInfo.stats.recvBidsRejected ) : 0; - + const successRate = totalBids ? ( ((identityInfo.stats.sentBidsSuccessful + identityInfo.stats.recvBidsSuccessful) / totalBids) * 100 ).toFixed(1) : 0; @@ -1846,14 +1847,14 @@ function createTooltips(offer, treatAsSentOffer, coinFrom, coinTo, fromAmount, t
- + - + - + - +