SHA256
Улучшить UI регистрации и связанные сценарии
This commit is contained in:
@@ -744,8 +744,8 @@ function validatePersonalChannelName(value) {
|
||||
const normalized = normalizeChannelDisplayName(value);
|
||||
if (!normalized) return { ok: false, error: 'Введите логин пользователя.' };
|
||||
const length = Array.from(normalized).length;
|
||||
if (length < 1 || length > 20) {
|
||||
return { ok: false, error: 'Логин: 1-20 символов.' };
|
||||
if (length < 4 || length > 20) {
|
||||
return { ok: false, error: 'Логин для нового персонального канала: 4–20 символов.' };
|
||||
}
|
||||
if (!/^[A-Za-z0-9_]+$/.test(normalized)) {
|
||||
return { ok: false, error: 'Логин: разрешены только латиница, цифры и _.' };
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const MIN_LEN = 3;
|
||||
const MIN_LEN = 4;
|
||||
const MAX_LEN = 32;
|
||||
const ALLOWED_CHARS_RE = /^[A-Za-z0-9_-]+$/;
|
||||
const DIGITS_ONLY_RE = /^[0-9]+$/;
|
||||
@@ -55,7 +55,7 @@ export function channelNameErrorText(code) {
|
||||
case 'blank':
|
||||
return 'Введите название канала.';
|
||||
case 'too_short':
|
||||
return 'Название слишком короткое: минимум 3 символа.';
|
||||
return 'Название слишком короткое: минимум 4 символа.';
|
||||
case 'too_long':
|
||||
return 'Название слишком длинное: максимум 32 символа.';
|
||||
case 'bad_chars':
|
||||
|
||||
@@ -1,19 +1,25 @@
|
||||
/** Расчёт минимального пополнения для перехода FREE_CERT → PAID. */
|
||||
/** Единая стоимость регистрации: цена namespace уже включает депозит PDA. */
|
||||
export const USER_PDA_SPACE = 768; // shine-solana/shine/programs/shine_users/src/settings.rs
|
||||
export const UPGRADE_NETWORK_RESERVE_LAMPORTS = 100_000; // запас на подписи/комиссию сети
|
||||
// Запас для предварительной проверки баланса; сеть списывает фактическую комиссию.
|
||||
export const REGISTRATION_NETWORK_RESERVE_LAMPORTS = 100_000n;
|
||||
export const UPGRADE_TEST_TOPUP_SOL = 0.02;
|
||||
export const LAMPORTS_PER_SOL = 1_000_000_000;
|
||||
|
||||
export function calculateUpgradeFunding({ namespaceFeeLamports, rentLamports }) {
|
||||
export function calculateRegistrationFunding({ namespaceFeeLamports, rentLamports }) {
|
||||
const namespaceFee = BigInt(namespaceFeeLamports);
|
||||
const rent = BigInt(rentLamports);
|
||||
if (namespaceFee < 0n || rent < 0n) throw new Error('Некорректная стоимость регистрации');
|
||||
const requiredLamports = namespaceFee + rent + BigInt(UPGRADE_NETWORK_RESERVE_LAMPORTS);
|
||||
// Рекомендуем небольшой запас на кошельке, но не ограничиваем 0.01 SOL без необходимости.
|
||||
const recommendedLamports = requiredLamports + 2_000_000n;
|
||||
return { requiredLamports, recommendedLamports, namespaceFee, rent };
|
||||
if (namespaceFee < rent) {
|
||||
throw new Error(`Цена namespace (${solFromLamports(namespaceFee)} SOL) меньше депозита PDA (${solFromLamports(rent)} SOL). Регистрация временно недоступна: обратитесь к администратору namespace.`);
|
||||
}
|
||||
const projectFee = namespaceFee - rent;
|
||||
const requiredLamports = namespaceFee + REGISTRATION_NETWORK_RESERVE_LAMPORTS;
|
||||
return { requiredLamports, namespaceFee, rent, projectFee, networkReserve: REGISTRATION_NETWORK_RESERVE_LAMPORTS };
|
||||
}
|
||||
|
||||
// Существующие потребители используют это имя; формула общая для обоих сценариев.
|
||||
export const calculateUpgradeFunding = calculateRegistrationFunding;
|
||||
|
||||
export function isUpgradeComplete(status) {
|
||||
// Старые серверы могут временно вернуть старые значения при последовательном развёртывании.
|
||||
return status === 'PAID' || status === 'PAID_DIRECT' || status === 'PAID_UPGRADED';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Общий бинарный протокол namespace PDA v1; используется платным create и upgrade.
|
||||
// Namespace PDA v1.0 (legacy) / v1.1 (валюта) для прямой регистрации и upgrade.
|
||||
import { sha256Bytes } from './crypto-utils.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import { SHINE_USERS_PROGRAM_ID } from '../solana-programs.js';
|
||||
@@ -35,7 +35,7 @@ export function buildFreeCertificateInnerMessage(fullLogin, root32, blockchain32
|
||||
}
|
||||
export function decodeNamespacePda(data) {
|
||||
const bytes = new Uint8Array(data);
|
||||
if (bytes.length < 13 || bytes[0] !== 1 || bytes[1] !== 0 || (bytes[2] !== 1 && bytes[2] !== 2)) throw new Error('Неподдерживаемый namespace PDA');
|
||||
if (bytes.length < 13 || bytes[0] !== 1 || ![0, 1].includes(bytes[1]) || (bytes[2] !== 1 && bytes[2] !== 2)) throw new Error('Неподдерживаемый namespace PDA');
|
||||
const type = bytes[2], minLocalpartLength = bytes[3], len = bytes[4];
|
||||
if (len === 0 || 5 + len + 8 > bytes.length) throw new Error('Обрезанный namespace PDA');
|
||||
const namespace = dec.decode(bytes.slice(5, 5 + len));
|
||||
@@ -43,6 +43,8 @@ export function decodeNamespacePda(data) {
|
||||
if (minLocalpartLength < 1 || minLocalpartLength + len + 1 > 30) throw new Error('Недопустимая минимальная длина');
|
||||
const fee = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getBigUint64(5 + len, true);
|
||||
let offset = 5 + len + 8, registrarPublicKey32 = null, serverLogin = null;
|
||||
const currencyCode = bytes[1] === 1 ? bytes[offset++] : 1;
|
||||
if (currencyCode !== 1) throw new Error('Валюта namespace пока не поддерживается (разрешена только SOL)');
|
||||
if (type === 2) {
|
||||
if (bytes.length < offset + 33) throw new Error('В namespace типа 2 отсутствует ключ регистратора');
|
||||
registrarPublicKey32 = bytes.slice(offset, offset + 32); offset += 32;
|
||||
@@ -52,21 +54,23 @@ export function decodeNamespacePda(data) {
|
||||
offset += serverLen;
|
||||
}
|
||||
if (bytes.length !== offset) throw new Error('Лишние данные namespace PDA');
|
||||
return { namespace, type, minLocalpartLength, registrationFeeLamports: fee, registrarPublicKey32, serverLogin };
|
||||
return { namespace, type, minLocalpartLength, registrationFeeLamports: fee, currencyCode, registrarPublicKey32, serverLogin };
|
||||
}
|
||||
export function encodeNamespacePda({ namespace, type, minLocalpartLength, registrationFeeLamports, registrarPublicKey32, serverLogin }) {
|
||||
export function encodeNamespacePda({ namespace, type, minLocalpartLength, registrationFeeLamports, currencyCode = 1, registrarPublicKey32, serverLogin }) {
|
||||
const name = enc.encode(normalizeNamespace(namespace));
|
||||
if (!Number.isInteger(minLocalpartLength) || minLocalpartLength < 1 || minLocalpartLength + name.length + 1 > 30) throw new Error('Недопустимая длина локального логина');
|
||||
if (type !== 1 && type !== 2) throw new Error('Недопустимый тип namespace');
|
||||
if (currencyCode !== 1) throw new Error('Валюта namespace пока не поддерживается (разрешена только SOL)');
|
||||
const fee = BigInt(registrationFeeLamports);
|
||||
if (fee < 0n || fee > (2n ** 64n - 1n)) throw new Error('Неверная цена регистрации');
|
||||
const server = type === 2 ? enc.encode(normalizeFullLogin(serverLogin)) : new Uint8Array();
|
||||
const pub = type === 2 ? new Uint8Array(registrarPublicKey32) : new Uint8Array();
|
||||
if (type === 2 && pub.length !== 32) throw new Error('Ключ регистратора должен быть 32 байта');
|
||||
const out = new Uint8Array(5 + name.length + 8 + (type === 2 ? 32 + 1 + server.length : 0));
|
||||
out.set([1, 0, type, minLocalpartLength, name.length]); out.set(name, 5);
|
||||
const out = new Uint8Array(5 + name.length + 8 + 1 + (type === 2 ? 32 + 1 + server.length : 0));
|
||||
out.set([1, 1, type, minLocalpartLength, name.length]); out.set(name, 5);
|
||||
let offset = 5 + name.length;
|
||||
new DataView(out.buffer).setBigUint64(offset, fee, true); offset += 8;
|
||||
out[offset++] = currencyCode;
|
||||
if (type === 2) { out.set(pub, offset); offset += 32; out[offset++] = server.length; out.set(server, offset); }
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,14 @@ export function normalizeLogin(value = '') {
|
||||
return String(value || '').trim().replace(/^@+/, '');
|
||||
}
|
||||
|
||||
// Видимый адрес канала: <login>@<namespace>/<channel>, без декоративной @ перед логином.
|
||||
// Нормализуем только отображение, не меняем сохранённый идентификатор или URL.
|
||||
export function formatChannelAddress({ ownerLogin = '', channelName = '' } = {}) {
|
||||
const owner = normalizeLogin(ownerLogin);
|
||||
const channel = String(channelName || '').trim();
|
||||
return [owner, channel].filter(Boolean).join('/');
|
||||
}
|
||||
|
||||
export function extractLoginFromBlockchainName(value = '') {
|
||||
const raw = String(value || '').trim();
|
||||
const match = raw.match(/^(.+)-\d+$/);
|
||||
|
||||
@@ -46,11 +46,11 @@ export async function resolveShineServerByServerLogin({ serverLogin, solanaEndpo
|
||||
solanaEndpoint,
|
||||
});
|
||||
if (!parsed?.isServer) {
|
||||
throw new Error(`Логин @${cleanServerLogin} не опубликован как сервер Сияния.`);
|
||||
throw new Error(`Логин ${cleanServerLogin} не опубликован как сервер Сияния.`);
|
||||
}
|
||||
const serverAddress = normalizeHostLike(parsed?.serverAddress || '');
|
||||
if (!serverAddress) {
|
||||
throw new Error(`У server PDA пользователя @${cleanServerLogin} не задан server_address.`);
|
||||
throw new Error(`У server PDA пользователя ${cleanServerLogin} не задан server_address.`);
|
||||
}
|
||||
return {
|
||||
serverLogin: cleanServerLogin,
|
||||
@@ -73,7 +73,7 @@ export async function resolveShineServerForUserLogin({ login, solanaEndpoint, fa
|
||||
: [];
|
||||
const pickedServerLogin = accessServers[0] || normalizeShineServerLogin(fallbackServerLogin);
|
||||
if (!pickedServerLogin) {
|
||||
throw new Error(`У пользователя @${cleanLogin} в PDA не указан access server.`);
|
||||
throw new Error(`У пользователя ${cleanLogin} в PDA не указан access server.`);
|
||||
}
|
||||
const resolved = await resolveShineServerByServerLogin({
|
||||
serverLogin: pickedServerLogin,
|
||||
|
||||
@@ -473,7 +473,7 @@ export async function readShineUserPda({ login, solanaEndpoint }) {
|
||||
const [pda] = solana.PublicKey.findProgramAddressSync(
|
||||
cleanLogin.includes('@') ? [await userPdaSeed32(cleanLogin)] : [new TextEncoder().encode(SHINE_USERS_USER_PDA_SEED_PREFIX), new TextEncoder().encode(cleanLogin)], usersProgram);
|
||||
const info = await connection.getAccountInfo(pda, 'confirmed');
|
||||
if (!info?.data) throw new Error(`PDA пользователя @${cleanLogin} не найдена`);
|
||||
if (!info?.data) throw new Error(`PDA пользователя ${cleanLogin} не найдена`);
|
||||
return { ...parseShineUserPda(new Uint8Array(info.data)), userPda: pda.toBase58(), pdaAddress: pda.toBase58(), endpoint };
|
||||
}
|
||||
|
||||
|
||||
@@ -106,11 +106,12 @@ export function toUserMessage(error, fallback = 'Действие не выпо
|
||||
text.includes('channel name must match') ||
|
||||
text.includes('channelname contains unsupported') ||
|
||||
text.includes('channelname must not contain only digits') ||
|
||||
text.includes('channelname length must be 4..32') ||
|
||||
text.includes('channelname length must be 3..32') ||
|
||||
text.includes('channelname length must be 1..32') ||
|
||||
text.includes('bad_channel_name')
|
||||
) {
|
||||
return 'Некорректное название канала. Разрешены только латинские буквы, цифры, _ и -. Длина: 3..32. Название не должно состоять только из цифр.';
|
||||
return 'Некорректное название канала. Разрешены только латинские буквы, цифры, _ и -. Длина: 4..32. Название не должно состоять только из цифр.';
|
||||
}
|
||||
|
||||
if (text.includes('channel name is required') || text.includes('введите имя канала')) {
|
||||
|
||||
Reference in New Issue
Block a user