SHA256
373 lines
19 KiB
JavaScript
373 lines
19 KiB
JavaScript
import { t } from '../i18n/index.js';
|
|
import { createTopBar } from '../components/topbar.js';
|
|
import { authService, state } from '../state.js';
|
|
import { getRegistrationStatus } from '../services/registration-v2-api.js';
|
|
import { getNamespace } from '../services/shine-namespace-service.js';
|
|
import { readShineUserPda, upgradeFreeUserOnSolana } from '../services/shine-user-pda-service.js';
|
|
import { checkLoginExistsOnSolana, formatSolanaErrorDetails } from '../services/solana-register-service.js';
|
|
import { base64ToBytes, bytesToBase58 } from '../services/crypto-utils.js';
|
|
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
|
|
import { fundDevnetRegistrationWallet } from './registration-payment-view.js';
|
|
import {
|
|
getBalanceSol, formatSol,
|
|
} from '../services/solana-wallet-service.js';
|
|
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
|
import {
|
|
USER_PDA_SPACE, UPGRADE_TEST_TOPUP_SOL, calculateUpgradeFunding,
|
|
isUpgradeComplete, solFromLamports,
|
|
} from '../services/registration-upgrade-helpers.js';
|
|
|
|
export const pageMeta = { id: 'registration-upgrade-view', get title() { return t('screens.registration_upgrade_view.text_001'); } };
|
|
const SYNC_INTERVAL_MS = 3000;
|
|
const SYNC_NOTICE_AFTER_MS = 90000;
|
|
|
|
function element(tag, className, content = '') {
|
|
const node = document.createElement(tag);
|
|
if (className) node.className = className;
|
|
node.textContent = content;
|
|
return node;
|
|
}
|
|
function makeButton(label, className = 'primary-btn') {
|
|
const button = element('button', className, label);
|
|
button.type = 'button';
|
|
return button;
|
|
}
|
|
function makeExplorerTxLink(signature) {
|
|
const tx = String(signature || '').trim();
|
|
if (!tx) return null;
|
|
const anchor = element('a', '', tx);
|
|
const url = new URL(`https://explorer.solana.com/tx/${encodeURIComponent(tx)}`);
|
|
const cluster = getSolanaCluster();
|
|
if (cluster && cluster !== 'mainnet-beta') url.searchParams.set('cluster', cluster);
|
|
anchor.href = url.toString();
|
|
anchor.target = '_blank';
|
|
anchor.rel = 'noopener noreferrer';
|
|
anchor.style.overflowWrap = 'anywhere';
|
|
return anchor;
|
|
}
|
|
|
|
export function render({ navigate, chrome }) {
|
|
const login = String(state.session?.login || '');
|
|
const solanaEndpoint = String(state.entrySettings?.solanaServer || '');
|
|
const isDevnet = getSolanaCluster() === 'devnet';
|
|
const screen = element('section', 'stack');
|
|
chrome?.setTopbar(createTopBar({
|
|
title: t('screens.registration_upgrade_view.text_002'),
|
|
back: { label: '←', onClick: () => navigate('settings-view') },
|
|
}));
|
|
|
|
const intro = element('div', 'card stack');
|
|
intro.append(
|
|
element('h3', '', t('screens.registration_upgrade_view.text_011')),
|
|
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_057', { value1: login })),
|
|
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_012')),
|
|
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_013')),
|
|
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_014')),
|
|
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_015')),
|
|
);
|
|
const introStatus = element('p', 'status-line', t('screens.registration_upgrade_view.text_016'));
|
|
introStatus.setAttribute('aria-live', 'polite');
|
|
const continueButton = makeButton(t('screens.registration_upgrade_view.text_017'));
|
|
continueButton.disabled = true;
|
|
intro.append(continueButton, introStatus);
|
|
|
|
const payment = element('div', 'card stack registration-payment-card');
|
|
payment.append(element('h3', '', t('screens.registration_upgrade_view.text_018')));
|
|
const walletHeading = element('h4', 'registration-payment-wallet-heading', t('screens.registration_upgrade_view.text_019'));
|
|
const walletHint = element('p', 'meta-muted registration-payment-wallet-hint', t('screens.registration_upgrade_view.text_020'));
|
|
const walletLabel = element('label', 'field-label', t('screens.registration_upgrade_view.text_021'));
|
|
const wallet = document.createElement('input');
|
|
wallet.className = 'input'; wallet.type = 'text'; wallet.readOnly = true;
|
|
wallet.style.width = '100%'; wallet.setAttribute('aria-label', t('screens.registration_upgrade_view.text_069'));
|
|
const copyButton = makeButton(t('screens.registration_upgrade_view.text_022'), 'secondary-btn registration-payment-action registration-payment-copy-btn');
|
|
const walletSection = element('div', 'registration-payment-wallet');
|
|
walletSection.append(walletHeading, walletHint, walletLabel, wallet, copyButton);
|
|
|
|
const balanceLine = element('strong', 'registration-payment-balance-value', '— SOL');
|
|
balanceLine.setAttribute('aria-live', 'polite');
|
|
const balanceLabel = element('span', 'registration-payment-balance-label', t('screens.registration_upgrade_view.text_023'));
|
|
const balanceInfo = element('div', 'registration-payment-balance-info');
|
|
balanceInfo.append(balanceLabel, balanceLine);
|
|
const refreshButton = makeButton(t('screens.registration_upgrade_view.text_024'), 'secondary-btn registration-payment-action registration-payment-refresh-btn');
|
|
refreshButton.title = t('screens.registration_upgrade_view.text_003');
|
|
const balanceRow = element('div', 'registration-payment-balance');
|
|
balanceRow.append(balanceInfo, refreshButton);
|
|
const topupButton = makeButton(t('screens.registration_upgrade_view.text_058', { value1: UPGRADE_TEST_TOPUP_SOL }), 'secondary-btn registration-payment-action registration-payment-topup-btn');
|
|
const testHint = element('p', 'meta-muted registration-payment-test-hint', t('screens.registration_upgrade_view.text_025'));
|
|
const amount = element('div', 'registration-payment-fees', t('screens.registration_upgrade_view.text_026'));
|
|
const passwordLabel = element('label', 'field-label', t('screens.registration_upgrade_view.text_027'));
|
|
const password = document.createElement('input');
|
|
password.className = 'input'; password.type = 'password'; password.autocomplete = 'current-password';
|
|
password.placeholder = t('screens.registration_upgrade_view.text_004');
|
|
const payButton = makeButton(t('screens.registration_upgrade_view.text_028'));
|
|
const payStatus = element('p', 'status-line');
|
|
payStatus.setAttribute('aria-live', 'polite');
|
|
payment.append(walletSection, balanceRow);
|
|
if (isDevnet) payment.append(topupButton, testHint);
|
|
payment.append(amount, passwordLabel, password, payButton, payStatus);
|
|
|
|
const syncing = element('div', 'card stack');
|
|
syncing.append(element('h3', '', t('screens.registration_upgrade_view.text_029')));
|
|
const syncInfo = element('p', 'meta-muted', t('screens.registration_upgrade_view.text_030'));
|
|
const txLine = element('p', 'meta-muted');
|
|
const syncStatus = element('p', 'status-line');
|
|
syncStatus.setAttribute('aria-live', 'polite');
|
|
const checkButton = makeButton(t('screens.registration_upgrade_view.text_031'), 'ghost-btn');
|
|
syncing.append(syncInfo, txLine, syncStatus, checkButton);
|
|
|
|
const done = element('div', 'card stack');
|
|
done.append(
|
|
element('h3', '', t('screens.registration_upgrade_view.text_032')),
|
|
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_059', { value1: login })),
|
|
element('p', 'meta-muted', t('screens.registration_upgrade_view.text_033')),
|
|
);
|
|
const settingsButton = makeButton(t('screens.registration_upgrade_view.text_034'));
|
|
settingsButton.addEventListener('click', () => navigate('settings-view'));
|
|
done.append(settingsButton);
|
|
screen.append(intro, payment, syncing, done);
|
|
|
|
let disposed = false;
|
|
let identity = null;
|
|
let namespace = null;
|
|
let funding = null;
|
|
let walletAddress = '';
|
|
let pollingTimer = null;
|
|
let startedPollingAt = 0;
|
|
let checking = false;
|
|
let sending = false;
|
|
|
|
function show(stageName) {
|
|
for (const [name, card] of [['intro', intro], ['payment', payment], ['syncing', syncing], ['done', done]]) {
|
|
card.style.display = name === stageName ? '' : 'none';
|
|
}
|
|
}
|
|
function message(node, value, error = false) {
|
|
if (disposed) return;
|
|
node.textContent = value;
|
|
node.className = `status-line ${error ? 'is-unavailable' : 'is-available'}`;
|
|
}
|
|
function stopPolling() {
|
|
if (pollingTimer !== null) window.clearInterval(pollingTimer);
|
|
pollingTimer = null;
|
|
}
|
|
function succeed() {
|
|
if (disposed) return;
|
|
stopPolling();
|
|
password.value = '';
|
|
show('done');
|
|
}
|
|
async function balanceUpdate(showError = true) {
|
|
if (!walletAddress) return null;
|
|
refreshButton.disabled = true;
|
|
refreshButton.textContent = t('screens.registration_upgrade_view.text_005');
|
|
try {
|
|
const balance = await getBalanceSol({ endpoint: solanaEndpoint, address: walletAddress });
|
|
if (disposed) return null;
|
|
balanceLine.textContent = `${formatSol(balance.sol, 6)} SOL`;
|
|
return BigInt(balance.lamports);
|
|
} catch (error) {
|
|
if (showError) message(payStatus, t('screens.registration_upgrade_view.text_060', { value1: error.message }), true);
|
|
return null;
|
|
} finally {
|
|
if (!disposed) {
|
|
refreshButton.disabled = false;
|
|
refreshButton.textContent = t('screens.registration_upgrade_view.text_006');
|
|
}
|
|
}
|
|
}
|
|
async function hasVerifiedPda(expectedIdentity = identity) {
|
|
const presence = await checkLoginExistsOnSolana({ login, solanaEndpoint });
|
|
if (!presence.exists) return false;
|
|
const pda = await readShineUserPda({ login, solanaEndpoint });
|
|
if (pda.login !== login) throw new Error(t('screens.registration_upgrade_view.text_047'));
|
|
// Если сервер ещё считает аккаунт бесплатным, проверяем совпадение с исходным сертификатом.
|
|
if (expectedIdentity?.registrationStatus === 'FREE_CERT') {
|
|
if (bytesToBase58(pda.rootKey) !== expectedIdentity.rootPublicKey ||
|
|
bytesToBase58(pda.clientKey) !== expectedIdentity.clientPublicKey ||
|
|
bytesToBase58(pda.forks[0].blockchainKey) !== expectedIdentity.blockchainPublicKey) {
|
|
throw new Error(t('screens.registration_upgrade_view.text_048'));
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
async function checkSync() {
|
|
if (disposed || checking) return;
|
|
checking = true;
|
|
checkButton.disabled = true;
|
|
try {
|
|
const onChainExists = await hasVerifiedPda();
|
|
if (disposed) return;
|
|
if (!onChainExists) {
|
|
message(syncStatus, t('screens.registration_upgrade_view.text_035'));
|
|
return;
|
|
}
|
|
const current = await getRegistrationStatus(login);
|
|
if (disposed) return;
|
|
if (isUpgradeComplete(current.registrationStatus)) {
|
|
succeed();
|
|
return;
|
|
}
|
|
if (current.registrationStatus !== 'FREE_CERT') {
|
|
message(syncStatus, t('screens.registration_upgrade_view.text_061', { value1: current.registrationStatus }), true);
|
|
return;
|
|
}
|
|
message(syncStatus, t('screens.registration_upgrade_view.text_036'));
|
|
} catch (error) {
|
|
message(syncStatus, t('screens.registration_upgrade_view.text_062', { value1: error.message }), true);
|
|
} finally {
|
|
checking = false;
|
|
if (!disposed) checkButton.disabled = false;
|
|
if (!disposed && Date.now() - startedPollingAt > SYNC_NOTICE_AFTER_MS) {
|
|
syncInfo.textContent = t('screens.registration_upgrade_view.text_007');
|
|
}
|
|
}
|
|
}
|
|
function watchSync() {
|
|
show('syncing');
|
|
startedPollingAt = Date.now();
|
|
stopPolling();
|
|
void checkSync();
|
|
pollingTimer = window.setInterval(() => void checkSync(), SYNC_INTERVAL_MS);
|
|
}
|
|
function markTransaction(signature) {
|
|
txLine.replaceChildren();
|
|
const anchor = makeExplorerTxLink(signature);
|
|
if (anchor) {
|
|
txLine.append('Tx ID: ', anchor);
|
|
} else {
|
|
txLine.textContent = t('screens.registration_upgrade_view.text_008');
|
|
}
|
|
}
|
|
async function initialize() {
|
|
if (!login.includes('@')) throw new Error(t('screens.registration_upgrade_view.text_049'));
|
|
const current = await getRegistrationStatus(login);
|
|
if (disposed) return;
|
|
// Уже платный аккаунт не должен повторно попадать в мастер покупки.
|
|
if (isUpgradeComplete(current.registrationStatus)) { navigate('settings-view'); return; }
|
|
if (current.registrationStatus !== 'FREE_CERT') throw new Error(t('screens.registration_upgrade_view.text_050'));
|
|
// Проверяем наличие PDA до любых новых платежей. Это также позволяет возобновить проверку после перезагрузки.
|
|
const onChainExists = await hasVerifiedPda(current);
|
|
if (disposed) return;
|
|
if (onChainExists) {
|
|
markTransaction('');
|
|
watchSync();
|
|
return;
|
|
}
|
|
const loadedNamespace = await getNamespace({ namespace: login.split('@')[1], solanaEndpoint });
|
|
if (loadedNamespace.type !== 2) throw new Error(t('screens.registration_upgrade_view.text_051'));
|
|
if (!current.innerSignature64B64 || !current.blockchainPublicKey) throw new Error(t('screens.registration_upgrade_view.text_052'));
|
|
const web3 = await loadSolanaWeb3();
|
|
const connection = new web3.Connection(solanaEndpoint, 'confirmed');
|
|
const rentLamports = await connection.getMinimumBalanceForRentExemption(USER_PDA_SPACE, 'confirmed');
|
|
if (disposed) return;
|
|
identity = current;
|
|
namespace = loadedNamespace;
|
|
funding = calculateUpgradeFunding({ namespaceFeeLamports: namespace.registrationFeeLamports, rentLamports });
|
|
walletAddress = identity.blockchainPublicKey;
|
|
// Проверяем адрес как настоящий публичный ключ Solana, не используем произвольный текст ответа сервера.
|
|
const pubkey = new web3.PublicKey(walletAddress);
|
|
walletAddress = pubkey.toBase58();
|
|
wallet.value = walletAddress;
|
|
amount.replaceChildren(element('h4', 'registration-payment-fees-title', t('screens.registration_upgrade_view.text_037')));
|
|
for (const [label, lamports, emphasized] of [
|
|
[t('screens.registration_upgrade_view.text_044'), funding.namespaceFee, true],
|
|
[t('screens.registration_upgrade_view.text_045'), funding.networkReserve, false],
|
|
[t('screens.registration_upgrade_view.text_046'), funding.requiredLamports, false],
|
|
]) {
|
|
const row = element('div', `registration-payment-fee-row${emphasized ? ' registration-payment-fee-row--emphasis' : ''}`);
|
|
row.append(element('span', '', label), element('strong', '', `${solFromLamports(lamports)} SOL`));
|
|
amount.append(row);
|
|
}
|
|
amount.append(element('p', 'meta-muted', t('screens.registration_upgrade_view.text_038')));
|
|
continueButton.disabled = false;
|
|
message(introStatus, t('screens.registration_upgrade_view.text_039'));
|
|
}
|
|
|
|
continueButton.addEventListener('click', () => {
|
|
show('payment');
|
|
void balanceUpdate(false);
|
|
});
|
|
copyButton.addEventListener('click', async () => {
|
|
try {
|
|
await navigator.clipboard.writeText(walletAddress);
|
|
copyButton.textContent = t('screens.registration_upgrade_view.text_009');
|
|
window.setTimeout(() => { if (!disposed) copyButton.textContent = t('screens.registration_upgrade_view.text_010'); }, 1600);
|
|
message(payStatus, t('screens.registration_upgrade_view.text_040'));
|
|
} catch {
|
|
message(payStatus, t('screens.registration_upgrade_view.text_041'), true);
|
|
}
|
|
});
|
|
refreshButton.addEventListener('click', () => void balanceUpdate());
|
|
topupButton.addEventListener('click', async () => {
|
|
if (!isDevnet || disposed || !walletAddress) return;
|
|
topupButton.disabled = true;
|
|
try {
|
|
message(payStatus, t('screens.registration_upgrade_view.text_063', { value1: UPGRADE_TEST_TOPUP_SOL }));
|
|
const result = await fundDevnetRegistrationWallet(walletAddress);
|
|
if (disposed) return;
|
|
balanceLine.textContent = `${formatSol(result.sol, 6)} SOL`;
|
|
message(payStatus, t('screens.registration_upgrade_view.text_064', { value1: UPGRADE_TEST_TOPUP_SOL }));
|
|
} catch (error) {
|
|
message(payStatus, t('screens.registration_upgrade_view.text_065', { value1: error.message }), true);
|
|
} finally {
|
|
if (!disposed) topupButton.disabled = false;
|
|
}
|
|
});
|
|
payButton.addEventListener('click', async () => {
|
|
if (disposed || sending) return;
|
|
sending = true;
|
|
payButton.disabled = true;
|
|
try {
|
|
if (!identity || !namespace || !funding) throw new Error(t('screens.registration_upgrade_view.text_053'));
|
|
if (!password.value) throw new Error(t('screens.registration_upgrade_view.text_054'));
|
|
// Повторно сверяем Solana: уже зарегистрированную PDA не оплачиваем второй раз.
|
|
const pdaExists = await hasVerifiedPda();
|
|
if (pdaExists) { password.value = ''; markTransaction(''); watchSync(); return; }
|
|
const balanceLamports = await balanceUpdate();
|
|
if (balanceLamports === null) return;
|
|
if (balanceLamports < funding.requiredLamports) {
|
|
const shortage = funding.requiredLamports - balanceLamports;
|
|
throw new Error(t('screens.registration_upgrade_view.text_066', { value1: solFromLamports(shortage) }));
|
|
}
|
|
message(payStatus, t('screens.registration_upgrade_view.text_042'));
|
|
const keys = await authService.derivePasswordKeyBundle(login, password.value);
|
|
if (disposed) return;
|
|
for (const [pair, expected] of [
|
|
[keys.rootPair, identity.rootPublicKey],
|
|
[keys.blockchainPair, identity.blockchainPublicKey],
|
|
[keys.clientPair, identity.clientPublicKey],
|
|
]) {
|
|
if (bytesToBase58(base64ToBytes(pair.publicKeyB64)) !== expected) {
|
|
throw new Error(t('screens.registration_upgrade_view.text_055'));
|
|
}
|
|
}
|
|
const signature = base64ToBytes(identity.innerSignature64B64);
|
|
if (signature.length !== 64) throw new Error(t('screens.registration_upgrade_view.text_056'));
|
|
message(payStatus, t('screens.registration_upgrade_view.text_043'));
|
|
const result = await upgradeFreeUserOnSolana({
|
|
login, keyBundle: keys, solanaEndpoint, innerSignature64: signature,
|
|
accessServers: identity.defaultServerLogin ? [identity.defaultServerLogin] : [],
|
|
});
|
|
if (disposed) return;
|
|
password.value = '';
|
|
markTransaction(result.signature);
|
|
watchSync();
|
|
} catch (error) {
|
|
// Если Solana успела подтвердить PDA, а HTTP-клиент потерял ответ, нельзя требовать новую оплату.
|
|
try {
|
|
const pdaExists = await hasVerifiedPda();
|
|
if (pdaExists) { password.value = ''; markTransaction(''); watchSync(); return; }
|
|
} catch { /* Отсутствие связи с RPC не доказывает отсутствие PDA. */ }
|
|
message(payStatus, t('screens.registration_upgrade_view.text_067', { value1: formatSolanaErrorDetails(error) }), true);
|
|
} finally {
|
|
sending = false;
|
|
if (!disposed) payButton.disabled = false;
|
|
}
|
|
});
|
|
checkButton.addEventListener('click', () => void checkSync());
|
|
show('intro');
|
|
void initialize().catch((error) => message(introStatus, t('screens.registration_upgrade_view.text_068', { value1: error.message }), true));
|
|
screen.cleanup = () => { disposed = true; stopPolling(); password.value = ''; };
|
|
return screen;
|
|
}
|