Files
basicswap/basicswap/templates/wallets.html
T

816 lines
34 KiB
HTML

{% include 'header.html' %}
{% from 'style.html' import breadcrumb_line_svg, circular_arrows_svg, withdraw_svg, utxo_groups_svg, create_utxo_svg, lock_svg, eye_show_svg %}
<div class="container mx-auto">
<section class="p-5 mt-5">
<div class="flex flex-wrap items-center -m-2">
<div class="w-full md:w-1/2 p-2">
<ul class="flex flex-wrap items-center gap-x-3 mb-2">
<li><a class="flex font-medium text-xs text-coolGray-500 dark:text-gray-300 hover:text-coolGray-700" href="/"><p>Home</p></a></li>
<li>{{ breadcrumb_line_svg | safe }}</li>
<li><a class="flex font-medium text-xs text-coolGray-500 dark:text-gray-300 hover:text-coolGray-700" href="/wallets">Wallets</a></li>
<li>{{ breadcrumb_line_svg | safe }}</li>
</ul>
</div>
</div>
</section>
<section class="py-3">
<div class="container px-4 mx-auto">
<div class="relative py-11 px-16 bg-coolGray-900 dark:bg-blue-500 rounded-md overflow-hidden">
<img class="absolute z-10 left-4 top-4" src="/static/images/elements/dots-red.svg" alt="dots-red">
<img class="absolute z-10 right-4 bottom-4" src="/static/images/elements/dots-red.svg" alt="dots-red">
<img class="absolute h-64 left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 object-cover" src="/static/images/elements/wave.svg" alt="wave">
<div class="relative z-20 flex flex-wrap items-center -m-3">
<div class="w-full md:w-1/2 p-3 h-48">
<h2 class="mb-6 text-4xl font-bold text-white tracking-tighter">Wallets</h2>
<div class="flex items-center">
<h2 class="text-lg font-bold text-white tracking-tighter mr-2">Total Assets:</h2>
<button id="hide-usd-amount-toggle" class="flex items-center justify-center p-1 focus:ring-0 focus:outline-none">{{ eye_show_svg | safe }}</button>
</div>
<div class="flex items-baseline mt-2">
<div id="total-usd-value" class="text-5xl font-bold text-white"></div>
<div id="usd-text" class="text-sm text-white ml-1">USD</div>
</div>
<div id="total-btc-value" class="text-sm text-white mt-2"></div>
</div>
<div class="w-full md:w-1/2 p-3 p-6 container flex flex-wrap items-center justify-end items-center mx-auto">
<a class="rounded-full mr-5 flex flex-wrap justify-center px-5 py-3 bg-blue-500 hover:bg-blue-600 font-medium text-sm text-white border dark:bg-gray-500 dark:hover:bg-gray-700 border-blue-500 rounded-md shadow-button focus:ring-0 focus:outline-none" id="refresh" href="/changepassword">{{ lock_svg | safe }}<span>Change/Set Password</span></a>
<a class="rounded-full flex flex-wrap justify-center px-5 py-3 bg-blue-500 hover:bg-blue-600 font-medium text-sm text-white border dark:bg-gray-500 dark:hover:bg-gray-700 border-blue-500 rounded-md shadow-button focus:ring-0 focus:outline-none" id="refresh" href="/wallets">{{ circular_arrows_svg | safe }}<span>Refresh</span></a>
</div>
</div>
</div>
</div>
</section>
{% include 'inc_messages.html' %}
<section class="py-4">
<div class="container px-4 mx-auto">
<div class="flex flex-wrap -m-4">
{% for w in wallets %}
{% if w.havedata %}
{% if w.error %}<p>Error: {{ w.error }}</p>
{% else %}
<div class="w-full lg:w-1/3 p-4">
<div class="bg-gray-50 rounded overflow-hidden dark:bg-gray-500">
<div class="pt-6 px-6 mb-10 flex justify-between items-center">
<span class="inline-flex items-center justify-center w-9 h-10 bg-white-50 rounded">
<img class="h-9" src="/static/images/coins/{{ w.name }}.png" alt="{{ w.name }}">
</span>
<a class="py-2 px-3 bg-blue-500 text-xs text-white rounded-full hover:bg-blue-600" href="/wallet/{{ w.ticker }}">Manage Wallet</a>
</div>
<div class="px-6 mb-6">
<h4 class="text-xl font-bold dark:text-white">{{ w.name }}
<span class="inline-block font-medium text-xs text-gray-500 dark:text-white">({{ w.ticker }})</span>
</h4>
<p class="text-xs text-gray-500 dark:text-gray-200">Version: {{ w.version }} {% if w.updating %} <span class="inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-700 dark:hover:bg-gray-700">Updating..</span></p>
{% endif %}
</div>
<div class="p-6 bg-coolGray-100 dark:bg-gray-600">
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">Balance:</h4>
<div class="bold inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200 coinname-value" data-coinname="{{ w.name }}">{{ w.balance }} {{ w.ticker }}</div>
</div>
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white usd-text">{{ w.ticker }} USD value:</h4>
<div class="bold inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200 usd-value" data-coinname="{{ w.name }}"></div>
</div>
{% if w.pending %}
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-bold text-green-500 dark:text-green-500">Pending:</h4>
<span class="bold inline-block py-1 px-2 rounded-full bg-green-100 text-xs text-green-500 dark:bg-gray-500 dark:text-green-500 coinname-value" data-coinname="{{ w.name }}">+{{ w.pending }} {{ w.ticker }}</span>
</div>
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-bold text-green-500 dark:text-green-500">Pending USD value:</h4>
<div class="bold inline-block py-1 px-2 rounded-full bg-green-100 text-xs text-green-500 dark:bg-gray-500 dark:text-green-500 usd-value"></div>
</div>
{% endif %}
{% if w.cid == '1' %} {# PART #}
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">Blind Balance:</h4>
<span class="bold inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200 coinname-value" data-coinname="{{ w.name }}">{{ w.blind_balance }} {{ w.ticker }}</span>
</div>
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">Blind USD value:</h4>
<div class="bold inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200 usd-value"></div>
</div>
{% if w.blind_unconfirmed %}
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-bold text-green-500 dark:text-green-500">Blind Unconfirmed:</h4>
<span class="bold inline-block py-1 px-2 rounded-full bg-green-100 text-xs text-green-500 dark:bg-gray-500 dark:text-green-500 coinname-value" data-coinname="{{ w.name }}" >+{{ w.blind_unconfirmed }} {{ w.ticker }}</span>
</div>
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-bold text-green-500 dark:text-green-500">Blind Unconfirmed USD value:</h4>
<div class="bold inline-block py-1 px-2 rounded-full bg-green-100 text-xs text-green-500 dark:bg-gray-500 dark:text-green-500 usd-value"></div>
</div>
{% endif %}
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">Anon Balance:</h4>
<span class="bold inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200 coinname-value" data-coinname="{{ w.name }}">{{ w.anon_balance }} {{ w.ticker }}</span>
</div>
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">Anon USD value:</h4>
<div class="bold inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200 usd-value"></div>
</div>
{% if w.anon_pending %}
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-bold text-green-500 dark:text-green-500">Anon Pending:</h4>
<span class="bold inline-block py-1 px-2 rounded-full bg-green-100 text-xs text-green-500 dark:bg-gray-500 dark:text-green-500 coinname-value" data-coinname="{{ w.name }}">
+{{ w.anon_pending }} {{ w.ticker }}</span>
</div>
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-bold text-green-500 dark:text-green-500">Anon Pending USD value:</h4>
<div class="bold inline-block py-1 px-2 rounded-full bg-green-100 text-xs text-green-500 dark:bg-gray-500 dark:text-green-500 usd-value"></div>
</div>
{% endif %}
{% endif %} {# / PART #}
{% if w.cid == '3' %} {# LTC #}
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">MWEB Balance:</h4>
<span class="bold inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200 coinname-value" data-coinname="{{ w.name }}">{{ w.mweb_balance }} {{ w.ticker }}</span>
</div>
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">MWEB USD value:</h4>
<div class="bold inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200 usd-value"></div>
</div>
{% if w.mweb_pending %}
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-bold text-green-500 dark:text-green-500">MWEB Pending:</h4>
<span class="bold inline-block py-1 px-2 rounded-full bg-green-100 text-xs text-green-500 dark:bg-gray-500 dark:text-green-500 coinname-value" data-coinname="{{ w.name }}">
+{{ w.mweb_pending }} {{ w.ticker }}</span>
</div>
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-bold text-green-500 dark:text-green-500">MWEB Pending USD value:</h4>
<div class="bold inline-block py-1 px-2 rounded-full bg-green-100 text-xs text-green-500 dark:bg-gray-500 dark:text-green-500 usd-value"></div>
</div>
{% endif %}
{% endif %}
{# / LTC #}
<hr class="border-t border-gray-100 dark:border-gray-500 my-5">
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">Blocks:</h4>
<span class="inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200">{{ w.blocks }}{% if w.known_block_count %} / {{ w.known_block_count }}
{% endif %}
</span>
</div>
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">Last Updated:</h4>
<span class="inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200">{{ w.lastupdated }}</span>
</div>
{% if w.bootstrapping %}
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">Bootstrapping:</h4>
<span class="inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200">{{ w.bootstrapping }}</span>
</div>
{% endif %}
{% if w.encrypted %}
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">Locked:</h4>
<span class="inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200">{{ w.locked }}</span>
</div>
{% endif %}
<div class="flex mb-2 justify-between items-center">
<h4 class="text-xs font-medium dark:text-white">Expected Seed:</h4>
<span class="inline-block py-1 px-2 rounded-full bg-blue-100 text-xs text-black-500 dark:bg-gray-500 dark:text-gray-200">{{ w.expected_seed }}</span>
</div>
<div class="flex justify-between mb-1 mt-10">
<span class="text-xs font-medium dark:text-gray-200">Blockchain</span>
<span class="text-xs font-medium dark:text-gray-200">{{ w.synced }}%</span>
</div>
<div class="w-full bg-gray-200 rounded-full h-1 " data-tooltip-target="tooltip-blocks{{loop.index}}">
<div class="{% if w.synced | float < 100 %} bg-red-500 sync-bar-color-change {% else %} bg-blue-500 {% endif %} h-1 rounded-full" style="width: {{ w.synced }}%;"></div>
</div>
<div class="flex justify-between mb-1 mt-5">
<span class="text-xs font-medium dark:text-gray-200">
<script>
if ({{ w.synced }} !== 100) {
document.write("<p class='bg-gray-50 rounded overflow-hidden dark:bg-gray-500 p-2.5 dark:text-white'>The order book/blockchain is currently syncing, offers will only display once the network has fully <b>100%</b> synced. Please wait until the process completes.</p>");
}
</script>
<div id="tooltip-blocks{{loop.index}}" role="tooltip" class="inline-block absolute invisible z-10 py-2 px-3 text-xs text-white {% if w.synced | float < 100 %} bg-red-500 sync-bar-color-change {% else %} bg-blue-500 {% endif %} rounded-lg shadow-sm opacity-0 transition-opacity duration-300 tooltip">
<div><span class="bold">Blocks: {{ w.blocks }}{% if w.known_block_count %} / {{ w.known_block_count }} {% endif %}</div>
<div class="tooltip-arrow pl-1" data-popper-arrow></div>
</div>
</span>
</div>
</div>
</div>
{% endif %}
{% endif %}
</div>
{% endfor %}
</div>
</section>
</div>
{% include 'footer.html' %}
<script>
// Config
const CONFIG = {
MAX_RETRIES: 3,
BASE_DELAY: 1000,
CACHE_EXPIRATION: 5 * 60 * 1000, // 5 minutes
PRICE_UPDATE_INTERVAL: 5 * 60 * 1000, // 5 minutes
API_TIMEOUT: 30000,
DEBOUNCE_DELAY: 500,
CACHE_MIN_INTERVAL: 60 * 1000, // Minimum 1 minute between API calls
MAX_PERCENTAGE_CHANGE: 50, // Max reasonable percentage change (50%)
MIN_VALUE_FOR_PERCENTAGE: 0.01 // Minimum value to calculate percentage changes
};
const STATE_KEYS = {
PERCENTAGE_CHANGE: 'last-percentage-change',
PERCENTAGE_COLOR: 'percentage-change-color',
PERCENTAGE_ICON: 'percentage-change-icon',
LAST_UPDATE: 'last-update-time',
PREVIOUS_TOTAL: 'previous-total-usd',
CURRENT_TOTAL: 'current-total-usd',
BALANCES_VISIBLE: 'balancesVisible'
};
const COIN_SYMBOLS = {
'Bitcoin': 'bitcoin',
'Particl': 'particl',
'Monero': 'monero',
'Wownero': 'wownero',
'Litecoin': 'litecoin',
'Firo': 'zcoin',
'Dash': 'dash',
'PIVX': 'pivx',
'Decred': 'decred',
'Zano': 'zano',
'Bitcoin Cash': 'bitcoin-cash'
};
const SHORT_NAMES = {
'Bitcoin': 'BTC',
'Particl': 'PART',
'Monero': 'XMR',
'Wownero': 'WOW',
'Litecoin': 'LTC',
'Litecoin MWEB': 'LTC MWEB',
'Firo': 'FIRO',
'Dash': 'DASH',
'PIVX': 'PIVX',
'Decred': 'DCR',
'Zano': 'ZANO',
'Bitcoin Cash': 'BCH'
};
// Cache
class Cache {
constructor(expirationTime) {
console.log(`Initializing cache with ${expirationTime/1000} seconds expiration time`);
this.data = null;
this.timestamp = null;
this.expirationTime = expirationTime;
}
isValid() {
console.log('Checking cache validity...');
const isValid = Boolean(
this.data &&
this.timestamp &&
(Date.now() - this.timestamp < this.expirationTime)
);
console.log(`Cache validity check result: ${isValid}`);
if (this.timestamp) {
const age = (Date.now() - this.timestamp) / 1000;
console.log(`Cache age: ${age.toFixed(1)} seconds`);
}
return isValid;
}
set(data) {
console.log('Updating cache with new data');
this.data = data;
this.timestamp = Date.now();
console.log('Cache updated successfully');
}
get() {
console.log('Attempting to retrieve data from cache');
if (this.isValid()) {
console.log('Returning valid cached data');
return this.data;
}
console.log('No valid cached data available');
return null;
}
clear() {
console.log('Clearing cache data');
this.data = null;
this.timestamp = null;
console.log('Cache cleared successfully');
}
}
// API
class ApiClient {
constructor() {
console.log('Initializing API client');
this.cache = new Cache(CONFIG.CACHE_EXPIRATION);
this.lastFetchTime = 0;
}
makeRequest(url, headers = {}) {
console.log(`Making API request to: ${url}`);
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/json/readurl');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.timeout = CONFIG.API_TIMEOUT;
xhr.ontimeout = () => {
console.error('API request timed out');
reject(new Error('Request timed out'));
};
xhr.onload = () => {
if (xhr.status === 200) {
console.log('Received 200 response from API');
try {
const response = JSON.parse(xhr.responseText);
if (response.Error) {
console.error('Error in API response:', response.Error);
reject(new Error(response.Error));
} else {
console.log('Successfully parsed API response');
resolve(response);
}
} catch (error) {
console.error('Failed to parse API response:', error);
reject(new Error(`Invalid JSON response: ${error.message}`));
}
} else {
console.error(`API request failed with status: ${xhr.status}`);
reject(new Error(`HTTP Error: ${xhr.status} ${xhr.statusText}`));
}
};
xhr.onerror = () => {
console.error('Network error occurred during API request');
reject(new Error('Network error occurred'));
};
console.log('Sending API request...');
xhr.send(JSON.stringify({ url, headers }));
});
}
async fetchPrices(forceUpdate = false) {
const now = Date.now();
const timeSinceLastFetch = now - this.lastFetchTime;
if (!forceUpdate && timeSinceLastFetch < CONFIG.CACHE_MIN_INTERVAL) {
console.log(`Skipping API call - only ${(timeSinceLastFetch/1000).toFixed(1)}s since last fetch`);
const cachedData = this.cache.get();
if (cachedData) {
console.log('Using recent cached data');
return cachedData;
}
}
let lastError = null;
for (let attempt = 0; attempt < CONFIG.MAX_RETRIES; attempt++) {
try {
console.log(`Attempting to fetch fresh prices (attempt ${attempt + 1}/${CONFIG.MAX_RETRIES})`);
const prices = await this.makeRequest(
'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,bitcoin-cash,dash,dogecoin,decred,litecoin,particl,pivx,monero,zano,wownero,zcoin&vs_currencies=USD,BTC'
);
console.log('Successfully fetched new prices, updating cache');
this.cache.set(prices);
this.lastFetchTime = now;
return prices;
} catch (error) {
lastError = error;
console.error(`Price fetch attempt ${attempt + 1} failed:`, error);
if (attempt < CONFIG.MAX_RETRIES - 1) {
const delay = Math.min(CONFIG.BASE_DELAY * Math.pow(2, attempt), 10000);
console.log(`Waiting ${delay/1000} seconds before next retry...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
const cachedData = this.cache.get();
if (cachedData) {
console.log('Using cached data after all fetch attempts failed');
return cachedData;
}
console.error('All fetch attempts failed and no cache available');
throw lastError || new Error('Failed to fetch prices');
}
}
class UiManager {
constructor() {
console.log('Initializing UI Manager');
this.api = new ApiClient();
this.toggleInProgress = false;
this.toggleDebounceTimer = null;
this.priceUpdateInterval = null;
this.lastUpdateTime = parseInt(localStorage.getItem(STATE_KEYS.LAST_UPDATE) || '0');
}
getShortName(fullName) {
return SHORT_NAMES[fullName] || fullName;
}
storeOriginalValues() {
console.log('Storing original coin values');
document.querySelectorAll('.coinname-value').forEach(el => {
const coinName = el.getAttribute('data-coinname');
const value = el.textContent?.trim() || '';
if (coinName) {
const amount = value ? parseFloat(value.replace(/[^0-9.-]+/g, '')) : 0;
const coinId = COIN_SYMBOLS[coinName];
const shortName = this.getShortName(coinName);
if (coinId) {
if (coinId === 'particl') {
const isBlind = el.closest('.flex')?.querySelector('h4')?.textContent.includes('Blind');
const isAnon = el.closest('.flex')?.querySelector('h4')?.textContent.includes('Anon');
const balanceType = isBlind ? 'blind' : isAnon ? 'anon' : 'public';
localStorage.setItem(`particl-${balanceType}-amount`, amount.toString());
} else if (coinId === 'litecoin') {
const isMWEB = el.closest('.flex')?.querySelector('h4')?.textContent.includes('MWEB');
const balanceType = isMWEB ? 'mweb' : 'public';
localStorage.setItem(`litecoin-${balanceType}-amount`, amount.toString());
} else {
localStorage.setItem(`${coinId}-amount`, amount.toString());
}
el.setAttribute('data-original-value', `${amount} ${shortName}`);
}
}
});
}
calculatePercentageChange(oldValue, newValue) {
if (!oldValue && !newValue) return 0;
oldValue = parseFloat(oldValue);
newValue = parseFloat(newValue);
if (isNaN(oldValue) || isNaN(newValue)) {
console.log('Invalid values for percentage calculation');
return 0;
}
if (oldValue === 0 && newValue === 0) return 0;
if (oldValue === 0) return 100;
const change = ((newValue - oldValue) / oldValue) * 100;
if (Math.abs(change) > CONFIG.MAX_PERCENTAGE_CHANGE) {
console.log(`Capping extreme percentage change: ${change}%`);
return change > 0 ? CONFIG.MAX_PERCENTAGE_CHANGE : -CONFIG.MAX_PERCENTAGE_CHANGE;
}
return change;
}
getPercentageChangeDisplay(percentageChange) {
let icon, iconColor, text;
const textColor = 'white';
if (percentageChange > 0) {
icon = '▲';
iconColor = 'rgb(34, 197, 94)';
text = `${Math.abs(percentageChange).toFixed(2)}%`;
} else if (percentageChange < 0) {
icon = '▼';
iconColor = 'rgb(239, 68, 68)';
text = `${Math.abs(percentageChange).toFixed(2)}%`;
} else {
icon = '→';
iconColor = 'white';
text = `0.00%`;
}
return {
icon,
color: textColor,
text: `<span style="color: ${iconColor}">${icon}</span> ${text}`,
useHTML: true
};
}
async updatePrices(forceUpdate = false) {
console.log(`Starting price update (force update: ${forceUpdate})`);
try {
const prices = await this.api.fetchPrices(forceUpdate);
const previousTotal = parseFloat(localStorage.getItem(STATE_KEYS.PREVIOUS_TOTAL) || '0');
let newTotal = 0;
const currentTime = Date.now();
localStorage.setItem(STATE_KEYS.LAST_UPDATE, currentTime.toString());
this.lastUpdateTime = currentTime;
if (prices) {
Object.entries(COIN_SYMBOLS).forEach(([coinName, coinId]) => {
if (prices[coinId]?.usd) {
localStorage.setItem(`${coinId}-price`, prices[coinId].usd.toString());
}
});
}
document.querySelectorAll('.coinname-value').forEach(el => {
const coinName = el.getAttribute('data-coinname');
const amountStr = el.getAttribute('data-original-value') || el.textContent?.trim() || '';
if (!coinName) return;
const amount = amountStr ? parseFloat(amountStr.replace(/[^0-9.-]+/g, '')) : 0;
const coinId = COIN_SYMBOLS[coinName];
if (!coinId) return;
const price = prices?.[coinId]?.usd || parseFloat(localStorage.getItem(`${coinId}-price`) || '0');
const usdValue = (amount * price).toFixed(2);
if (coinId === 'particl') {
const isBlind = el.closest('.flex')?.querySelector('h4')?.textContent.includes('Blind');
const isAnon = el.closest('.flex')?.querySelector('h4')?.textContent.includes('Anon');
const balanceType = isBlind ? 'blind' : isAnon ? 'anon' : 'public';
localStorage.setItem(`particl-${balanceType}-last-value`, usdValue);
localStorage.setItem(`particl-${balanceType}-amount`, amount.toString());
} else if (coinId === 'litecoin') {
const isMWEB = el.closest('.flex')?.querySelector('h4')?.textContent.includes('MWEB');
const balanceType = isMWEB ? 'mweb' : 'public';
localStorage.setItem(`litecoin-${balanceType}-last-value`, usdValue);
localStorage.setItem(`litecoin-${balanceType}-amount`, amount.toString());
} else {
localStorage.setItem(`${coinId}-last-value`, usdValue);
localStorage.setItem(`${coinId}-amount`, amount.toString());
}
newTotal += parseFloat(usdValue);
const usdEl = el.closest('.flex')?.nextElementSibling?.querySelector('.usd-value');
if (usdEl) {
usdEl.textContent = `$${usdValue} USD`;
}
});
const percentageChange = this.calculatePercentageChange(previousTotal, newTotal);
this.updateTotalValues(newTotal, prices?.bitcoin?.usd, percentageChange);
localStorage.setItem(STATE_KEYS.PREVIOUS_TOTAL, localStorage.getItem(STATE_KEYS.CURRENT_TOTAL) || '0');
localStorage.setItem(STATE_KEYS.CURRENT_TOTAL, newTotal.toString());
localStorage.setItem(STATE_KEYS.PERCENTAGE_CHANGE, percentageChange.toString());
return true;
} catch (error) {
console.error('Price update failed:', error);
return false;
}
}
updateTotalValues(totalUsd, btcPrice, percentageChange) {
const totalUsdEl = document.getElementById('total-usd-value');
if (totalUsdEl) {
totalUsdEl.textContent = `$${totalUsd.toFixed(2)}`;
totalUsdEl.setAttribute('data-original-value', totalUsd.toString());
localStorage.setItem('total-usd', totalUsd.toString());
}
if (btcPrice) {
const btcTotal = btcPrice ? totalUsd / btcPrice : 0;
const totalBtcEl = document.getElementById('total-btc-value');
if (totalBtcEl) {
totalBtcEl.textContent = `~ ${btcTotal.toFixed(8)} BTC`;
totalBtcEl.setAttribute('data-original-value', btcTotal.toString());
}
}
let percentageChangeEl = document.querySelector('.percentage-change');
if (!percentageChangeEl) {
percentageChangeEl = this.createPercentageChangeElement();
}
if (percentageChangeEl) {
const { color, text, useHTML } = this.getPercentageChangeDisplay(percentageChange);
if (useHTML) {
percentageChangeEl.innerHTML = text;
}
percentageChangeEl.style.color = color;
percentageChangeEl.style.display = 'inline';
}
}
async toggleBalances() {
if (this.toggleInProgress) return;
try {
this.toggleInProgress = true;
const balancesVisible = localStorage.getItem('balancesVisible') === 'true';
const newVisibility = !balancesVisible;
localStorage.setItem('balancesVisible', newVisibility.toString());
this.updateVisibility(newVisibility);
if (this.toggleDebounceTimer) {
clearTimeout(this.toggleDebounceTimer);
}
this.toggleDebounceTimer = window.setTimeout(async () => {
this.toggleInProgress = false;
if (newVisibility) {
await this.updatePrices(true);
}
}, CONFIG.DEBOUNCE_DELAY);
} catch (error) {
console.error('Failed to toggle balances:', error);
this.toggleInProgress = false;
}
}
updateVisibility(isVisible) {
if (isVisible) {
this.showBalances();
} else {
this.hideBalances();
}
const eyeIcon = document.querySelector("#hide-usd-amount-toggle svg");
if (eyeIcon) {
eyeIcon.innerHTML = isVisible ?
'<path d="M23.444,10.239C21.905,8.062,17.708,3,12,3S2.1,8.062,.555,10.24a3.058,3.058,0,0,0,0,3.52h0C2.1,15.938,6.292,21,12,21s9.905-5.062,11.445-7.24A3.058,3.058,0,0,0,23.444,10.239ZM12,17a5,5,0,1,1,5-5A5,5,0,0,1,12,17Z"></path>' :
'<path d="M23.444,10.239a22.936,22.936,0,0,0-2.492-2.948l-4.021,4.021A5.026,5.026,0,0,1,17,12a5,5,0,0,1-5,5,5.026,5.026,0,0,1-.688-.069L8.055,20.188A10.286,10.286,0,0,0,12,21c5.708,0,9.905-5.062,11.445-7.24A3.058,3.058,0,0,0,23.444,10.239Z"></path><path d="M12,3C6.292,3,2.1,8.062,.555,10.24a3.058,3.058,0,0,0,0,3.52h0a21.272,21.272,0,0,0,4.784,4.9l3.124-3.124a5,5,0,0,1,7.071-7.072L8.464,15.536l10.2-10.2A11.484,11.484,0,0,0,12,3Z"></path><path data-color="color-2" d="M1,24a1,1,0,0,1-.707-1.707l22-22a1,1,0,0,1,1.414,1.414l-22,22A1,1,0,0,1,1,24Z"></path>';
}
}
showBalances() {
const usdText = document.getElementById('usd-text');
if (usdText) {
usdText.style.display = 'inline';
}
document.querySelectorAll('.coinname-value').forEach(el => {
const originalValue = el.getAttribute('data-original-value');
if (originalValue) {
el.textContent = originalValue;
}
});
document.querySelectorAll('.usd-value').forEach(el => {
const storedValue = el.getAttribute('data-original-value');
if (storedValue) {
el.textContent = `($${parseFloat(storedValue).toFixed(2)} USD)`;
el.style.color = 'white';
}
});
['total-usd-value', 'total-btc-value'].forEach(id => {
const el = document.getElementById(id);
const originalValue = el?.getAttribute('data-original-value');
if (el && originalValue) {
if (id === 'total-usd-value') {
el.textContent = `$${parseFloat(originalValue).toFixed(2)}`;
el.classList.add('font-extrabold');
} else {
el.textContent = `~ ${parseFloat(originalValue).toFixed(8)} BTC`;
}
}
});
const percentageChangeEl = document.querySelector('.percentage-change');
if (percentageChangeEl) {
const storedPercentage = parseFloat(localStorage.getItem(STATE_KEYS.PERCENTAGE_CHANGE) || '0');
const { text } = this.getPercentageChangeDisplay(storedPercentage);
percentageChangeEl.innerHTML = text;
percentageChangeEl.style.display = 'inline';
}
}
hideBalances() {
console.log('Hiding balances');
const usdText = document.getElementById('usd-text');
if (usdText) {
usdText.style.display = 'none';
}
document.querySelectorAll('.coinname-value, .usd-value').forEach(el => {
el.textContent = '****';
});
['total-usd-value', 'total-btc-value'].forEach(id => {
const el = document.getElementById(id);
if (el) {
el.textContent = '****';
}
});
const percentageChangeEl = document.querySelector('.percentage-change');
if (percentageChangeEl) {
percentageChangeEl.textContent = '****';
percentageChangeEl.style.display = 'none';
}
const totalUsdEl = document.getElementById('total-usd-value');
if (totalUsdEl) {
totalUsdEl.classList.remove('font-extrabold');
}
}
createPercentageChangeElement() {
const totalUsdEl = document.getElementById('total-usd-value');
if (totalUsdEl) {
const percentageChangeEl = document.createElement('span');
percentageChangeEl.className = 'ml-2 text-base percentage-change cursor-help';
totalUsdEl.parentNode.appendChild(percentageChangeEl);
const tooltipId = 'tooltip-percentage';
percentageChangeEl.setAttribute('data-tooltip-target', tooltipId);
if (!document.getElementById(tooltipId)) {
const tooltip = document.createElement('div');
tooltip.id = tooltipId;
tooltip.role = 'tooltip';
tooltip.className = 'inline-block absolute invisible z-50 py-2 px-3 text-sm font-medium text-white bg-gray-500 rounded-lg shadow-sm opacity-0 transition-opacity duration-300 tooltip';
tooltip.innerHTML = `
Price change since last update<br>
<span style="color: rgb(34, 197, 94);">▲ Green:</span><span> Price increased</span><br>
<span style="color: rgb(239, 68, 68);">▼ Red:</span><span> Price decreased</span><br>
<span style="color: white;">→ White:</span><span> No change</span>
`;
document.body.appendChild(tooltip);
if (typeof Tooltip !== 'undefined') {
new Tooltip(tooltip, percentageChangeEl);
}
}
return percentageChangeEl;
}
return null;
}
async initialize() {
console.log('Initializing UI Manager...');
this.storeOriginalValues();
if (localStorage.getItem('balancesVisible') === null) {
localStorage.setItem('balancesVisible', 'true');
}
const hideBalancesToggle = document.getElementById('hide-usd-amount-toggle');
if (hideBalancesToggle) {
hideBalancesToggle.addEventListener('click', () => this.toggleBalances());
}
await this.loadBalanceVisibility();
if (this.priceUpdateInterval) {
clearInterval(this.priceUpdateInterval);
}
this.priceUpdateInterval = setInterval(() => {
if (localStorage.getItem('balancesVisible') === 'true' && !this.toggleInProgress) {
this.updatePrices(false);
}
}, CONFIG.PRICE_UPDATE_INTERVAL);
}
async loadBalanceVisibility() {
const balancesVisible = localStorage.getItem('balancesVisible') === 'true';
this.updateVisibility(balancesVisible);
if (balancesVisible) {
await this.updatePrices(true);
}
}
}
// Cleanup
window.addEventListener('beforeunload', () => {
console.log('Page unloading, cleaning up...');
const uiManager = window.uiManager;
if (uiManager?.priceUpdateInterval) {
clearInterval(uiManager.priceUpdateInterval);
console.log('Cleared price update interval');
}
});
// Initialize
window.addEventListener('load', () => {
console.log('Page loaded, starting application initialization');
const uiManager = new UiManager();
window.uiManager = uiManager; // Store reference for cleanup
uiManager.initialize().catch(error => {
console.error('Failed to initialize application:', error);
});
});
console.log('Loaded..');
</script>
</body>
</html>