Добавить систему поддержки SHiNE

This commit is contained in:
AidarKC
2026-11-12 11:01:31 +03:00
parent 6b120731a3
commit c97df82538
34 changed files with 1323 additions and 52 deletions
@@ -0,0 +1,125 @@
import { t } from '../i18n/index.js';
import { authService, state } from '../state.js';
import { readShineUserPda, supportShineUserOnSolana, supportShineDaoOnSolana } from '../services/shine-user-pda-service.js';
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 { parseSolLamports, formatLamportsSol } from '../services/shine-support-amount.js';
import { toUserMessage } from '../services/ui-error-texts.js';
/** One shared payment dialog for profiles, posts and donations to the SHiNE economy. */
export function openShineSupportDialog({ recipientLogin = '', target = { type: 0 }, onSuccess = () => {} } = {}) {
const dao = !recipientLogin;
const login = String(state.session.login || '').trim();
if (!login) { window.alert(t('screens.support_phase2.login_required')); return; }
if (!dao && login.toLowerCase() === String(recipientLogin).trim().toLowerCase()) {
window.alert(t('screens.support_phase2.self_support')); return;
}
const overlay = document.createElement('div');
overlay.className = 'shine-support-dialog-overlay';
overlay.style.cssText = 'position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.66);display:flex;align-items:center;justify-content:center;padding:16px;';
const panel = document.createElement('section');
panel.className = 'card stack shine-support-dialog';
panel.style.cssText = 'width:min(100%,440px);max-height:90vh;overflow:auto;padding:20px;gap:12px;';
const header = document.createElement('h2');
header.textContent = dao ? t('screens.support_phase2.donate_shine') : t('screens.support_phase2.donate');
const description = document.createElement('p');
description.className = 'meta-muted';
description.textContent = dao ? t('screens.support_phase2.dao_info') : `${t('screens.support_phase2.to')} ${recipientLogin}`;
const amountLabel = document.createElement('label');
amountLabel.textContent = t('screens.support_phase2.amount');
const input = document.createElement('input');
input.className = 'input';
input.type = 'text';
input.inputMode = 'decimal';
input.autocomplete = 'off';
input.placeholder = '0.01';
const details = document.createElement('p');
details.className = 'meta-muted';
const status = document.createElement('p');
status.setAttribute('role', 'status');
status.className = 'meta-muted';
const donate = document.createElement('button');
donate.type = 'button';
donate.className = 'primary-btn';
donate.textContent = t('screens.support_phase2.donate');
const direct = document.createElement('button');
direct.type = 'button';
direct.className = 'secondary-btn';
direct.textContent = t('screens.support_phase2.direct');
const cancel = document.createElement('button');
cancel.type = 'button';
cancel.className = 'text-btn';
cancel.textContent = t('screens.support_phase2.close');
panel.append(header, description, amountLabel, input, details, status, donate);
if (!dao) panel.append(direct);
panel.append(cancel);
overlay.append(panel);
document.body.append(overlay);
let busy = false;
let closed = false;
const close = () => { if (busy) return; closed = true; overlay.remove(); };
cancel.addEventListener('click', close);
overlay.addEventListener('click', (event) => { if (event.target === overlay) close(); });
const update = () => {
if (dao) { details.textContent = t('screens.support_phase2.dao_info'); return; }
try {
const amount = parseSolLamports(input.value);
details.textContent = amount % 10n === 0n
? `${t('screens.support_phase2.recipient')}: ${formatLamportsSol(amount * 9n / 10n)} SOL · ${t('screens.support_phase2.fund')}: ${formatLamportsSol(amount / 10n)} SOL`
: t('screens.support_phase2.divisible');
} catch { details.textContent = t('screens.support_phase2.explanation'); }
};
input.addEventListener('input', update);
update();
const send = async (isDirect) => {
if (busy || closed) return;
let amount;
try {
amount = parseSolLamports(input.value);
if (!dao && !isDirect && amount % 10n !== 0n) throw new Error(t('screens.support_phase2.divisible'));
} catch (error) { status.textContent = error.message; return; }
if (isDirect && !window.confirm(t('screens.support_phase2.direct_warning'))) return;
busy = true;
donate.disabled = direct.disabled = cancel.disabled = input.disabled = true;
status.textContent = t('screens.support_phase2.sending');
try {
const { storagePwdInMemory: password } = state.session;
const endpoint = state.entrySettings.solanaServer;
let result;
if (isDirect) {
let address = '';
try {
const pda = await readShineUserPda({ login: recipientLogin, solanaEndpoint: endpoint });
address = bytesToBase58(pda.forks.at(-1).blockchainKey);
} catch {
const recipient = await authService.getUser(recipientLogin);
if (!recipient?.exists) throw new Error(t('screens.support_phase2.unavailable'));
address = solanaAddressFromPublicKeyBase64(recipient.blockchainKey);
}
const wallet = await getWalletFromStoredBlockchainKey({ login, storagePwd: password });
result = await transferSolLamports({ endpoint, fromKeypair: wallet.keypair, toAddress: address, amountLamports: amount });
} else {
const secrets = await loadEncryptedUserSecrets(login, password);
if (!secrets?.blockchainKey || !secrets?.clientKey) throw new Error(t('screens.support_phase2.keys_required'));
const args = { senderLogin: login, amountLamports: amount, solanaEndpoint: endpoint, blockchainPrivatePkcs8B64: secrets.blockchainKey, clientPrivatePkcs8B64: secrets.clientKey };
result = dao ? await supportShineDaoOnSolana(args) : await supportShineUserOnSolana({ ...args, recipientLogin, target });
}
status.textContent = `${t('screens.support_phase2.success')} ${result.signature || ''}`;
try { onSuccess(result); } catch { /* page may have been closed */ }
donate.hidden = true;
direct.hidden = true;
cancel.disabled = false;
cancel.textContent = t('screens.support_phase2.close');
} catch (error) {
status.textContent = toUserMessage(error, t('screens.support_phase2.failed'));
} finally {
busy = false;
donate.disabled = direct.disabled = cancel.disabled = input.disabled = false;
}
};
donate.addEventListener('click', () => void send(false));
direct.addEventListener('click', () => void send(true));
input.focus();
return overlay;
}
+50
View File
@@ -0,0 +1,50 @@
import { t } from '../i18n/index.js';
import { readShineUserPda } from '../services/shine-user-pda-service.js';
import { formatLamportsSol } from '../services/shine-support-amount.js';
export function supportStatsValues(stats = {}) {
const sent = BigInt(stats.supportSent ?? 0);
const received = BigInt(stats.supportReceived ?? 0);
const daoDirect = BigInt(stats.daoDirect ?? 0);
return [sent, received, sent / 10n + daoDirect];
}
/** Adds an independent asynchronous block; failure/Free accounts do not get fictitious statistics. */
export function attachSupportStats(parent, { login, solanaEndpoint, isActive = () => true }) {
const section = document.createElement('section');
section.className = 'card stack profile-support-stats';
section.style.cssText = 'margin-top:12px;gap:8px;';
const title = document.createElement('strong');
title.textContent = t('screens.support_phase2.statistics');
const content = document.createElement('div');
content.className = 'meta-muted';
content.textContent = t('screens.support_phase2.loading');
section.append(title, content);
parent.append(section);
const refresh = async () => {
try {
const pda = await readShineUserPda({ login, solanaEndpoint });
if (!isActive() || !section.isConnected) return;
const values = supportStatsValues(pda.supportStats ?? {});
content.replaceChildren();
content.className = 'stack';
[t('screens.support_phase2.sent'), t('screens.support_phase2.received'), t('screens.support_phase2.shine')].forEach((label, idx) => {
const row = document.createElement('div');
row.className = 'row';
row.style.cssText = 'display:flex;justify-content:space-between;gap:8px;';
const name = document.createElement('span');
const amount = document.createElement('strong');
name.textContent = label;
amount.textContent = `${formatLamportsSol(values[idx])} SOL`;
row.append(name, amount);
content.append(row);
});
} catch {
if (!isActive() || !section.isConnected) return;
// A missing Paid PDA means Free, but network errors must not be displayed as zero.
content.textContent = t('screens.support_phase2.unavailable');
}
};
void refresh();
return { element: section, refresh };
}
+41
View File
@@ -4211,6 +4211,47 @@
"error": "Could not load connections. Check your connection or try another user.",
"clearing": "Clearing cache…",
"a11y": "Center: {value1}. {value2} users shown on the map."
},
"support_flow": {
"donate": "Donate · 90% to creator",
"direct": "Transfer directly · 100%",
"recipient": "To creator",
"fund": "To SHiNE economy",
"explanation": "10% goes to the SHiNE economy fund. This transfer counts toward public support statistics.",
"paid_required": "The recipient needs a paid Solana PDA for tracked support. Direct transfers remain available.",
"divisible": "The amount must be divisible by 10 lamports.",
"direct_warning": "The recipient will get 100%. Direct transfers are NOT counted in SHiNE support statistics because they bypass anti-manipulation checks. Continue?",
"keys_required": "Saved blockchain and client keys are required on this device for tracked support."
},
"support_phase2": {
"statistics": "Support",
"loading": "Loading support totals…",
"sent": "❤️ Supported others",
"received": "💚 Support received",
"shine": "✨ Supported SHiNE",
"unavailable": "Totals unavailable (Free account or Solana error)",
"donate_shine": "✨ Support SHiNE",
"donate": "Donate",
"to": "Recipient:",
"amount": "Amount, SOL",
"recipient": "Recipient",
"fund": "SHiNE economy",
"dao_info": "100% of your donation goes to the SHiNE economic fund and participates in its existing payout system.",
"direct": "Direct transfer — 100%",
"direct_warning": "The recipient gets 100%. Direct transfers are not included in SHiNE support totals because they bypass the verified anti-manipulation mechanism. Continue?",
"divisible": "Tracked support must be divisible by 10 lamports",
"explanation": "90% to recipient, 10% to the SHiNE economy; included in public support totals.",
"login_required": "Sign in to SHiNE to transfer",
"self_support": "You cannot support yourself",
"keys_required": "Cannot find keys needed for tracked support",
"sending": "Sending transfer…",
"success": "Transfer confirmed:",
"failed": "Transfer failed",
"close": "Close",
"invalid_target": "This post has no verified block number or hash"
},
"support_phase3": {
"channel_total": "Channel support received"
}
},
"errors": {
+41
View File
@@ -4211,6 +4211,47 @@
"error": "Не удалось загрузить связи. Проверьте соединение или попробуйте другого пользователя.",
"clearing": "Очистка кэша…",
"a11y": "Центр: {value1}. На карте {value2} пользователей."
},
"support_flow": {
"donate": "Пожертвовать · 90% автору",
"direct": "Перевести напрямую · 100%",
"recipient": "Автору",
"fund": "Экономике SHiNE",
"explanation": "10% поступает в экономический фонд SHiNE. Перевод учитывается в статистике поддержки.",
"paid_required": "Для учитываемой поддержки автору нужен платный Solana PDA. Прямой перевод доступен.",
"divisible": "Сумма должна быть кратна 10 lamports.",
"direct_warning": "Получатель получит 100% суммы. Прямой перевод НЕ учитывается в статистике поддержки SHiNE, так как не проходит проверяемую защиту от накруток. Продолжить?",
"keys_required": "Для учитываемой поддержки нужны сохранённые blockchain и client ключи на этом устройстве."
},
"support_phase2": {
"statistics": "Поддержка",
"loading": "Загрузка статистики…",
"sent": "❤️ Поддержал других",
"received": "💚 Получил поддержку",
"shine": "✨ Поддержал SHiNE",
"unavailable": "Статистика недоступна (Free или ошибка Solana)",
"donate_shine": "✨ Поддержать SHiNE",
"donate": "Пожертвовать",
"to": "Получатель:",
"amount": "Сумма, SOL",
"recipient": "Получателю",
"fund": "Экономике SHiNE",
"dao_info": "100% пожертвования поступает в экономический фонд SHiNE и участвует в действующей системе выплат.",
"direct": "Перевести напрямую — 100%",
"direct_warning": "Получатель получит всю сумму. Прямой перевод не учитывается в статистике поддержки SHiNE, поскольку не проходит проверяемую защиту от накруток. Продолжить?",
"divisible": "Для учитываемого перевода сумма должна быть кратной 10 lamports",
"explanation": "90% получателю, 10% на развитие экономики SHiNE; учитывается в статистике.",
"login_required": "Войдите в SHiNE, чтобы отправить перевод",
"self_support": "Нельзя поддерживать самого себя",
"keys_required": "Не найдены ключи для отправки учитываемой поддержки",
"sending": "Отправка перевода…",
"success": "Перевод подтверждён:",
"failed": "Не удалось отправить перевод",
"close": "Закрыть",
"invalid_target": "Для этой публикации отсутствует проверенный номер или хеш блока"
},
"support_phase3": {
"channel_total": "Канал получил поддержку"
}
},
"errors": {
+86 -44
View File
@@ -9,10 +9,15 @@ import {
getSolanaWalletFromStoredSecret,
getWalletFromStoredBlockchainKey,
solanaAddressFromPublicKeyBase64,
transferSol,
} from '../services/solana-wallet-service.js';
import { showToast } from '../services/channels-ux.js';
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 { parseSolLamports, formatLamportsSol, hexHash32 } from '../services/shine-support-amount.js';
import { transferSolLamports } from '../services/solana-wallet-service.js';
import { loadVerifiedSupportTotals, formatVerifiedSupportLamports } from '../services/support-totals-service.js';
export const pageMeta = { id: 'channel-donate-view', get title() { return t('screens.channel_donate_view.text_001'); } };
@@ -135,12 +140,14 @@ export function render({ navigate, route, chrome }) {
walletCache.clear();
};
const renderDonationForm = ({ channel, selector, ownerUser }) => {
const renderDonationForm = ({ channel, selector, ownerUser, recipientPda }) => {
const ownerLogin = String(channel?.ownerLogin || extractLoginFromBlockchainName(selector?.ownerBlockchainName) || '').trim();
const channelTitle = String(channel?.displayTitle || channel?.displayName || channel?.channelName || t('screens.channel_donate_view.text_018')).trim();
const channelName = String(channel?.channelName || selector?.channelName || '').trim();
const recipientChoices = [
publicKeyChoice(ownerUser, 'blockchainKey', 'blockchain-key', 'Blockchain key'),
recipientPda?.forks?.length
? { id: 'blockchain-key', label: 'Blockchain key', address: bytesToBase58(recipientPda.forks.at(-1).blockchainKey) }
: publicKeyChoice(ownerUser, 'blockchainKey', 'blockchain-key', 'Blockchain key'),
].filter(Boolean);
content.innerHTML = `
@@ -149,6 +156,7 @@ export function render({ navigate, route, chrome }) {
<strong>${escapeHtml(channelTitle)}</strong>
<span>${escapeHtml(formatChannelAddress({ ownerLogin, channelName }))}</span>
</div>
<div class="meta-muted" id="channel-donate-verified-total"></div>
<section class="channel-donate-section">
<label class="field-label" for="channel-donate-blockchain">${th('screens.channel_donate_view.text_024')}</label>
@@ -180,14 +188,17 @@ export function render({ navigate, route, chrome }) {
<section class="channel-donate-section">
<label class="field-label" for="channel-donate-amount">${th('screens.channel_donate_view.text_029')}</label>
<div class="channel-donate-amount-row">
<input class="input" id="channel-donate-amount" type="number" min="0" step="0.000001" inputmode="decimal" placeholder="0.1" />
<input class="input" id="channel-donate-amount" type="text" inputmode="decimal" placeholder="0.1" autocomplete="off" />
<span>SOL</span>
</div>
</section>
<p class="meta-muted" id="channel-donate-split"></p>
<p class="meta-muted" id="channel-donate-explanation"></p>
<p class="meta-muted inline-error channel-donate-status" id="channel-donate-status"></p>
<div class="channel-donate-result" id="channel-donate-result" hidden></div>
<button class="primary-btn channel-donate-submit" id="channel-donate-submit" type="button" ${recipientChoices.length ? '' : 'disabled'}>${th('screens.channel_donate_view.text_030')}</button>
<button class="primary-btn channel-donate-submit" id="channel-donate-submit" type="button" ${recipientChoices.length && recipientPda ? '' : 'disabled'}>${th('screens.support_flow.donate')}</button>
<button class="secondary-btn channel-donate-submit" id="channel-donate-direct" type="button" ${recipientChoices.length ? '' : 'disabled'}>${th('screens.support_flow.direct')}</button>
`;
const recipientSelect = content.querySelector('#channel-donate-recipient-key');
@@ -200,10 +211,14 @@ export function render({ navigate, route, chrome }) {
const resultEl = content.querySelector('#channel-donate-result');
const submitEl = content.querySelector('#channel-donate-submit');
const refreshEl = content.querySelector('#channel-donate-refresh');
const directEl = content.querySelector('#channel-donate-direct');
const splitEl = content.querySelector('#channel-donate-split');
const explanationEl = content.querySelector('#channel-donate-explanation');
const setBusy = (nextBusy) => {
busy = Boolean(nextBusy);
if (submitEl) submitEl.disabled = busy || recipientChoices.length === 0;
if (submitEl) submitEl.disabled = busy || recipientChoices.length === 0 || !recipientPda;
if (directEl) directEl.disabled = busy || recipientChoices.length === 0;
if (refreshEl) refreshEl.disabled = busy;
if (recipientSelect) recipientSelect.disabled = busy || recipientChoices.length === 0;
if (senderSelect) senderSelect.disabled = busy;
@@ -274,60 +289,83 @@ export function render({ navigate, route, chrome }) {
});
refreshEl?.addEventListener('click', () => void refreshBalance());
submitEl?.addEventListener('click', async () => {
const renderSplit = () => {
try {
const amount = parseSolLamports(amountEl?.value || '');
if (splitEl) splitEl.textContent = `${t('screens.support_flow.recipient')}: ${formatLamportsSol(amount * 9n / 10n)} SOL · ${t('screens.support_flow.fund')}: ${formatLamportsSol(amount / 10n)} SOL`;
} catch { if (splitEl) splitEl.textContent = ''; }
};
if (explanationEl) explanationEl.textContent = recipientPda
? t('screens.support_flow.explanation')
: t('screens.support_flow.paid_required');
amountEl?.addEventListener('input', renderSplit);
const submitTransfer = async (direct) => {
if (busy || disposed) return;
const recipient = selectedRecipient();
if (!recipient?.address) {
setStatus(t('screens.channel_donate_view.text_007'), 'error');
return;
}
const amount = Number(String(amountEl?.value || '').replace(',', '.'));
if (!Number.isFinite(amount) || amount <= 0) {
setStatus(t('screens.channel_donate_view.text_008'), 'error');
return;
}
if (!recipient?.address) { setStatus(t('screens.channel_donate_view.text_007'), 'error'); return; }
let amount;
try {
amount = parseSolLamports(amountEl?.value || '');
if (!direct && amount % 10n !== 0n) throw new Error(t('screens.support_flow.divisible'));
} catch (error) { setStatus(error.message || t('screens.channel_donate_view.text_008'), 'error'); return; }
if (direct && !window.confirm(t('screens.support_flow.direct_warning'))) return;
setBusy(true);
setStatus(t('screens.channel_donate_view.text_009'));
if (resultEl) {
resultEl.hidden = true;
resultEl.innerHTML = '';
}
if (resultEl) { resultEl.hidden = true; resultEl.innerHTML = ''; }
try {
const wallet = await resolveSenderWallet();
const result = await transferSol({
endpoint: state.entrySettings.solanaServer,
fromKeypair: wallet.keypair,
toAddress: recipient.address,
amountSol: amount,
});
let result;
if (direct) {
// Свежий ключ читается перед отправкой; если PDA есть, он приоритетнее серверного профиля.
let address = recipient.address;
if (recipientPda) {
const fresh = await readShineUserPda({ login: ownerLogin, solanaEndpoint: state.entrySettings.solanaServer });
const key = fresh.forks.at(-1).blockchainKey;
address = bytesToBase58(key);
} else {
const latest = await authService.getUser(ownerLogin);
address = publicKeyChoice(latest, 'blockchainKey', 'blockchain-key', 'Blockchain key')?.address || '';
if (!address) throw new Error(t('screens.channel_donate_view.text_007'));
}
result = await transferSolLamports({ endpoint: state.entrySettings.solanaServer, fromKeypair: wallet.keypair, toAddress: address, amountLamports: amount });
} else {
if (!recipientPda) throw new Error(t('screens.support_flow.paid_required'));
const { login, storagePwdInMemory: storagePwd } = state.session;
const secrets = await loadEncryptedUserSecrets(login, storagePwd);
if (!secrets?.blockchainKey || !secrets?.clientKey) throw new Error(t('screens.support_flow.keys_required'));
result = await supportShineUserOnSolana({
senderLogin: login, recipientLogin: ownerLogin, amountLamports: amount,
target: { type: 1, channelBlockNumber: BigInt(selector.channelRootBlockNumber), channelBlockHash: hexHash32(selector.channelRootBlockHash) },
solanaEndpoint: state.entrySettings.solanaServer,
blockchainPrivatePkcs8B64: secrets.blockchainKey,
clientPrivatePkcs8B64: secrets.clientKey,
});
}
if (disposed) return;
setStatus('');
if (resultEl) {
resultEl.hidden = false;
resultEl.innerHTML = `
<strong>${th('screens.channel_donate_view.text_031')}</strong>
<span>${escapeHtml(formatSol(amount))} SOL → ${escapeHtml(recipient.label)}</span>
<code>${escapeHtml(String(result.signature || ''))}</code>
`;
resultEl.innerHTML = `<strong>${th('screens.channel_donate_view.text_031')}</strong><span>${escapeHtml(formatLamportsSol(amount))} SOL → ${escapeHtml(recipient.label)}</span><code>${escapeHtml(String(result.signature || ''))}</code>`;
}
showToast(t('screens.channel_donate_view.text_010'));
const balance = await getBalanceSol({
endpoint: state.entrySettings.solanaServer,
address: wallet.address,
});
const balance = await getBalanceSol({ endpoint: state.entrySettings.solanaServer, address: wallet.address });
if (!disposed && balanceEl) balanceEl.textContent = `${formatSol(balance.sol)} SOL`;
} catch (error) {
if (!disposed) setStatus(toUserMessage(error, t('screens.channel_donate_view.text_011')), 'error');
} finally {
if (!disposed) setBusy(false);
}
});
} finally { if (!disposed) setBusy(false); }
};
submitEl?.addEventListener('click', () => void submitTransfer(false));
directEl?.addEventListener('click', () => void submitTransfer(true));
renderSplit();
void loadVerifiedSupportTotals(selector).then((totals) => {
if (disposed) return;
const label = content.querySelector('#channel-donate-verified-total');
const total = totals && formatVerifiedSupportLamports(totals.channelReceivedLamports);
if (label && total) label.textContent = `${t('screens.support_phase3.channel_total')}: ${total}`;
});
updateRecipientAddress();
if (!recipientChoices.length) {
setStatus(t('screens.channel_donate_view.text_012'), 'error');
@@ -351,7 +389,11 @@ export function render({ navigate, route, chrome }) {
if (disposed || seq !== refreshSeq) return;
if (!ownerUser?.exists) throw new Error(t('screens.channel_donate_view.text_022'));
renderDonationForm({ channel, selector, ownerUser });
let recipientPda = null;
try { recipientPda = await readShineUserPda({ login: ownerLogin, solanaEndpoint: state.entrySettings.solanaServer }); }
catch { /* Free пользователь: доступен только прямой перевод. */ }
if (disposed || seq !== refreshSeq) return;
renderDonationForm({ channel, selector, ownerUser, recipientPda });
} catch (error) {
if (disposed || seq !== refreshSeq) return;
content.innerHTML = `
+33
View File
@@ -1,3 +1,5 @@
import { openShineSupportDialog } from '../components/shine-support-dialog.js';
import { hexHash32 } from '../services/shine-support-amount.js';
import { formatDateTime } from '../i18n/format.js';
import { t, th } from '../i18n/index.js';
import { appendShineMessageLinks } from '../services/shine-message-links.js';
@@ -954,6 +956,14 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
});
if (threadsLayout) actions.append(likeButton, ...(likes > 0 ? [likesStatsButton] : []), discussionButton, repostButton, shareButton);
else actions.append(likeButton, ...(likes > 0 ? [likesStatsButton] : []), shareButton, discussionButton);
const supportBtn = document.createElement('button');
supportBtn.type = 'button';
supportBtn.className = 'ui-button channel-action-item channel-action-support';
supportBtn.textContent = '♥ SOL';
supportBtn.title = t('screens.support_phase2.donate');
supportBtn.addEventListener('click', (event) => { event.stopPropagation(); handlers.onSupport?.(node, target); });
actions.append(supportBtn);
menuItems.unshift({ label: t('screens.channel_thread_view.text_009'), iconHtml: iconHtml('reply'), action: () => replyButton.click() });
// Те же действия, что у ответов в обсуждении.
menuItems.splice(1, 0, { label: t('screens.channel_thread_view.text_010'), iconHtml: iconHtml('copy'), action: async () => {
@@ -1257,6 +1267,14 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
// Ряд действий как у записи канала: лайк, ответы, репост, поделиться.
actions.append(like, ...(likes > 0 ? [commentLikeStats] : []), reply, repost, share);
const supportBtn = document.createElement('button');
supportBtn.type = 'button';
supportBtn.className = 'channel-action-item thread-comment__support';
supportBtn.textContent = '♥ SOL';
supportBtn.title = t('screens.support_phase2.donate');
supportBtn.addEventListener('click', (event) => { event.stopPropagation(); handlers.onSupport?.(node, target); });
actions.append(supportBtn);
main.append(actions);
item.append(who, main);
// Как в Threads: нажатие на ответ открывает его обсуждение (кнопки, ссылки и вложения работают сами по себе).
@@ -1678,6 +1696,21 @@ export function render({ navigate, route, chrome }) {
// Пришли по «Обсуждение» из ленты – после первой загрузки сразу открыть редактор ответа.
let openEditorOnLoad = consumeReplyEditorOnOpen(window.location.pathname);
const handlers = {
onSupport: (node, target) => {
const rootNumber = selector?.channel?.channelRootBlockNumber;
const rootHash = String(selector?.channel?.channelRootBlockHash || '').trim();
const messageHash = String(target?.blockHash || '').trim();
const recipientLogin = String(node?.authorLogin || '').trim();
if (!recipientLogin || !Number.isSafeInteger(Number(rootNumber))
|| !/^[0-9a-f]{64}$/i.test(rootHash) || !/^[0-9a-f]{64}$/i.test(messageHash)) {
showToast(t('screens.support_phase2.invalid_target'), { kind: 'error' });
return;
}
openShineSupportDialog({ recipientLogin, target: {
type: 2, channelBlockNumber: BigInt(rootNumber), channelBlockHash: hexHash32(rootHash),
messageBlockNumber: BigInt(target.blockNumber), messageBlockHash: hexHash32(messageHash),
} });
},
navigate,
isActive: () => !disposed,
openReplyEditor: (node) => replyEditorOpener?.(node),
+36
View File
@@ -1,3 +1,6 @@
import { openShineSupportDialog } from '../components/shine-support-dialog.js';
import { hexHash32 } from '../services/shine-support-amount.js';
import { loadVerifiedSupportTotals, formatVerifiedSupportLamports } from '../services/support-totals-service.js';
import { formatDateTime, getIntlLocale } from '../i18n/format.js';
import { t, th } from '../i18n/index.js';
import { appendShineMessageLinks } from '../services/shine-message-links.js';
@@ -2155,9 +2158,42 @@ function renderPostCard(post, {
if (!REPOSTS_ENABLED) { notifyRepostSoon(); return; }
void onRepost?.(post.messageRef);
});
// Support posts through the verified on-chain 90/10 flow (separate from likes).
const supportButton = document.createElement('button');
supportButton.type = 'button';
supportButton.className = 'ui-button channel-action-item channel-action-support';
supportButton.textContent = '♥ SOL';
supportButton.title = t('screens.support_phase2.donate');
// Проверенные сервером суммы; если индексатор не готов, число не показываем.
if (post.messageRef?.blockNumber != null && post.messageRef?.blockHash) {
const messageId = `${String(post.messageRef.blockNumber)}:${String(post.messageRef.blockHash).toLowerCase()}`;
void loadVerifiedSupportTotals(selector).then((totals) => {
if (!totals || !supportButton.isConnected) return;
const formatted = formatVerifiedSupportLamports(totals.messages.get(messageId));
if (formatted) supportButton.textContent = `♥ ${formatted}`;
});
}
supportButton.addEventListener('click', (event) => {
event.stopPropagation();
const messageRef = post.messageRef;
const rootHash = String(selector?.channelRootBlockHash || '');
const msgHash = String(messageRef?.blockHash || '');
const recipient = String(post.authorLogin || '').trim();
if (!recipient || !/^[0-9a-f]{64}$/i.test(rootHash) || !/^[0-9a-f]{64}$/i.test(msgHash)) {
showToast(t('screens.support_phase2.invalid_target'), { kind: 'error' });
return;
}
openShineSupportDialog({ recipientLogin: recipient, target: {
type: 2,
channelBlockNumber: BigInt(selector.channelRootBlockNumber), channelBlockHash: hexHash32(rootHash),
messageBlockNumber: BigInt(messageRef.blockNumber), messageBlockHash: hexHash32(msgHash),
} });
});
// Четыре кнопки как в Threads: лайк, ответы, репост, поделиться.
if (threadsLayout) actions.append(likeButton, ...(Number(post.likesCount) > 0 ? [likesStatsButton] : []), discussionButton, repostButton, shareButton);
else actions.append(likeButton, ...(Number(post.likesCount) > 0 ? [likesStatsButton] : []), shareButton, discussionButton);
actions.append(supportButton);
if (selector?.publicOrdinalUrlsAllowed && post.messageRef?.blockNumber != null) {
const streamRoute = makeShineChannelStreamRoute({
ownerBlockchainName: selector?.ownerBlockchainName,
+2
View File
@@ -1,3 +1,4 @@
import { attachSupportStats } from '../components/support-stats.js';
import { t, th } from '../i18n/index.js';
import { profile } from '../mock-data.js';
import { state } from '../state.js';
@@ -66,6 +67,7 @@ export function render({ navigate, chrome }) {
<button class="nav-row" type="button" data-self-profile-action="profiles"><span class="nav-row__label">${th('screens.profile_view.text_015')}</span><span class="nav-row__hint">${th('screens.profile_view.text_016')}</span></button>
</div>`;
attachSupportStats(body, { login: card.login || login, solanaEndpoint: state.entrySettings.solanaServer, isActive: () => !disposed });
avatarPreview = attachProfileAvatarPreview(body.querySelector('.user-profile-avatar-slot'), card);
status.replaceChildren();
+8
View File
@@ -1,3 +1,5 @@
import { openShineSupportDialog } from '../components/shine-support-dialog.js';
import { attachSupportStats } from '../components/support-stats.js';
import { t } from '../i18n/index.js';
import { createTopBar } from '../components/topbar.js';
import { SHINE_CONNECTIONS_LOGO_SRC } from '../components/shine-logo.js';
@@ -61,9 +63,11 @@ export function render({ navigate, route, chrome }) {
profileTileHtml({ icon: 'user-plus', label: t('screens.user_profile_view.text_004'), attrs: 'data-profile-action="add"' }),
profileTileHtml({ label: t('screens.user_profile_view.text_005'), attrs: 'data-profile-action="links"', iconMarkup: `<img class="pf-tile-mandala" src="${SHINE_CONNECTIONS_LOGO_SRC}" alt="" aria-hidden="true">` }),
profileTileHtml({ icon: 'message', label: t('screens.user_profile_view.text_006'), attrs: 'data-profile-action="chat"' }),
profileTileHtml({ icon: 'heart', label: t('screens.support_phase2.donate'), attrs: 'data-profile-action="support"' }),
].join(''),
});
attachSupportStats(body, { login: card.login, solanaEndpoint: state.entrySettings.solanaServer, isActive: () => !disposed });
syncRelationTile();
avatarPreview = attachProfileAvatarPreview(body.querySelector('.user-profile-avatar-slot'), card);
@@ -121,6 +125,10 @@ export function render({ navigate, route, chrome }) {
navigate(makeProfileLinksRoute(card.login));
return;
}
if (action === 'support') {
openShineSupportDialog({ recipientLogin: card.login, onSuccess: () => { if (!disposed) renderProfile(); } });
return;
}
if (action === 'chat') {
navigate(`chat/${encodeURIComponent(card.login)}`);
}
+3
View File
@@ -1,3 +1,4 @@
import { openShineSupportDialog } from '../components/shine-support-dialog.js';
import { formatDateTime, formatNumber } from '../i18n/format.js';
import { t, th } from '../i18n/index.js';
import { getSolanaCluster, confirmSolanaTransactionHttp } from '../services/solana-rpc-gateway.js';
@@ -1867,10 +1868,12 @@ export function render({navigate, chrome}) {
<button class="primary-btn" id="refresh-balance" style="flex:1;">${th('screens.wallet_view.text_293')}</button>
<button class="primary-btn" id="send-sol" style="flex:1;">${th('screens.wallet_view.text_294')}</button>
</div>
<button class="secondary-btn" id="donate-shine" type="button">${th('screens.support_phase2.donate_shine')}</button>
`;
const refreshBtn = actions.querySelector('#refresh-balance');
const sendBtn = actions.querySelector('#send-sol');
actions.querySelector('#donate-shine')?.addEventListener('click', () => openShineSupportDialog({ onSuccess: () => void refreshBalance() }));
const refreshBalance = async () => {
if (!walletAddress) {
+10
View File
@@ -1598,6 +1598,16 @@ export class AuthService {
return response.payload || {};
}
async getSupportTotals(channel) {
const payload = {
channelRootBlockNumber: Number(channel?.channelRootBlockNumber),
channelRootBlockHash: String(channel?.channelRootBlockHash || '').trim(),
};
const response = await this.ws.request('GetSupportTotals', payload);
if (response.status !== 200) throw opError('GetSupportTotals', response);
return response.payload || {};
}
async getMessageThread(message, depthUp = 20, depthDown = 2, limitChildrenPerNode = 50, login = '') {
const normalizedMessage = {
blockchainName: String(message?.blockchainName || '').trim(),
@@ -4,4 +4,6 @@ export {
getShineBlockchainUsage,
getShineUsersEconomyConfig,
updateShineUserPdaOnSolana,
supportShineUserOnSolana,
supportShineDaoOnSolana,
} from './shine-user-pda-service.js';
@@ -0,0 +1,20 @@
/** Точная денежная арифметика для пожертвований SHiNE: без Number. */
export function parseSolLamports(input) {
const text = String(input ?? '').trim().replace(',', '.');
if (!/^(?:0|[1-9]\d*)(?:\.\d{1,9})?$/.test(text)) throw new Error('Введите положительную сумму SOL (не более 9 знаков после запятой)');
const [whole, fraction = ''] = text.split('.');
const amount = BigInt(whole) * 1_000_000_000n + BigInt(fraction.padEnd(9, '0') || '0');
if (amount <= 0n || amount > 0xffff_ffff_ffff_ffffn) throw new Error('Сумма SOL вне допустимого диапазона');
return amount;
}
export function formatLamportsSol(value) {
const n = BigInt(value);
const sign = n < 0n ? '-' : '';
const abs = n < 0n ? -n : n;
return sign + String(abs / 1_000_000_000n) + (abs % 1_000_000_000n ? '.' + String(abs % 1_000_000_000n).padStart(9, '0').replace(/0+$/, '') : '');
}
export function hexHash32(value) {
const hex = String(value || '').trim().toLowerCase();
if (!/^[0-9a-f]{64}$/.test(hex)) throw new Error('Некорректный 32-байтовый хеш блока канала');
return Uint8Array.from({ length: 32 }, (_, i) => parseInt(hex.slice(i * 2, i * 2 + 2), 16));
}
+59 -1
View File
@@ -33,6 +33,8 @@ const AUTH_MODE_ROOT = 1;
const IX_CREATE_USER_PDA = 3;
const IX_UPDATE_USER_PDA = 4;
const IX_CLOSE_LEGACY_USER_PDA = 6;
const IX_SUPPORT_USER = 9;
const IX_SUPPORT_DAO = 10;
const DAY_MS = 86_400_000n;
const FORK_COOLDOWN_MS = 3n * DAY_MS;
const MAX_EFFECTIVE_ACCESS_SERVERS = 1;
@@ -288,7 +290,14 @@ export function parseShineUserPda(dataBytes) {
const blocksOffset = reader.offset;
const signature = bytes.slice(recordLen - 64, recordLen);
const unsignedBytes = bytes.slice(0, recordLen - 64);
const header = { formatMajor, formatMinor, recordLen, createdAtMs, updatedAtMs, recordNumber, prevRecordHash, login, blocksCount, blocksOffset, signature, unsignedBytes };
let supportStats = { version: 0, supportSent: 0n, supportReceived: 0n, daoDirect: 0n };
if (recordLen < bytes.length && bytes[recordLen] !== 0) {
if (bytes[recordLen] !== 1) throw new Error('Неподдерживаемая версия статистики поддержки');
if (recordLen + 25 > bytes.length) throw new Error('Обрезан блок статистики поддержки');
const statsReader = makeReader(bytes.slice(recordLen + 1, recordLen + 25));
supportStats = { version: 1, supportSent: statsReader.readU64(), supportReceived: statsReader.readU64(), daoDirect: statsReader.readU64() };
}
const header = { formatMajor, formatMinor, recordLen, createdAtMs, updatedAtMs, recordNumber, prevRecordHash, login, blocksCount, blocksOffset, signature, unsignedBytes, supportStats };
return parseV12Pda(bytes, header);
}
@@ -815,3 +824,52 @@ export function calcLimitTopupPriceLamports(additionalLimitBytes, lamportsPerLim
}
export function getLimitStepBytes() { return LIMIT_STEP; }
function supportData(tag, senderLogin, recipientLogin, amountLamports, target) {
const out = [tag];
const putString = (value) => { const bytes = new TextEncoder().encode(String(value)); if (bytes.length > 255) throw new Error('Слишком длинный login'); out.push(bytes.length, ...bytes); };
putString(senderLogin);
if (recipientLogin != null) putString(recipientLogin);
pushU64LE(out, amountLamports);
if (target != null) {
out.push(target.type);
if (target.type === 1 || target.type === 2) { pushU64LE(out, target.channelBlockNumber); out.push(...toUint8Array(target.channelBlockHash, 32)); }
if (target.type === 2) { pushU64LE(out, target.messageBlockNumber); out.push(...toUint8Array(target.messageBlockHash, 32)); }
}
return new Uint8Array(out);
}
/** Выполняет учитываемую поддержку через shine_users без Number и округлений. */
export async function supportShineUserOnSolana({ senderLogin, recipientLogin, amountLamports, target = { type: 0 }, solanaEndpoint, blockchainPrivatePkcs8B64, clientPrivatePkcs8B64 }) {
const amount = BigInt(amountLamports);
if (amount <= 0n || amount % 10n !== 0n) throw new Error('Сумма учитываемой поддержки должна быть положительной и кратной 10 lamports');
const sender = await readShineUserPda({ login: senderLogin, solanaEndpoint });
const recipient = await readShineUserPda({ login: recipientLogin, solanaEndpoint });
const ctx = await buildCommonContext({ login: sender.login, solanaEndpoint, clientPrivatePkcs8B64, payerPrivatePkcs8B64: blockchainPrivatePkcs8B64 });
const recipientSeed = await userPdaSeed32(recipient.login);
const [recipientPda] = await ctx.solana.PublicKey.findProgramAddress([recipientSeed], new ctx.solana.PublicKey(SHINE_USERS_PROGRAM_ID));
const recipientKey = new ctx.solana.PublicKey(recipient.forks.at(-1).blockchainKey);
if (!ctx.payerKeypair.publicKey.equals(new ctx.solana.PublicKey(sender.forks.at(-1).blockchainKey))) throw new Error('Подписант должен быть актуальным blockchain key отправителя');
const ix = new ctx.solana.TransactionInstruction({ programId: new ctx.solana.PublicKey(SHINE_USERS_PROGRAM_ID), keys: [
{ pubkey: ctx.payerKeypair.publicKey, isSigner: true, isWritable: true }, { pubkey: ctx.userPda, isSigner: false, isWritable: true },
{ pubkey: recipientKey, isSigner: false, isWritable: true }, { pubkey: recipientPda, isSigner: false, isWritable: true },
{ pubkey: ctx.inflowVault, isSigner: false, isWritable: true }, { pubkey: ctx.economyConfigPda, isSigner: false, isWritable: false },
{ pubkey: ctx.solana.SystemProgram.programId, isSigner: false, isWritable: false },
], data: supportData(IX_SUPPORT_USER, sender.login, recipient.login, amount, target) });
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(ix), [ctx.payerKeypair]);
return { signature, amountLamports: amount, recipientLamports: amount * 9n / 10n, inflowLamports: amount / 10n };
}
export async function supportShineDaoOnSolana({ senderLogin, amountLamports, solanaEndpoint, blockchainPrivatePkcs8B64, clientPrivatePkcs8B64 }) {
const amount = BigInt(amountLamports);
if (amount <= 0n) throw new Error('Сумма пожертвования должна быть положительной');
const sender = await readShineUserPda({ login: senderLogin, solanaEndpoint });
const ctx = await buildCommonContext({ login: sender.login, solanaEndpoint, clientPrivatePkcs8B64, payerPrivatePkcs8B64: blockchainPrivatePkcs8B64 });
const ix = new ctx.solana.TransactionInstruction({ programId: new ctx.solana.PublicKey(SHINE_USERS_PROGRAM_ID), keys: [
{ pubkey: ctx.payerKeypair.publicKey, isSigner: true, isWritable: true }, { pubkey: ctx.userPda, isSigner: false, isWritable: true },
{ pubkey: ctx.inflowVault, isSigner: false, isWritable: true }, { pubkey: ctx.economyConfigPda, isSigner: false, isWritable: false },
{ pubkey: ctx.solana.SystemProgram.programId, isSigner: false, isWritable: false },
], data: supportData(IX_SUPPORT_DAO, sender.login, null, amount, null) });
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(ix), [ctx.payerKeypair]);
return { signature, amountLamports: amount };
}
@@ -290,6 +290,21 @@ export async function transferSol({ endpoint, fromKeypair, toAddress, amountSol
return { endpoint: rpc, signature, lamports };
}
/** Прямой перевод точной суммы в lamports, без преобразований через дробный SOL. */
export async function transferSolLamports({ endpoint, fromKeypair, toAddress, amountLamports }) {
const solana = await loadSolanaLib();
const amount = BigInt(amountLamports);
if (amount <= 0n || amount > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error('Сумма вне безопасного диапазона прямого перевода');
const connection = new solana.Connection(normalizeEndpoint(endpoint), 'confirmed');
const tx = new solana.Transaction().add(solana.SystemProgram.transfer({
fromPubkey: fromKeypair.publicKey,
toPubkey: new solana.PublicKey(String(toAddress || '').trim()),
lamports: Number(amount),
}));
const signature = await sendAndConfirmSolanaHttp(connection, tx, [fromKeypair]);
return { signature, lamports: amount };
}
export async function transferAllSol({ endpoint, fromKeypair, toAddress }) {
const solana = await loadSolanaLib();
const rpc = normalizeEndpoint(endpoint);
@@ -0,0 +1,34 @@
import { authService } from '../state.js';
// Один запрос на канал; только сервер проверяет привязку транзакции к блоку.
const cache = new Map();
export function loadVerifiedSupportTotals(selector) {
const number = Number(selector?.channelRootBlockNumber);
const hash = String(selector?.channelRootBlockHash || '').toLowerCase();
if (!Number.isSafeInteger(number) || !/^[0-9a-f]{64}$/.test(hash)) return Promise.resolve(null);
const key = `${number}:${hash}`;
if (!cache.has(key)) {
const promise = authService.getSupportTotals({ channelRootBlockNumber: number, channelRootBlockHash: hash })
.then((response) => {
const messages = new Map();
for (const row of response?.messages || []) {
const id = `${String(row.blockNumber)}:${String(row.blockHash).toLowerCase()}`;
messages.set(id, String(row.receivedLamports));
}
return { channelReceivedLamports: String(response?.channelReceivedLamports || '0'), messages };
})
.catch(() => { cache.delete(key); return null; });
cache.set(key, promise);
}
return cache.get(key);
}
export function formatVerifiedSupportLamports(value) {
try {
const n = BigInt(value);
if (n <= 0n) return null;
const whole = n / 1_000_000_000n;
const fraction = String(n % 1_000_000_000n).padStart(9, '0').replace(/0+$/, '');
return `${whole}${fraction ? '.' + fraction : ''} SOL`;
} catch { return null; }
}
@@ -0,0 +1,30 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { parseSolLamports, formatLamportsSol, hexHash32 } from '../js/services/shine-support-amount.js';
const source = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
test('десятичная сумма SOL обрабатывается точно без Number', () => {
assert.equal(parseSolLamports('0.000000010'), 10n);
assert.equal(parseSolLamports('1,25'), 1250000000n);
assert.equal(formatLamportsSol(1250000001n), '1.250000001');
assert.equal(parseSolLamports('0.000000001'), 1n);
for (const value of ['0', '-1', '1.1234567890', '1e3', 'NaN', '']) {
assert.throws(() => parseSolLamports(value), undefined, value);
}
});
test('идентификаторы канала требуют ровно 32 байта hex', () => {
assert.equal(hexHash32('ab'.repeat(32)).length, 32);
assert.equal(hexHash32('ab'.repeat(32))[0], 171);
assert.throws(() => hexHash32('0'));
assert.throws(() => hexHash32('x'.repeat(64)));
});
test('страница канала использует контракт 90/10 и прямой перевод с подтверждением', () => {
const page = source('../js/pages/channel-donate-view.js');
assert.match(page, /supportShineUserOnSolana\(/);
assert.match(page, /transferSolLamports\(/);
assert.match(page, /window\.confirm\(t\('screens\.support_flow\.direct_warning'\)\)/);
assert.match(page, /target: \{ type: 1, channelBlockNumber:/);
assert.match(page, /readShineUserPda\(/);
assert.match(source('../js/services/solana-wallet-service.js'), /export async function transferSolLamports/);
});
+43
View File
@@ -0,0 +1,43 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { supportStatsValues } from '../js/components/support-stats.js';
function file(path) { return readFileSync(new URL(path, import.meta.url), 'utf8'); }
test('three displayed counters: full sent, net received, sent/10 + direct', () => {
assert.deepEqual(supportStatsValues({ supportSent: 1_000_000_000n, supportReceived: 900_000_000n, daoDirect: 200_000_000n }), [1_000_000_000n, 900_000_000n, 300_000_000n]);
assert.deepEqual(supportStatsValues({}), [0n, 0n, 0n]);
});
test('profile views attach counters from Solana PDA and support user action', () => {
assert.match(file('../js/pages/profile-view.js'), /attachSupportStats\(body/);
const other = file('../js/pages/user-profile-view.js');
assert.match(other, /attachSupportStats\(body/);
assert.match(other, /data-profile-action=\\?"support/);
assert.match(other, /openShineSupportDialog\(\{ recipientLogin: card\.login/);
});
test('wallet supports direct SHiNE economy donation', () => {
const wallet = file('../js/pages/wallet-view.js');
assert.match(wallet, /id="donate-shine"/);
assert.match(wallet, /openShineSupportDialog\(\{ onSuccess/);
});
test('message buttons pass checked block hashes, not message text', () => {
for (const page of ['channel-view.js', 'channel-thread-view.js']) {
const src = file(`../js/pages/${page}`);
assert.match(src, /hexHash32\(rootHash\)/);
assert.match(src, /hexHash32\(msgHash\)|hexHash32\(messageHash\)/);
assert.match(src, /type: 2/);
}
});
test('shared modal protects direct and tracked workflows', () => {
const src = file('../js/components/shine-support-dialog.js');
assert.match(src, /supportShineUserOnSolana/);
assert.match(src, /supportShineDaoOnSolana/);
assert.match(src, /transferSolLamports/);
assert.match(src, /window\.confirm\(t\('screens\.support_phase2\.direct_warning'\)\)/);
assert.match(src, /amount % 10n/);
});