SHA256
Добавить систему поддержки SHiNE
This commit is contained in:
@@ -1598,6 +1598,16 @@ export class AuthService {
|
||||
return response.payload || {};
|
||||
}
|
||||
|
||||
async getSupportTotals(channel) {
|
||||
const payload = {
|
||||
channelRootBlockNumber: Number(channel?.channelRootBlockNumber),
|
||||
channelRootBlockHash: String(channel?.channelRootBlockHash || '').trim(),
|
||||
};
|
||||
const response = await this.ws.request('GetSupportTotals', payload);
|
||||
if (response.status !== 200) throw opError('GetSupportTotals', response);
|
||||
return response.payload || {};
|
||||
}
|
||||
|
||||
async getMessageThread(message, depthUp = 20, depthDown = 2, limitChildrenPerNode = 50, login = '') {
|
||||
const normalizedMessage = {
|
||||
blockchainName: String(message?.blockchainName || '').trim(),
|
||||
|
||||
@@ -4,4 +4,6 @@ export {
|
||||
getShineBlockchainUsage,
|
||||
getShineUsersEconomyConfig,
|
||||
updateShineUserPdaOnSolana,
|
||||
supportShineUserOnSolana,
|
||||
supportShineDaoOnSolana,
|
||||
} from './shine-user-pda-service.js';
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Точная денежная арифметика для пожертвований SHiNE: без Number. */
|
||||
export function parseSolLamports(input) {
|
||||
const text = String(input ?? '').trim().replace(',', '.');
|
||||
if (!/^(?:0|[1-9]\d*)(?:\.\d{1,9})?$/.test(text)) throw new Error('Введите положительную сумму SOL (не более 9 знаков после запятой)');
|
||||
const [whole, fraction = ''] = text.split('.');
|
||||
const amount = BigInt(whole) * 1_000_000_000n + BigInt(fraction.padEnd(9, '0') || '0');
|
||||
if (amount <= 0n || amount > 0xffff_ffff_ffff_ffffn) throw new Error('Сумма SOL вне допустимого диапазона');
|
||||
return amount;
|
||||
}
|
||||
export function formatLamportsSol(value) {
|
||||
const n = BigInt(value);
|
||||
const sign = n < 0n ? '-' : '';
|
||||
const abs = n < 0n ? -n : n;
|
||||
return sign + String(abs / 1_000_000_000n) + (abs % 1_000_000_000n ? '.' + String(abs % 1_000_000_000n).padStart(9, '0').replace(/0+$/, '') : '');
|
||||
}
|
||||
export function hexHash32(value) {
|
||||
const hex = String(value || '').trim().toLowerCase();
|
||||
if (!/^[0-9a-f]{64}$/.test(hex)) throw new Error('Некорректный 32-байтовый хеш блока канала');
|
||||
return Uint8Array.from({ length: 32 }, (_, i) => parseInt(hex.slice(i * 2, i * 2 + 2), 16));
|
||||
}
|
||||
@@ -33,6 +33,8 @@ const AUTH_MODE_ROOT = 1;
|
||||
const IX_CREATE_USER_PDA = 3;
|
||||
const IX_UPDATE_USER_PDA = 4;
|
||||
const IX_CLOSE_LEGACY_USER_PDA = 6;
|
||||
const IX_SUPPORT_USER = 9;
|
||||
const IX_SUPPORT_DAO = 10;
|
||||
const DAY_MS = 86_400_000n;
|
||||
const FORK_COOLDOWN_MS = 3n * DAY_MS;
|
||||
const MAX_EFFECTIVE_ACCESS_SERVERS = 1;
|
||||
@@ -288,7 +290,14 @@ export function parseShineUserPda(dataBytes) {
|
||||
const blocksOffset = reader.offset;
|
||||
const signature = bytes.slice(recordLen - 64, recordLen);
|
||||
const unsignedBytes = bytes.slice(0, recordLen - 64);
|
||||
const header = { formatMajor, formatMinor, recordLen, createdAtMs, updatedAtMs, recordNumber, prevRecordHash, login, blocksCount, blocksOffset, signature, unsignedBytes };
|
||||
let supportStats = { version: 0, supportSent: 0n, supportReceived: 0n, daoDirect: 0n };
|
||||
if (recordLen < bytes.length && bytes[recordLen] !== 0) {
|
||||
if (bytes[recordLen] !== 1) throw new Error('Неподдерживаемая версия статистики поддержки');
|
||||
if (recordLen + 25 > bytes.length) throw new Error('Обрезан блок статистики поддержки');
|
||||
const statsReader = makeReader(bytes.slice(recordLen + 1, recordLen + 25));
|
||||
supportStats = { version: 1, supportSent: statsReader.readU64(), supportReceived: statsReader.readU64(), daoDirect: statsReader.readU64() };
|
||||
}
|
||||
const header = { formatMajor, formatMinor, recordLen, createdAtMs, updatedAtMs, recordNumber, prevRecordHash, login, blocksCount, blocksOffset, signature, unsignedBytes, supportStats };
|
||||
return parseV12Pda(bytes, header);
|
||||
}
|
||||
|
||||
@@ -815,3 +824,52 @@ export function calcLimitTopupPriceLamports(additionalLimitBytes, lamportsPerLim
|
||||
}
|
||||
|
||||
export function getLimitStepBytes() { return LIMIT_STEP; }
|
||||
|
||||
function supportData(tag, senderLogin, recipientLogin, amountLamports, target) {
|
||||
const out = [tag];
|
||||
const putString = (value) => { const bytes = new TextEncoder().encode(String(value)); if (bytes.length > 255) throw new Error('Слишком длинный login'); out.push(bytes.length, ...bytes); };
|
||||
putString(senderLogin);
|
||||
if (recipientLogin != null) putString(recipientLogin);
|
||||
pushU64LE(out, amountLamports);
|
||||
if (target != null) {
|
||||
out.push(target.type);
|
||||
if (target.type === 1 || target.type === 2) { pushU64LE(out, target.channelBlockNumber); out.push(...toUint8Array(target.channelBlockHash, 32)); }
|
||||
if (target.type === 2) { pushU64LE(out, target.messageBlockNumber); out.push(...toUint8Array(target.messageBlockHash, 32)); }
|
||||
}
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
/** Выполняет учитываемую поддержку через shine_users без Number и округлений. */
|
||||
export async function supportShineUserOnSolana({ senderLogin, recipientLogin, amountLamports, target = { type: 0 }, solanaEndpoint, blockchainPrivatePkcs8B64, clientPrivatePkcs8B64 }) {
|
||||
const amount = BigInt(amountLamports);
|
||||
if (amount <= 0n || amount % 10n !== 0n) throw new Error('Сумма учитываемой поддержки должна быть положительной и кратной 10 lamports');
|
||||
const sender = await readShineUserPda({ login: senderLogin, solanaEndpoint });
|
||||
const recipient = await readShineUserPda({ login: recipientLogin, solanaEndpoint });
|
||||
const ctx = await buildCommonContext({ login: sender.login, solanaEndpoint, clientPrivatePkcs8B64, payerPrivatePkcs8B64: blockchainPrivatePkcs8B64 });
|
||||
const recipientSeed = await userPdaSeed32(recipient.login);
|
||||
const [recipientPda] = await ctx.solana.PublicKey.findProgramAddress([recipientSeed], new ctx.solana.PublicKey(SHINE_USERS_PROGRAM_ID));
|
||||
const recipientKey = new ctx.solana.PublicKey(recipient.forks.at(-1).blockchainKey);
|
||||
if (!ctx.payerKeypair.publicKey.equals(new ctx.solana.PublicKey(sender.forks.at(-1).blockchainKey))) throw new Error('Подписант должен быть актуальным blockchain key отправителя');
|
||||
const ix = new ctx.solana.TransactionInstruction({ programId: new ctx.solana.PublicKey(SHINE_USERS_PROGRAM_ID), keys: [
|
||||
{ pubkey: ctx.payerKeypair.publicKey, isSigner: true, isWritable: true }, { pubkey: ctx.userPda, isSigner: false, isWritable: true },
|
||||
{ pubkey: recipientKey, isSigner: false, isWritable: true }, { pubkey: recipientPda, isSigner: false, isWritable: true },
|
||||
{ pubkey: ctx.inflowVault, isSigner: false, isWritable: true }, { pubkey: ctx.economyConfigPda, isSigner: false, isWritable: false },
|
||||
{ pubkey: ctx.solana.SystemProgram.programId, isSigner: false, isWritable: false },
|
||||
], data: supportData(IX_SUPPORT_USER, sender.login, recipient.login, amount, target) });
|
||||
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(ix), [ctx.payerKeypair]);
|
||||
return { signature, amountLamports: amount, recipientLamports: amount * 9n / 10n, inflowLamports: amount / 10n };
|
||||
}
|
||||
|
||||
export async function supportShineDaoOnSolana({ senderLogin, amountLamports, solanaEndpoint, blockchainPrivatePkcs8B64, clientPrivatePkcs8B64 }) {
|
||||
const amount = BigInt(amountLamports);
|
||||
if (amount <= 0n) throw new Error('Сумма пожертвования должна быть положительной');
|
||||
const sender = await readShineUserPda({ login: senderLogin, solanaEndpoint });
|
||||
const ctx = await buildCommonContext({ login: sender.login, solanaEndpoint, clientPrivatePkcs8B64, payerPrivatePkcs8B64: blockchainPrivatePkcs8B64 });
|
||||
const ix = new ctx.solana.TransactionInstruction({ programId: new ctx.solana.PublicKey(SHINE_USERS_PROGRAM_ID), keys: [
|
||||
{ pubkey: ctx.payerKeypair.publicKey, isSigner: true, isWritable: true }, { pubkey: ctx.userPda, isSigner: false, isWritable: true },
|
||||
{ pubkey: ctx.inflowVault, isSigner: false, isWritable: true }, { pubkey: ctx.economyConfigPda, isSigner: false, isWritable: false },
|
||||
{ pubkey: ctx.solana.SystemProgram.programId, isSigner: false, isWritable: false },
|
||||
], data: supportData(IX_SUPPORT_DAO, sender.login, null, amount, null) });
|
||||
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(ix), [ctx.payerKeypair]);
|
||||
return { signature, amountLamports: amount };
|
||||
}
|
||||
|
||||
@@ -290,6 +290,21 @@ export async function transferSol({ endpoint, fromKeypair, toAddress, amountSol
|
||||
return { endpoint: rpc, signature, lamports };
|
||||
}
|
||||
|
||||
/** Прямой перевод точной суммы в lamports, без преобразований через дробный SOL. */
|
||||
export async function transferSolLamports({ endpoint, fromKeypair, toAddress, amountLamports }) {
|
||||
const solana = await loadSolanaLib();
|
||||
const amount = BigInt(amountLamports);
|
||||
if (amount <= 0n || amount > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error('Сумма вне безопасного диапазона прямого перевода');
|
||||
const connection = new solana.Connection(normalizeEndpoint(endpoint), 'confirmed');
|
||||
const tx = new solana.Transaction().add(solana.SystemProgram.transfer({
|
||||
fromPubkey: fromKeypair.publicKey,
|
||||
toPubkey: new solana.PublicKey(String(toAddress || '').trim()),
|
||||
lamports: Number(amount),
|
||||
}));
|
||||
const signature = await sendAndConfirmSolanaHttp(connection, tx, [fromKeypair]);
|
||||
return { signature, lamports: amount };
|
||||
}
|
||||
|
||||
export async function transferAllSol({ endpoint, fromKeypair, toAddress }) {
|
||||
const solana = await loadSolanaLib();
|
||||
const rpc = normalizeEndpoint(endpoint);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { authService } from '../state.js';
|
||||
|
||||
// Один запрос на канал; только сервер проверяет привязку транзакции к блоку.
|
||||
const cache = new Map();
|
||||
export function loadVerifiedSupportTotals(selector) {
|
||||
const number = Number(selector?.channelRootBlockNumber);
|
||||
const hash = String(selector?.channelRootBlockHash || '').toLowerCase();
|
||||
if (!Number.isSafeInteger(number) || !/^[0-9a-f]{64}$/.test(hash)) return Promise.resolve(null);
|
||||
const key = `${number}:${hash}`;
|
||||
if (!cache.has(key)) {
|
||||
const promise = authService.getSupportTotals({ channelRootBlockNumber: number, channelRootBlockHash: hash })
|
||||
.then((response) => {
|
||||
const messages = new Map();
|
||||
for (const row of response?.messages || []) {
|
||||
const id = `${String(row.blockNumber)}:${String(row.blockHash).toLowerCase()}`;
|
||||
messages.set(id, String(row.receivedLamports));
|
||||
}
|
||||
return { channelReceivedLamports: String(response?.channelReceivedLamports || '0'), messages };
|
||||
})
|
||||
.catch(() => { cache.delete(key); return null; });
|
||||
cache.set(key, promise);
|
||||
}
|
||||
return cache.get(key);
|
||||
}
|
||||
|
||||
export function formatVerifiedSupportLamports(value) {
|
||||
try {
|
||||
const n = BigInt(value);
|
||||
if (n <= 0n) return null;
|
||||
const whole = n / 1_000_000_000n;
|
||||
const fraction = String(n % 1_000_000_000n).padStart(9, '0').replace(/0+$/, '');
|
||||
return `${whole}${fraction ? '.' + fraction : ''} SOL`;
|
||||
} catch { return null; }
|
||||
}
|
||||
Reference in New Issue
Block a user