Files
SHiNE-server/shine-UI/js/pages/registration-upgrade-view.js
T

65 lines
4.9 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 { 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;
}