Улучшить UI регистрации и связанные сценарии

This commit is contained in:
AidarKC
2026-11-08 18:04:06 +03:00
parent 9405f28525
commit 4068465ee6
66 changed files with 842 additions and 221 deletions
+79 -45
View File
@@ -1,7 +1,6 @@
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
import { createTopBar } from '../components/topbar.js';
import { createRegistrationStepper } from '../components/registration-stepper.js';
import { iconHtml } from '../components/ui-icon.js';
import {
authService,
authorizeSession,
@@ -28,11 +27,10 @@ import {
registerUserOnSolana,
} from '../services/solana-register-service.js';
import { defaultServerLogin } from '../deploy-config.js';
import { normalizeFullLogin } from '../services/shine-namespace-service.js';
import { getNamespace, normalizeFullLogin } from '../services/shine-namespace-service.js';
import { calculateRegistrationFunding, USER_PDA_SPACE, solFromLamports } from '../services/registration-upgrade-helpers.js';
export const pageMeta = { id: 'registration-payment-view', title: 'Оплата регистрации', showAppChrome: false };
const MIN_REQUIRED_SOL = 0.01;
const RECOMMENDED_TOPUP_SOL = 0.02;
const TEST_TOPUP_AMOUNT_SOL = 0.02;
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
const TEST_TOPUP_SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
@@ -147,7 +145,7 @@ export async function completeRegistrationLogin({ navigate, keyBundle }) {
state.registrationPayment.balanceSOL = '0.0000';
await refreshSessions();
setAuthInfo(`Регистрация завершена. Вы автоматически вошли как @${resumedLogin}.`);
setAuthInfo(`Регистрация завершена. Вы автоматически вошли как ${resumedLogin}.`);
const nextHash = String(state.authReturnHash || '').trim();
state.authReturnHash = '';
@@ -163,7 +161,9 @@ export function render({ navigate }) {
screen.className = 'stack';
const card = document.createElement('div');
card.className = 'card stack';
card.className = 'card stack registration-payment-card';
let funding = null;
let pricingValid = false;
const status = document.createElement('p');
status.className = 'status-line is-unavailable';
@@ -177,41 +177,50 @@ export function render({ navigate }) {
walletValue.style.width = '100%';
const walletRow = document.createElement('div');
walletRow.className = 'stack';
walletRow.className = 'registration-payment-wallet';
const copyButton = document.createElement('button');
copyButton.className = 'ghost-btn';
copyButton.className = 'secondary-btn registration-payment-action registration-payment-copy-btn';
copyButton.type = 'button';
copyButton.textContent = 'Скопировать номер';
copyButton.style.width = '100%';
copyButton.textContent = 'Скопировать адрес';
copyButton.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(walletValue.value);
copyButton.textContent = 'Скопировано';
copyButton.textContent = '✓ Адрес скопирован';
window.setTimeout(() => {
copyButton.textContent = 'Скопировать номер';
copyButton.textContent = 'Скопировать адрес';
}, 1500);
} catch {
status.className = 'status-line is-unavailable';
status.textContent = 'Не удалось скопировать номер кошелька.';
status.textContent = 'Не удалось скопировать адрес кошелька.';
status.style.display = '';
}
});
walletRow.append(walletValue, copyButton);
const walletHeading = document.createElement('h4');
walletHeading.className = 'registration-payment-wallet-heading';
walletHeading.textContent = 'Ваш Solana-кошелёк в Сиянии';
const walletHint = document.createElement('p');
walletHint.className = 'meta-muted registration-payment-wallet-hint';
walletHint.textContent = 'Для регистрации пополните этот Solana-кошелёк. Он уже создан из ваших ключей SHiNE.';
const walletLabel = document.createElement('label');
walletLabel.className = 'field-label';
walletLabel.textContent = 'Адрес кошелька';
walletRow.append(walletHeading, walletHint, walletLabel, walletValue, copyButton);
const balanceRow = document.createElement('div');
balanceRow.className = 'row wrap-row';
balanceRow.className = 'registration-payment-balance';
const balanceValue = document.createElement('strong');
balanceValue.className = 'registration-payment-balance-value';
balanceValue.setAttribute('aria-live', 'polite');
balanceValue.textContent = `${formatSol(parseBalanceSol(state.registrationPayment.balanceSOL), 6)} SOL`;
const refreshButton = document.createElement('button');
refreshButton.className = 'icon-btn payment-refresh-btn';
refreshButton.className = 'secondary-btn registration-payment-action registration-payment-refresh-btn';
refreshButton.type = 'button';
refreshButton.innerHTML = iconHtml('refresh');
refreshButton.title = 'Обновить баланс';
refreshButton.setAttribute('aria-label', 'Обновить баланс');
refreshButton.textContent = '↻ Обновить';
refreshButton.title = 'Обновить баланс Solana';
// Коротко и по-человечески; технические подробности — во всплывающей подсказке.
const showWalletError = (error, fallback) => {
@@ -227,7 +236,7 @@ export function render({ navigate }) {
const address = String(addressOverride || walletValue.value || '').trim();
if (!address) return null;
refreshButton.disabled = true;
refreshButton.classList.add('is-loading');
refreshButton.textContent = '↻ Обновляем…';
try {
const balance = await getBalanceSol({
endpoint: state.entrySettings.solanaServer,
@@ -235,13 +244,13 @@ export function render({ navigate }) {
});
state.registrationPayment.balanceSOL = String(balance.sol);
balanceValue.textContent = `${formatSol(balance.sol, 6)} SOL`;
return Number(balance.sol) || 0;
return BigInt(balance.lamports);
} catch (error) {
if (showError) showWalletError(error, 'Не удалось обновить баланс. Проверьте связь и попробуйте ещё раз.');
return null;
} finally {
refreshButton.disabled = false;
refreshButton.classList.remove('is-loading');
refreshButton.textContent = '↻ Обновить';
}
};
@@ -263,17 +272,23 @@ export function render({ navigate }) {
void refreshBalance();
});
balanceRow.append(balanceValue, refreshButton);
const balanceInfo = document.createElement('div');
balanceInfo.className = 'registration-payment-balance-info';
const balanceLabel = document.createElement('span');
balanceLabel.className = 'registration-payment-balance-label';
balanceLabel.textContent = 'Баланс';
balanceInfo.append(balanceLabel, balanceValue);
balanceRow.append(balanceInfo, refreshButton);
const isTestContour = isTestRegistrationContour();
const topupButton = document.createElement('button');
topupButton.className = 'ghost-btn';
topupButton.className = 'secondary-btn registration-payment-action registration-payment-topup-btn';
topupButton.type = 'button';
topupButton.textContent = 'Тестовое пополнение (пока доступно в тестовом режиме)';
topupButton.textContent = `Тестовое пополнение (+${TEST_TOPUP_AMOUNT_SOL} SOL)`;
topupButton.addEventListener('click', async () => {
status.style.display = 'none';
topupButton.disabled = true;
const defaultText = 'Тестовое пополнение (пока доступно в тестовом режиме)';
const defaultText = `Тестовое пополнение (+${TEST_TOPUP_AMOUNT_SOL} SOL)`;
topupButton.textContent = 'Пополняем...';
try {
const address = await deriveUserWalletAddress();
@@ -320,20 +335,18 @@ export function render({ navigate }) {
submitButton.disabled = true;
submitButton.textContent = 'Регистрация...';
if (!pricingValid) throw new Error('Актуальная стоимость ещё не загружена. Проверьте соединение с Solana.');
const walletAddress = await deriveUserWalletAddress();
const currentBalance = await refreshBalance({ showError: true, addressOverride: walletAddress });
if (currentBalance == null) return;
const namespaceFeeSol = Number(state.registrationDraft.namespaceFeeLamports || 0) / 1e9;
const requiredSol = Math.max(MIN_REQUIRED_SOL, namespaceFeeSol + 0.004);
if (currentBalance < requiredSol) {
// Получаем цену из namespace-PDA непосредственно перед отправкой, а не из черновика.
funding = await loadFunding();
if (currentBalance < funding.requiredLamports) {
const shortage = funding.requiredLamports - currentBalance;
status.className = 'status-line is-unavailable';
status.textContent = isTestContour
? `Для регистрации нужно минимум ${requiredSol.toFixed(6)} SOL. Рекомендуем пополнить кошелёк примерно на ${Math.max(RECOMMENDED_TOPUP_SOL, namespaceFeeSol + 0.004).toFixed(6)} SOL. Сейчас на кошельке ${formatSol(currentBalance, 6)} SOL.`
: `Для регистрации пополните этот кошелёк соланами примерно на ${Math.max(RECOMMENDED_TOPUP_SOL, namespaceFeeSol + 0.004).toFixed(6)} SOL. Сейчас на кошельке ${formatSol(currentBalance, 6)} SOL. Минимум для продолжения: ${requiredSol.toFixed(6)} SOL.`;
status.textContent = `Для регистрации пополните кошелёк минимум на ${solFromLamports(shortage)} SOL. Цена namespace ${solFromLamports(funding.namespaceFee)} SOL уже включает депозит PDA; фактическая комиссия сети оплачивается отдельно.`;
if (isTestContour) status.textContent += ` В devnet можно использовать «Тестовое пополнение».`;
status.style.display = '';
if (isTestContour) {
status.textContent += ` Нажмите «Тестовое пополнение», чтобы сразу добавить ${TEST_TOPUP_AMOUNT_SOL} SOL без перехода на другой экран.`;
}
return;
}
@@ -387,20 +400,38 @@ export function render({ navigate }) {
}
});
const namespaceFeeSol = Number(state.registrationDraft.namespaceFeeLamports || 0) / 1e9;
const displayTopupSol = Math.max(RECOMMENDED_TOPUP_SOL, namespaceFeeSol + 0.004);
card.innerHTML = `
<h1 class="signup-title">Создание аккаунта в Solana</h1>
<p class="auth-copy">В блокчейне Solana для вас будет создана личная запись (PDA), которая не зависит от одного сервера Сияния. Разовая регистрация в namespace: ${formatSol(namespaceFeeSol, 6)} SOL. Пополните кошелёк примерно на ${formatSol(displayTopupSol, 6)} SOL с учётом сетевых расходов.</p>
<label class="stack"><span class="field-label">Номер кошелька</span></label>
<div class="stack">
<span class="field-label">Баланс (Solana)</span>
</div>
<p class="auth-copy">В Solana будет создана ваша независимая запись (PDA). Депозит PDA включён в стоимость namespace. Сетевая комиссия Solana оплачивается отдельно.</p>
`;
card.children[2].append(walletRow);
card.children[3].append(balanceRow);
const priceLine = document.createElement('p');
priceLine.className = 'registration-payment-fees';
priceLine.textContent = 'Проверяем актуальную стоимость в Solana…';
card.append(priceLine);
submitButton.disabled = true;
const loadFunding = async () => {
const fullLogin = String(state.registrationDraft.login || '').trim();
const name = fullLogin.split('@')[1];
if (!name) throw new Error('В логине не указан namespace');
const solanaEndpoint = state.entrySettings.solanaServer;
const [namespace, solana] = await Promise.all([
getNamespace({ namespace: name, solanaEndpoint }),
loadSolanaWeb3(),
]);
const connection = new solana.Connection(solanaEndpoint, 'confirmed');
const rentLamports = await connection.getMinimumBalanceForRentExemption(USER_PDA_SPACE, 'confirmed');
const latestFunding = calculateRegistrationFunding({ namespaceFeeLamports: namespace.registrationFeeLamports, rentLamports });
funding = latestFunding;
priceLine.textContent = `Регистрация в namespace: ${solFromLamports(funding.namespaceFee)} SOL (депозит PDA включён). Для оплаты на кошельке: не менее ${solFromLamports(funding.requiredLamports)} SOL, включая небольшой запас на комиссию сети. Спишется фактическая комиссия сети, остаток сохранится.`;
return funding;
};
card.append(walletRow, balanceRow);
if (isTestContour) {
card.append(topupButton);
const testHint = document.createElement('p');
testHint.className = 'meta-muted registration-payment-test-hint';
testHint.textContent = 'Только для сети devnet. Тестовые SOL не имеют реальной стоимости.';
card.append(testHint);
}
card.append(submitButton, status);
card.prepend(createRegistrationStepper(3));
@@ -420,9 +451,12 @@ export function render({ navigate }) {
try {
const walletAddress = await deriveUserWalletAddress();
await refreshBalance({ addressOverride: walletAddress });
await loadFunding();
pricingValid = true;
submitButton.disabled = false;
} catch (error) {
status.className = 'status-line is-unavailable';
status.textContent = `Не удалось подготовить blockchain key: ${error?.message || 'unknown'}`;
status.textContent = `Не удалось подготовить регистрацию: ${error?.message || 'unknown'}`;
status.style.display = '';
}
})();