SHA256
766 lines
34 KiB
JavaScript
766 lines
34 KiB
JavaScript
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
|
||
import { createTopBar } from '../components/topbar.js';
|
||
import { createRegistrationStepper } from '../components/registration-stepper.js';
|
||
import {
|
||
authService,
|
||
authorizeSession,
|
||
refreshSessions,
|
||
resetRegistrationFlow,
|
||
setAuthError,
|
||
setAuthInfo,
|
||
state,
|
||
} from '../state.js';
|
||
import { clearStoredMessages } from '../services/message-store.js';
|
||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||
import {
|
||
createSolanaWalletFromPrivateBase58,
|
||
formatSol,
|
||
getBalanceSol,
|
||
transferSol,
|
||
} from '../services/solana-wallet-service.js';
|
||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||
import {
|
||
checkLoginExistsOnSolana,
|
||
formatSolanaErrorDetails,
|
||
isSolanaRpcUnavailableError,
|
||
isUserAlreadyExistsSolanaError,
|
||
registerUserOnSolana,
|
||
} from '../services/solana-register-service.js';
|
||
import { defaultServerLogin } from '../deploy-config.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 TEST_TOPUP_AMOUNT_SOL = 0.02;
|
||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||
const TEST_TOPUP_SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
||
const AUTO_LOGIN_INITIAL_DELAY_MS = 1000;
|
||
const AUTO_LOGIN_RETRY_MS = 2000;
|
||
const REGISTRATION_PROGRESS_DURATION_MS = 12000;
|
||
const REGISTRATION_POLL_START_DELAY_MS = 4000;
|
||
const REGISTRATION_POLL_INTERVAL_MS = 2000;
|
||
const REGISTRATION_CONFIRM_TIMEOUT_MS = 25000;
|
||
const REGISTRATION_SUCCESS_SETTLE_DELAY_MS = 2000;
|
||
const EMPTY_PASSWORD_WORDS = Array.from({ length: 12 }, () => '');
|
||
|
||
function getExplorerClusterName(endpoint) {
|
||
const source = String(endpoint || '').trim().toLowerCase();
|
||
if (!source) return 'mainnet-beta';
|
||
if (source.includes('devnet')) return 'devnet';
|
||
if (source.includes('testnet')) return 'testnet';
|
||
return 'mainnet-beta';
|
||
}
|
||
|
||
function isTestRegistrationContour() {
|
||
return getSolanaCluster() === 'devnet';
|
||
}
|
||
|
||
function makeSolanaExplorerTxUrl(signature, endpoint) {
|
||
const cleanSignature = String(signature || '').trim();
|
||
if (!cleanSignature) return '';
|
||
const cluster = getSolanaCluster() || getExplorerClusterName(endpoint);
|
||
const url = new URL(`https://explorer.solana.com/tx/${encodeURIComponent(cleanSignature)}`);
|
||
if (cluster !== 'mainnet-beta') {
|
||
url.searchParams.set('cluster', cluster);
|
||
}
|
||
return url.toString();
|
||
}
|
||
|
||
function parseBalanceSol(value) {
|
||
const parsed = Number.parseFloat(String(value || '').replace(',', '.'));
|
||
return Number.isFinite(parsed) ? parsed : 0;
|
||
}
|
||
|
||
function registrationAccessServerLogin() {
|
||
const configured = String(state.entrySettings.shineServerLogin || defaultServerLogin || '').trim().toLowerCase();
|
||
if (!configured) return '';
|
||
return normalizeFullLogin(configured.includes('@') ? configured : `${configured}@shine`);
|
||
}
|
||
|
||
function getCryptoRuntimeState() {
|
||
const hasCrypto = Boolean(globalThis.crypto);
|
||
const hasGetRandomValues = Boolean(globalThis.crypto && typeof globalThis.crypto.getRandomValues === 'function');
|
||
const hasSubtle = Boolean(globalThis.crypto && (globalThis.crypto.subtle || globalThis.crypto.webkitSubtle));
|
||
const secureContext = window.isSecureContext === true;
|
||
return { hasCrypto, hasGetRandomValues, hasSubtle, secureContext };
|
||
}
|
||
|
||
function clamp(value, min, max) {
|
||
return Math.max(min, Math.min(max, value));
|
||
}
|
||
|
||
export async function completeRegistrationLogin({ navigate, keyBundle }) {
|
||
await authService.reconnect(state.entrySettings.shineServer);
|
||
const result = await authService.createSessionForExistingUser(
|
||
state.registrationDraft.login,
|
||
state.registrationDraft.password,
|
||
);
|
||
|
||
// После регистрации оба рабочих ключа сохраняются автоматически.
|
||
// Приватный Recovery/root key не записывается на устройство.
|
||
await authService.persistSelectedKeys(result.login, result.storagePwd, keyBundle);
|
||
await authService.persistSessionMaterial(result.login, result.sessionMaterial);
|
||
await clearStoredMessages(state.registrationDraft.login).catch(() => {});
|
||
|
||
const resumed = await authService.resumeSession(result.login, result.sessionId);
|
||
const resumedLogin = resumed.login || result.login;
|
||
const resumedSessionId = resumed.sessionId || result.sessionId;
|
||
const resumedStoragePwd = resumed.storagePwd || result.storagePwd;
|
||
|
||
authorizeSession({
|
||
login: resumedLogin,
|
||
sessionId: resumedSessionId,
|
||
storagePwd: resumedStoragePwd,
|
||
});
|
||
|
||
// Создаём HEADER сразу после успешной регистрации (Solana и Arweave).
|
||
// При сбое регистрация остаётся успешной: перед первым блоком AddBlock
|
||
// повторно создаст отсутствующий HEADER существующим механизмом.
|
||
try {
|
||
await authService.ensureBlockchainHeader(resumedLogin, resumedStoragePwd);
|
||
} catch (error) {
|
||
console.warn('Не удалось создать HEADER после регистрации; повторим перед первым блоком', error);
|
||
}
|
||
|
||
state.loginDraft.login = resumedLogin;
|
||
state.loginDraft.password = '';
|
||
state.loginDraft.passwordMode = 'single';
|
||
state.loginDraft.passwordWords = EMPTY_PASSWORD_WORDS.slice();
|
||
|
||
state.registrationSuccess = { flowType: state.registrationDraft.flowType, login: resumedLogin };
|
||
state.registrationDraft.flowType = '';
|
||
state.registrationDraft.password = '';
|
||
state.registrationDraft.passwordMode = 'single';
|
||
state.registrationDraft.passwordWords = EMPTY_PASSWORD_WORDS.slice();
|
||
state.registrationDraft.passwordWordsLinked = false;
|
||
state.registrationDraft.usePromoCode = false;
|
||
state.registrationDraft.promoCode = '';
|
||
state.registrationDraft.storagePwd = '';
|
||
state.registrationDraft.sessionId = '';
|
||
state.registrationDraft.pendingKeyBundle = null;
|
||
state.registrationDraft.pendingSessionMaterial = null;
|
||
state.registrationDraft.preGeneratedKeyBundle = null;
|
||
|
||
state.registrationPayment.walletAddress = '';
|
||
state.registrationPayment.balanceSOL = '0.0000';
|
||
|
||
await refreshSessions();
|
||
setAuthInfo(`Регистрация завершена. Вы автоматически вошли как ${resumedLogin}.`);
|
||
|
||
const nextHash = String(state.authReturnHash || '').trim();
|
||
state.authReturnHash = '';
|
||
if (nextHash.startsWith('/')) {
|
||
navigate(nextHash.slice(1));
|
||
} else {
|
||
navigate('registration-success-view');
|
||
}
|
||
}
|
||
|
||
export function render({ navigate }) {
|
||
const screen = document.createElement('section');
|
||
screen.className = 'stack';
|
||
|
||
const card = document.createElement('div');
|
||
card.className = 'card stack registration-payment-card';
|
||
let funding = null;
|
||
let pricingValid = false;
|
||
|
||
const status = document.createElement('p');
|
||
status.className = 'status-line is-unavailable';
|
||
status.style.display = 'none';
|
||
|
||
const walletValue = document.createElement('input');
|
||
walletValue.className = 'input';
|
||
walletValue.type = 'text';
|
||
walletValue.value = state.registrationPayment.walletAddress || '';
|
||
walletValue.readOnly = true;
|
||
walletValue.style.width = '100%';
|
||
|
||
const walletRow = document.createElement('div');
|
||
walletRow.className = 'registration-payment-wallet';
|
||
|
||
const copyButton = document.createElement('button');
|
||
copyButton.className = 'secondary-btn registration-payment-action registration-payment-copy-btn';
|
||
copyButton.type = 'button';
|
||
copyButton.textContent = 'Скопировать адрес';
|
||
copyButton.addEventListener('click', async () => {
|
||
try {
|
||
await navigator.clipboard.writeText(walletValue.value);
|
||
copyButton.textContent = '✓ Адрес скопирован';
|
||
window.setTimeout(() => {
|
||
copyButton.textContent = 'Скопировать адрес';
|
||
}, 1500);
|
||
} catch {
|
||
status.className = 'status-line is-unavailable';
|
||
status.textContent = 'Не удалось скопировать адрес кошелька.';
|
||
status.style.display = '';
|
||
}
|
||
});
|
||
|
||
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 = '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 = 'secondary-btn registration-payment-action registration-payment-refresh-btn';
|
||
refreshButton.type = 'button';
|
||
refreshButton.textContent = '↻ Обновить';
|
||
refreshButton.title = 'Обновить баланс Solana';
|
||
|
||
// Коротко и по-человечески; технические подробности — во всплывающей подсказке.
|
||
const showWalletError = (error, fallback) => {
|
||
status.className = 'status-line is-unavailable';
|
||
status.textContent = error?.code === 'NO_KEYS'
|
||
? 'Не хватает данных регистрации. Вернитесь назад и нажмите «Далее».'
|
||
: fallback;
|
||
status.title = error?.message || '';
|
||
status.style.display = '';
|
||
};
|
||
|
||
const refreshBalance = async ({ showError = true, addressOverride = '' } = {}) => {
|
||
const address = String(addressOverride || walletValue.value || '').trim();
|
||
if (!address) return null;
|
||
refreshButton.disabled = true;
|
||
refreshButton.textContent = '↻ Обновляем…';
|
||
try {
|
||
const balance = await getBalanceSol({
|
||
endpoint: state.entrySettings.solanaServer,
|
||
address,
|
||
});
|
||
state.registrationPayment.balanceSOL = String(balance.sol);
|
||
balanceValue.textContent = `${formatSol(balance.sol, 6)} SOL`;
|
||
return BigInt(balance.lamports);
|
||
} catch (error) {
|
||
if (showError) showWalletError(error, 'Не удалось обновить баланс. Проверьте связь и попробуйте ещё раз.');
|
||
return null;
|
||
} finally {
|
||
refreshButton.disabled = false;
|
||
refreshButton.textContent = '↻ Обновить';
|
||
}
|
||
};
|
||
|
||
const deriveUserWalletAddress = async () => {
|
||
const keyBundle = state.registrationDraft.preGeneratedKeyBundle;
|
||
if (!keyBundle) throw new Error('Ключи ещё не сгенерированы. Вернитесь на предыдущий шаг.');
|
||
const { publicKeyB64 } = keyBundle.blockchainPair;
|
||
const raw = atob(publicKeyB64);
|
||
const bytes = new Uint8Array(raw.length);
|
||
for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
|
||
const { PublicKey } = await loadSolanaWeb3();
|
||
const address = new PublicKey(bytes).toBase58();
|
||
state.registrationPayment.walletAddress = address;
|
||
walletValue.value = address;
|
||
return address;
|
||
};
|
||
|
||
refreshButton.addEventListener('click', () => {
|
||
void refreshBalance();
|
||
});
|
||
|
||
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 = 'secondary-btn registration-payment-action registration-payment-topup-btn';
|
||
topupButton.type = 'button';
|
||
topupButton.textContent = `Тестовое пополнение (+${TEST_TOPUP_AMOUNT_SOL} SOL)`;
|
||
topupButton.addEventListener('click', async () => {
|
||
status.style.display = 'none';
|
||
topupButton.disabled = true;
|
||
const defaultText = `Тестовое пополнение (+${TEST_TOPUP_AMOUNT_SOL} SOL)`;
|
||
topupButton.textContent = 'Пополняем...';
|
||
try {
|
||
const address = await deriveUserWalletAddress();
|
||
const sender = await createSolanaWalletFromPrivateBase58(TEST_TOPUP_SENDER_PRIVATE_32_BASE58);
|
||
await transferSol({
|
||
endpoint: DEVNET_ENDPOINT,
|
||
fromKeypair: sender.keypair,
|
||
toAddress: address,
|
||
amountSol: TEST_TOPUP_AMOUNT_SOL,
|
||
});
|
||
const balance = await getBalanceSol({
|
||
endpoint: DEVNET_ENDPOINT,
|
||
address,
|
||
});
|
||
state.registrationPayment.balanceSOL = String(balance.sol);
|
||
balanceValue.textContent = `${formatSol(balance.sol, 6)} SOL`;
|
||
status.className = 'status-line is-available';
|
||
status.textContent = `Тестовое пополнение выполнено: +${TEST_TOPUP_AMOUNT_SOL} SOL. Баланс: ${formatSol(balance.sol, 6)} SOL.`;
|
||
status.style.display = '';
|
||
} catch (error) {
|
||
showWalletError(error, 'Не удалось выполнить тестовое пополнение. Попробуйте ещё раз.');
|
||
} finally {
|
||
topupButton.disabled = false;
|
||
topupButton.textContent = defaultText;
|
||
}
|
||
});
|
||
|
||
const submitButton = document.createElement('button');
|
||
submitButton.className = 'primary-btn';
|
||
submitButton.type = 'button';
|
||
submitButton.textContent = 'Зарегистрироваться';
|
||
submitButton.addEventListener('click', async () => {
|
||
status.style.display = 'none';
|
||
|
||
const cryptoState = getCryptoRuntimeState();
|
||
if (!cryptoState.hasCrypto || !cryptoState.hasGetRandomValues || !cryptoState.hasSubtle) {
|
||
status.className = 'status-line is-unavailable';
|
||
status.textContent = 'Криптография браузера недоступна. Откройте приложение через HTTPS tunnel или localhost и повторите регистрацию.';
|
||
status.style.display = '';
|
||
return;
|
||
}
|
||
|
||
try {
|
||
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;
|
||
// Получаем цену из namespace-PDA непосредственно перед отправкой, а не из черновика.
|
||
funding = await loadFunding();
|
||
if (currentBalance < funding.requiredLamports) {
|
||
const shortage = funding.requiredLamports - currentBalance;
|
||
status.className = 'status-line is-unavailable';
|
||
status.textContent = `Для регистрации пополните кошелёк минимум на ${solFromLamports(shortage)} SOL. Цена namespace ${solFromLamports(funding.namespaceFee)} SOL уже включает депозит PDA; фактическая комиссия сети оплачивается отдельно.`;
|
||
if (isTestContour) status.textContent += ` В devnet можно использовать «Тестовое пополнение».`;
|
||
status.style.display = '';
|
||
return;
|
||
}
|
||
|
||
const keyBundle = state.registrationDraft.preGeneratedKeyBundle;
|
||
if (!keyBundle) throw new Error('Ключи не найдены. Вернитесь на предыдущий шаг.');
|
||
|
||
// Перед on-chain регистрацией перепроверяем логин ещё раз:
|
||
// между экраном выбора логина и оплатой его мог занять кто-то другой.
|
||
const loginStateBeforeRegister = await checkLoginExistsOnSolana({
|
||
login: state.registrationDraft.login,
|
||
solanaEndpoint: state.entrySettings.solanaServer,
|
||
});
|
||
if (loginStateBeforeRegister?.exists) {
|
||
throw new Error('Этот логин уже зарегистрирован. Войдите в существующий аккаунт или выберите другой логин.');
|
||
}
|
||
|
||
// Регистрация на Solana (смарт контракт)
|
||
submitButton.textContent = 'Регистрация в Solana...';
|
||
let registrationTxId = '';
|
||
try {
|
||
const registrationResult = await registerUserOnSolana({
|
||
login: state.registrationDraft.login,
|
||
keyBundle,
|
||
solanaEndpoint: state.entrySettings.solanaServer,
|
||
accessServers: [registrationAccessServerLogin()],
|
||
});
|
||
registrationTxId = String(registrationResult?.signature || '').trim();
|
||
} catch (solanaError) {
|
||
const solanaMsg = formatSolanaErrorDetails(solanaError);
|
||
if (solanaMsg.includes('already') || isUserAlreadyExistsSolanaError(solanaError)) {
|
||
throw new Error('Этот логин уже зарегистрирован. Войдите в существующий аккаунт или выберите другой логин.');
|
||
}
|
||
if (isSolanaRpcUnavailableError(solanaError)) {
|
||
throw new Error('Нет связи с сервером Solana. Попробуйте ещё раз позже.');
|
||
}
|
||
throw new Error(`Ошибка регистрации в Solana: ${solanaMsg}`);
|
||
}
|
||
|
||
renderSolanaRegistrationStage({ navigate, status, keyBundle, registrationTxId });
|
||
} catch (error) {
|
||
const message = isSolanaRpcUnavailableError(error)
|
||
? 'Нет связи с сервером Solana. Попробуйте ещё раз позже.'
|
||
: toUserMessage(error, 'Не удалось завершить регистрацию.');
|
||
setAuthError(message);
|
||
status.className = 'status-line is-unavailable';
|
||
status.textContent = message;
|
||
status.style.display = '';
|
||
} finally {
|
||
submitButton.disabled = false;
|
||
submitButton.textContent = 'Зарегистрироваться';
|
||
}
|
||
});
|
||
|
||
card.innerHTML = `
|
||
<h1 class="signup-title">Создание аккаунта в Solana</h1>
|
||
<p class="auth-copy">В Solana будет создана ваша независимая запись (PDA). Депозит PDA включён в стоимость namespace. Сетевая комиссия Solana оплачивается отдельно.</p>
|
||
`;
|
||
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));
|
||
|
||
screen.append(
|
||
createTopBar({
|
||
title: 'Оплата регистрации',
|
||
back: { label: '←', onClick: () => {
|
||
if (parseBalanceSol(state.registrationPayment.balanceSOL) > 0 && !window.confirm('Если вы уже пополнили этот кошелёк, не меняйте логин и пароль: это изменит адрес кошелька. Вернуться к паролю?')) return;
|
||
state.registrationDraft.uiStep = 2; navigate('register-view');
|
||
} },
|
||
}),
|
||
card,
|
||
);
|
||
|
||
(async () => {
|
||
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 = `Не удалось подготовить регистрацию: ${error?.message || 'unknown'}`;
|
||
status.style.display = '';
|
||
}
|
||
})();
|
||
|
||
return screen;
|
||
}
|
||
|
||
function renderSolanaRegistrationStage({ navigate, status, keyBundle, registrationTxId = '' }) {
|
||
const screen = document.querySelector('section.stack');
|
||
if (!screen) return;
|
||
const headerBackButton = screen.querySelector('.topbar .topbar__back');
|
||
const card = screen.querySelector('.card.stack');
|
||
if (!card) return;
|
||
card.classList.add('registration-finish-card');
|
||
|
||
let progressTimerId = null;
|
||
let pollStartTimerId = null;
|
||
let pollTimerId = null;
|
||
let successTimerId = null;
|
||
let confirmationInFlight = false;
|
||
let stageClosed = false;
|
||
let successPending = false;
|
||
let timeoutShown = false;
|
||
const stageStartedAt = Date.now();
|
||
const txExplorerUrl = makeSolanaExplorerTxUrl(registrationTxId, state.entrySettings.solanaServer);
|
||
|
||
const title = document.createElement('h2');
|
||
title.className = 'registration-finish-title';
|
||
title.textContent = 'Идёт регистрация в блокчейне...';
|
||
|
||
const hint = document.createElement('p');
|
||
hint.className = 'auth-copy registration-finish-text';
|
||
hint.textContent = 'Ждём, пока транзакция будет полностью одобрена сетью Solana.';
|
||
|
||
const txIdLine = document.createElement('p');
|
||
txIdLine.className = 'meta-muted registration-finish-tx';
|
||
if (registrationTxId && txExplorerUrl) {
|
||
const txLabel = document.createElement('span');
|
||
txLabel.textContent = 'Tx ID регистрации: ';
|
||
const txLink = document.createElement('a');
|
||
txLink.className = 'registration-finish-tx-link';
|
||
txLink.href = txExplorerUrl;
|
||
txLink.target = '_blank';
|
||
txLink.rel = 'noopener noreferrer';
|
||
txLink.textContent = registrationTxId;
|
||
txIdLine.append(txLabel, txLink);
|
||
} else {
|
||
txIdLine.textContent = 'Tx ID регистрации: ожидаем подтверждённую подпись';
|
||
}
|
||
|
||
const progressWrap = document.createElement('div');
|
||
progressWrap.className = 'registration-progress';
|
||
|
||
const progressBar = document.createElement('div');
|
||
progressBar.className = 'registration-progress-bar';
|
||
progressWrap.append(progressBar);
|
||
|
||
const progress = document.createElement('p');
|
||
progress.className = 'meta-muted registration-finish-progress';
|
||
progress.textContent = 'Подготавливаем проверку подтверждения...';
|
||
|
||
const pollStatus = document.createElement('p');
|
||
pollStatus.className = 'meta-muted registration-finish-progress';
|
||
pollStatus.textContent = 'Через несколько секунд начнём проверять подтверждение регистрации.';
|
||
|
||
const stopTimers = () => {
|
||
if (progressTimerId) {
|
||
window.clearInterval(progressTimerId);
|
||
progressTimerId = null;
|
||
}
|
||
if (pollStartTimerId) {
|
||
window.clearTimeout(pollStartTimerId);
|
||
pollStartTimerId = null;
|
||
}
|
||
if (pollTimerId) {
|
||
window.clearInterval(pollTimerId);
|
||
pollTimerId = null;
|
||
}
|
||
if (successTimerId) {
|
||
window.clearTimeout(successTimerId);
|
||
successTimerId = null;
|
||
}
|
||
};
|
||
|
||
const updateVisualProgress = () => {
|
||
const elapsed = Date.now() - stageStartedAt;
|
||
let widthPercent = 0;
|
||
if (elapsed <= REGISTRATION_PROGRESS_DURATION_MS) {
|
||
const phaseRatio = clamp(elapsed / REGISTRATION_PROGRESS_DURATION_MS, 0, 1);
|
||
widthPercent = 100 * (1 - ((1 - phaseRatio) ** 1.85));
|
||
} else {
|
||
const extraRatio = 1 - Math.exp(-(elapsed - REGISTRATION_PROGRESS_DURATION_MS) / 9000);
|
||
widthPercent = 88 + (10 * clamp(extraRatio, 0, 1));
|
||
}
|
||
progressBar.style.width = `${clamp(widthPercent, 0, 98)}%`;
|
||
|
||
if (elapsed < REGISTRATION_POLL_START_DELAY_MS) {
|
||
progress.textContent = 'Отправили регистрацию в сеть. Даём транзакции несколько секунд на обработку.';
|
||
return;
|
||
}
|
||
if (elapsed < REGISTRATION_CONFIRM_TIMEOUT_MS) {
|
||
progress.textContent = 'Идёт ожидание подтверждения Solana. Индикатор может замедлиться, это нормально.';
|
||
return;
|
||
}
|
||
progress.textContent = 'Подтверждение затянулось. Продолжаем автоматическую проверку.';
|
||
};
|
||
|
||
const finalizeSuccess = () => {
|
||
if (stageClosed || successPending) return;
|
||
successPending = true;
|
||
stopTimers();
|
||
progress.textContent = 'Подтверждение получено. Завершаем регистрацию...';
|
||
pollStatus.textContent = 'Запись уже найдена в Solana, готовим финальный экран.';
|
||
status.style.display = 'none';
|
||
progressBar.style.transition = `width ${REGISTRATION_SUCCESS_SETTLE_DELAY_MS}ms ease-out`;
|
||
progressBar.style.width = '100%';
|
||
successTimerId = window.setTimeout(() => {
|
||
if (stageClosed) return;
|
||
stageClosed = true;
|
||
renderSolanaDoneStage({ navigate, status, keyBundle, registrationTxId });
|
||
}, REGISTRATION_SUCCESS_SETTLE_DELAY_MS);
|
||
};
|
||
|
||
const showTimeoutState = () => {
|
||
if (timeoutShown || stageClosed) return;
|
||
timeoutShown = true;
|
||
status.className = 'status-line is-unavailable';
|
||
status.textContent = 'Подтверждение не пришло вовремя. Возможно, регистрация уже прошла, а возможно ещё нет. Проверьте Tx ID ниже: мы продолжим автоматическую проверку.';
|
||
status.style.display = '';
|
||
pollStatus.textContent = 'Пока подтверждения нет. Подождите ещё немного, мы продолжаем проверять регистрацию.';
|
||
};
|
||
|
||
const tryCheckRegistration = async () => {
|
||
if (stageClosed || confirmationInFlight) return;
|
||
confirmationInFlight = true;
|
||
progress.textContent = 'Проверяем подтверждение регистрации в Solana...';
|
||
status.style.display = timeoutShown ? '' : 'none';
|
||
try {
|
||
const result = await checkLoginExistsOnSolana({
|
||
login: state.registrationDraft.login,
|
||
solanaEndpoint: state.entrySettings.solanaServer,
|
||
});
|
||
if (result?.exists) {
|
||
finalizeSuccess();
|
||
return;
|
||
}
|
||
pollStatus.textContent = 'Пока ещё не прошла, подождите ещё немного...';
|
||
if ((Date.now() - stageStartedAt) >= REGISTRATION_CONFIRM_TIMEOUT_MS) {
|
||
showTimeoutState();
|
||
}
|
||
} catch (error) {
|
||
console.warn('Registration confirmation check failed', toUserMessage(error, 'registration-confirmation'));
|
||
pollStatus.textContent = 'Проверяем регистрацию повторно...';
|
||
if ((Date.now() - stageStartedAt) >= REGISTRATION_CONFIRM_TIMEOUT_MS) {
|
||
showTimeoutState();
|
||
}
|
||
} finally {
|
||
confirmationInFlight = false;
|
||
}
|
||
};
|
||
|
||
if (headerBackButton) {
|
||
const replacement = headerBackButton.cloneNode(true);
|
||
replacement.addEventListener('click', () => {
|
||
stageClosed = true;
|
||
stopTimers();
|
||
resetRegistrationFlow();
|
||
navigate('start-view');
|
||
});
|
||
headerBackButton.replaceWith(replacement);
|
||
}
|
||
|
||
card.innerHTML = '';
|
||
status.style.display = 'none';
|
||
card.append(title, hint, txIdLine, progressWrap, progress, pollStatus, status);
|
||
|
||
updateVisualProgress();
|
||
progressTimerId = window.setInterval(() => {
|
||
if (stageClosed) return;
|
||
updateVisualProgress();
|
||
if ((Date.now() - stageStartedAt) >= REGISTRATION_CONFIRM_TIMEOUT_MS) {
|
||
showTimeoutState();
|
||
}
|
||
}, 160);
|
||
|
||
pollStartTimerId = window.setTimeout(() => {
|
||
if (stageClosed) return;
|
||
void tryCheckRegistration();
|
||
pollTimerId = window.setInterval(() => {
|
||
void tryCheckRegistration();
|
||
}, REGISTRATION_POLL_INTERVAL_MS);
|
||
}, REGISTRATION_POLL_START_DELAY_MS);
|
||
}
|
||
|
||
function renderSolanaDoneStage({ navigate, status, keyBundle, registrationTxId = '' }) {
|
||
const screen = document.querySelector('section.stack');
|
||
if (!screen) return;
|
||
const headerBackButton = screen.querySelector('.topbar .topbar__back');
|
||
const card = screen.querySelector('.card.stack');
|
||
if (!card) return;
|
||
card.classList.add('registration-finish-card');
|
||
|
||
let initialDelayId = null;
|
||
let retryTimerId = null;
|
||
let loginInFlight = false;
|
||
let loginCompleted = false;
|
||
const txExplorerUrl = makeSolanaExplorerTxUrl(registrationTxId, state.entrySettings.solanaServer);
|
||
|
||
const title = document.createElement('h2');
|
||
title.className = 'registration-finish-title';
|
||
title.textContent = 'Поздравляем, регистрация завершена';
|
||
|
||
const hint = document.createElement('p');
|
||
hint.className = 'auth-copy registration-finish-text';
|
||
hint.textContent = 'Регистрация подтверждена в блокчейне Solana. Сейчас выполним автоматический вход в аккаунт.';
|
||
|
||
const txIdLine = document.createElement('p');
|
||
txIdLine.className = 'meta-muted registration-finish-tx';
|
||
if (registrationTxId && txExplorerUrl) {
|
||
const txLabel = document.createElement('span');
|
||
txLabel.textContent = 'Tx ID регистрации: ';
|
||
const txLink = document.createElement('a');
|
||
txLink.className = 'registration-finish-tx-link';
|
||
txLink.href = txExplorerUrl;
|
||
txLink.target = '_blank';
|
||
txLink.rel = 'noopener noreferrer';
|
||
txLink.textContent = registrationTxId;
|
||
txIdLine.append(txLabel, txLink);
|
||
} else {
|
||
txIdLine.textContent = 'Tx ID регистрации: ожидаем подтверждённую подпись';
|
||
}
|
||
|
||
const progress = document.createElement('p');
|
||
progress.className = 'meta-muted registration-finish-progress';
|
||
progress.textContent = 'Подготавливаем проверку регистрации...';
|
||
|
||
const stopAutoLogin = () => {
|
||
if (initialDelayId) {
|
||
window.clearTimeout(initialDelayId);
|
||
initialDelayId = null;
|
||
}
|
||
if (retryTimerId) {
|
||
window.clearInterval(retryTimerId);
|
||
retryTimerId = null;
|
||
}
|
||
};
|
||
|
||
const tryAutoLogin = async () => {
|
||
if (loginCompleted || loginInFlight) return;
|
||
loginInFlight = true;
|
||
progress.textContent = 'Проверяем, прошла ли регистрация...';
|
||
status.style.display = 'none';
|
||
try {
|
||
await completeRegistrationLogin({ navigate, keyBundle });
|
||
loginCompleted = true;
|
||
stopAutoLogin();
|
||
} catch (error) {
|
||
if (!loginCompleted) {
|
||
progress.textContent = 'Пока ещё не прошла, подождите ещё секундочку...';
|
||
console.warn('Auto login after registration is not ready yet', toUserMessage(error, 'auto-login-wait'));
|
||
}
|
||
} finally {
|
||
loginInFlight = false;
|
||
}
|
||
};
|
||
|
||
if (headerBackButton) {
|
||
const replacement = headerBackButton.cloneNode(true);
|
||
replacement.addEventListener('click', () => {
|
||
loginCompleted = true;
|
||
stopAutoLogin();
|
||
resetRegistrationFlow();
|
||
navigate('start-view');
|
||
});
|
||
headerBackButton.replaceWith(replacement);
|
||
}
|
||
|
||
card.innerHTML = '';
|
||
card.append(title, hint, txIdLine, progress, status);
|
||
|
||
initialDelayId = window.setTimeout(() => {
|
||
if (loginCompleted) return;
|
||
void tryAutoLogin();
|
||
retryTimerId = window.setInterval(() => {
|
||
void tryAutoLogin();
|
||
}, AUTO_LOGIN_RETRY_MS);
|
||
}, AUTO_LOGIN_INITIAL_DELAY_MS);
|
||
}
|
||
|
||
/** Тот же тестовый источник +0.02 devnet SOL, что используется обычной регистрацией.
|
||
* Экспорт добавлен для FREE_CERT → Solana upgrade; поведение обычной регистрации не изменяется.
|
||
* Никогда не используйте этот встроенный devnet-кошелёк для реальных средств.
|
||
*/
|
||
export async function fundDevnetRegistrationWallet(address) {
|
||
if (!isTestRegistrationContour()) throw new Error('Тестовое пополнение разрешено только в devnet');
|
||
const cleanAddress = String(address || '').trim();
|
||
if (!cleanAddress) throw new Error('Не указан адрес пополняемого кошелька');
|
||
const sender = await createSolanaWalletFromPrivateBase58(TEST_TOPUP_SENDER_PRIVATE_32_BASE58);
|
||
await transferSol({
|
||
endpoint: DEVNET_ENDPOINT,
|
||
fromKeypair: sender.keypair,
|
||
toAddress: cleanAddress,
|
||
amountSol: TEST_TOPUP_AMOUNT_SOL,
|
||
});
|
||
return getBalanceSol({ endpoint: DEVNET_ENDPOINT, address: cleanAddress });
|
||
}
|