SHA256
344 lines
19 KiB
JavaScript
344 lines
19 KiB
JavaScript
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', title: 'Регистрация в Solana' };
|
|
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: 'Закрепить аккаунт в Solana',
|
|
back: { label: '←', onClick: () => navigate('settings-view') },
|
|
}));
|
|
|
|
const intro = element('div', 'card stack');
|
|
intro.append(
|
|
element('h3', '', 'Сделайте аккаунт независимым от сервера'),
|
|
element('p', 'meta-muted', `Ваш аккаунт ${login} зарегистрирован с помощью бесплатного сертификата Arweave. Запись неизменяема и подписана сервером-регистратором.`),
|
|
element('p', 'meta-muted', 'Сейчас управление ключами и переход на другой сервер ограничены: ваша регистрация зависит от сервера и сохранности его ключей.'),
|
|
element('p', 'meta-muted', 'После закрепления в Solana у вас появится собственная PDA: вы сможете самостоятельно менять пароль и ключи, а также пользоваться совместимыми серверами.'),
|
|
element('p', 'meta-muted', 'Логин, namespace, три публичных ключа, публикации и история Arweave останутся прежними. Для доступности истории на другом сервере требуется её синхронизация.'),
|
|
element('p', 'meta-muted', 'Регистрация в Solana оплачивается один раз. Для проведения транзакции на вашем Solana-кошельке должны быть SOL.'),
|
|
);
|
|
const introStatus = element('p', 'status-line', 'Проверяем бесплатный сертификат, PDA и актуальную стоимость…');
|
|
introStatus.setAttribute('aria-live', 'polite');
|
|
const continueButton = makeButton('Продолжить и пополнить кошелёк');
|
|
continueButton.disabled = true;
|
|
intro.append(continueButton, introStatus);
|
|
|
|
const payment = element('div', 'card stack');
|
|
payment.append(element('h3', '', 'Оплата регистрации Solana'));
|
|
const walletHint = element('p', 'meta-muted', 'Пополните этот Solana-адрес. Это ваш существующий blockchain key, новый кошелёк не создаётся.');
|
|
const walletLabel = element('label', 'field-label', 'Ваш Solana-кошелёк');
|
|
const wallet = document.createElement('input');
|
|
wallet.className = 'input'; wallet.type = 'text'; wallet.readOnly = true;
|
|
wallet.style.width = '100%'; wallet.setAttribute('aria-label', 'Адрес Solana-кошелька');
|
|
const copyButton = makeButton('Скопировать адрес', 'ghost-btn');
|
|
const amount = element('p', 'meta-muted', 'Получаем стоимость регистрации…');
|
|
const balanceLine = element('p', 'meta-muted', 'Баланс: —');
|
|
const refreshButton = makeButton('Обновить баланс', 'ghost-btn');
|
|
const topupButton = makeButton(`Тестовое пополнение (+${UPGRADE_TEST_TOPUP_SOL} SOL)`, 'ghost-btn');
|
|
const testHint = element('p', 'meta-muted', 'Тестовое пополнение доступно только в сети devnet. Тестовые SOL не имеют реальной стоимости.');
|
|
const passwordLabel = element('label', 'field-label', 'Пароль действующего аккаунта');
|
|
const password = document.createElement('input');
|
|
password.className = 'input'; password.type = 'password'; password.autocomplete = 'current-password';
|
|
password.placeholder = 'Введите пароль для подтверждения исходных ключей';
|
|
const payButton = makeButton('Оплатить и закрепить аккаунт');
|
|
const payStatus = element('p', 'status-line');
|
|
payStatus.setAttribute('aria-live', 'polite');
|
|
payment.append(walletHint, walletLabel, wallet, copyButton, amount, balanceLine, refreshButton);
|
|
if (isDevnet) payment.append(topupButton, testHint);
|
|
payment.append(passwordLabel, password, payButton, payStatus);
|
|
|
|
const syncing = element('div', 'card stack');
|
|
syncing.append(element('h3', '', 'Проверяем регистрацию'));
|
|
const syncInfo = element('p', 'meta-muted', 'Проверяем PDA в Solana и обновление статуса на сервере…');
|
|
const txLine = element('p', 'meta-muted');
|
|
const syncStatus = element('p', 'status-line');
|
|
syncStatus.setAttribute('aria-live', 'polite');
|
|
const checkButton = makeButton('Проверить ещё раз', 'ghost-btn');
|
|
syncing.append(syncInfo, txLine, syncStatus, checkButton);
|
|
|
|
const done = element('div', 'card stack');
|
|
done.append(
|
|
element('h3', '', 'Аккаунт зарегистрирован в Solana!'),
|
|
element('p', 'meta-muted', `Ваш логин ${login} и namespace не изменились. Регистрация подтверждена PDA Solana. Прежние ключи и история сохранены.`),
|
|
element('p', 'meta-muted', 'Теперь вы можете управлять ключами и выбирать совместимые серверы доступа.'),
|
|
);
|
|
const settingsButton = makeButton('Вернуться в настройки');
|
|
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;
|
|
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, `Не удалось прочитать баланс: ${error.message}`, true);
|
|
return null;
|
|
} finally {
|
|
if (!disposed) refreshButton.disabled = false;
|
|
}
|
|
}
|
|
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('Найденная PDA принадлежит другому логину');
|
|
// Если сервер ещё считает аккаунт бесплатным, проверяем совпадение с исходным сертификатом.
|
|
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('Ключи существующей PDA не соответствуют бесплатному сертификату');
|
|
}
|
|
}
|
|
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, 'PDA пока не обнаружена в Solana. Продолжаем проверку…');
|
|
return;
|
|
}
|
|
const current = await getRegistrationStatus(login);
|
|
if (disposed) return;
|
|
if (isUpgradeComplete(current.registrationStatus)) {
|
|
succeed();
|
|
return;
|
|
}
|
|
if (current.registrationStatus !== 'FREE_CERT') {
|
|
message(syncStatus, `Сервер вернул неожиданный статус: ${current.registrationStatus}.`, true);
|
|
return;
|
|
}
|
|
message(syncStatus, 'PDA создана в Solana. Ожидаем, пока сервер синхронизирует аккаунт…');
|
|
} catch (error) {
|
|
message(syncStatus, `Проверка пока не удалась: ${error.message}`, true);
|
|
} finally {
|
|
checking = false;
|
|
if (!disposed) checkButton.disabled = false;
|
|
if (!disposed && Date.now() - startedPollingAt > SYNC_NOTICE_AFTER_MS) {
|
|
syncInfo.textContent = 'Синхронизация задержалась. Можете вернуться в настройки и открыть этот экран позже: повторная оплата не нужна.';
|
|
}
|
|
}
|
|
}
|
|
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 = 'Проверяем запись Solana по вашему логину.';
|
|
}
|
|
}
|
|
async function initialize() {
|
|
if (!login.includes('@')) throw new Error('Войдите в существующий аккаунт login@namespace');
|
|
const current = await getRegistrationStatus(login);
|
|
if (disposed) return;
|
|
if (isUpgradeComplete(current.registrationStatus)) { succeed(); return; }
|
|
if (current.registrationStatus !== 'FREE_CERT') throw new Error('Переход доступен только для бесплатного аккаунта');
|
|
// Проверяем наличие 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('Для бесплатного сертификата требуется namespace типа 2');
|
|
if (!current.innerSignature64B64 || !current.blockchainPublicKey) throw new Error('Исходный сертификат отсутствует или неполон');
|
|
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.textContent = `Комиссия namespace: ${solFromLamports(funding.namespaceFee)} SOL; депозит PDA: ${solFromLamports(funding.rent)} SOL; минимум с запасом на сеть: ${solFromLamports(funding.requiredLamports)} SOL. Рекомендуется ${solFromLamports(funding.recommendedLamports)} SOL.`;
|
|
continueButton.disabled = false;
|
|
message(introStatus, 'Данные аккаунта и стоимость проверены.');
|
|
}
|
|
|
|
continueButton.addEventListener('click', () => {
|
|
show('payment');
|
|
void balanceUpdate(false);
|
|
});
|
|
copyButton.addEventListener('click', async () => {
|
|
try {
|
|
await navigator.clipboard.writeText(walletAddress);
|
|
message(payStatus, 'Адрес кошелька скопирован.');
|
|
} catch {
|
|
message(payStatus, 'Не удалось скопировать адрес. Можно скопировать его вручную.', true);
|
|
}
|
|
});
|
|
refreshButton.addEventListener('click', () => void balanceUpdate());
|
|
topupButton.addEventListener('click', async () => {
|
|
if (!isDevnet || disposed || !walletAddress) return;
|
|
topupButton.disabled = true;
|
|
try {
|
|
message(payStatus, `Переводим ${UPGRADE_TEST_TOPUP_SOL} тестовых SOL в devnet…`);
|
|
const result = await fundDevnetRegistrationWallet(walletAddress);
|
|
if (disposed) return;
|
|
balanceLine.textContent = `Баланс: ${formatSol(result.sol, 6)} SOL`;
|
|
message(payStatus, `Тестовое пополнение +${UPGRADE_TEST_TOPUP_SOL} SOL выполнено.`);
|
|
} catch (error) {
|
|
message(payStatus, `Тестовое пополнение недоступно (${error.message}). Используйте внешний devnet faucet и обновите баланс.`, 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('Данные регистрации ещё не готовы');
|
|
if (!password.value) throw new Error('Введите пароль существующего аккаунта');
|
|
// Повторно сверяем 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(`Недостаточно SOL. Пополните кошелёк ещё минимум на ${solFromLamports(shortage)} SOL.`);
|
|
}
|
|
message(payStatus, 'Проверяем исходный пароль и восстанавливаем ваши ключи локально…');
|
|
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('Пароль не совпадает с исходными ключами сертификата');
|
|
}
|
|
}
|
|
const signature = base64ToBytes(identity.innerSignature64B64);
|
|
if (signature.length !== 64) throw new Error('Сертификат не содержит подписи регистратора');
|
|
message(payStatus, 'Подписываем транзакцию и создаём вашу PDA в Solana…');
|
|
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, `Регистрация не завершена: ${formatSolanaErrorDetails(error)}. Проверьте статус перед повторной попыткой.`, true);
|
|
} finally {
|
|
sending = false;
|
|
if (!disposed) payButton.disabled = false;
|
|
}
|
|
});
|
|
checkButton.addEventListener('click', () => void checkSync());
|
|
show('intro');
|
|
void initialize().catch((error) => message(introStatus, `Не удалось подготовить переход: ${error.message}`, true));
|
|
screen.cleanup = () => { disposed = true; stopPolling(); password.value = ''; };
|
|
return screen;
|
|
}
|