Обновить учёт поддержки, лайки и профиль перед MVP

This commit is contained in:
AidarKC
2026-12-02 00:01:51 +03:00
parent d05d9db8a2
commit af0beccb4a
21 changed files with 109 additions and 57 deletions
+15 -13
View File
@@ -1,6 +1,7 @@
import { t } from '../i18n/index.js';
import { getShowPublicHistoryWarning, setShowPublicHistoryWarning, getPublicHistoryRememberLabel } from '../services/public-history-consent.js';
import { confirmPublicHistoryAction } from '../services/public-history-consent.js';
import { openSheet } from './sheet.js';
import { iconHtml } from './ui-icon.js';
function safeCount(raw, maximum = Infinity) {
const count = Number(raw);
@@ -9,7 +10,6 @@ function safeCount(raw, maximum = Infinity) {
// Значения счётчиков получены от сервера, это не криптографическая аттестация личности.
export function confirmLikeAction(options = {}) {
if (!getShowPublicHistoryWarning()) return Promise.resolve(true);
return openLikeSheet(options);
}
@@ -21,6 +21,7 @@ export function showLikeStatistics({ counts = {}, onViewList = null } = {}) {
function openLikeSheet({ liked = false, counts = {}, onViewList = null, readOnly = false } = {}) {
return new Promise((resolve) => {
let accepted = false;
let confirming = false;
const all = safeCount(counts.all ?? counts.likesCount);
const official = safeCount(counts.official ?? counts.primaryLikesCount, all);
const shining = safeCount(counts.shining ?? counts.shiningLikesCount, official);
@@ -49,19 +50,16 @@ function openLikeSheet({ liked = false, counts = {}, onViewList = null, readOnly
number.textContent = String(count);
const name = document.createElement('span');
name.textContent = label;
item.append(number, name);
const heart = document.createElement('span');
heart.className = 'like-consent-heart';
heart.innerHTML = iconHtml('heart', true);
heart.setAttribute('aria-hidden', 'true');
item.append(heart, number, name);
grid.append(item);
});
const warning = document.createElement('p');
warning.className = 'meta-muted';
warning.textContent = t('dialogs.modals.like_action_sheet.label_002');
const rememberLabel = document.createElement('label');
rememberLabel.className = 'confirm-dialog__remember';
const remember = document.createElement('input');
remember.type = 'checkbox';
const rememberText = document.createElement('span');
rememberText.textContent = getPublicHistoryRememberLabel();
rememberLabel.append(remember, rememberText);
const actions = document.createElement('div');
actions.className = 'form-actions-grid';
const cancel = document.createElement('button');
@@ -75,10 +73,14 @@ function openLikeSheet({ liked = false, counts = {}, onViewList = null, readOnly
if (readOnly) actions.append(cancel);
else actions.append(cancel, confirm);
body.append(intro, grid);
if (!readOnly) body.append(warning, rememberLabel);
body.append(actions);
const sheet = openSheet({ title: t('dialogs.modals.like_action_sheet.label_005'), className: 'like-consent-sheet', content: body, onClose: () => resolve(accepted) });
const sheet = openSheet({ title: t('dialogs.modals.like_action_sheet.label_005'), className: 'like-consent-sheet', content: body, onClose: () => { if (!confirming) resolve(accepted); } });
cancel.addEventListener('click', () => sheet.close());
confirm.addEventListener('click', () => { if (remember.checked) setShowPublicHistoryWarning(false); accepted = true; sheet.close(); });
confirm.addEventListener('click', async () => {
confirming = true;
sheet.close();
accepted = await confirmPublicHistoryAction({ text: warning.textContent });
resolve(accepted);
});
});
}
+16 -2
View File
@@ -83,7 +83,8 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
<span class="pf-row-label">${th('screens.profile_card.text_019')}</span>
<p class="pf-row-text">${esc(spiritualPath)}</p>
</div>` : '';
const listInner = aboutRow + contacts + pathRow;
const detailButtons = (contacts || pathRow) ? `<div class="pf-detail-actions">${contacts ? `<button type="button" class="ui-button" data-profile-detail="contacts">${th('screens.profile_card.text_008')}</button>` : ''}${pathRow ? `<button type="button" class="ui-button" data-profile-detail="path">${th('screens.profile_card.text_019')}</button>` : ''}</div>` : '';
const listInner = aboutRow + detailButtons + (contacts ? `<div class="pf-detail-panel" data-profile-panel="contacts" hidden>${contacts}</div>` : '') + (pathRow ? `<div class="pf-detail-panel" data-profile-panel="path" hidden>${pathRow}</div>` : '');
const listHtml = listInner.trim() ? `<div class="pf-list">${listInner}</div>` : '';
const friends = Number(stats.friendsCount || 0);
const closeFriends = Number(stats.closeFriendsCount || 0);
@@ -115,7 +116,7 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
<span class="pf-stat-relation"><strong class="pf-stat-value">${closeFriends}</strong><span class="pf-stat-label">${esc(t('remaining.share.close_friends'))}</span></span>
<span class="pf-stat-relation"><strong class="pf-stat-value">${friends}</strong><span class="pf-stat-label">${esc(t('screens.profile_card.text_003'))}</span></span>
</button>
${statHtml({ kind: 'channels_owned', label: t('screens.profile_card.text_004'), valueHtml: String(Number(stats.ownedPublicChannelsCount || 0)), ariaLabel: t('screens.profile_card.text_015', { value1: Number(stats.ownedPublicChannelsCount || 0) }) })}
${statHtml({ kind: 'channels_owned', label: t('screens.profile_card.text_004'), valueHtml: String(Math.max(0, Number(stats.ownedPublicChannelsCount || 0) - 1)), ariaLabel: t('screens.profile_card.text_015', { value1: Math.max(0, Number(stats.ownedPublicChannelsCount || 0) - 1) }) })}
${statHtml({ kind: 'channels_following', label: t('screens.profile_card.text_005'), valueHtml: String(Number(stats.followingChannelsCount || 0)), ariaLabel: t('screens.profile_card.text_016', { value1: Number(stats.followingChannelsCount || 0) }) })}
</div>
@@ -128,6 +129,19 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
${listHtml}`;
}
export function attachProfileDetails(root) {
root.querySelectorAll('[data-profile-detail]').forEach((button) => {
button.addEventListener('click', async () => {
const panel = root.querySelector(`[data-profile-panel="${button.dataset.profileDetail}"]`);
if (!panel) return;
const { openSheet } = await import('./sheet.js');
const content = panel.cloneNode(true);
content.hidden = false;
openSheet({ title: button.textContent.trim(), content });
});
});
}
export function profileTileHtml({ icon, label, attrs = '', iconMarkup = '' }) {
return `<button type="button" class="pf-tile user-profile-action-btn" ${attrs}>${iconMarkup || iconHtml(icon)}<span>${esc(label)}</span></button>`;
}
@@ -4,7 +4,7 @@ import { readShineUserPda, supportShineUserOnSolana, supportShineDaoOnSolana } f
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
import { getWalletFromStoredBlockchainKey, transferSolLamports, solanaAddressFromPublicKeyBase64 } from '../services/solana-wallet-service.js';
import { bytesToBase58 } from '../services/crypto-utils.js';
import { parseStarCents, formatStars, splitStarCents, starCentsToLamports, formatLamportsSol } from '../services/shine-support-amount.js';
import { parseStarCents, formatStars, formatExactStars, splitStarCents, starCentsToLamports, formatLamportsSol } from '../services/shine-support-amount.js';
import { toUserMessage } from '../services/ui-error-texts.js';
import { getStarsQuoteFromRpc } from '../services/shine-stars-pyth.js';
@@ -34,7 +34,7 @@ export function openShineSupportDialog({ recipientLogin = '', target = { type: 0
input.type = 'text';
input.inputMode = 'decimal';
input.autocomplete = 'off';
input.placeholder = '0.10';
input.placeholder = '0.1';
const details = document.createElement('p');
details.className = 'meta-muted';
const status = document.createElement('p');
@@ -69,8 +69,8 @@ export function openShineSupportDialog({ recipientLogin = '', target = { type: 0
const split = splitStarCents(cents);
const sol = quote ? ` · ≈ ${formatLamportsSol(starCentsToLamports(cents, quote.solUsdE8, quote.usdtUsdE8))} SOL` : '';
details.textContent = dao ? `${formatStars(cents)}${sol}` :
`${t('screens.support_phase2.recipient')}: ${formatStars(split.author)} · ${t('screens.support_phase2.fund')}: ${formatStars(split.dao)}${sol}`;
} catch { details.textContent = 'Минимум 0,10 ⭐'; }
`${t('screens.support_phase2.recipient')}: ${formatExactStars(split.author)} · ${t('screens.support_phase2.fund')}: ${formatExactStars(split.dao)}${sol}`;
} catch { details.textContent = 'Минимум 0,1 ⭐'; }
};
input.addEventListener('input', update);
amountLabel.textContent = 'Сумма поддержки, ⭐';
+2 -2
View File
@@ -51,10 +51,10 @@ function renderAmount(cents, sign = '') {
value.className = 'profile-support-amount__value';
value.setAttribute('aria-hidden', 'true');
value.dataset.cents = String(cents);
value.textContent = `${sign}${formatStarAmount(cents)}`;
value.textContent = formatStarAmount(cents) ? `${sign}${formatStarAmount(cents)}` : '';
const spoken = document.createElement('span');
spoken.className = 'sr-only';
spoken.textContent = `${sign}${formatStars(cents)}`;
spoken.textContent = formatStarAmount(cents) ? `${sign}${formatStars(cents)}` : '⭐';
wrap.append(value);
wrap.insertAdjacentHTML('beforeend', iconHtml('star', true, 'profile-support-amount__star'));
wrap.append(spoken);
+3 -3
View File
@@ -15,7 +15,7 @@ import { toUserMessage } from '../services/ui-error-texts.js';
import { bytesToBase58 } from '../services/crypto-utils.js';
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
import { readShineUserPda, supportShineUserOnSolana } from '../services/shine-user-pda-service.js';
import { parseStarCents, splitStarCents, formatStars, starCentsToLamports, formatLamportsSol, hexHash32 } from '../services/shine-support-amount.js';
import { parseStarCents, splitStarCents, formatStars, formatExactStars, starCentsToLamports, formatLamportsSol, hexHash32 } from '../services/shine-support-amount.js';
import { transferSolLamports } from '../services/solana-wallet-service.js';
import { getStarsQuoteFromRpc } from '../services/shine-stars-pyth.js';
import { loadVerifiedSupportTotals, formatVerifiedSupportStars } from '../services/support-totals-service.js';
@@ -296,8 +296,8 @@ export function render({ navigate, route, chrome }) {
const cents = parseStarCents(amountEl?.value || '');
const parts = splitStarCents(cents);
const sol = starsQuote ? ` · ≈ ${formatLamportsSol(starCentsToLamports(cents, starsQuote.solUsdE8, starsQuote.usdtUsdE8))} SOL` : '';
if (splitEl) splitEl.textContent = `${t('screens.support_flow.recipient')}: ${formatStars(parts.author)} · ${t('screens.support_flow.fund')}: ${formatStars(parts.dao)}${sol}`;
} catch { if (splitEl) splitEl.textContent = 'Минимальная поддержка 0,10 ⭐'; }
if (splitEl) splitEl.textContent = `${t('screens.support_flow.recipient')}: ${formatExactStars(parts.author)} · ${t('screens.support_flow.fund')}: ${formatExactStars(parts.dao)}${sol}`;
} catch { if (splitEl) splitEl.textContent = 'Минимальная поддержка 0,1 ⭐'; }
};
void getStarsQuoteFromRpc({ solanaEndpoint: state.entrySettings.solanaServer }).then(v => { starsQuote = v; if (!disposed) renderSplit(); })
.catch(() => { if (splitEl && !disposed) splitEl.textContent = 'Курс временно недоступен'; });
+10 -1
View File
@@ -8,6 +8,7 @@ import { openBlockchainDetailsModal } from '../components/blockchain-details-dia
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
import { publicLikeCount, hasLikeStatistics } from '../services/public-like-count.js';
import { iconHtml } from '../components/ui-icon.js';
import { loadUserProfileCard } from '../services/user-connections.js';
import { consumeReplyEditorOnOpen, rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
import { attachMessageMenu } from '../components/message-menu.js';
import { createTopBar } from '../components/topbar.js';
@@ -802,6 +803,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
likeButton.className = 'ui-button channel-action-item channel-action-like thread-like-btn';
if (isLiked) likeButton.classList.add('is-liked');
likeButton.innerHTML = `
${handlers.viewerShining ? `<span class="channel-action-counter">${Number(node?.shiningLikesCount || 0)}</span>` : ''}
<span class="channel-action-icon" aria-hidden="true">${iconHtml('heart', isLiked)}</span>
<span class="channel-action-label">${isPending ? t('screens.channel_thread_view.text_062') : t('screens.channel_thread_view.text_063')}</span>
`;
@@ -1168,7 +1170,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
const like = document.createElement('button');
like.type = 'button';
like.className = `channel-action-item thread-comment__like${liked ? ' is-liked' : ''}`;
like.innerHTML = `${iconHtml('heart', liked)}`;
like.innerHTML = `${handlers.viewerShining ? `<span class="channel-action-counter">${Number(node?.shiningLikesCount || 0)}</span>` : ''}${iconHtml('heart', liked)}`;
like.setAttribute('aria-pressed', String(liked));
like.setAttribute('aria-label', `${liked ? t('dialogs.modals.channel_thread_view.label_026') : t('screens.channel_thread_view.text_067')}, ${likes}`);
like.addEventListener('click', async () => {
@@ -1571,6 +1573,7 @@ export function prefetchThreadPage(path) {
}
export function render({ navigate, route, chrome }) {
let viewerShining = false;
let selector = parseThreadSelector(route);
const channelDisplayName = resolveChannelDisplayName(selector?.channel);
const routeKey = selector?.publicationOrdinal
@@ -1653,6 +1656,7 @@ export function render({ navigate, route, chrome }) {
// Пришли по «Обсуждение» из ленты – после первой загрузки сразу открыть редактор ответа.
let openEditorOnLoad = consumeReplyEditorOnOpen(window.location.pathname);
const handlers = {
get viewerShining() { return viewerShining; },
onSupport: (node, target) => {
const rootNumber = selector?.channel?.channelRootBlockNumber;
const rootHash = String(selector?.channel?.channelRootBlockHash || '').trim();
@@ -2238,5 +2242,10 @@ export function render({ navigate, route, chrome }) {
};
void refresh();
if (state.session.login) void loadUserProfileCard(state.session.login).then((profile) => {
if (disposed) return;
viewerShining = profile?.shineStatus === 'shining';
if (viewerShining) void refresh();
}).catch(() => {});
return screen;
}
+13 -2
View File
@@ -9,6 +9,7 @@ import { openBlockchainDetailsModal } from '../components/blockchain-details-dia
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
import { publicLikeCount, hasLikeStatistics } from '../services/public-like-count.js';
import { iconHtml } from '../components/ui-icon.js';
import { loadUserProfileCard } from '../services/user-connections.js';
import { createOverflowDots } from '../components/overflow-dots.js';
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
import { getPreviousTrackedPath, navigateUp, parseRouteFromPath, toPrettyPath } from '../router.js';
@@ -1784,6 +1785,7 @@ function openMessageLikesListModal({ navigate, messageRef, initialTab = 'shining
function renderPostCard(post, {
navigate,
selector,
viewerShining = false,
onToggleLike,
onReply,
onRating,
@@ -1997,6 +1999,7 @@ function renderPostCard(post, {
const isLiked = post.reactionState === 'liked';
if (isLiked) likeButton.classList.add('is-liked');
likeButton.innerHTML = `
${viewerShining ? `<span class="channel-action-counter">${Number(post.shiningLikesCount || 0)}</span>` : ''}
<span class="channel-action-icon" aria-hidden="true">${iconHtml('heart', isLiked)}</span>
<span class="channel-action-label">${isPending ? t('screens.channel_view.text_096') : t('screens.channel_view.text_097')}</span>
`;
@@ -2140,7 +2143,7 @@ function renderPostCard(post, {
const supportButton = document.createElement('button');
supportButton.type = 'button';
supportButton.className = 'ui-button channel-action-item channel-action-support';
supportButton.textContent = '♥ SOL';
supportButton.textContent = '⭐';
supportButton.title = t('screens.support_phase2.donate');
// Проверенные сервером суммы; если индексатор не готов, число не показываем.
if (post.messageRef?.blockNumber != null && post.messageRef?.blockHash) {
@@ -2148,7 +2151,7 @@ function renderPostCard(post, {
void loadVerifiedSupportTotals(selector).then((totals) => {
if (!totals || !supportButton.isConnected) return;
const formatted = formatVerifiedSupportStars(totals.messages.get(messageId));
if (formatted) supportButton.textContent = `♥ ${formatted}`;
if (formatted) supportButton.textContent = formatted;
});
}
@@ -2363,6 +2366,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
}
const row = renderPostCard(item.post, {
navigate,
viewerShining: handlers.viewerShining,
selector: channelData.selector,
onToggleLike: handlers.onToggleLike,
onReply: handlers.onReply,
@@ -2547,6 +2551,7 @@ function renderSkeleton(screen) {
}
export function render({ navigate, route, chrome }) {
let viewerShining = false;
const channelId = route.params.channelId || '';
const scrollToMessageOrdinal = route.params.scrollToMessageOrdinal || '';
const routeSelector = buildSelectorFromRoute(route, channelId);
@@ -3068,6 +3073,7 @@ export function render({ navigate, route, chrome }) {
}
clearContent();
const stopSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
viewerShining,
chrome,
restorePosition,
scrollToMessageOrdinal,
@@ -3247,5 +3253,10 @@ export function render({ navigate, route, chrome }) {
};
void refresh();
if (state.session.login) void loadUserProfileCard(state.session.login).then((profile) => {
if (disposed) return;
viewerShining = profile?.shineStatus === 'shining';
if (viewerShining) void refresh();
}).catch(() => {});
return screen;
}
+2 -1
View File
@@ -5,7 +5,7 @@ import { state } from '../state.js';
import { attachProfileAvatarPreview } from '../components/profile-avatar-preview.js';
import { createTopBar } from '../components/topbar.js';
import { loadUserProfileCard } from '../services/user-connections.js';
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
import { profileCardHtml, profileTileHtml, attachProfileDetails } from '../components/profile-card.js';
import { openShareSheet } from '../components/share-sheet.js';
import { createErrorState, createLoadingState } from '../components/feedback.js';
import { makeSharedProfileRoute } from '../services/shine-routes.js';
@@ -64,6 +64,7 @@ export function render({ navigate, chrome }) {
].join(''),
});
attachProfileDetails(body);
attachSupportStats(body, { login: card.login || login, isActive: () => !disposed });
avatarPreview = attachProfileAvatarPreview(body.querySelector('.user-profile-avatar-slot'), card);
+2 -1
View File
@@ -10,7 +10,7 @@ import { createErrorState, createLoadingState } from '../components/feedback.js'
import { toUserMessage } from '../services/ui-error-texts.js';
import { makeProfileLinksRoute } from '../services/shine-routes.js';
import { navigateBack } from '../router.js';
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
import { profileCardHtml, profileTileHtml, attachProfileDetails } from '../components/profile-card.js';
import { iconHtml } from '../components/ui-icon.js';
export const pageMeta = { id: 'user', get title() { return t('screens.user_profile_view.text_001'); } };
@@ -72,6 +72,7 @@ export function render({ navigate, route, chrome }) {
])].join(''),
});
attachProfileDetails(body);
attachSupportStats(body, { login: card.login, isActive: () => !disposed });
syncRelationTile();
+10 -4
View File
@@ -19,10 +19,10 @@ export function hexHash32(value) {
return Uint8Array.from({ length: 32 }, (_, i) => parseInt(hex.slice(i * 2, i * 2 + 2), 16));
}
/** Integer Star cents: 0.10 minimum, exactly two decimal places maximum. */
/** Сумма поддержки: минимум и шаг 0,1 звезды. */
export function parseStarCents(input) {
const value = String(input ?? '').trim().replace(',', '.');
if (!/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/.test(value)) throw new Error('Введите сумму ⭐ с точностью до 0,01');
if (!/^(?:0|[1-9]\d*)(?:\.\d{1})?$/.test(value)) throw new Error('Введите сумму ⭐ с точностью до 0,1');
const [whole, frac = ''] = value.split('.');
const cents = BigInt(whole) * 100n + BigInt(frac.padEnd(2, '0') || '0');
if (cents < 10n || cents > 0xffff_ffff_ffff_ffffn) throw new Error('Минимальная поддержка — 0,10 ⭐');
@@ -31,10 +31,16 @@ export function parseStarCents(input) {
/** Только число («0.10»): для вёрстки, где единица показана отдельной SVG-иконкой. */
export function formatStarAmount(value) {
const cents = BigInt(value);
return `${cents / 100n}.${String(cents % 100n).padStart(2, '0')}`;
const tenths = (cents + 5n) / 10n;
return tenths === 0n ? '' : `${tenths / 10n}.${tenths % 10n}`;
}
export function formatStars(value) {
return `${formatStarAmount(value)} ⭐`;
const amount = formatStarAmount(value);
return amount ? `${amount} ⭐` : '⭐';
}
export function formatExactStars(value) {
const cents = BigInt(value);
return `${cents / 100n}.${String(cents % 100n).padStart(2, '0')} ⭐`;
}
export function splitStarCents(value) {
const cents = BigInt(value);
@@ -1,4 +1,5 @@
import { authService } from '../state.js';
import { formatStars } from './shine-support-amount.js';
// Один запрос на канал; только сервер проверяет привязку транзакции к блоку.
const cache = new Map();
@@ -26,9 +27,6 @@ export function loadVerifiedSupportTotals(selector) {
export function formatVerifiedSupportStars(value) {
try {
const n = BigInt(value);
if (n <= 0n) return null;
const whole = n / 100n;
const fraction = String(n % 100n).padStart(2, '0');
return `${whole}.${fraction} ⭐`;
return formatStars(n);
} catch { return null; }
}
+1
View File
@@ -74,6 +74,7 @@
.like-consent-count { display: grid; justify-items: center; align-content: center; gap: 5px; min-width: 0; padding: 12px 6px; border: 1px solid var(--border-control); border-radius: 12px; color: var(--text-primary); background: var(--surface-raised); text-align: center; font: inherit; }
.like-consent-count > strong { font-size: 1.3rem; font-variant-numeric: tabular-nums; }
.like-consent-count > span { font-size: .73rem; line-height: 1.3; color: var(--text-secondary); }
.like-consent-count .like-consent-heart { color: var(--accent); }
button.like-consent-count { cursor: pointer; }
button.like-consent-count:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.like-consent-sheet .sheet__card { width: min(100%, 420px); }
@@ -120,6 +120,8 @@
.user-profile-screen .pf-tile img { width: 24px; height: 24px; object-fit: contain; filter: none; }
.user-profile-screen .pf-list { display: grid; border: 1px solid var(--border-subtle); border-radius: var(--radius-lg); background: var(--surface); overflow: hidden; }
.user-profile-screen .pf-detail-actions { display: flex; justify-content: space-between; gap: 12px; padding: 8px 12px; }
.user-profile-screen .pf-detail-panel[hidden] { display: none; }
.user-profile-screen .pf-row { display: grid; gap: 2px; padding: 12px 14px; border-top: 1px solid var(--border-subtle); }
.user-profile-screen .pf-row:first-child { border-top: 0; }
.user-profile-screen .pf-row-label { color: var(--text-secondary); font-size: var(--text-xs); line-height: var(--leading-xs); }
+12 -7
View File
@@ -1,19 +1,24 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { parseStarCents, formatStars, splitStarCents, starCentsToLamports } from '../js/services/shine-support-amount.js';
test('strictly two fractional digits, minimum 0.10 Stars', () => {
assert.equal(parseStarCents('0,10'), 10n);
assert.equal(parseStarCents('0.75'), 75n);
assert.equal(formatStars(75n), '0.75 ⭐');
test('one fractional digit, minimum 0.1 Stars', () => {
assert.equal(parseStarCents('0,1'), 10n);
assert.equal(parseStarCents('0.7'), 70n);
assert.equal(formatStars(70n), '0.7 ⭐');
assert.equal(formatStars(100n), '1.0 ⭐');
assert.equal(formatStars(0n), '⭐');
assert.equal(formatStars(9n), '0.1 ⭐');
assert.equal(formatStars(15n), '0.2 ⭐');
assert.throws(() => parseStarCents('0.09'));
assert.throws(() => parseStarCents('0.001'));
assert.throws(() => parseStarCents('0.11'));
});
test('DAO star share rounds UP to cents', () => {
assert.deepEqual(splitStarCents(10n), {author: 9n, dao: 1n});
assert.deepEqual(splitStarCents(15n), {author: 13n, dao: 2n});
assert.deepEqual(splitStarCents(75n), {author: 67n, dao: 8n});
assert.deepEqual(splitStarCents(20n), {author: 18n, dao: 2n});
assert.deepEqual(splitStarCents(70n), {author: 63n, dao: 7n});
});
test('quote works in integer lamports without floats', () => {
assert.equal(starCentsToLamports(75n, 150n * 100_000_000n, 100_000_000n), 5_000_000n);
assert.equal(starCentsToLamports(70n, 150n * 100_000_000n, 100_000_000n), 4_666_667n);
assert.equal(starCentsToLamports(10n, 150n * 100_000_000n, 100_000_000n), 666_667n);
});