Files
SHiNE-server/shine-UI/js/services/shine-support-amount.js
T

47 lines
2.6 KiB
JavaScript

/** Точная денежная арифметика для пожертвований 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));
}
/** Integer Star cents: 0.10 minimum, exactly two decimal places maximum. */
export function parseStarCents(input) {
const value = String(input ?? '').trim().replace(',', '.');
if (!/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/.test(value)) throw new Error('Введите сумму ⭐ с точностью до 0,01');
const [whole, frac = ''] = value.split('.');
const cents = BigInt(whole) * 100n + BigInt(frac.padEnd(2, '0') || '0');
if (cents < 10n || cents > 0xffff_ffff_ffff_ffffn) throw new Error('Минимальная поддержка — 0,10 ⭐');
return cents;
}
export function formatStars(value) {
const cents = BigInt(value);
return `${cents / 100n}.${String(cents % 100n).padStart(2, '0')} ⭐`;
}
export function splitStarCents(value) {
const cents = BigInt(value);
const dao = (cents + 9n) / 10n;
return { author: cents - dao, dao };
}
/** Quote Pyth prices as USD x 10^8; no Number or rounding-sensitive floats. */
export function starCentsToLamports(starCents, solPriceE8, usdtPriceE8) {
const cents = BigInt(starCents), sol = BigInt(solPriceE8), usdt = BigInt(usdtPriceE8);
if (sol <= 0n || usdt <= 0n) throw new Error('Нет актуального курса');
// ceil ensures enough lamports for the requested Stars.
return (cents * 1_000_000_000n * usdt + 100n * sol - 1n) / (100n * sol);
}