SHA256
419 lines
19 KiB
JavaScript
419 lines
19 KiB
JavaScript
import { t, th } from '../i18n/index.js';
|
||
import { createTopBar } from '../components/topbar.js';
|
||
import { authService, state } from '../state.js';
|
||
import { navigateBack } from '../router.js';
|
||
import { extractLoginFromBlockchainName, formatChannelAddress } from '../services/shine-routes.js';
|
||
import {
|
||
formatSol,
|
||
getBalanceSol,
|
||
getSolanaWalletFromStoredSecret,
|
||
getWalletFromStoredBlockchainKey,
|
||
solanaAddressFromPublicKeyBase64,
|
||
} 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'); } };
|
||
|
||
function escapeHtml(text) {
|
||
return String(text || '')
|
||
.replaceAll('&', '&')
|
||
.replaceAll('<', '<')
|
||
.replaceAll('>', '>')
|
||
.replaceAll('"', '"')
|
||
.replaceAll("'", ''');
|
||
}
|
||
|
||
function normalizeHash(hash) {
|
||
const normalized = String(hash || '').trim().toLowerCase();
|
||
return normalized || '0';
|
||
}
|
||
|
||
function toSafeInt(value) {
|
||
if (value === '' || value == null) return null;
|
||
const parsed = Number(value);
|
||
return Number.isFinite(parsed) ? parsed : null;
|
||
}
|
||
|
||
async function resolveChannelSelector(route) {
|
||
const ownerRef = String(route?.params?.ownerBlockchainName || '').trim();
|
||
const rootNo = toSafeInt(route?.params?.channelRootBlockNumber);
|
||
const rootHash = normalizeHash(route?.params?.channelRootBlockHash);
|
||
const channelName = String(route?.params?.channelName || '').trim();
|
||
|
||
if (ownerRef && rootNo != null) {
|
||
return {
|
||
ownerBlockchainName: ownerRef,
|
||
channelRootBlockNumber: rootNo,
|
||
channelRootBlockHash: rootHash,
|
||
channelName,
|
||
};
|
||
}
|
||
|
||
if (!ownerRef || !channelName) {
|
||
throw new Error(t('screens.channel_donate_view.text_014'));
|
||
}
|
||
|
||
const ownerLogin = extractLoginFromBlockchainName(ownerRef);
|
||
const ownerUser = await authService.getUser(ownerLogin);
|
||
if (!ownerUser?.exists) throw new Error(t('screens.channel_donate_view.text_015'));
|
||
|
||
const ownerBlockchainName = String(ownerUser.blockchainName || ownerRef).trim();
|
||
const ownerFeed = await authService.listSubscriptionsFeed(ownerLogin, 500);
|
||
const ownedRows = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels : [];
|
||
const row = ownedRows.find((item) => (
|
||
String(item?.channel?.channelName || '').trim().toLowerCase() === channelName.toLowerCase()
|
||
&& String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerBlockchainName.toLowerCase()
|
||
));
|
||
if (!row?.channel?.channelRoot) throw new Error(t('screens.channel_donate_view.text_016'));
|
||
|
||
return {
|
||
ownerBlockchainName,
|
||
channelRootBlockNumber: Number(row.channel.channelRoot.blockNumber),
|
||
channelRootBlockHash: normalizeHash(row.channel.channelRoot.blockHash),
|
||
channelName,
|
||
};
|
||
}
|
||
|
||
function publicKeyChoice(ownerUser, field, id, label) {
|
||
const publicKeyB64 = String(ownerUser?.[field] || '').trim();
|
||
if (!publicKeyB64) return null;
|
||
try {
|
||
return {
|
||
id,
|
||
label,
|
||
address: solanaAddressFromPublicKeyBase64(publicKeyB64),
|
||
};
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
export function render({ navigate, route, chrome }) {
|
||
const screen = document.createElement('section');
|
||
screen.className = 'stack channels-screen channels-screen--channel-donate';
|
||
|
||
const topbar = createTopBar({
|
||
title: t('screens.channel_donate_view.text_002'),
|
||
back: {
|
||
label: '←',
|
||
onClick: () => {
|
||
if (window.history.length > 1) {
|
||
navigateBack();
|
||
return;
|
||
}
|
||
navigate('channels-list');
|
||
},
|
||
ariaLabel: t('screens.channel_donate_view.text_003'),
|
||
title: t('screens.channel_donate_view.text_004'),
|
||
},
|
||
});
|
||
chrome?.setTopbar(topbar);
|
||
|
||
const card = document.createElement('div');
|
||
card.className = 'card stack channel-donate-card';
|
||
const content = document.createElement('div');
|
||
content.className = 'stack channel-donate-content';
|
||
content.innerHTML = t('screens.channel_donate_view.text_017');
|
||
card.append(content);
|
||
screen.append(card);
|
||
|
||
let disposed = false;
|
||
let refreshSeq = 0;
|
||
let busy = false;
|
||
const walletCache = new Map();
|
||
|
||
const cleanupWallets = () => {
|
||
for (const wallet of walletCache.values()) {
|
||
try {
|
||
wallet?.keypair?.secretKey?.fill?.(0);
|
||
} catch {
|
||
// Секретные ключи живут только в памяти этой страницы.
|
||
}
|
||
}
|
||
walletCache.clear();
|
||
};
|
||
|
||
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 = [
|
||
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 = `
|
||
<div class="channel-donate-hero">
|
||
<h2>${th('screens.channel_donate_view.text_023')}</h2>
|
||
<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>
|
||
<select class="select" id="channel-donate-blockchain">
|
||
<option value="solana">Solana</option>
|
||
</select>
|
||
</section>
|
||
|
||
<section class="channel-donate-section">
|
||
<label class="field-label" for="channel-donate-recipient-key">${th('screens.channel_donate_view.text_025')}</label>
|
||
<select class="select" id="channel-donate-recipient-key" ${recipientChoices.length ? '' : 'disabled'}>
|
||
${recipientChoices.map((choice) => `<option value="${escapeHtml(choice.id)}">${escapeHtml(choice.label)}</option>`).join('')}
|
||
</select>
|
||
<div class="channel-donate-address" id="channel-donate-recipient-address">–</div>
|
||
</section>
|
||
|
||
<section class="channel-donate-section">
|
||
<label class="field-label" for="channel-donate-sender-key">${th('screens.channel_donate_view.text_026')}</label>
|
||
<div class="channel-donate-address" id="channel-donate-sender-key">Blockchain key</div>
|
||
<div class="channel-donate-address" id="channel-donate-sender-address">—</div>
|
||
|
||
<div class="channel-donate-balance-row">
|
||
<span class="meta-muted">${th('screens.channel_donate_view.text_027')}</span>
|
||
<strong id="channel-donate-balance">–</strong>
|
||
<button class="secondary-btn channel-donate-refresh" id="channel-donate-refresh" type="button">${th('screens.channel_donate_view.text_028')}</button>
|
||
</div>
|
||
</section>
|
||
|
||
<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="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 && 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');
|
||
const senderSelect = content.querySelector('#channel-donate-sender-key');
|
||
const recipientAddressEl = content.querySelector('#channel-donate-recipient-address');
|
||
const senderAddressEl = content.querySelector('#channel-donate-sender-address');
|
||
const balanceEl = content.querySelector('#channel-donate-balance');
|
||
const amountEl = content.querySelector('#channel-donate-amount');
|
||
const statusEl = content.querySelector('#channel-donate-status');
|
||
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 || !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;
|
||
if (amountEl) amountEl.disabled = busy;
|
||
};
|
||
|
||
const setStatus = (message, kind = '') => {
|
||
if (!statusEl) return;
|
||
statusEl.textContent = String(message || '');
|
||
statusEl.classList.toggle('is-error', kind === 'error');
|
||
};
|
||
|
||
const selectedRecipient = () => (
|
||
recipientChoices.find((choice) => choice.id === String(recipientSelect?.value || ''))
|
||
|| recipientChoices[0]
|
||
|| null
|
||
);
|
||
|
||
const updateRecipientAddress = () => {
|
||
const choice = selectedRecipient();
|
||
if (recipientAddressEl) recipientAddressEl.textContent = choice?.address || t('screens.channel_donate_view.text_019');
|
||
};
|
||
|
||
const resolveSenderWallet = async () => {
|
||
const keyId = 'blockchain-key';
|
||
if (walletCache.has(keyId)) return walletCache.get(keyId);
|
||
|
||
const login = String(state.session.login || '').trim();
|
||
const storagePwd = String(state.session.storagePwdInMemory || '').trim();
|
||
if (!login || !storagePwd) throw new Error(t('screens.channel_donate_view.text_020'));
|
||
const wallet = await getWalletFromStoredBlockchainKey({ login, storagePwd });
|
||
|
||
walletCache.set(keyId, wallet);
|
||
return wallet;
|
||
};
|
||
|
||
const refreshBalance = async () => {
|
||
if (busy || disposed) return;
|
||
setBusy(true);
|
||
setStatus(t('screens.channel_donate_view.text_005'));
|
||
if (balanceEl) balanceEl.textContent = '–';
|
||
try {
|
||
const wallet = await resolveSenderWallet();
|
||
if (disposed) return;
|
||
if (senderAddressEl) senderAddressEl.textContent = wallet.address;
|
||
const balance = await getBalanceSol({
|
||
endpoint: state.entrySettings.solanaServer,
|
||
address: wallet.address,
|
||
});
|
||
if (disposed) return;
|
||
if (balanceEl) balanceEl.textContent = `${formatSol(balance.sol)} SOL`;
|
||
setStatus('');
|
||
} catch (error) {
|
||
if (disposed) return;
|
||
if (senderAddressEl) senderAddressEl.textContent = '–';
|
||
setStatus(toUserMessage(error, t('screens.channel_donate_view.text_006')), 'error');
|
||
} finally {
|
||
if (!disposed) setBusy(false);
|
||
}
|
||
};
|
||
|
||
recipientSelect?.addEventListener('change', updateRecipientAddress);
|
||
senderSelect?.addEventListener('change', () => {
|
||
if (senderAddressEl) senderAddressEl.textContent = '–';
|
||
if (balanceEl) balanceEl.textContent = '–';
|
||
setStatus('');
|
||
void refreshBalance();
|
||
});
|
||
refreshEl?.addEventListener('click', () => void refreshBalance());
|
||
|
||
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; }
|
||
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 = ''; }
|
||
try {
|
||
const wallet = await resolveSenderWallet();
|
||
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(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 });
|
||
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); }
|
||
};
|
||
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');
|
||
} else {
|
||
void refreshBalance();
|
||
}
|
||
};
|
||
|
||
const refresh = async () => {
|
||
const seq = ++refreshSeq;
|
||
cleanupWallets();
|
||
content.innerHTML = t('screens.channel_donate_view.text_021');
|
||
try {
|
||
const selector = await resolveChannelSelector(route);
|
||
const payload = await authService.getChannelMessages(selector, 1, 'asc', String(state.session.login || '').trim());
|
||
if (disposed || seq !== refreshSeq) return;
|
||
|
||
const channel = payload?.channel || {};
|
||
const ownerLogin = String(channel?.ownerLogin || extractLoginFromBlockchainName(selector.ownerBlockchainName) || '').trim();
|
||
const ownerUser = await authService.getUser(ownerLogin);
|
||
if (disposed || seq !== refreshSeq) return;
|
||
if (!ownerUser?.exists) throw new Error(t('screens.channel_donate_view.text_022'));
|
||
|
||
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 = `
|
||
<div class="meta-muted">${th('screens.channel_donate_view.text_032')}</div>
|
||
<div class="meta-muted">${escapeHtml(toUserMessage(error, t('screens.channel_donate_view.text_013')))}</div>
|
||
<button class="secondary-btn" id="channel-donate-retry" type="button">${th('screens.channel_donate_view.text_033')}</button>
|
||
`;
|
||
content.querySelector('#channel-donate-retry')?.addEventListener('click', () => void refresh());
|
||
}
|
||
};
|
||
|
||
screen.refresh = refresh;
|
||
screen.cleanup = () => {
|
||
if (disposed) return;
|
||
disposed = true;
|
||
refreshSeq += 1;
|
||
cleanupWallets();
|
||
};
|
||
|
||
void refresh();
|
||
return screen;
|
||
}
|