SHA256
Регистрация V2: не проверено end-to-end
This commit is contained in:
@@ -1,197 +1,28 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { formatSol, getBalanceSol, transferSol, createSolanaWalletFromPrivateBase58 } from '../services/solana-wallet-service.js';
|
||||
|
||||
export const pageMeta = { id: 'devnet-topup-view', title: 'Пополнение DEVNET', showAppChrome: false };
|
||||
|
||||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||||
const SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
||||
const TRANSFER_AMOUNT_SOL = 0.02;
|
||||
import { formatSol, getBalanceSol } from '../services/solana-wallet-service.js';
|
||||
|
||||
export const pageMeta = {id:'devnet-topup-view', title:'Пополнение DEVNET', showAppChrome:false};
|
||||
const DEVNET_ENDPOINT='https://api.devnet.solana.com';
|
||||
function readWalletFromUrl() {
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
return String(url.searchParams.get('wallet') || '').trim();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
try { return new URL(window.location.href).searchParams.get('wallet')?.trim() || ''; }
|
||||
catch { return ''; }
|
||||
}
|
||||
|
||||
export function render() {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
screen.style.width = '100%';
|
||||
screen.style.justifyItems = 'center';
|
||||
|
||||
const targetWallet = readWalletFromUrl();
|
||||
|
||||
const senderBox = document.createElement('div');
|
||||
senderBox.className = 'card stack';
|
||||
senderBox.style.width = 'min(100%, 320px)';
|
||||
senderBox.innerHTML = `
|
||||
<strong>Тестовый DEVNET-кошелёк</strong>
|
||||
<p class="meta-muted" id="devnet-topup-sender-address">Адрес: ...</p>
|
||||
<p class="meta-muted" id="devnet-topup-sender-balance">Баланс: ...</p>
|
||||
`;
|
||||
|
||||
const targetBox = document.createElement('div');
|
||||
targetBox.className = 'card stack';
|
||||
targetBox.style.width = 'min(100%, 320px)';
|
||||
targetBox.innerHTML = `
|
||||
<strong>Кошелёк получателя</strong>
|
||||
<p class="meta-muted" style="word-break:break-all;">${targetWallet || 'Не передан параметр wallet'}</p>
|
||||
<p class="meta-muted">Сумма перевода: ${TRANSFER_AMOUNT_SOL} SOL</p>
|
||||
<p class="meta-muted" id="devnet-topup-target-balance">Баланс: ...</p>
|
||||
`;
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'meta-muted';
|
||||
status.style.width = 'min(100%, 320px)';
|
||||
status.style.overflowWrap = 'anywhere';
|
||||
status.style.wordBreak = 'break-word';
|
||||
status.style.whiteSpace = 'pre-wrap';
|
||||
status.textContent = `Готово к пополнению.\nСеть: DEVNET (${DEVNET_ENDPOINT})`;
|
||||
|
||||
const amountHint = document.createElement('p');
|
||||
amountHint.style.width = 'min(100%, 320px)';
|
||||
amountHint.style.display = 'none';
|
||||
amountHint.style.margin = '0';
|
||||
amountHint.style.fontSize = '22px';
|
||||
amountHint.style.fontWeight = '800';
|
||||
amountHint.style.lineHeight = '1.25';
|
||||
amountHint.style.color = 'var(--success)';
|
||||
amountHint.style.textAlign = 'center';
|
||||
amountHint.textContent = '';
|
||||
|
||||
const balanceHint = document.createElement('p');
|
||||
balanceHint.className = 'meta-muted';
|
||||
balanceHint.style.width = 'min(100%, 320px)';
|
||||
balanceHint.style.display = 'none';
|
||||
balanceHint.style.margin = '0';
|
||||
balanceHint.style.textAlign = 'center';
|
||||
balanceHint.style.fontSize = '14px';
|
||||
balanceHint.style.color = 'var(--text-primary)';
|
||||
balanceHint.textContent = '';
|
||||
|
||||
const closeHint = document.createElement('p');
|
||||
closeHint.style.width = 'min(100%, 320px)';
|
||||
closeHint.style.display = 'none';
|
||||
closeHint.style.margin = '0';
|
||||
closeHint.style.fontSize = '26px';
|
||||
closeHint.style.fontWeight = '800';
|
||||
closeHint.style.lineHeight = '1.25';
|
||||
closeHint.style.color = 'var(--success)';
|
||||
closeHint.style.textAlign = 'center';
|
||||
closeHint.textContent = 'Можете закрыть эту страницу и продолжить регистрацию.';
|
||||
|
||||
const fillBtn = document.createElement('button');
|
||||
fillBtn.className = 'primary-btn';
|
||||
fillBtn.type = 'button';
|
||||
fillBtn.textContent = `Пополнить на ${TRANSFER_AMOUNT_SOL} SOL`;
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
actions.style.width = 'min(100%, 320px)';
|
||||
actions.style.justifySelf = 'center';
|
||||
actions.append(fillBtn);
|
||||
|
||||
let senderAddress = '';
|
||||
let senderKeypair = null;
|
||||
|
||||
const updateSenderBalance = async () => {
|
||||
if (!senderAddress) return;
|
||||
const balance = await getBalanceSol({ endpoint: DEVNET_ENDPOINT, address: senderAddress });
|
||||
const senderBalanceEl = senderBox.querySelector('#devnet-topup-sender-balance');
|
||||
if (senderBalanceEl) senderBalanceEl.textContent = `Баланс: ${formatSol(balance.sol, 6)} SOL`;
|
||||
};
|
||||
|
||||
const updateTargetBalance = async () => {
|
||||
if (!targetWallet) return null;
|
||||
const balance = await getBalanceSol({ endpoint: DEVNET_ENDPOINT, address: targetWallet });
|
||||
const targetBalanceEl = targetBox.querySelector('#devnet-topup-target-balance');
|
||||
if (targetBalanceEl) targetBalanceEl.textContent = `Баланс: ${formatSol(balance.sol, 6)} SOL`;
|
||||
return balance.sol;
|
||||
};
|
||||
|
||||
fillBtn.addEventListener('click', async () => {
|
||||
if (!targetWallet) {
|
||||
status.textContent = 'Ошибка: в URL не передан параметр wallet.';
|
||||
return;
|
||||
}
|
||||
if (!senderKeypair) {
|
||||
status.textContent = 'Ошибка: кошелёк отправителя не инициализирован.';
|
||||
return;
|
||||
}
|
||||
|
||||
fillBtn.disabled = true;
|
||||
status.textContent = 'Отправляем перевод...';
|
||||
amountHint.style.display = 'none';
|
||||
balanceHint.style.display = 'none';
|
||||
closeHint.style.display = 'none';
|
||||
|
||||
try {
|
||||
const tx = await transferSol({
|
||||
endpoint: DEVNET_ENDPOINT,
|
||||
fromKeypair: senderKeypair,
|
||||
toAddress: targetWallet,
|
||||
amountSol: TRANSFER_AMOUNT_SOL,
|
||||
});
|
||||
await updateSenderBalance();
|
||||
const targetBalanceSol = await updateTargetBalance();
|
||||
status.textContent = `Транзакция прошла.\nSignature: ${tx.signature}`;
|
||||
status.style.fontSize = '13px';
|
||||
status.style.fontWeight = '500';
|
||||
status.style.color = 'var(--text-secondary)';
|
||||
fillBtn.style.display = 'none';
|
||||
actions.style.display = 'none';
|
||||
amountHint.style.display = '';
|
||||
amountHint.textContent = `Кошелёк пополнен на ${TRANSFER_AMOUNT_SOL} SOL`;
|
||||
balanceHint.style.display = '';
|
||||
balanceHint.textContent = `Новый баланс: ${formatSol(targetBalanceSol || 0, 6)} SOL`;
|
||||
closeHint.style.display = '';
|
||||
} catch (error) {
|
||||
status.textContent = `Ошибка перевода: ${error?.message || 'unknown'}`;
|
||||
status.style.fontSize = '';
|
||||
status.style.fontWeight = '';
|
||||
status.style.color = '';
|
||||
amountHint.style.display = 'none';
|
||||
balanceHint.style.display = 'none';
|
||||
closeHint.style.display = 'none';
|
||||
} finally {
|
||||
fillBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const sender = await createSolanaWalletFromPrivateBase58(SENDER_PRIVATE_32_BASE58);
|
||||
senderAddress = sender.address;
|
||||
senderKeypair = sender.keypair;
|
||||
const senderAddressEl = senderBox.querySelector('#devnet-topup-sender-address');
|
||||
if (senderAddressEl) senderAddressEl.textContent = `Адрес: ${senderAddress}`;
|
||||
await updateSenderBalance();
|
||||
await updateTargetBalance();
|
||||
if (!targetWallet) {
|
||||
fillBtn.disabled = true;
|
||||
status.textContent = 'Передайте адрес получателя в параметре wallet.';
|
||||
}
|
||||
} catch (error) {
|
||||
fillBtn.disabled = true;
|
||||
status.textContent = `Ошибка инициализации отправителя: ${error?.message || 'unknown'}`;
|
||||
}
|
||||
})();
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: 'DEVNET пополнение',
|
||||
}),
|
||||
senderBox,
|
||||
targetBox,
|
||||
status,
|
||||
amountHint,
|
||||
balanceHint,
|
||||
closeHint,
|
||||
actions,
|
||||
);
|
||||
|
||||
const screen=document.createElement('section');screen.className='stack registration-screen';
|
||||
const card=document.createElement('div');card.className='card stack';
|
||||
const title=document.createElement('h3');title.textContent='Пополнение DEVNET';
|
||||
const note=document.createElement('p');note.className='meta-muted';
|
||||
note.textContent='Автоматическое пополнение из браузера отключено: приватный ключ отправителя нельзя публиковать в приложении. Используйте внешний доверенный Solana devnet faucet.';
|
||||
const wallet=readWalletFromUrl();
|
||||
const input=document.createElement('input');input.className='input';input.readOnly=true;input.value=wallet;
|
||||
const copy=document.createElement('button');copy.className='secondary-btn';copy.textContent='Скопировать адрес';
|
||||
copy.addEventListener('click',()=>navigator.clipboard.writeText(input.value).catch(()=>{}));
|
||||
const balance=document.createElement('p');balance.className='meta-muted';
|
||||
balance.textContent=wallet?'Проверяем баланс…':'Не передан параметр wallet';
|
||||
if(wallet)void getBalanceSol({endpoint:DEVNET_ENDPOINT,address:wallet})
|
||||
.then(value=>balance.textContent=`Баланс: ${formatSol(value.sol,6)} SOL`)
|
||||
.catch(()=>balance.textContent='Баланс недоступен; проверьте адрес и сеть');
|
||||
card.append(title,note,input,copy,balance);
|
||||
screen.append(createTopBar({title:'Пополнение DEVNET'}),card);
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -1,427 +1,86 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { authService, clearAuthMessages, resetRegistrationFlow, state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
checkLoginExistsOnSolana,
|
||||
formatSolanaErrorDetails,
|
||||
isSolanaRpcUnavailableError,
|
||||
precheckLoginClassOnSolana,
|
||||
} from '../services/solana-register-service.js';
|
||||
import {
|
||||
emptyPasswordWords,
|
||||
PASSWORD_MAX_LENGTH,
|
||||
} from '../services/password-words.js';
|
||||
import { openRegistrationFaq } from './registration-faq-view.js';
|
||||
import { PASSWORD_MAX_LENGTH } from '../services/password-words.js';
|
||||
import { getRegistrationNamespaces, checkRegistrationLogin } from '../services/registration-v2-api.js';
|
||||
import { normalizeFullLogin } from '../services/shine-namespace-service.js';
|
||||
|
||||
export const pageMeta = { id: 'register-view', title: 'Регистрация', showAppChrome: false };
|
||||
const MIN_REGISTRATION_LOGIN_LENGTH = 8;
|
||||
|
||||
function normalizeLoginForTemporaryUiGuard(login) {
|
||||
const source = String(login || '').trim();
|
||||
if (!source || source.length > 20) return null;
|
||||
let normalized = '';
|
||||
for (const ch of source) {
|
||||
if (ch === '_') continue;
|
||||
if (!/[0-9A-Za-z]/.test(ch)) return null;
|
||||
normalized += ch.toLowerCase();
|
||||
}
|
||||
if (!normalized || normalized.length > 20) return null;
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function makePasswordToggleIcons() {
|
||||
return {
|
||||
eye: iconHtml('eye', false, 'key-toggle-icon'),
|
||||
eyeOff: iconHtml('eyeOff', false, 'key-toggle-icon'),
|
||||
};
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack registration-screen';
|
||||
|
||||
export function render({navigate}) {
|
||||
clearAuthMessages();
|
||||
|
||||
const form = document.createElement('div');
|
||||
form.className = 'card stack registration-form';
|
||||
|
||||
state.registrationDraft.passwordMode = 'single';
|
||||
state.registrationDraft.passwordWords = emptyPasswordWords();
|
||||
state.registrationDraft.passwordWordsLinked = false;
|
||||
state.registrationDraft.usePromoCode = false;
|
||||
state.registrationDraft.promoCode = '';
|
||||
let loginCheckTimer = 0;
|
||||
let loginCheckRunId = 0;
|
||||
|
||||
const loginInput = document.createElement('input');
|
||||
loginInput.className = 'input';
|
||||
loginInput.type = 'text';
|
||||
loginInput.autocomplete = 'off';
|
||||
loginInput.autocapitalize = 'off';
|
||||
loginInput.spellcheck = false;
|
||||
loginInput.value = state.registrationDraft.login;
|
||||
loginInput.placeholder = 'Введите логин';
|
||||
|
||||
const passwordInput = document.createElement('input');
|
||||
passwordInput.className = 'input';
|
||||
passwordInput.type = 'password';
|
||||
passwordInput.name = 'shine-register-password';
|
||||
passwordInput.autocomplete = 'new-password';
|
||||
passwordInput.autocapitalize = 'off';
|
||||
passwordInput.spellcheck = false;
|
||||
passwordInput.maxLength = PASSWORD_MAX_LENGTH;
|
||||
passwordInput.value = String(state.registrationDraft.password || '');
|
||||
passwordInput.placeholder = 'Введите пароль';
|
||||
|
||||
const passwordIcons = makePasswordToggleIcons();
|
||||
|
||||
const passwordToggleButton = document.createElement('button');
|
||||
passwordToggleButton.className = 'icon-btn key-toggle-btn registration-password-toggle';
|
||||
passwordToggleButton.type = 'button';
|
||||
passwordToggleButton.setAttribute('aria-label', 'Показать пароль');
|
||||
passwordToggleButton.setAttribute('title', 'Показать пароль');
|
||||
passwordToggleButton.innerHTML = passwordIcons.eyeOff;
|
||||
|
||||
const passwordInputRow = document.createElement('div');
|
||||
passwordInputRow.className = 'inline-input-row';
|
||||
passwordInputRow.append(passwordInput, passwordToggleButton);
|
||||
|
||||
// Строка под логином всегда занимает место — сообщения не сдвигают форму.
|
||||
const statusText = document.createElement('span');
|
||||
statusText.className = 'status-line registration-login-status';
|
||||
statusText.setAttribute('aria-live', 'polite');
|
||||
|
||||
const formError = document.createElement('p');
|
||||
formError.className = 'status-line is-unavailable';
|
||||
formError.style.display = 'none';
|
||||
|
||||
// Компактная ссылка на экран «Вопросы о регистрации» (registration-faq-view).
|
||||
const faqButton = document.createElement('button');
|
||||
faqButton.className = 'registration-faq-link';
|
||||
faqButton.type = 'button';
|
||||
faqButton.textContent = 'Вопросы о регистрации';
|
||||
faqButton.addEventListener('click', () => openRegistrationFaq(navigate, 'key-derivation'));
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
|
||||
const nextButton = document.createElement('button');
|
||||
nextButton.className = 'primary-btn';
|
||||
nextButton.type = 'button';
|
||||
nextButton.textContent = 'Далее';
|
||||
|
||||
const passwordLengthText = document.createElement('p');
|
||||
passwordLengthText.className = 'password-length-hint';
|
||||
let lastCheckedLogin = '';
|
||||
let lastCheckedFree = false;
|
||||
let lastCheckedClassName = '';
|
||||
let generationRunId = 0;
|
||||
|
||||
function getCurrentPassword() {
|
||||
return String(passwordInput.value || '');
|
||||
}
|
||||
|
||||
function updatePasswordLength() {
|
||||
passwordLengthText.textContent = `Символов в пароле: ${getCurrentPassword().length}`;
|
||||
}
|
||||
|
||||
function setStatusMessage(message, kind = '', details = '') {
|
||||
statusText.textContent = message;
|
||||
statusText.title = details || message;
|
||||
statusText.className = kind ? `status-line registration-login-status ${kind}` : 'status-line registration-login-status';
|
||||
}
|
||||
|
||||
function showCheckedLoginStatus(isFree, className) {
|
||||
if (!isFree) {
|
||||
setStatusMessage('Логин уже занят', 'is-unavailable');
|
||||
} else if (className === 'free') {
|
||||
setStatusMessage('Логин свободен', 'is-available');
|
||||
} else if (className === 'premium') {
|
||||
setStatusMessage('Премиум-логин – покупка через DAO', 'is-unavailable');
|
||||
} else if (className === 'company') {
|
||||
setStatusMessage('Логин бренда – нужно согласование', 'is-unavailable');
|
||||
} else {
|
||||
setStatusMessage('Не подходит для обычной регистрации', 'is-unavailable');
|
||||
const screen=document.createElement('section'); screen.className='stack registration-screen';
|
||||
const form=document.createElement('div'); form.className='card stack registration-form';
|
||||
const method=document.createElement('select'); method.className='input';
|
||||
method.innerHTML='<option value="1">Регистрация через Solana</option><option value="2">Бесплатная регистрация</option>';
|
||||
method.value=state.registrationDraft.flowType==='free'?'2':'1';
|
||||
const namespace=document.createElement('select'); namespace.className='input';
|
||||
const local=document.createElement('input'); local.className='input'; local.placeholder='Логин (без @)';
|
||||
local.autocomplete='off';local.spellcheck=false;local.autocapitalize='off';
|
||||
local.value=String(state.registrationDraft.login || '').split('@')[0];
|
||||
const full=document.createElement('p'); full.className='meta-muted';
|
||||
const password=document.createElement('input'); password.className='input';password.type='password';
|
||||
password.autocomplete='new-password';password.maxLength=PASSWORD_MAX_LENGTH;
|
||||
password.placeholder='Пароль';password.value=state.registrationDraft.password || '';
|
||||
const status=document.createElement('p'); status.className='status-line';status.setAttribute('aria-live','polite');
|
||||
const action=document.createElement('button');action.className='primary-btn';action.textContent='Проверить логин и продолжить';
|
||||
const nsLabel=document.createElement('label');nsLabel.className='stack';nsLabel.textContent='Пространство имён'; nsLabel.append(namespace);
|
||||
const methodLabel=document.createElement('label');methodLabel.className='stack'; methodLabel.textContent='Способ регистрации';methodLabel.append(method);
|
||||
const pwLabel=document.createElement('label');pwLabel.className='stack';pwLabel.textContent='Пароль (ключи остаются только у вас)';pwLabel.append(password);
|
||||
form.append(methodLabel,nsLabel,local,full,pwLabel,status,action);
|
||||
let namespaces=[]; let disposed=false; let request=0;
|
||||
const feeToSol = fee => (Number(fee || '0')/1e9).toFixed(6);
|
||||
function selected() { return namespaces.find(n=>n.name===namespace.value); }
|
||||
function display() {
|
||||
namespace.replaceChildren();
|
||||
for (const ns of namespaces.filter(n=>Number(n.type)===Number(method.value))) {
|
||||
const opt=document.createElement('option');opt.value=ns.name;
|
||||
opt.textContent=`@${ns.name} · от ${ns.minLocalLength} симв. · ${feeToSol(ns.registrationFeeLamports)} SOL`;
|
||||
namespace.append(opt);
|
||||
}
|
||||
}
|
||||
|
||||
function resetLoginCheckState() {
|
||||
lastCheckedLogin = '';
|
||||
lastCheckedFree = false;
|
||||
lastCheckedClassName = '';
|
||||
loginCheckRunId += 1;
|
||||
if (loginCheckTimer) {
|
||||
window.clearTimeout(loginCheckTimer);
|
||||
loginCheckTimer = 0;
|
||||
if (state.registrationDraft.login.includes('@')) {
|
||||
const wanted=state.registrationDraft.login.split('@')[1];
|
||||
if([...namespace.options].some(x=>x.value===wanted))namespace.value=wanted;
|
||||
}
|
||||
showFull();
|
||||
}
|
||||
|
||||
function scheduleAvailabilityCheck() {
|
||||
resetLoginCheckState();
|
||||
setStatusMessage('');
|
||||
if (!loginInput.value.trim()) return;
|
||||
loginCheckTimer = window.setTimeout(() => {
|
||||
loginCheckTimer = 0;
|
||||
runAvailabilityCheck({ automatic: true }).catch(() => {});
|
||||
}, 1500);
|
||||
function showFull() {
|
||||
full.textContent=namespace.value?`Полное имя: ${local.value.trim()}@${namespace.value}`:'Нет доступных namespace этого типа';
|
||||
status.textContent='';request++;
|
||||
}
|
||||
|
||||
function togglePasswordVisibility() {
|
||||
const reveal = passwordInput.type === 'password';
|
||||
passwordInput.type = reveal ? 'text' : 'password';
|
||||
passwordToggleButton.innerHTML = reveal ? passwordIcons.eye : passwordIcons.eyeOff;
|
||||
passwordToggleButton.setAttribute('aria-label', reveal ? 'Скрыть пароль' : 'Показать пароль');
|
||||
passwordToggleButton.setAttribute('title', reveal ? 'Скрыть пароль' : 'Показать пароль');
|
||||
}
|
||||
|
||||
function syncDraftState() {
|
||||
state.registrationDraft.login = String(loginInput.value.trim());
|
||||
state.registrationDraft.password = getCurrentPassword();
|
||||
}
|
||||
|
||||
async function runAvailabilityCheck({ automatic = false } = {}) {
|
||||
const runId = ++loginCheckRunId;
|
||||
const login = loginInput.value.trim();
|
||||
if (!login) {
|
||||
setStatusMessage(automatic ? '' : 'Введите логин');
|
||||
formError.style.display = 'none';
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalizedLogin = normalizeLoginForTemporaryUiGuard(login);
|
||||
if (!normalizedLogin) {
|
||||
setStatusMessage('Только латиница, цифры и _, до 20 символов', 'is-unavailable');
|
||||
formError.style.display = 'none';
|
||||
return false;
|
||||
}
|
||||
|
||||
if (normalizedLogin.length < MIN_REGISTRATION_LOGIN_LENGTH) {
|
||||
setStatusMessage(`Не короче ${MIN_REGISTRATION_LOGIN_LENGTH} символов`, 'is-unavailable');
|
||||
formError.style.display = 'none';
|
||||
return false;
|
||||
}
|
||||
|
||||
if (login === lastCheckedLogin) {
|
||||
showCheckedLoginStatus(lastCheckedFree, lastCheckedClassName);
|
||||
formError.style.display = 'none';
|
||||
return lastCheckedFree && lastCheckedClassName === 'free';
|
||||
}
|
||||
|
||||
setStatusMessage('Проверяем логин…', 'is-checking');
|
||||
method.addEventListener('change',display);namespace.addEventListener('change',showFull);local.addEventListener('input',showFull);
|
||||
void getRegistrationNamespaces().then(data=>{
|
||||
if(disposed)return;namespaces=Array.isArray(data.namespaces)?data.namespaces:[];display();
|
||||
if(!namespaces.length)status.textContent='Solana namespace ещё не синхронизированы с сервером';
|
||||
}).catch(error=>{if(!disposed)status.textContent=`Не удалось получить namespace: ${error.message}`;});
|
||||
action.addEventListener('click',async()=>{
|
||||
const ns=selected();if(!ns){status.textContent='Выберите доступный namespace';return;}
|
||||
let login;
|
||||
try {
|
||||
const check = await checkLoginExistsOnSolana({
|
||||
login,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
});
|
||||
if (runId !== loginCheckRunId) return false;
|
||||
const isFree = !check.exists;
|
||||
let className = '';
|
||||
if (isFree) {
|
||||
try {
|
||||
const precheck = await precheckLoginClassOnSolana({
|
||||
login,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
});
|
||||
className = precheck.className;
|
||||
} catch (precheckError) {
|
||||
className = 'free';
|
||||
console.warn('Solana login precheck fallback to free', formatSolanaErrorDetails(precheckError));
|
||||
}
|
||||
}
|
||||
lastCheckedLogin = login;
|
||||
lastCheckedFree = isFree;
|
||||
lastCheckedClassName = className;
|
||||
showCheckedLoginStatus(isFree, className);
|
||||
formError.style.display = 'none';
|
||||
return isFree && className === 'free';
|
||||
} catch (error) {
|
||||
if (runId !== loginCheckRunId) return false;
|
||||
if (isSolanaRpcUnavailableError(error)) {
|
||||
setStatusMessage('Нет связи с Solana – попробуйте позже', 'is-unavailable');
|
||||
return false;
|
||||
}
|
||||
const base = toUserMessage(error, 'Не удалось проверить логин');
|
||||
const details = formatSolanaErrorDetails(error);
|
||||
setStatusMessage(base, 'is-unavailable', `${base}. Детали: ${details}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
passwordToggleButton.addEventListener('click', togglePasswordVisibility);
|
||||
|
||||
loginInput.addEventListener('input', () => {
|
||||
syncDraftState();
|
||||
scheduleAvailabilityCheck();
|
||||
});
|
||||
|
||||
passwordInput.addEventListener('input', () => {
|
||||
syncDraftState();
|
||||
updatePasswordLength();
|
||||
});
|
||||
|
||||
nextButton.addEventListener('click', async () => {
|
||||
formError.style.display = 'none';
|
||||
const isFree = await runAvailabilityCheck();
|
||||
if (!isFree) return;
|
||||
|
||||
const prevLogin = String(state.registrationDraft.login || '');
|
||||
const prevPassword = String(state.registrationDraft.password || '');
|
||||
const nextLogin = String(loginInput.value.trim());
|
||||
const nextPassword = getCurrentPassword();
|
||||
if (nextPassword.length === 0) {
|
||||
formError.textContent = 'Пустой пароль запрещён. Введите непустой пароль для регистрации.';
|
||||
formError.style.display = '';
|
||||
return;
|
||||
}
|
||||
if (nextPassword.length > PASSWORD_MAX_LENGTH) {
|
||||
formError.textContent = `Пароль получился слишком длинным. Максимальная длина: ${PASSWORD_MAX_LENGTH} символов.`;
|
||||
formError.style.display = '';
|
||||
return;
|
||||
}
|
||||
const credsChanged = prevLogin !== nextLogin || prevPassword !== nextPassword;
|
||||
|
||||
state.registrationDraft.login = nextLogin;
|
||||
state.registrationDraft.password = nextPassword;
|
||||
if (credsChanged) {
|
||||
state.registrationDraft.preGeneratedKeyBundle = null;
|
||||
}
|
||||
|
||||
startGenerationStage();
|
||||
});
|
||||
|
||||
function renderInputStage() {
|
||||
form.innerHTML = '';
|
||||
const loginField = document.createElement('label');
|
||||
loginField.className = 'stack';
|
||||
loginField.innerHTML = '<span class="field-label">Логин</span>';
|
||||
const passwordLabel = document.createElement('label');
|
||||
passwordLabel.className = 'stack registration-password-single';
|
||||
passwordLabel.innerHTML = '<span class="field-label">Пароль</span>';
|
||||
form.append(loginField, passwordLabel);
|
||||
loginField.append(loginInput, statusText);
|
||||
passwordLabel.append(passwordInputRow);
|
||||
form.append(passwordLengthText, formError, faqButton);
|
||||
actions.innerHTML = '';
|
||||
actions.append(nextButton);
|
||||
updatePasswordLength();
|
||||
syncDraftState();
|
||||
}
|
||||
|
||||
async function startGenerationStage() {
|
||||
const runId = ++generationRunId;
|
||||
form.innerHTML = '';
|
||||
|
||||
const title = document.createElement('p');
|
||||
title.className = 'auth-copy';
|
||||
title.textContent = 'Для повышения безопасности мы генерируем секрет из вашего логина и пароля с помощью Argon2id.';
|
||||
|
||||
const subtitle = document.createElement('p');
|
||||
subtitle.className = 'meta-muted';
|
||||
subtitle.textContent = 'Процесс запускается сразу: из этого секрета будут вычислены ключ восстановления, ключ блокчейна и ключ доступа.';
|
||||
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
details.textContent = 'Параметры: t=2, m=65536 KiB (64 MB), p=1, dkLen=32.';
|
||||
|
||||
const details2 = document.createElement('p');
|
||||
details2.className = 'meta-muted';
|
||||
details2.textContent = 'Замедление нужно специально: оно усложняет подбор пароля и повышает цену атак на видеокартах и GPU.';
|
||||
|
||||
const details3 = document.createElement('p');
|
||||
details3.className = 'meta-muted';
|
||||
details3.textContent = `Длина вашего текущего пароля: ${getCurrentPassword().length} символов.`;
|
||||
|
||||
const progressWrap = document.createElement('div');
|
||||
progressWrap.className = 'registration-progress';
|
||||
|
||||
const progressBar = document.createElement('div');
|
||||
progressBar.className = 'registration-progress-bar';
|
||||
progressWrap.append(progressBar);
|
||||
|
||||
const progressText = document.createElement('p');
|
||||
progressText.className = 'meta-muted';
|
||||
progressText.textContent = 'Подготовка...';
|
||||
|
||||
const genError = document.createElement('p');
|
||||
genError.className = 'status-line is-unavailable';
|
||||
genError.style.display = 'none';
|
||||
|
||||
form.append(title, subtitle, details, details2, details3, progressWrap, progressText, genError);
|
||||
|
||||
const cancelBtn = document.createElement('button');
|
||||
cancelBtn.className = 'ghost-btn';
|
||||
cancelBtn.type = 'button';
|
||||
cancelBtn.textContent = 'Отмена';
|
||||
cancelBtn.addEventListener('click', () => {
|
||||
generationRunId += 1;
|
||||
renderInputStage();
|
||||
});
|
||||
actions.innerHTML = '';
|
||||
actions.append(cancelBtn);
|
||||
|
||||
login=normalizeFullLogin(`${local.value.trim()}@${ns.name}`);
|
||||
if(local.value.trim().length < Number(ns.minLocalLength))throw new Error(`Логин не короче ${ns.minLocalLength} символов`);
|
||||
if(!password.value || password.value.length>PASSWORD_MAX_LENGTH)throw new Error('Введите непустой пароль допустимой длины');
|
||||
}catch(error){status.textContent=error.message;return;}
|
||||
const thisRun=++request;
|
||||
action.disabled=true;status.textContent='Проверяем выбранный логин…';
|
||||
try {
|
||||
if (!state.registrationDraft.preGeneratedKeyBundle) {
|
||||
const keyBundle = await authService.derivePasswordKeyBundle(
|
||||
state.registrationDraft.login,
|
||||
state.registrationDraft.password,
|
||||
{
|
||||
onProgress: ({ percent, message }) => {
|
||||
if (runId !== generationRunId) return;
|
||||
const safePercent = Math.max(0, Math.min(100, Number(percent) || 0));
|
||||
progressBar.style.width = `${safePercent}%`;
|
||||
progressText.textContent = `${safePercent}% · ${String(message || '').trim()}`;
|
||||
},
|
||||
isCancelled: () => runId !== generationRunId,
|
||||
},
|
||||
);
|
||||
if (runId !== generationRunId) return;
|
||||
state.registrationDraft.preGeneratedKeyBundle = keyBundle;
|
||||
}
|
||||
if (runId !== generationRunId) return;
|
||||
progressBar.style.width = '100%';
|
||||
progressText.textContent = '100%';
|
||||
title.textContent = 'Ключи сгенерированы';
|
||||
window.setTimeout(() => navigate('registration-payment-view'), 350);
|
||||
} catch (error) {
|
||||
if (runId !== generationRunId) return;
|
||||
if (String(error?.message || '') === 'DERIVE_CANCELLED') {
|
||||
renderInputStage();
|
||||
return;
|
||||
}
|
||||
genError.textContent = `Ошибка генерации ключей: ${error?.message || 'неизвестная ошибка'}`;
|
||||
genError.style.display = '';
|
||||
const retry = document.createElement('button');
|
||||
retry.className = 'primary-btn';
|
||||
retry.type = 'button';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.addEventListener('click', startGenerationStage);
|
||||
const goBack = document.createElement('button');
|
||||
goBack.className = 'ghost-btn';
|
||||
goBack.type = 'button';
|
||||
goBack.textContent = 'Назад';
|
||||
goBack.addEventListener('click', renderInputStage);
|
||||
actions.innerHTML = '';
|
||||
actions.append(goBack, retry);
|
||||
}
|
||||
}
|
||||
|
||||
renderInputStage();
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: 'Регистрация',
|
||||
back: {
|
||||
label: '←',
|
||||
onClick: () => {
|
||||
resetRegistrationFlow();
|
||||
navigate('start-view');
|
||||
},
|
||||
},
|
||||
}),
|
||||
form,
|
||||
actions,
|
||||
);
|
||||
|
||||
const check=await checkRegistrationLogin(login);
|
||||
if(disposed || thisRun!==request)return;
|
||||
if(!check.loginAvailable)throw new Error('Этот логин уже занят');
|
||||
if(Number(check.namespaceType)!==Number(method.value))throw new Error('Тип namespace изменился. Обновите список.');
|
||||
const draft=state.registrationDraft;
|
||||
const changed=draft.login!==login || draft.password!==password.value;
|
||||
draft.login=login;draft.password=password.value;draft.flowType=method.value==='2'?'free':'paid';
|
||||
draft.namespaceFeeLamports=String(check.registrationFeeLamports||ns.registrationFeeLamports);
|
||||
draft.namespaceServerLogin=ns.defaultServerLogin||'';
|
||||
if(changed)draft.preGeneratedKeyBundle=null;
|
||||
status.textContent='Создаём ключи локально (Argon2id)…';
|
||||
const bundle=draft.preGeneratedKeyBundle || await authService.derivePasswordKeyBundle(login,password.value);
|
||||
if(disposed || thisRun!==request)return;
|
||||
draft.preGeneratedKeyBundle=bundle;
|
||||
navigate(draft.flowType==='free'?'registration-email-view':'registration-payment-view');
|
||||
}catch(error){if(!disposed && thisRun===request)status.textContent=error.message;}
|
||||
finally {action.disabled=false;}
|
||||
});
|
||||
screen.append(createTopBar({title:'Регистрация',back:{label:'←',onClick:()=>{resetRegistrationFlow();navigate('start-view');}}}),form);
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { state } from '../state.js';
|
||||
import { checkRegistrationEmail, startFreeRegistration, confirmFreeRegistration } from '../services/registration-v2-api.js';
|
||||
import { completeRegistrationLogin } from './registration-payment-view.js';
|
||||
|
||||
export const pageMeta={ id:'registration-email-view', title:'Проверка email', showAppChrome:false };
|
||||
export function render({navigate}) {
|
||||
const screen=document.createElement('section'); screen.className='stack registration-screen';
|
||||
const form=document.createElement('div');form.className='card stack registration-form';
|
||||
const draft=state.registrationDraft;
|
||||
const input=document.createElement('input');input.className='input';input.type='email';input.autocomplete='email';
|
||||
input.placeholder='Email';input.value=draft.email || '';
|
||||
const info=document.createElement('p');info.className='meta-muted';
|
||||
info.textContent='Email используется только для регистрации. В Arweave публикуется SHA-256 от email; его можно подобрать перебором.';
|
||||
const status=document.createElement('p');status.className='status-line';status.setAttribute('aria-live','polite');
|
||||
const next=document.createElement('button');next.className='primary-btn';next.textContent='Проверить email';
|
||||
const code=document.createElement('input');code.className='input';code.inputMode='numeric';code.placeholder='Код 1111';
|
||||
const codeLabel=document.createElement('p');codeLabel.className='meta-muted';
|
||||
codeLabel.textContent='Тест: код 1111. Письмо не отправляется, владение email не подтверждается.';
|
||||
const confirm=document.createElement('button');confirm.className='primary-btn';confirm.textContent='Подтвердить и зарегистрироваться';
|
||||
const retry=document.createElement('button');retry.className='secondary-btn';retry.textContent='Проверить статус и повторить';
|
||||
code.hidden=true;codeLabel.hidden=true;confirm.hidden=true;retry.hidden=true;
|
||||
form.append(info,input,status,next,codeLabel,code,confirm,retry);
|
||||
let disposed=false;
|
||||
function showConfirm(){ input.disabled=true;next.hidden=true;code.hidden=false;codeLabel.hidden=false;confirm.hidden=false;retry.hidden=false; }
|
||||
next.addEventListener('click',async()=>{
|
||||
if(!draft.preGeneratedKeyBundle || draft.flowType!=='free'){status.textContent='Сначала подготовьте ключи на предыдущем экране';return;}
|
||||
next.disabled=true;status.textContent='Проверяем email…';
|
||||
try {
|
||||
const address=input.value.trim();
|
||||
const available=await checkRegistrationEmail(address);
|
||||
if(!available.emailAvailable) throw new Error('Этот email уже использован для бесплатной регистрации');
|
||||
draft.email=address;
|
||||
status.textContent='Создаём временную заявку…';
|
||||
const started=await startFreeRegistration({fullLogin:draft.login,keyBundle:draft.preGeneratedKeyBundle,email:address});
|
||||
if(disposed)return;
|
||||
draft.challengeId=started.challengeId;draft.challengeExpiresAtMs=started.expiresAtMs;
|
||||
status.textContent='Заявка создана. Введите тестовый код 1111.';showConfirm();
|
||||
}catch(error){if(!disposed)status.textContent=error.message;next.disabled=false;}
|
||||
});
|
||||
async function submit(){
|
||||
if(!draft.challengeId){status.textContent='Нет активной заявки';return;}
|
||||
confirm.disabled=true;retry.disabled=true;
|
||||
status.textContent='Подписываем сертификат и отправляем его через Turbo…';
|
||||
try{
|
||||
const res=await confirmFreeRegistration(draft.challengeId,code.value.trim());
|
||||
if(disposed)return;
|
||||
draft.dataItemId=res.dataItemId;
|
||||
status.textContent='Turbo принял сертификат. Входим без ожидания блока Arweave…';
|
||||
await completeRegistrationLogin({navigate,keyBundle:draft.preGeneratedKeyBundle});
|
||||
}catch(error){if(!disposed){status.textContent=`${error.message}. При сетевой ошибке повторите ту же заявку, ключи не меняются.`;}}
|
||||
finally{confirm.disabled=false;retry.disabled=false;}
|
||||
}
|
||||
confirm.addEventListener('click',submit);retry.addEventListener('click',submit);
|
||||
if(draft.challengeId && draft.challengeExpiresAtMs>Date.now()){
|
||||
status.textContent='Есть незавершённая заявка. Можно повторить подтверждение без новых ключей.';showConfirm();
|
||||
}
|
||||
screen.append(createTopBar({title:'Подтверждение email',back:{label:'←',onClick:()=>navigate('register-view')}}),form);
|
||||
return screen;
|
||||
}
|
||||
@@ -13,10 +13,8 @@ import {
|
||||
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 {
|
||||
@@ -33,7 +31,6 @@ 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';
|
||||
const AUTO_LOGIN_INITIAL_DELAY_MS = 1000;
|
||||
const AUTO_LOGIN_RETRY_MS = 2000;
|
||||
const REGISTRATION_PROGRESS_DURATION_MS = 12000;
|
||||
@@ -83,7 +80,7 @@ function clamp(value, min, max) {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
async function completeRegistrationLogin({ navigate, keyBundle }) {
|
||||
export async function completeRegistrationLogin({ navigate, keyBundle }) {
|
||||
await authService.reconnect(state.entrySettings.shineServer);
|
||||
const result = await authService.createSessionForExistingUser(
|
||||
state.registrationDraft.login,
|
||||
@@ -252,35 +249,13 @@ export function render({ navigate }) {
|
||||
topupButton.className = 'ghost-btn';
|
||||
topupButton.type = 'button';
|
||||
topupButton.textContent = 'Тестовое пополнение (пока доступно в тестовом режиме)';
|
||||
topupButton.addEventListener('click', async () => {
|
||||
status.style.display = 'none';
|
||||
topupButton.disabled = true;
|
||||
const defaultText = 'Тестовое пополнение (пока доступно в тестовом режиме)';
|
||||
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;
|
||||
}
|
||||
// Браузерная раздача devnet SOL с приватным ключом отправителя опасна.
|
||||
// Ссылка на публичный faucet безопаснее, чем встраивать секрет в JS.
|
||||
topupButton.textContent = 'Как пополнить через devnet faucet';
|
||||
topupButton.addEventListener('click', () => {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = 'Скопируйте адрес кошелька выше и пополните его через доверенный Solana devnet faucet. Приватный ключ отправителя не должен находиться в приложении.';
|
||||
status.style.display = '';
|
||||
});
|
||||
|
||||
const submitButton = document.createElement('button');
|
||||
@@ -305,14 +280,16 @@ export function render({ navigate }) {
|
||||
const walletAddress = await deriveUserWalletAddress();
|
||||
const currentBalance = await refreshBalance({ showError: true, addressOverride: walletAddress });
|
||||
if (currentBalance == null) return;
|
||||
if (currentBalance < MIN_REQUIRED_SOL) {
|
||||
const namespaceFeeSol = Number(state.registrationDraft.namespaceFeeLamports || 0) / 1e9;
|
||||
const requiredSol = Math.max(MIN_REQUIRED_SOL, namespaceFeeSol + 0.004);
|
||||
if (currentBalance < requiredSol) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = isTestContour
|
||||
? `Для регистрации нужно минимум ${MIN_REQUIRED_SOL} SOL. Рекомендуем пополнить кошелёк примерно на ${RECOMMENDED_TOPUP_SOL} SOL. Сейчас на кошельке ${formatSol(currentBalance, 6)} SOL.`
|
||||
: `Для регистрации пополните этот кошелёк соланами примерно на ${RECOMMENDED_TOPUP_SOL} SOL. Сейчас на кошельке ${formatSol(currentBalance, 6)} SOL. Минимум для продолжения: ${MIN_REQUIRED_SOL} SOL.`;
|
||||
? `Для регистрации нужно минимум ${requiredSol.toFixed(6)} SOL. Рекомендуем пополнить кошелёк примерно на ${RECOMMENDED_TOPUP_SOL} SOL. Сейчас на кошельке ${formatSol(currentBalance, 6)} SOL.`
|
||||
: `Для регистрации пополните этот кошелёк соланами примерно на ${RECOMMENDED_TOPUP_SOL} SOL. Сейчас на кошельке ${formatSol(currentBalance, 6)} SOL. Минимум для продолжения: ${requiredSol.toFixed(6)} SOL.`;
|
||||
status.style.display = '';
|
||||
if (isTestContour) {
|
||||
status.textContent += ` Нажмите «Тестовое пополнение», чтобы сразу добавить ${TEST_TOPUP_AMOUNT_SOL} SOL без перехода на другой экран.`;
|
||||
status.textContent += ' Для тестового пополнения используйте внешний devnet faucet.';
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -339,7 +316,6 @@ export function render({ navigate }) {
|
||||
keyBundle,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
accessServers: [state.entrySettings.shineServerLogin || defaultServerLogin],
|
||||
promoCode: '',
|
||||
});
|
||||
registrationTxId = String(registrationResult?.signature || '').trim();
|
||||
} catch (solanaError) {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
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 { upgradeFreeUserOnSolana } from '../services/shine-user-pda-service.js';
|
||||
import { base64ToBytes, bytesToBase58 } from '../services/crypto-utils.js';
|
||||
|
||||
export const pageMeta={id:'registration-upgrade-view',title:'Регистрация в Solana'};
|
||||
export function render({navigate,chrome}) {
|
||||
const screen=document.createElement('section');screen.className='stack';
|
||||
chrome?.setTopbar(createTopBar({title:'Регистрация в Solana',back:{label:'←',onClick:()=>navigate('settings-view')}}));
|
||||
const card=document.createElement('div');card.className='card stack';
|
||||
const heading=document.createElement('h3');heading.textContent='Закрепить существующий аккаунт в Solana';
|
||||
const description=document.createElement('p');description.className='meta-muted';
|
||||
description.textContent='Имя, история Arweave, каналы и три публичных ключа не меняются. Создаётся только пользовательский PDA Solana.';
|
||||
const price=document.createElement('p');price.className='meta-muted';price.textContent='Читаем стоимость из Solana…';
|
||||
const password=document.createElement('input');password.className='input';password.type='password';
|
||||
password.autocomplete='current-password';password.placeholder='Пароль существующего аккаунта';
|
||||
const action=document.createElement('button');action.className='primary-btn';action.textContent='Зарегистрировать в Solana';
|
||||
const status=document.createElement('p');status.className='status-line';status.setAttribute('aria-live','polite');
|
||||
card.append(heading,description,price,password,action,status);screen.append(card);
|
||||
const login=state.session?.login || '';
|
||||
let identity=null;let namespace=null;let disposed=false;
|
||||
async function refresh(){
|
||||
if(!login.includes('@'))throw new Error('Нужен полный login@namespace');
|
||||
identity=await getRegistrationStatus(login);
|
||||
if(identity.registrationStatus!=='FREE_CERT') throw new Error('Платная регистрация доступна только для бесплатного аккаунта');
|
||||
namespace=await getNamespace({namespace:login.split('@')[1],solanaEndpoint:state.entrySettings.solanaServer});
|
||||
if(namespace.type!==2)throw new Error('Сертификат не соответствует namespace');
|
||||
if(disposed)return;
|
||||
price.textContent=`Комиссия namespace: ${(Number(namespace.registrationFeeLamports)/1e9).toFixed(6)} SOL + rent/сетевые комиссии`;
|
||||
action.disabled=false;
|
||||
}
|
||||
action.disabled=true;
|
||||
void refresh().catch(error=>{if(!disposed)status.textContent=error.message;});
|
||||
action.addEventListener('click',async()=>{
|
||||
action.disabled=true;
|
||||
try{
|
||||
if(!identity || !namespace)throw new Error('Namespace/сертификат ещё не проверены');
|
||||
if(!password.value)throw new Error('Введите исходный пароль для восстановления тех же ключей');
|
||||
status.textContent='Восстанавливаем первоначальные ключи локально…';
|
||||
const keys=await authService.derivePasswordKeyBundle(login,password.value);
|
||||
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('Не получена проверяемая подпись регистратора');
|
||||
status.textContent='Подписываем новую запись PDA существующими ключами…';
|
||||
const tx=await upgradeFreeUserOnSolana({
|
||||
login,keyBundle:keys,solanaEndpoint:state.entrySettings.solanaServer,
|
||||
innerSignature64:signature,
|
||||
accessServers:identity.defaultServerLogin?[identity.defaultServerLogin]:[],
|
||||
});
|
||||
if(disposed)return;
|
||||
password.value='';
|
||||
status.textContent=`Транзакция отправлена (${tx.signature||'успешно'}). Ожидаем синхронизацию статуса Solana; история и ключи сохранены.`;
|
||||
// UI не делает ложных выводов до фактической синхронизации PDA.
|
||||
}catch(error){if(!disposed)status.textContent=error.message;}
|
||||
finally {if(!disposed)action.disabled=false;}
|
||||
});
|
||||
return screen;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { getRegistrationStatus } from '../services/registration-v2-api.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { addAppLogEntry, authService, closeSavedProfile, state } from '../state.js';
|
||||
import { openSheet } from '../components/sheet.js';
|
||||
@@ -143,6 +144,19 @@ export function render({navigate, chrome}) {
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Кнопка доступна только владельцу действительного бесплатного сертификата.
|
||||
if (String(state.session?.login||'').includes('@')) {
|
||||
void getRegistrationStatus(state.session.login).then(info=>{
|
||||
if (isDisposed || info.registrationStatus!=='FREE_CERT') return;
|
||||
const list=card.querySelector('.nav-list');
|
||||
if(!list || card.querySelector('#settings-solana-upgrade')) return;
|
||||
const button=document.createElement('button');
|
||||
button.id='settings-solana-upgrade'; button.className='nav-row';
|
||||
button.textContent='Зарегистрировать аккаунт в Solana';
|
||||
button.addEventListener('click',()=>navigate('registration-upgrade-view'));
|
||||
list.append(button);
|
||||
}).catch(()=>{});
|
||||
}
|
||||
card.querySelector('#settings-appearance').addEventListener('click', () => navigate('appearance-view'));
|
||||
card.querySelector('#settings-notifications').addEventListener('click', () => navigate('notification-settings-view'));
|
||||
card.querySelector('#settings-about').addEventListener('click', () => {
|
||||
|
||||
@@ -2,18 +2,15 @@ import { createTopBar } from '../components/topbar.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { state } from '../state.js';
|
||||
import {
|
||||
createSolanaWalletFromPrivateBase58,
|
||||
formatSol,
|
||||
getBalanceSol,
|
||||
getTopupSiteUrl,
|
||||
transferSol,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'topup-view', title: 'Пополнение solana счета', showAppChrome: false };
|
||||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||||
const SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
||||
const REGISTRATION_TOPUP_AMOUNT_SOL = 0.02;
|
||||
|
||||
// Канонический Solana-кошелёк пользователя = текущий blockchain key.
|
||||
@@ -72,7 +69,7 @@ export function render({ navigate }) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
card.innerHTML = `
|
||||
<p class="auth-copy">Можете или пополнить счёт тестовыми соланами и продолжить регистрацию.</p>
|
||||
<p class="auth-copy">Пополните счёт через доверенный devnet faucet и продолжите регистрацию.</p>
|
||||
<div class="card stack" style="padding:12px; max-width:320px;">
|
||||
<div class="field-label" style="margin-bottom:6px;">Кошелёк для пополнения (blockchain key = Solana wallet)</div>
|
||||
</div>
|
||||
@@ -87,43 +84,9 @@ export function render({ navigate }) {
|
||||
testButton.className = 'ghost-btn';
|
||||
testButton.type = 'button';
|
||||
testButton.textContent = 'Тестовое пополнение для регистрации';
|
||||
testButton.addEventListener('click', async () => {
|
||||
const address = String(walletValue.value || '').trim();
|
||||
if (!address) {
|
||||
showToast('Адрес кошелька не найден.', { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
if (!senderKeypair) {
|
||||
status.textContent = 'Ошибка: тестовый кошелёк отправителя ещё не инициализирован.';
|
||||
return;
|
||||
}
|
||||
testButton.disabled = true;
|
||||
try {
|
||||
status.textContent = 'Отправляем тестовое пополнение для регистрации...';
|
||||
const tx = await transferSol({
|
||||
endpoint: DEVNET_ENDPOINT,
|
||||
fromKeypair: senderKeypair,
|
||||
toAddress: address,
|
||||
amountSol: REGISTRATION_TOPUP_AMOUNT_SOL,
|
||||
});
|
||||
const bal = await getBalanceSol({
|
||||
endpoint: DEVNET_ENDPOINT,
|
||||
address,
|
||||
});
|
||||
state.registrationPayment.balanceSOL = String(bal.sol);
|
||||
status.style.fontSize = '12px';
|
||||
status.textContent = [
|
||||
'Тестовое пополнение для регистрации выполнено.',
|
||||
`Кошелёк пополнен на ${REGISTRATION_TOPUP_AMOUNT_SOL} SOL.`,
|
||||
`Новый баланс: ${formatSol(bal.sol, 6)} SOL.`,
|
||||
`Signature: ${tx.signature}`,
|
||||
].join('\n');
|
||||
} catch (error) {
|
||||
status.style.fontSize = '13px';
|
||||
status.textContent = actionErrorText('Ошибка тестового пополнения', error);
|
||||
} finally {
|
||||
testButton.disabled = false;
|
||||
}
|
||||
testButton.textContent = 'Как пополнить через devnet faucet';
|
||||
testButton.addEventListener('click', () => {
|
||||
status.textContent = 'Для пополнения скопируйте адрес блокчейн-кошелька и используйте внешний доверенный Solana devnet faucet. Приватный ключ отправителя не должен находиться в публичном приложении.';
|
||||
});
|
||||
|
||||
const backButton = document.createElement('button');
|
||||
@@ -135,7 +98,6 @@ export function render({ navigate }) {
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
actions.append(testButton, backButton);
|
||||
let senderKeypair = null;
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
@@ -154,8 +116,6 @@ export function render({ navigate }) {
|
||||
});
|
||||
state.registrationPayment.balanceSOL = String(balance.sol);
|
||||
status.textContent = `Текущий баланс: ${formatSol(balance.sol, 6)} SOL`;
|
||||
const sender = await createSolanaWalletFromPrivateBase58(SENDER_PRIVATE_32_BASE58);
|
||||
senderKeypair = sender.keypair;
|
||||
} catch (error) {
|
||||
status.textContent = actionErrorText('Не удалось получить баланс', error);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user