SHA256
Перевести донаты на Stars и обновить Devnet
This commit is contained in:
@@ -4,8 +4,9 @@ import { readShineUserPda, supportShineUserOnSolana, supportShineDaoOnSolana } f
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
import { getWalletFromStoredBlockchainKey, transferSolLamports, solanaAddressFromPublicKeyBase64 } from '../services/solana-wallet-service.js';
|
||||
import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||
import { parseSolLamports, formatLamportsSol } from '../services/shine-support-amount.js';
|
||||
import { parseStarCents, formatStars, splitStarCents, starCentsToLamports, formatLamportsSol } from '../services/shine-support-amount.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { getStarsQuoteFromRpc } from '../services/shine-stars-pyth.js';
|
||||
|
||||
/** One shared payment dialog for profiles, posts and donations to the SHiNE economy. */
|
||||
export function openShineSupportDialog({ recipientLogin = '', target = { type: 0 }, onSuccess = () => {} } = {}) {
|
||||
@@ -33,7 +34,7 @@ export function openShineSupportDialog({ recipientLogin = '', target = { type: 0
|
||||
input.type = 'text';
|
||||
input.inputMode = 'decimal';
|
||||
input.autocomplete = 'off';
|
||||
input.placeholder = '0.01';
|
||||
input.placeholder = '0.10';
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
const status = document.createElement('p');
|
||||
@@ -52,38 +53,45 @@ export function openShineSupportDialog({ recipientLogin = '', target = { type: 0
|
||||
cancel.className = 'text-btn';
|
||||
cancel.textContent = t('screens.support_phase2.close');
|
||||
panel.append(header, description, amountLabel, input, details, status, donate);
|
||||
if (!dao) panel.append(direct);
|
||||
// Direct transfers bypass Stars accounting and must not appear in the support dialog.
|
||||
panel.append(cancel);
|
||||
overlay.append(panel);
|
||||
document.body.append(overlay);
|
||||
let quote = null;
|
||||
let busy = false;
|
||||
let closed = false;
|
||||
const close = () => { if (busy) return; closed = true; overlay.remove(); };
|
||||
cancel.addEventListener('click', close);
|
||||
overlay.addEventListener('click', (event) => { if (event.target === overlay) close(); });
|
||||
const update = () => {
|
||||
if (dao) { details.textContent = t('screens.support_phase2.dao_info'); return; }
|
||||
try {
|
||||
const amount = parseSolLamports(input.value);
|
||||
details.textContent = amount % 10n === 0n
|
||||
? `${t('screens.support_phase2.recipient')}: ${formatLamportsSol(amount * 9n / 10n)} SOL · ${t('screens.support_phase2.fund')}: ${formatLamportsSol(amount / 10n)} SOL`
|
||||
: t('screens.support_phase2.divisible');
|
||||
} catch { details.textContent = t('screens.support_phase2.explanation'); }
|
||||
const cents = parseStarCents(input.value);
|
||||
const split = splitStarCents(cents);
|
||||
const sol = quote ? ` · ≈ ${formatLamportsSol(starCentsToLamports(cents, quote.solUsdE8, quote.usdtUsdE8))} SOL` : '';
|
||||
details.textContent = dao ? `${formatStars(cents)}${sol}` :
|
||||
`${t('screens.support_phase2.recipient')}: ${formatStars(split.author)} · ${t('screens.support_phase2.fund')}: ${formatStars(split.dao)}${sol}`;
|
||||
} catch { details.textContent = 'Минимум 0,10 ⭐'; }
|
||||
};
|
||||
input.addEventListener('input', update);
|
||||
amountLabel.textContent = 'Сумма поддержки, ⭐';
|
||||
update();
|
||||
void getStarsQuoteFromRpc({ solanaEndpoint: state.entrySettings.solanaServer }).then((value) => { quote = value; if (!closed) update(); })
|
||||
.catch(() => { if (!closed) details.textContent = 'Курс недоступен. Повторите попытку позднее.'; });
|
||||
const send = async (isDirect) => {
|
||||
if (busy || closed) return;
|
||||
let amount;
|
||||
let amount, cents;
|
||||
try {
|
||||
amount = parseSolLamports(input.value);
|
||||
if (!dao && !isDirect && amount % 10n !== 0n) throw new Error(t('screens.support_phase2.divisible'));
|
||||
cents = parseStarCents(input.value);
|
||||
if (isDirect) throw new Error('Прямой перевод не учитывается в Stars');
|
||||
} catch (error) { status.textContent = error.message; return; }
|
||||
if (isDirect && !window.confirm(t('screens.support_phase2.direct_warning'))) return;
|
||||
busy = true;
|
||||
donate.disabled = direct.disabled = cancel.disabled = input.disabled = true;
|
||||
status.textContent = t('screens.support_phase2.sending');
|
||||
try {
|
||||
// Fetch a fresh quote immediately before signing; Pyth on-chain check is authoritative.
|
||||
quote = await getStarsQuoteFromRpc({ solanaEndpoint: state.entrySettings.solanaServer });
|
||||
amount = starCentsToLamports(cents, quote.solUsdE8, quote.usdtUsdE8);
|
||||
const { storagePwdInMemory: password } = state.session;
|
||||
const endpoint = state.entrySettings.solanaServer;
|
||||
let result;
|
||||
@@ -102,7 +110,9 @@ export function openShineSupportDialog({ recipientLogin = '', target = { type: 0
|
||||
} else {
|
||||
const secrets = await loadEncryptedUserSecrets(login, password);
|
||||
if (!secrets?.blockchainKey || !secrets?.clientKey) throw new Error(t('screens.support_phase2.keys_required'));
|
||||
const args = { senderLogin: login, amountLamports: amount, solanaEndpoint: endpoint, blockchainPrivatePkcs8B64: secrets.blockchainKey, clientPrivatePkcs8B64: secrets.clientKey };
|
||||
const args = { senderLogin: login, amountLamports: amount, starCents: cents,
|
||||
oracleAccounts: { solUsd: quote.solOracleAccount, usdtUsd: quote.usdtOracleAccount },
|
||||
solanaEndpoint: endpoint, blockchainPrivatePkcs8B64: secrets.blockchainKey, clientPrivatePkcs8B64: secrets.clientKey };
|
||||
result = dao ? await supportShineDaoOnSolana(args) : await supportShineUserOnSolana({ ...args, recipientLogin, target });
|
||||
}
|
||||
status.textContent = `${t('screens.support_phase2.success')} ${result.signature || ''}`;
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { authService } from '../state.js';
|
||||
import { formatLamportsSol } from '../services/shine-support-amount.js';
|
||||
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
|
||||
import { formatStars } from '../services/shine-support-amount.js';
|
||||
|
||||
export function supportStatsValues(stats = {}) {
|
||||
const sent = BigInt(stats.supportSent ?? 0);
|
||||
const received = BigInt(stats.supportReceived ?? 0);
|
||||
const daoDirect = BigInt(stats.daoDirect ?? 0);
|
||||
return [sent, received, sent / 10n + daoDirect];
|
||||
return [sent, received, daoDirect];
|
||||
}
|
||||
|
||||
/** Adds an independent asynchronous block; failure/Free accounts do not get fictitious statistics. */
|
||||
@@ -20,7 +21,87 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
|
||||
content.className = 'meta-muted';
|
||||
content.textContent = t('screens.support_phase2.loading');
|
||||
section.append(title, content);
|
||||
const history = document.createElement('details');
|
||||
history.className = 'profile-support-history';
|
||||
const historySummary = document.createElement('summary');
|
||||
historySummary.textContent = t('screens.support_phase2.history');
|
||||
const historyRows = document.createElement('div');
|
||||
historyRows.className = 'stack';
|
||||
historyRows.style.cssText = 'gap:8px;margin-top:10px;';
|
||||
history.append(historySummary, historyRows);
|
||||
section.append(history);
|
||||
parent.append(section);
|
||||
let historyOffset = 0;
|
||||
let loadingHistory = false;
|
||||
let historyLoaded = false;
|
||||
const historyLogin = String(login || '').trim().toLowerCase();
|
||||
const loadHistory = async () => {
|
||||
if (loadingHistory || !isActive() || !section.isConnected) return;
|
||||
loadingHistory = true;
|
||||
const note = document.createElement('div');
|
||||
note.className = 'meta-muted';
|
||||
note.textContent = t('screens.support_phase2.loading');
|
||||
historyRows.append(note);
|
||||
try {
|
||||
const result = await authService.getSupportHistory(login, 20, historyOffset);
|
||||
if (!isActive() || !section.isConnected) return;
|
||||
note.remove();
|
||||
if (!result.ready) {
|
||||
historyRows.textContent = t('screens.support_phase2.loading');
|
||||
return;
|
||||
}
|
||||
if (!historyOffset && !result.transfers?.length) {
|
||||
historyRows.textContent = t('screens.support_phase2.no_history');
|
||||
}
|
||||
const more = historyRows.querySelector('[data-stars-more]');
|
||||
more?.remove();
|
||||
for (const transfer of result.transfers || []) {
|
||||
const outgoing = transfer.senderLogin?.trim().toLowerCase() === historyLogin;
|
||||
const cents = transfer.kind === 'DAO' || outgoing
|
||||
? transfer.amountStarCents : transfer.recipientStarCents;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'row';
|
||||
row.style.cssText = 'display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:6px;';
|
||||
const info = document.createElement('span');
|
||||
info.textContent = transfer.kind === 'DAO'
|
||||
? t('screens.support_phase2.history_dao')
|
||||
: `${outgoing ? '→' : '←'} ${outgoing ? transfer.recipientLogin : transfer.senderLogin}`;
|
||||
const value = document.createElement('strong');
|
||||
value.textContent = `${outgoing ? '−' : '+'}${formatStars(cents)}`;
|
||||
const detail = document.createElement('small');
|
||||
detail.className = 'meta-muted';
|
||||
const date = transfer.blockTime ? new Date(Number(transfer.blockTime) * 1000).toLocaleString() : '';
|
||||
const lamports = BigInt(transfer.amountLamports || '0');
|
||||
const sol = `${lamports / 1_000_000_000n}.${String(lamports % 1_000_000_000n).padStart(9, '0').replace(/0+$/, '') || '0'} SOL`;
|
||||
detail.textContent = `${date} · ${sol}`;
|
||||
const explorer = document.createElement('a');
|
||||
const sig = String(transfer.signature || '');
|
||||
if (/^[1-9A-HJ-NP-Za-km-z]{64,90}$/.test(sig)) {
|
||||
const network = getSolanaCluster();
|
||||
explorer.href = `https://explorer.solana.com/tx/${sig}${network && network !== 'mainnet-beta' ? `?cluster=${encodeURIComponent(network)}` : ''}`;
|
||||
explorer.target = '_blank'; explorer.rel = 'noopener noreferrer';
|
||||
explorer.textContent = t('screens.support_phase2.transaction');
|
||||
row.append(info, value, detail, explorer);
|
||||
} else row.append(info, value, detail);
|
||||
historyRows.append(row);
|
||||
}
|
||||
historyOffset += (result.transfers || []).length;
|
||||
if (result.hasMore) {
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'text-btn'; btn.type = 'button';
|
||||
btn.dataset.starsMore = '1';
|
||||
btn.textContent = t('screens.support_phase2.more');
|
||||
btn.addEventListener('click', () => void loadHistory());
|
||||
historyRows.append(btn);
|
||||
}
|
||||
historyLoaded = true;
|
||||
} catch {
|
||||
if (isActive() && section.isConnected) note.textContent = t('screens.support_phase2.history_unavailable');
|
||||
} finally { loadingHistory = false; }
|
||||
};
|
||||
history.addEventListener('toggle', () => {
|
||||
if (history.open && !historyLoaded) void loadHistory();
|
||||
});
|
||||
let pendingRefresh = null;
|
||||
const scheduleRetry = () => {
|
||||
if (pendingRefresh !== null) return;
|
||||
@@ -45,9 +126,9 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
|
||||
return;
|
||||
}
|
||||
const values = supportStatsValues({
|
||||
supportSent: stats.supportSentLamports,
|
||||
supportReceived: stats.supportReceivedLamports,
|
||||
daoDirect: stats.daoDirectLamports,
|
||||
supportSent: stats.supportSentStarCents,
|
||||
supportReceived: stats.supportReceivedStarCents,
|
||||
daoDirect: stats.daoDirectStarCents,
|
||||
});
|
||||
content.replaceChildren();
|
||||
content.className = 'stack';
|
||||
@@ -58,7 +139,7 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
|
||||
const name = document.createElement('span');
|
||||
const amount = document.createElement('strong');
|
||||
name.textContent = label;
|
||||
amount.textContent = `${formatLamportsSol(values[idx])} SOL`;
|
||||
amount.textContent = formatStars(values[idx]);
|
||||
row.append(name, amount);
|
||||
content.append(row);
|
||||
});
|
||||
|
||||
@@ -2216,15 +2216,15 @@
|
||||
},
|
||||
"chat_view": {
|
||||
"security_notice": {
|
||||
"title": "Your conversation is protected by end-to-end encryption",
|
||||
"encryption": "All private messages are encrypted using modern cryptographic algorithms. Encryption keys are stored ONLY on the participants’ devices.",
|
||||
"servers": "SHiNE servers do not possess your private keys and cannot technically read your messages.",
|
||||
"derivation": "Your encryption key is derived from your login and password.",
|
||||
"rotation": "When you change your password, your messages are re-encrypted from the old password to the new one on your device.",
|
||||
"source": "The source code of our applications is fully open, so you can verify these claims yourself.",
|
||||
"title": "Private chat security",
|
||||
"encryption": "Messages in this chat are encrypted on the participants' devices.",
|
||||
"servers": "The server delivers encrypted data but should not be able to read the conversation.",
|
||||
"derivation": "Chat keys are derived from account keys and stored on the devices.",
|
||||
"rotation": "After key rotation, some messages may require the keys to be received again.",
|
||||
"source": "Before sending, make sure you are communicating with the intended user and server.",
|
||||
"warning_label": "Important:",
|
||||
"warning": "if you forget your password, you will not be able to recover access to your encrypted conversations.",
|
||||
"recovery": "SHiNE does not store your secret keys and cannot help you restore your conversations."
|
||||
"warning": "never share private keys or your account password with anyone.",
|
||||
"recovery": "Access recovery depends on your saved keys and password. Keep them secure."
|
||||
},
|
||||
"text_002": "Muted",
|
||||
"text_015": "Search",
|
||||
@@ -4246,7 +4246,7 @@
|
||||
"donate_shine": "✨ Support SHiNE",
|
||||
"donate": "Donate",
|
||||
"to": "Recipient:",
|
||||
"amount": "Amount, SOL",
|
||||
"amount": "Amount, ⭐",
|
||||
"recipient": "Recipient",
|
||||
"fund": "SHiNE economy",
|
||||
"dao_info": "100% of your donation goes to the SHiNE economic fund and participates in its existing payout system.",
|
||||
@@ -4261,7 +4261,13 @@
|
||||
"success": "Transfer confirmed:",
|
||||
"failed": "Transfer failed",
|
||||
"close": "Close",
|
||||
"invalid_target": "This post has no verified block number or hash"
|
||||
"invalid_target": "This post has no verified block number or hash",
|
||||
"history": "Transfer history",
|
||||
"no_history": "No transfers yet",
|
||||
"history_dao": "→ SHiNE fund",
|
||||
"transaction": "Transaction ↗",
|
||||
"more": "Show more",
|
||||
"history_unavailable": "Could not load transfer history"
|
||||
},
|
||||
"support_phase3": {
|
||||
"channel_total": "Channel support received"
|
||||
|
||||
@@ -2349,15 +2349,15 @@
|
||||
},
|
||||
"chat_view": {
|
||||
"security_notice": {
|
||||
"title": "Ваша переписка защищена сквозным шифрованием",
|
||||
"encryption": "Все личные сообщения шифруются с использованием современных криптографических алгоритмов. Ключи шифрования хранятся ТОЛЬКО на устройствах участников переписки.",
|
||||
"servers": "Сервера SHiNE не имеют ваших приватных ключей и даже технически никак не могут прочитать ваши сообщения.",
|
||||
"derivation": "Ваш ключ шифрования высчитывается из вашего логина и пароля.",
|
||||
"rotation": "При смене пароля перекодирование всех ваших сообщений со старого пароля на новый происходит на устройстве пользователя.",
|
||||
"source": "Код наших приложений полностью открыт и вы легко можете проверить всё это сами.",
|
||||
"title": "Безопасность личной переписки",
|
||||
"encryption": "Сообщения в этом чате шифруются на устройствах участников.",
|
||||
"servers": "Сервер доставляет зашифрованные данные, но не должен видеть содержимое переписки.",
|
||||
"derivation": "Ключи переписки производятся из ключей аккаунта и хранятся на устройствах.",
|
||||
"rotation": "При смене ключей часть сообщений может потребовать повторного получения ключей.",
|
||||
"source": "Перед отправкой проверьте, что вы общаетесь с нужным пользователем и сервером.",
|
||||
"warning_label": "Важно:",
|
||||
"warning": "если вы забудете свой пароль, восстановить доступ к вашей зашифрованной переписке будет невозможно.",
|
||||
"recovery": "SHiNE не хранит ваши секретные ключи и никак не сможет помочь вам восстановить вашу переписку."
|
||||
"warning": "не передавайте приватные ключи и пароль аккаунта другим людям.",
|
||||
"recovery": "Восстановление доступа зависит от сохранённых ключей и пароля. Храните их безопасно."
|
||||
},
|
||||
"text_001": "Чат",
|
||||
"text_002": "Без звука",
|
||||
@@ -4246,7 +4246,7 @@
|
||||
"donate_shine": "✨ Поддержать SHiNE",
|
||||
"donate": "Пожертвовать",
|
||||
"to": "Получатель:",
|
||||
"amount": "Сумма, SOL",
|
||||
"amount": "Сумма, ⭐",
|
||||
"recipient": "Получателю",
|
||||
"fund": "Экономике SHiNE",
|
||||
"dao_info": "100% пожертвования поступает в экономический фонд SHiNE и участвует в действующей системе выплат.",
|
||||
@@ -4261,7 +4261,13 @@
|
||||
"success": "Перевод подтверждён:",
|
||||
"failed": "Не удалось отправить перевод",
|
||||
"close": "Закрыть",
|
||||
"invalid_target": "Для этой публикации отсутствует проверенный номер или хеш блока"
|
||||
"invalid_target": "Для этой публикации отсутствует проверенный номер или хеш блока",
|
||||
"history": "История переводов",
|
||||
"no_history": "Переводов пока нет",
|
||||
"history_dao": "→ Фонд SHiNE",
|
||||
"transaction": "Транзакция ↗",
|
||||
"more": "Показать ещё",
|
||||
"history_unavailable": "Не удалось загрузить историю"
|
||||
},
|
||||
"support_phase3": {
|
||||
"channel_total": "Канал получил поддержку"
|
||||
|
||||
@@ -15,9 +15,10 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
||||
import { readShineUserPda, supportShineUserOnSolana } from '../services/shine-user-pda-service.js';
|
||||
import { parseSolLamports, formatLamportsSol, hexHash32 } from '../services/shine-support-amount.js';
|
||||
import { parseStarCents, splitStarCents, formatStars, starCentsToLamports, formatLamportsSol, hexHash32 } from '../services/shine-support-amount.js';
|
||||
import { transferSolLamports } from '../services/solana-wallet-service.js';
|
||||
import { loadVerifiedSupportTotals, formatVerifiedSupportLamports } from '../services/support-totals-service.js';
|
||||
import { getStarsQuoteFromRpc } from '../services/shine-stars-pyth.js';
|
||||
import { loadVerifiedSupportTotals, formatVerifiedSupportStars } from '../services/support-totals-service.js';
|
||||
|
||||
export const pageMeta = { id: 'channel-donate-view', get title() { return t('screens.channel_donate_view.text_001'); } };
|
||||
|
||||
@@ -189,7 +190,7 @@ export function render({ navigate, route, chrome }) {
|
||||
<label class="field-label" for="channel-donate-amount">${th('screens.channel_donate_view.text_029')}</label>
|
||||
<div class="channel-donate-amount-row">
|
||||
<input class="input" id="channel-donate-amount" type="text" inputmode="decimal" placeholder="0.1" autocomplete="off" />
|
||||
<span>SOL</span>
|
||||
<span>⭐</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -198,7 +199,7 @@ export function render({ navigate, route, chrome }) {
|
||||
<p class="meta-muted inline-error channel-donate-status" id="channel-donate-status"></p>
|
||||
<div class="channel-donate-result" id="channel-donate-result" hidden></div>
|
||||
<button class="primary-btn channel-donate-submit" id="channel-donate-submit" type="button" ${recipientChoices.length && recipientPda ? '' : 'disabled'}>${th('screens.support_flow.donate')}</button>
|
||||
<button class="secondary-btn channel-donate-submit" id="channel-donate-direct" type="button" ${recipientChoices.length ? '' : 'disabled'}>${th('screens.support_flow.direct')}</button>
|
||||
|
||||
`;
|
||||
|
||||
const recipientSelect = content.querySelector('#channel-donate-recipient-key');
|
||||
@@ -289,12 +290,17 @@ export function render({ navigate, route, chrome }) {
|
||||
});
|
||||
refreshEl?.addEventListener('click', () => void refreshBalance());
|
||||
|
||||
let starsQuote = null;
|
||||
const renderSplit = () => {
|
||||
try {
|
||||
const amount = parseSolLamports(amountEl?.value || '');
|
||||
if (splitEl) splitEl.textContent = `${t('screens.support_flow.recipient')}: ${formatLamportsSol(amount * 9n / 10n)} SOL · ${t('screens.support_flow.fund')}: ${formatLamportsSol(amount / 10n)} SOL`;
|
||||
} catch { if (splitEl) splitEl.textContent = ''; }
|
||||
const cents = parseStarCents(amountEl?.value || '');
|
||||
const parts = splitStarCents(cents);
|
||||
const sol = starsQuote ? ` · ≈ ${formatLamportsSol(starCentsToLamports(cents, starsQuote.solUsdE8, starsQuote.usdtUsdE8))} SOL` : '';
|
||||
if (splitEl) splitEl.textContent = `${t('screens.support_flow.recipient')}: ${formatStars(parts.author)} · ${t('screens.support_flow.fund')}: ${formatStars(parts.dao)}${sol}`;
|
||||
} catch { if (splitEl) splitEl.textContent = 'Минимальная поддержка 0,10 ⭐'; }
|
||||
};
|
||||
void getStarsQuoteFromRpc({ solanaEndpoint: state.entrySettings.solanaServer }).then(v => { starsQuote = v; if (!disposed) renderSplit(); })
|
||||
.catch(() => { if (splitEl && !disposed) splitEl.textContent = 'Курс временно недоступен'; });
|
||||
if (explanationEl) explanationEl.textContent = recipientPda
|
||||
? t('screens.support_flow.explanation')
|
||||
: t('screens.support_flow.paid_required');
|
||||
@@ -304,10 +310,10 @@ export function render({ navigate, route, chrome }) {
|
||||
if (busy || disposed) return;
|
||||
const recipient = selectedRecipient();
|
||||
if (!recipient?.address) { setStatus(t('screens.channel_donate_view.text_007'), 'error'); return; }
|
||||
let amount;
|
||||
let amount, cents;
|
||||
try {
|
||||
amount = parseSolLamports(amountEl?.value || '');
|
||||
if (!direct && amount % 10n !== 0n) throw new Error(t('screens.support_flow.divisible'));
|
||||
cents = parseStarCents(amountEl?.value || '');
|
||||
if (direct) throw new Error('Прямой перевод отключён в системе Stars');
|
||||
} catch (error) { setStatus(error.message || t('screens.channel_donate_view.text_008'), 'error'); return; }
|
||||
if (direct && !window.confirm(t('screens.support_flow.direct_warning'))) return;
|
||||
|
||||
@@ -315,6 +321,8 @@ export function render({ navigate, route, chrome }) {
|
||||
setStatus(t('screens.channel_donate_view.text_009'));
|
||||
if (resultEl) { resultEl.hidden = true; resultEl.innerHTML = ''; }
|
||||
try {
|
||||
starsQuote = await getStarsQuoteFromRpc({ solanaEndpoint: state.entrySettings.solanaServer });
|
||||
amount = starCentsToLamports(cents, starsQuote.solUsdE8, starsQuote.usdtUsdE8);
|
||||
const wallet = await resolveSenderWallet();
|
||||
let result;
|
||||
if (direct) {
|
||||
@@ -337,6 +345,7 @@ export function render({ navigate, route, chrome }) {
|
||||
if (!secrets?.blockchainKey || !secrets?.clientKey) throw new Error(t('screens.support_flow.keys_required'));
|
||||
result = await supportShineUserOnSolana({
|
||||
senderLogin: login, recipientLogin: ownerLogin, amountLamports: amount,
|
||||
starCents: cents, oracleAccounts: { solUsd: starsQuote.solOracleAccount, usdtUsd: starsQuote.usdtOracleAccount },
|
||||
target: { type: 1, channelBlockNumber: BigInt(selector.channelRootBlockNumber), channelBlockHash: hexHash32(selector.channelRootBlockHash) },
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
blockchainPrivatePkcs8B64: secrets.blockchainKey,
|
||||
@@ -347,7 +356,7 @@ export function render({ navigate, route, chrome }) {
|
||||
setStatus('');
|
||||
if (resultEl) {
|
||||
resultEl.hidden = false;
|
||||
resultEl.innerHTML = `<strong>${th('screens.channel_donate_view.text_031')}</strong><span>${escapeHtml(formatLamportsSol(amount))} SOL → ${escapeHtml(recipient.label)}</span><code>${escapeHtml(String(result.signature || ''))}</code>`;
|
||||
resultEl.innerHTML = `<strong>${th('screens.channel_donate_view.text_031')}</strong><span>${escapeHtml(formatStars(cents))} → ${escapeHtml(recipient.label)}</span><code>${escapeHtml(String(result.signature || ''))}</code>`;
|
||||
}
|
||||
showToast(t('screens.channel_donate_view.text_010'));
|
||||
const balance = await getBalanceSol({ endpoint: state.entrySettings.solanaServer, address: wallet.address });
|
||||
@@ -363,7 +372,7 @@ export function render({ navigate, route, chrome }) {
|
||||
void loadVerifiedSupportTotals(selector).then((totals) => {
|
||||
if (disposed) return;
|
||||
const label = content.querySelector('#channel-donate-verified-total');
|
||||
const total = totals && formatVerifiedSupportLamports(totals.channelReceivedLamports);
|
||||
const total = totals && formatVerifiedSupportStars(totals.channelReceivedStarCents);
|
||||
if (label && total) label.textContent = `${t('screens.support_phase3.channel_total')}: ${total}`;
|
||||
});
|
||||
updateRecipientAddress();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { openShineSupportDialog } from '../components/shine-support-dialog.js';
|
||||
import { hexHash32 } from '../services/shine-support-amount.js';
|
||||
import { loadVerifiedSupportTotals, formatVerifiedSupportLamports } from '../services/support-totals-service.js';
|
||||
import { loadVerifiedSupportTotals, formatVerifiedSupportStars } from '../services/support-totals-service.js';
|
||||
import { formatDateTime, getIntlLocale } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
@@ -2169,7 +2169,7 @@ function renderPostCard(post, {
|
||||
const messageId = `${String(post.messageRef.blockNumber)}:${String(post.messageRef.blockHash).toLowerCase()}`;
|
||||
void loadVerifiedSupportTotals(selector).then((totals) => {
|
||||
if (!totals || !supportButton.isConnected) return;
|
||||
const formatted = formatVerifiedSupportLamports(totals.messages.get(messageId));
|
||||
const formatted = formatVerifiedSupportStars(totals.messages.get(messageId));
|
||||
if (formatted) supportButton.textContent = `♥ ${formatted}`;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import {
|
||||
deriveStarsPythOracleAccounts,
|
||||
getStarsQuoteFromRpc,
|
||||
parseVerifiedPythPriceAccount,
|
||||
PYTH_SOL_USD_FEED_ID,
|
||||
PYTH_USDT_USD_FEED_ID,
|
||||
PYTH_RECEIVER_PROGRAM_ID,
|
||||
} from '../js/services/shine-stars-pyth.js';
|
||||
|
||||
const validOwner = { toBase58: () => PYTH_RECEIVER_PROGRAM_ID };
|
||||
const now = 1_800_000_000;
|
||||
const discr = [34,241,35,99,157,126,244,205];
|
||||
function fakePrice(feed, value, { publish = now - 15, confidence = 20_000_000n, verified = true, owner = validOwner, exponent = -8 } = {}) {
|
||||
const bytes = new Uint8Array(133);
|
||||
bytes.set(discr);
|
||||
bytes[40] = verified ? 1 : 0;
|
||||
bytes.set(Uint8Array.from(feed.match(/../g), (hex) => parseInt(hex, 16)), 41);
|
||||
const v = new DataView(bytes.buffer);
|
||||
v.setBigInt64(73, BigInt(value), true);
|
||||
v.setBigUint64(81, confidence, true);
|
||||
v.setInt32(89, exponent, true);
|
||||
v.setBigInt64(93, BigInt(publish), true);
|
||||
return { owner, data: bytes };
|
||||
}
|
||||
const solPrice = fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n); // $150.00
|
||||
const usdtPrice = fakePrice(PYTH_USDT_USD_FEED_ID, 100_000_000n, {confidence: 1000n}); // $1.00
|
||||
|
||||
// Browser-vendored Solana web3.js; no network required, same code as production.
|
||||
const context = { Buffer, Uint8Array, TextEncoder, TextDecoder, console, setTimeout, crypto: globalThis.crypto };
|
||||
vm.createContext(context);
|
||||
vm.runInContext(readFileSync(new URL('../js/vendor/solana-web3.iife.min.js', import.meta.url), 'utf8'), context);
|
||||
const solana = context.solanaWeb3;
|
||||
|
||||
test('derive shard-0 Pyth Core oracle PDAs (official mainnet examples)', () => {
|
||||
assert.deepEqual(deriveStarsPythOracleAccounts(solana), {
|
||||
solUsd: '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE',
|
||||
usdtUsd: 'HT2PLQBcG5EiCcNSaMHAjSgd9F98ecpATbk4Sk5oYuM',
|
||||
});
|
||||
});
|
||||
test('read raw Anchor PriceUpdateV2 without precision loss', () => {
|
||||
assert.equal(parseVerifiedPythPriceAccount(solPrice, PYTH_SOL_USD_FEED_ID, now).priceE8, 15_000_000_000n);
|
||||
assert.equal(parseVerifiedPythPriceAccount(usdtPrice, PYTH_USDT_USD_FEED_ID, now).priceE8, 100_000_000n);
|
||||
});
|
||||
test('fail closed for stale/future/unverified/malformed/foreign price accounts', () => {
|
||||
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n, {publish: now - 3_601}), PYTH_SOL_USD_FEED_ID, now), /устарела/);
|
||||
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n, {publish: now + 16}), PYTH_SOL_USD_FEED_ID, now), /время/);
|
||||
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n, {verified:false}), PYTH_SOL_USD_FEED_ID, now), /проверку/);
|
||||
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n), PYTH_USDT_USD_FEED_ID, now), /другую/);
|
||||
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n, {owner:{toBase58:()=> 'Bad'}}), PYTH_SOL_USD_FEED_ID, now), /владельца/);
|
||||
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n, {confidence: 150_000_001n}), PYTH_SOL_USD_FEED_ID, now), /интервал/);
|
||||
const invalid = fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n);
|
||||
invalid.data[0] ^= 1;
|
||||
assert.throws(() => parseVerifiedPythPriceAccount(invalid, PYTH_SOL_USD_FEED_ID, now), /формат/);
|
||||
});
|
||||
test('request both accounts once from authenticated Solana RPC, no Hermes', async () => {
|
||||
let invoked = 0;
|
||||
const connection = { getMultipleAccountsInfo: async (keys, commitment) => {
|
||||
invoked++;
|
||||
assert.equal(keys.length, 2);
|
||||
assert.equal(commitment, 'confirmed');
|
||||
assert.equal(keys[0].toBase58(), '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE');
|
||||
return [solPrice, usdtPrice];
|
||||
} };
|
||||
const quote = await getStarsQuoteFromRpc({ solanaEndpoint: 'https://test.shineup.me/solana-rpc', solana, connection, nowSeconds: now });
|
||||
assert.equal(quote.solUsdE8, '15000000000');
|
||||
assert.equal(quote.usdtUsdE8, '100000000');
|
||||
assert.equal(invoked, 1);
|
||||
await assert.rejects(() => getStarsQuoteFromRpc({ solanaEndpoint: 'https://test.shineup.me/solana-rpc', solana,
|
||||
connection: { getMultipleAccountsInfo: async () => [solPrice, null] }, nowSeconds: now }), /отсутствует/);
|
||||
});
|
||||
test('no server GetStarsQuote in active WS registry or UI', () => {
|
||||
const reg = readFileSync(new URL('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/JsonHandlerRegistry.java', import.meta.url), 'utf8');
|
||||
const auth = readFileSync(new URL('../js/services/auth-service.js', import.meta.url), 'utf8');
|
||||
assert.doesNotMatch(reg, /GetStarsQuote/);
|
||||
assert.doesNotMatch(auth, /GetStarsQuote/);
|
||||
for (const p of ['../js/components/shine-support-dialog.js', '../js/pages/channel-donate-view.js']) {
|
||||
const s = readFileSync(new URL(p, import.meta.url), 'utf8');
|
||||
assert.match(s, /getStarsQuoteFromRpc/);
|
||||
assert.doesNotMatch(s, /authService\.getStarsQuote/);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseStarCents, formatStars, splitStarCents, starCentsToLamports } from '../js/services/shine-support-amount.js';
|
||||
test('strictly two fractional digits, minimum 0.10 Stars', () => {
|
||||
assert.equal(parseStarCents('0,10'), 10n);
|
||||
assert.equal(parseStarCents('0.75'), 75n);
|
||||
assert.equal(formatStars(75n), '0.75 ⭐');
|
||||
assert.throws(() => parseStarCents('0.09'));
|
||||
assert.throws(() => parseStarCents('0.001'));
|
||||
});
|
||||
test('DAO star share rounds UP to cents', () => {
|
||||
assert.deepEqual(splitStarCents(10n), {author: 9n, dao: 1n});
|
||||
assert.deepEqual(splitStarCents(15n), {author: 13n, dao: 2n});
|
||||
assert.deepEqual(splitStarCents(75n), {author: 67n, dao: 8n});
|
||||
});
|
||||
test('quote works in integer lamports without floats', () => {
|
||||
assert.equal(starCentsToLamports(75n, 150n * 100_000_000n, 100_000_000n), 5_000_000n);
|
||||
assert.equal(starCentsToLamports(10n, 150n * 100_000_000n, 100_000_000n), 666_667n);
|
||||
});
|
||||
@@ -5,10 +5,10 @@ import { supportStatsValues } from '../js/components/support-stats.js';
|
||||
|
||||
function file(path) { return readFileSync(new URL(path, import.meta.url), 'utf8'); }
|
||||
|
||||
test('three displayed counters: full sent, net received, sent/10 + direct', () => {
|
||||
assert.deepEqual(supportStatsValues({ supportSent: 1_000_000_000n, supportReceived: 900_000_000n, daoDirect: 200_000_000n }), [1_000_000_000n, 900_000_000n, 300_000_000n]);
|
||||
test('three displayed counters: sent, received, direct DAO in star cents', () => {
|
||||
assert.deepEqual(supportStatsValues({ supportSent: 1_000_000_000n, supportReceived: 900_000_000n, daoDirect: 200_000_000n }), [1_000_000_000n, 900_000_000n, 200_000_000n]);
|
||||
assert.deepEqual(supportStatsValues({}), [0n, 0n, 0n]);
|
||||
assert.deepEqual(supportStatsValues({ supportSent: '10000000000000000000', supportReceived: '9000000000000000000', daoDirect: '250000000000000000' }), [10000000000000000000n, 9000000000000000000n, 1250000000000000000n]);
|
||||
assert.deepEqual(supportStatsValues({ supportSent: '10000000000000000000', supportReceived: '9000000000000000000', daoDirect: '250000000000000000' }), [10000000000000000000n, 9000000000000000000n, 250000000000000000n]);
|
||||
});
|
||||
|
||||
test('profile views attach counters from server cache and support user action', () => {
|
||||
@@ -35,13 +35,13 @@ test('message buttons pass checked block hashes, not message text', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('shared modal protects direct and tracked workflows', () => {
|
||||
test('shared modal requires Stars and oracle quote', () => {
|
||||
const src = file('../js/components/shine-support-dialog.js');
|
||||
assert.match(src, /supportShineUserOnSolana/);
|
||||
assert.match(src, /supportShineDaoOnSolana/);
|
||||
assert.match(src, /transferSolLamports/);
|
||||
assert.match(src, /window\.confirm\(t\('screens\.support_phase2\.direct_warning'\)\)/);
|
||||
assert.match(src, /amount % 10n/);
|
||||
assert.match(src, /starCentsToLamports/);
|
||||
assert.match(src, /getStarsQuoteFromRpc/);
|
||||
assert.match(src, /parseStarCents/);
|
||||
});
|
||||
|
||||
test('profile statistics use server API without Solana RPC', () => {
|
||||
|
||||
Reference in New Issue
Block a user