SHA256
Перевести донаты на Stars и обновить Devnet
This commit is contained in:
@@ -1604,6 +1604,14 @@ export class AuthService {
|
||||
return response.payload || {};
|
||||
}
|
||||
|
||||
async getSupportHistory(login, limit = 20, offset = 0) {
|
||||
const response = await this.ws.request('GetSupportHistory', {
|
||||
login: String(login || '').trim(), limit, offset,
|
||||
});
|
||||
if (response.status !== 200) throw opError('GetSupportHistory', response);
|
||||
return response.payload || {};
|
||||
}
|
||||
|
||||
async getSupportTotals(channel) {
|
||||
const payload = {
|
||||
channelRootBlockNumber: Number(channel?.channelRootBlockNumber),
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* SHiNE Stars / Pyth Core: local price quote through SHiNE's existing authenticated
|
||||
* Solana RPC endpoint. No Hermes, private API keys or server-side prices.
|
||||
* Pyth price feed account format: PriceUpdateV2 (Anchor / Borsh).
|
||||
*/
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
|
||||
export const PYTH_SOL_USD_FEED_ID = 'ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d';
|
||||
export const PYTH_USDT_USD_FEED_ID = '2b89b9dc8fdf9f34709a5b106b472f0f39bb6ca9ce04b0fd7f2e971688e2e53b';
|
||||
export const PYTH_PUSH_ORACLE_PROGRAM_ID = 'pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT';
|
||||
export const PYTH_RECEIVER_PROGRAM_ID = 'rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ';
|
||||
const PYTH_PRICE_UPDATE_DISCRIMINATOR = [34, 241, 35, 99, 157, 126, 244, 205];
|
||||
// Devnet допускает более редкие обновления Pyth; production-лимит должен быть строже.
|
||||
export const MAX_PYTH_PRICE_AGE_SECONDS = 3_600;
|
||||
export const MAX_PYTH_CONFIDENCE_PPM = 10_000n; // 1%, same as shine_users.
|
||||
const MAX_SIGNED_FUTURE_SECONDS = 15;
|
||||
|
||||
function bytesFromHex(hex) {
|
||||
if (!/^[0-9a-f]{64}$/i.test(hex)) throw new Error('Invalid Pyth price feed ID');
|
||||
return Uint8Array.from(hex.match(/../g), (b) => parseInt(b, 16));
|
||||
}
|
||||
function hexFromBytes(bytes) { return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); }
|
||||
|
||||
/** Pyth's getPriceFeedAccountForProgram(shard=0, feedId): PDA([u16LE(shard), feedId], pushOracle). */
|
||||
export function deriveStarsPythOracleAccounts(solana) {
|
||||
const program = new solana.PublicKey(PYTH_PUSH_ORACLE_PROGRAM_ID);
|
||||
const shardZero = Uint8Array.of(0, 0);
|
||||
const derive = (id) => solana.PublicKey.findProgramAddressSync([shardZero, bytesFromHex(id)], program)[0];
|
||||
return { solUsd: derive(PYTH_SOL_USD_FEED_ID).toBase58(), usdtUsd: derive(PYTH_USDT_USD_FEED_ID).toBase58() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse verified Pyth PriceUpdateV2. The contract independently enforces identical
|
||||
* owner/feed/age/confidence checks; this preflight parser is for UX, not security.
|
||||
* Returns exact USD price * 10^8 as BigInt (same normalization as the Rust program).
|
||||
*/
|
||||
export function parseVerifiedPythPriceAccount(account, expectedFeedId, nowSeconds = Math.floor(Date.now() / 1000)) {
|
||||
if (!account?.data || account.owner?.toBase58?.() !== PYTH_RECEIVER_PROGRAM_ID) {
|
||||
throw new Error('Pyth: ценовой аккаунт отсутствует или имеет неверного владельца');
|
||||
}
|
||||
const bytes = account.data instanceof Uint8Array ? account.data : new Uint8Array(account.data);
|
||||
if (bytes.length < 133 || PYTH_PRICE_UPDATE_DISCRIMINATOR.some((b, i) => bytes[i] !== b)) {
|
||||
throw new Error('Pyth: неверный формат ценового аккаунта');
|
||||
}
|
||||
// Anchor discriminator (8), write authority (32), Borsh enum Full = 1 (Partial = 0 + signatures byte).
|
||||
if (bytes[40] !== 1) throw new Error('Pyth: цена не прошла полную проверку подписей');
|
||||
const start = 41;
|
||||
if (hexFromBytes(bytes.subarray(start, start + 32)) !== expectedFeedId) {
|
||||
throw new Error('Pyth: аккаунт содержит другую валютную пару');
|
||||
}
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const price = view.getBigInt64(start + 32, true);
|
||||
const confidence = view.getBigUint64(start + 40, true);
|
||||
const exponent = view.getInt32(start + 48, true);
|
||||
const publishedAt = view.getBigInt64(start + 52, true);
|
||||
if (price <= 0n || price * MAX_PYTH_CONFIDENCE_PPM < confidence * 1_000_000n) {
|
||||
throw new Error('Pyth: некорректная цена или высокий доверительный интервал');
|
||||
}
|
||||
const now = BigInt(Math.floor(nowSeconds));
|
||||
if (publishedAt > now + BigInt(MAX_SIGNED_FUTURE_SECONDS) ||
|
||||
now - publishedAt > BigInt(MAX_PYTH_PRICE_AGE_SECONDS)) {
|
||||
throw new Error('Pyth: цена устарела или имеет некорректное время');
|
||||
}
|
||||
const power = exponent + 8;
|
||||
if (power < -18 || power > 18) throw new Error('Pyth: неподдерживаемая точность цены');
|
||||
const priceE8 = power >= 0 ? price * 10n ** BigInt(power) : price / (10n ** BigInt(-power));
|
||||
if (priceE8 <= 0n) throw new Error('Pyth: цена слишком мала');
|
||||
return { priceE8, publishTimeSeconds: Number(publishedAt), confidence, exponent };
|
||||
}
|
||||
|
||||
/** Always read BOTH feeds in the same Solana RPC request; no cached/off-chain quote accepted. */
|
||||
export async function getStarsQuoteFromRpc({ solanaEndpoint, solana = null, connection = null, nowSeconds } = {}) {
|
||||
const endpoint = String(solanaEndpoint || '').trim();
|
||||
if (!connection && !endpoint) throw new Error('Solana RPC для SHiNE не подключён');
|
||||
const web3 = solana || await loadSolanaWeb3();
|
||||
const conn = connection || new web3.Connection(endpoint, 'confirmed');
|
||||
const oracleAccounts = deriveStarsPythOracleAccounts(web3);
|
||||
const keys = [new web3.PublicKey(oracleAccounts.solUsd), new web3.PublicKey(oracleAccounts.usdtUsd)];
|
||||
const infos = await conn.getMultipleAccountsInfo(keys, 'confirmed');
|
||||
if (!infos || infos.length !== 2) throw new Error('Pyth: не получены цены SOL и USDT из Solana');
|
||||
const now = nowSeconds ?? Math.floor(Date.now() / 1000);
|
||||
const sol = parseVerifiedPythPriceAccount(infos[0], PYTH_SOL_USD_FEED_ID, now);
|
||||
const usdt = parseVerifiedPythPriceAccount(infos[1], PYTH_USDT_USD_FEED_ID, now);
|
||||
return {
|
||||
solUsdE8: sol.priceE8.toString(), usdtUsdE8: usdt.priceE8.toString(),
|
||||
solOracleAccount: oracleAccounts.solUsd, usdtOracleAccount: oracleAccounts.usdtUsd,
|
||||
publishedAtSeconds: Math.min(sol.publishTimeSeconds, usdt.publishTimeSeconds),
|
||||
};
|
||||
}
|
||||
@@ -18,3 +18,29 @@ export function hexHash32(value) {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -292,10 +292,10 @@ export function parseShineUserPda(dataBytes) {
|
||||
const unsignedBytes = bytes.slice(0, recordLen - 64);
|
||||
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 (bytes[recordLen] !== 2) 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() };
|
||||
supportStats = { version: 2, 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);
|
||||
@@ -825,12 +825,13 @@ export function calcLimitTopupPriceLamports(additionalLimitBytes, lamportsPerLim
|
||||
|
||||
export function getLimitStepBytes() { return LIMIT_STEP; }
|
||||
|
||||
function supportData(tag, senderLogin, recipientLogin, amountLamports, target) {
|
||||
function supportData(tag, senderLogin, recipientLogin, amountLamports, starCents, 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);
|
||||
pushU64LE(out, starCents);
|
||||
if (target != null) {
|
||||
out.push(target.type);
|
||||
if (target.type === 1 || target.type === 2) { pushU64LE(out, target.channelBlockNumber); out.push(...toUint8Array(target.channelBlockHash, 32)); }
|
||||
@@ -840,9 +841,9 @@ function supportData(tag, senderLogin, recipientLogin, amountLamports, target) {
|
||||
}
|
||||
|
||||
/** Выполняет учитываемую поддержку через shine_users без Number и округлений. */
|
||||
export async function supportShineUserOnSolana({ senderLogin, recipientLogin, amountLamports, target = { type: 0 }, solanaEndpoint, blockchainPrivatePkcs8B64, clientPrivatePkcs8B64 }) {
|
||||
export async function supportShineUserOnSolana({ senderLogin, recipientLogin, amountLamports, starCents, oracleAccounts, target = { type: 0 }, solanaEndpoint, blockchainPrivatePkcs8B64, clientPrivatePkcs8B64 }) {
|
||||
const amount = BigInt(amountLamports);
|
||||
if (amount <= 0n || amount % 10n !== 0n) throw new Error('Сумма учитываемой поддержки должна быть положительной и кратной 10 lamports');
|
||||
if (amount <= 0n || BigInt(starCents) < 10n) throw new Error('Сумма поддержки должна быть не менее 0,10 ⭐');
|
||||
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 });
|
||||
@@ -855,21 +856,25 @@ export async function supportShineUserOnSolana({ senderLogin, recipientLogin, am
|
||||
{ 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) });
|
||||
{ pubkey: new ctx.solana.PublicKey(oracleAccounts.solUsd), isSigner: false, isWritable: false },
|
||||
{ pubkey: new ctx.solana.PublicKey(oracleAccounts.usdtUsd), isSigner: false, isWritable: false },
|
||||
], data: supportData(IX_SUPPORT_USER, sender.login, recipient.login, amount, BigInt(starCents), 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 };
|
||||
return { signature, amountLamports: amount, starCents: BigInt(starCents), recipientLamports: amount - (amount + 9n) / 10n, inflowLamports: (amount + 9n) / 10n };
|
||||
}
|
||||
|
||||
export async function supportShineDaoOnSolana({ senderLogin, amountLamports, solanaEndpoint, blockchainPrivatePkcs8B64, clientPrivatePkcs8B64 }) {
|
||||
export async function supportShineDaoOnSolana({ senderLogin, amountLamports, starCents, oracleAccounts, solanaEndpoint, blockchainPrivatePkcs8B64, clientPrivatePkcs8B64 }) {
|
||||
const amount = BigInt(amountLamports);
|
||||
if (amount <= 0n) throw new Error('Сумма пожертвования должна быть положительной');
|
||||
if (amount <= 0n || BigInt(starCents) < 10n) throw new Error('Минимальный донат 0,10 ⭐');
|
||||
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) });
|
||||
{ pubkey: new ctx.solana.PublicKey(oracleAccounts.solUsd), isSigner: false, isWritable: false },
|
||||
{ pubkey: new ctx.solana.PublicKey(oracleAccounts.usdtUsd), isSigner: false, isWritable: false },
|
||||
], data: supportData(IX_SUPPORT_DAO, sender.login, null, amount, BigInt(starCents), null) });
|
||||
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(ix), [ctx.payerKeypair]);
|
||||
return { signature, amountLamports: amount };
|
||||
return { signature, amountLamports: amount, starCents: BigInt(starCents) };
|
||||
}
|
||||
|
||||
@@ -13,9 +13,9 @@ export function loadVerifiedSupportTotals(selector) {
|
||||
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));
|
||||
messages.set(id, String(row.receivedStarCents));
|
||||
}
|
||||
return { channelReceivedLamports: String(response?.channelReceivedLamports || '0'), messages };
|
||||
return { channelReceivedStarCents: String(response?.channelReceivedStarCents || '0'), messages };
|
||||
})
|
||||
.catch(() => { cache.delete(key); return null; });
|
||||
cache.set(key, promise);
|
||||
@@ -23,12 +23,12 @@ export function loadVerifiedSupportTotals(selector) {
|
||||
return cache.get(key);
|
||||
}
|
||||
|
||||
export function formatVerifiedSupportLamports(value) {
|
||||
export function formatVerifiedSupportStars(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`;
|
||||
const whole = n / 100n;
|
||||
const fraction = String(n % 100n).padStart(2, '0');
|
||||
return `${whole}.${fraction} ⭐`;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user